今日已更新 233 条资讯 | 累计 20205 条内容
关于我们

标签:#tutorial

找到 373 篇相关文章

AI 资讯

Mastering Design Principles: Dependency Inversion in Kotlin

Abstract In modern software engineering, writing code that simply "works" is only the first step. The real challenge lies in designing systems that are maintainable, scalable, and easy to test. This article explores the Dependency Inversion Principle (DIP), the final pillar of the SOLID design principles. Through a practical, real-world example in Kotlin, we will demonstrate how to transition from a tightly coupled architecture to an abstraction-based design. This shift dramatically improves our codebase, facilitates unit testing, and prepares our applications for future growth. Introduction: The Chaos of Coupling As applications grow, it is common to see how a minor change in a database schema or a third-party API triggers a domino effect, breaking unrelated parts of the system. This fragility is a direct consequence of tight coupling. Software design principles, particularly SOLID, were established to prevent this architectural decay. Today, we focus on the "D" in SOLID: the Dependency Inversion Principle (DIP). This principle establishes two core rules: High-level modules should not depend on low-level modules. Both should depend on abstractions (interfaces). Abstractions should not depend on details. Details (concrete implementations) should depend on abstractions. The Scenario: An E-commerce Payment Processor Imagine you are building the billing system for an online store. To process purchases, the system needs to connect to a payment gateway, such as PayPal. The Bad Way: Tight Coupling (Violating DIP) In this initial design, our high-level business logic (OrderProcessor) directly instantiates and depends on the concrete low-level class (PayPalService). // Low-level component (Concrete detail) class PayPalService { fun executePayment(amount: Double) { println("Processing payment of $$amount via PayPal API.") } } // High-level component (Business logic) class OrderProcessor { // Tight coupling: this class depends directly on a concrete implementation private val

2026-06-18 原文 →
AI 资讯

Two patterns, five services, one n8n workflow

The first two articles in this series each showed one technique. Implementation notes #001 was a dynamic dropdown — a form field that fills itself from an API. Implementation notes #002 was a dynamic credential — an API key that arrives from the form and threads through to the HTTP nodes. This article is the capstone. It walks through all-services-demo , the example workflow that ships with n8n-nodes-ldxhub , where those two techniques combine with a Switch node to host five different AI document-processing services inside one workflow — structured extraction, translation refinement, OCR, PDF conversion, and text extraction. The screenshots and the workflow JSON below come from the n8n-nodes-ldxhub package. The patterns themselves are generic — they work for any set of services you want to consolidate into a single template. This is not a "follow these steps" article. It's a parts catalog. No two readers are solving the same problem, and templates rarely fit anyone's situation as-is. Take what fits. Drop the rest. You don't need to understand all 46 nodes to reuse the patterns. The shape The workflow has 46 nodes — large enough to look intimidating in the editor, but structurally it's just five repeated paths plus a small routing section. The entry section is two nodes: On form submission — the trigger. Asks the user which service they want and collects an API key. Route by Service — a Switch node with five outputs, one per service. Everything to the right of the Switch is service-specific. Five paths fan out: StructFlow, RefineLoop, RenderOCR, CastDoc, ExtractDoc. Each path ends in two Form Ending nodes — one for success (auto-downloads the result), one for error. That's the spine: form → switch → service path → ending. The complexity is pushed into the service paths. The spine: routing by static comparison The Switch node ("Route by Service") uses Rules mode. Each rule reads the same expression from the form — {{ $json.service }} — and compares it to a static serv

2026-06-17 原文 →
AI 资讯

Why git pull --rebase should probably be your default

Most developers run git pull dozens of times a week without thinking about it. And most of the time, it works. Then one day you open a PR and the reviewer says "can you clean up the merge commits?" You look at your branch and see three "Merge branch 'main' into feature/login" commits scattered through history. The feature itself is 5 commits. The log is a mess. That mess comes from one decision: using git pull instead of git pull --rebase . Here's what's actually happening, and why the rebase variant produces cleaner history for teams. The setup: diverged history You're working on feature/login . You commit two changes locally ( X , Y ). Meanwhile, your teammate pushes two commits to main ( C , D ). Your branch and main have now diverged . Neither is a strict superset of the other. Git needs to reconcile them when you pull. Shared history: A → B Your local: A → B → X → Y (you added X, Y) Remote main: A → B → C → D (teammate added C, D) Git has two strategies for this reconciliation. Strategy 1: git pull (merge) A plain git pull creates a merge commit that joins your local history with the remote. Your commits and the remote's commits both appear in the log, connected by a merge node. The git log reads: M Merge branch 'main' into feature/login D fix: timeout on slow connections Y feat: client-side validation C chore: upgrade eslint X feat: login form B (shared) A (shared) This is honest history — it records exactly what happened: parallel development that was joined at a specific point. But it's also noisy history — the merge commit has no meaningful changes, and the log interleaves commits that weren't conceptually related. Strategy 2: git pull --rebase With --rebase , Git takes a different approach. It: Temporarily sets aside your local commits ( X , Y ) Fast-forwards your branch to the tip of the remote ( D ) Replays your commits on top, one by one, creating new commits ( X' , Y' ) The git log reads: Y' feat: client-side validation X' feat: login form D fix: timeo

2026-06-17 原文 →
AI 资讯

I Stopped Trusting the LLM With the Score: Building an Honest AI Portfolio Reviewer

Ask a language model to score a developer portfolio out of 100 and you get a confident number back. Hand it a near-empty page with a name and a broken avatar, and it will often still tell you something like 92. Nice layout. Strong personal branding. The model is being polite, not accurate. That was the first wall I hit building Leon, the reviewer inside getfolio. If the score is not trustworthy, nothing downstream matters: the critique, the suggestions, and the fix button all hang off a number the model invented to sound encouraging. This is the build log of how I stopped letting the model hold the pen. Short version: a deterministic rules engine owns the score, and the language model only owns the words around it. The failure mode: an LLM judge wants to be liked If you have shipped anything with an LLM evaluator you have probably seen this. You hand it a rubric, a JSON schema, even worked examples, and it still drifts upward. Empty inputs get encouraging scores. Weak inputs get the benefit of the doubt. Strong inputs land in the same band as the weak ones, just with longer praise. A few reasons, roughly in order of how much they hurt: Tuning rewards a helpful, encouraging tone. Harsh scoring reads as unhelpful, so the model softens it. The model has no ground truth for what a 70 versus an 85 looks like in your specific domain. It is scoring on vibes. Scoring and explaining are entangled. The model writes the kind explanation first, then picks a number to match the nice things it just said. Run it twice on the same input and you get two different numbers. There is no anchor. For a portfolio reviewer that real recruiters and developers would act on, that was a non-starter. If Leon says 64, an empty page should not be able to reach 64 by accident, and a strong portfolio should not get talked down to it either. The number has to mean something. The fix: rules engine owns the score, model owns the language The architecture splits responsibilities hard. A deterministic e

2026-06-17 原文 →
AI 资讯

How to Build a WordPress Plugin Licensing System from Scratch (Without Freemius)

If you're shipping a commercial WordPress plugin, sooner or later you'll need a licensing system. Something that lets paying customers activate the plugin on their site, locks it to that domain, and stops people from sharing the same key across fifty sites. The default answer in the WordPress world is Freemius or EDD Software Licensing. They're great. They're also a revenue share, a third-party dependency, and a black box you don't control. When we built RideCab WP , a commercial WooCommerce taxi booking plugin, we decided to build our own. Here's the architecture, the code, and the gotchas we hit along the way. What a Licensing System Actually Needs to Do Before writing any code, get clear on the requirements. A real plugin licensing system needs to: Generate unique license keys when someone buys Let the customer activate the key on their site Bind that key to one (or N) domains Validate the key periodically so revoked or expired keys stop working Handle deactivation when a customer moves to a new domain Fail gracefully — never lock a paying customer out because your license server hiccuped Optionally: deliver plugin updates only to valid license holders We'll cover 1 through 6 in this post. Update delivery is a separate beast and I'll write it up next. The Architecture The system has two halves that live in two different places. The license server runs on your own infrastructure — for us, it's a WordPress must-use plugin (mu-plugin) on the same WordPress install that powers our marketing site. It: Stores license keys in a custom database table Exposes a small REST API for activate, deactivate, and validate calls Provides an admin dashboard to view, create, and revoke keys The client is a PHP class shipped inside the commercial plugin (RideCab WP, in our case). It: Adds a license settings page to the plugin Calls home on activation Caches the validation result Re-validates quietly in the background Two pieces, talking over HTTPS, with the customer's domain as the b

2026-06-17 原文 →
AI 资讯

Ollama Structured Outputs in Practice — Getting Type-Safe JSON from Local LLMs with Pydantic

json.loads(response) fails at a certain point. You told the model "return JSON only," but it added a ```json markdown code fence around everything. A quick regex strips it — until that regex hits an edge case, and that edge case blows up in production. Since Ollama 0.3.0, passing a JSON schema to the format parameter eliminates this problem at the root. The model's inference itself is constrained by the schema, so no code fences, no explanatory text, no mid-thought artifacts. Just parseable JSON. I ran these tests locally with Gemma4 and Ollama 0.30.7 to see how well it holds up in practice. Why LLM Response Parsing Is Tricky The most common problem when running Ollama locally — without a cloud LLM API — is JSON parsing. Two reasons. First, text generation models are trained toward "natural text." Even if you ask for JSON only, they'll often wrap it in json ... blocks or prepend "Of course! Here is the JSON you requested:" style text. Here's what I reproduced directly: json Input: 'Give me 3 Python tips as JSON with keys: tips (array), difficulty (1-5)' Model output (no format parameter): ```json { "tips": [ "Master the fundamentals first...", ... ] } JSON parse: FAILED Python ' s `json.loads()` can ' t handle the markdown wrapper . The " JSON only " instruction is unreliable in production . Second , speed . I measured the same query both ways : 32 seconds without structured output , 5 seconds with it . More on why below . ## How the Ollama format Parameter Works Ollama ' s `/api/generate` endpoint has a `format` field. Pass a JSON schema object and Ollama applies **constrained decoding** during inference. python import json import urllib.request def ollama_structured(prompt, schema, model="gemma4:e4b"): payload = { "model": model, "prompt": prompt, "format": schema, # ← pass JSON schema object directly "stream": False, "options": {"temperature": 0} } data = json.dumps(payload).encode() req = urllib.request.Request( " http://localhost:11434/api/generate ", data=data

2026-06-17 原文 →
AI 资讯

Fine-Tuning AI Models for Specialized Tasks

🚀 Technical Briefing: This tutorial is part of our deep-dive series on Agentic Workflows at Gate of AI . For the full technical breakdown, interactive code sandbox, and the native Arabic translation, visit the original article here . <span>Tutorial</span> <span>Advanced</span> <span>⏱ 45 min read</span> <span>© Gate of AI 2026-06-16</span> Learn how to fine-tune large language models (LLMs) to enhance communication capabilities in specialized domains, such as homeless shelters, using modern AI tools and techniques like LoRA. Prerequisites Python 3.10+ OpenAI API key (latest version) Familiarity with machine learning concepts What We're Building In this tutorial, we will embark on a journey to fine-tune a large language model (LLM) to cater to the specific communication needs of homeless shelters. By leveraging a bespoke dataset compiled from the Youth Spirit Artworks (YSA) Tiny House Empowerment Village website, we aim to create a model that can effectively assist in the nuances of communication required in such environments. The finished project will result in a model capable of generating contextually relevant and empathetic responses to inquiries typical within the homeless shelter community. This involves structuring data into a standardized question-and-answer format to enhance the training process, ensuring the model's outputs are aligned with the communication style and needs of the target audience. Setup and Installation To begin, we need to set up our development environment with the necessary tools and libraries for model fine-tuning. We'll be using Python along with the OpenAI library to interact with the LLMs. pip install openai pandas numpy Additionally, you'll need to configure environment variables to securely store your API keys. This ensures that sensitive information is not hardcoded into your scripts. .env file OPENAI_API_KEY=your_openai_api_key Step 1: Data Collection and Preparation The first step in fine-tuning our model involves collecting and

2026-06-17 原文 →
AI 资讯

**Quick Tip: How to Choose the Right Model for Slack AI Workflows in 2026

Quick Tip: How to Choose the Right Model for Slack AI Workflows in 2026 I've been running Slack-integrated AI workflows in production for about three years now, and the question I get asked most often is deceptively simple: "Which model should I actually use?" Back in 2024, the answer was easy — you picked GPT-4o and moved on. But in 2026, with 184 models accessible through Global API and price points ranging from $0.01 to $3.50 per million tokens, that decision has become a genuine engineering problem. Pick wrong and you're either burning budget or shipping a sluggish experience. Pick right and your CFO actually smiles at you. Let me walk you through how I think about this, what the numbers actually look like, and where I've landed after months of benchmarking across multi-region deployments. Why Slack Workloads Are Weird Most people underestimate what a Slack AI assistant needs to do well. It's not a chatbot. It's a latency-sensitive, always-on, context-heavy workload that has to feel native inside a chat client where users expect responses faster than they can refresh the channel. In my experience, the three constraints that matter most are: p99 latency under 1.5 seconds for the first token — anything slower and users start double-messaging 99.9% uptime across at least two regions — Slack itself is up, so your AI better be too Cost per active user per month under $0.40 — this is the line where finance stops asking questions If a model can't hit those numbers consistently, it's not viable, no matter how clever the benchmark scores look. The Pricing Landscape I Actually Use Here's the table I keep pinned in my team's documentation. These are the models we rotate between depending on the workload. I haven't changed a single number — these are the exact rates as of writing this: Model Input ($/M) Output ($/M) Context DeepSeek V4 Flash 0.27 1.10 128K DeepSeek V4 Pro 0.55 2.20 200K Qwen3-32B 0.30 1.20 32K GLM-4 Plus 0.20 0.80 128K GPT-4o 2.50 10.00 128K The spread is w

2026-06-17 原文 →
AI 资讯

Mid-Conversation System Prompts: Steering an Agent Without Breaking the Cache

Here is a problem I hit building a long-running agent: I needed to inject a new instruction partway through a session ("the project is Go, write Go") but editing the top-level system prompt to add it invalidated my entire prompt cache. Every cached turn got reprocessed at full price. The fix is a feature that landed in the current Claude models: mid-conversation system messages. Here is what it is and when to use it. The setup that breaks A long agent session has a large, stable system prompt and a growing message history, and you cache the prefix so each turn reuses the prior work cheaply. That works until you learn something mid-session that the agent needs to know: a mode toggled, the user delivered async context, files changed on disk, the token budget dropped. The naive move is to edit the system prompt to include the new fact. But the system prompt sits at the front of the cached prefix. Change one byte there and you invalidate everything after it. Your whole conversation history reprocesses at full input price on the next request. For a long session, that is expensive and slow. The fix: a system message in the messages array The current models let you put a system -role message directly in the messages array, after the history, instead of editing the top-level system : const response = await client . messages . create ( { model : " claude-opus-4-8 " , max_tokens : 16000 , system : [ { type : " text " , text : STABLE_SYSTEM , cache_control : { type : " ephemeral " } }, ], messages : [ ... history , // cached prefix, untouched { role : " user " , content : latestUserMessage }, // @ts-expect-error: role:"system" SDK types may still be landing { role : " system " , content : " This project is Go. Write all code in Go. " }, ], }, { headers : { " anthropic-beta " : " mid-conversation-system-2026-04-07 " } }, ); Because the new instruction sits after the cached history, it invalidates nothing before it. The cached prefix stays intact, you pay full price only for the

2026-06-16 原文 →
AI 资讯

How to Track Local SEO Rankings by City with an API

Local SEO rankings are not the same everywhere. Your website may rank in position 2 in Austin, position 8 in Dallas, and not appear at all in Chicago. That is why checking one generic Google result is not enough for local SEO. If you are working on local SEO , agency reporting, competitor monitoring, or location-based search analysis, you need to track rankings by city. A simple workflow looks like this: Keyword + city → SERP API → local search results → ranking check → CSV report In this tutorial, we’ll build a basic Python script that tracks local SEO rankings by city using a SERP API. We will: Define target keywords Define target cities Send city-specific searches to a SERP API Extract organic results Check where a target domain appears Save the ranking data to CSV This is not a full SEO platform, but it gives you the core logic behind many local rank tracking tools. Why city-level rankings matter Google search results are location-sensitive. A query like: best digital marketing agency may return different results in: New York Austin London Singapore Sydney This matters even more for local intent keywords, such as: dentist near me plumber in Chicago coffee shop in Austin real estate agent in Miami For these searches, the result page can include: organic results local packs Google Maps results ads business directories review sites service pages location-specific landing pages If you only check one location, you may miss what users actually see in other cities. For local SEO, ranking data without location context is incomplete. Why use a SERP API? You could try to check Google rankings manually. But that does not scale. You could also try to scrape Google directly, but that brings a lot of maintenance work: changing page layouts CAPTCHA blocked requests proxy handling inconsistent HTML location mismatch parser updates retry logic A SERP API gives you structured search results in JSON. Instead of parsing raw HTML, you get data like this: { "query" : "plumber in Aust

2026-06-16 原文 →
AI 资讯

TypeScript Patterns for Environment Variables

Yesterday, as I was working on a CORS configuration, AI generated a block of code for me: const allowedOrigins = [ process . env . FRONTEND_URL || " http://localhost:3000 " , process . env . ADMIN_URL || " http://localhost:3001 " , ]. filter ( Boolean ); I was wondering... why use .filter(Boolean) here? 🤔 The fallbacks already guarantee strings. So I hovered on the variable. The type definition read: const allowedOrigins : string [] Fine. Made sense. But then I got curious. What if I removed the hardcoded fallbacks? const allowedOrigins = [ process . env . FRONTEND_URL , process . env . ADMIN_URL , ]. filter ( Boolean ); My type definition changed to: const allowedOrigins : ( string | undefined )[] I was shocked. I just filtered the array. How can TypeScript still think there's an undefined in there? First: What Does .filter(Boolean) Even Do? Boolean used as a filter function removes any falsy value from an array: false null undefined 0 "" NaN So: [ " https://app.com " , "" , undefined ]. filter ( Boolean ) // Result: ["https://app.com"] At runtime, this works exactly as you'd expect. No undefined survives. So why does TypeScript disagree? 🤷‍♀️ The Real Answer: TypeScript Doesn't Run Your Code TypeScript is a transpiler. It doesn't execute .filter(Boolean) — it only looks at types. When it sees this: array . filter ( Boolean ) It knows the callback returns a boolean . But it doesn't know what that means for the type of the elements that survive. It can't infer "if Boolean(x) is true, then x must be a string." So the undefined stays in the type — even though it'll never actually be there at runtime. That's the gap: your runtime behavior is correct, but your types are lying. The Fix: Type Predicates TypeScript lets you close that gap with a type predicate — a way of explicitly telling the compiler what a filter function guarantees: const allowedOrigins = [ process . env . FRONTEND_URL , process . env . ADMIN_URL , ]. filter (( origin ): origin is string => Boolean ( o

2026-06-16 原文 →
AI 资讯

Agent Accounts Quickstart in Python

A connected Gmail grant starts with an OAuth consent screen and ends with a refresh token you have to babysit; a Nylas Agent Account starts and ends with one POST request. Same API surface afterward — same messages endpoints, same webhooks, same calendar — but the provisioning story couldn't be more different, and that difference is what makes these hosted mailboxes such a natural fit for Python automation, agents, and test harnesses. Agent Accounts are in beta, and the official quickstart gets you from nothing to a sending-and-receiving mailbox in under 5 minutes using curl. Here's the whole flow as a Python script. Step 0: prerequisites You need an API key (run nylas init with the CLI, or use the Dashboard) and a domain. The fast path for testing: register a *.nylas.email trial subdomain from the Dashboard — no DNS records, instantly usable. Custom domains need MX and TXT records published at your DNS provider, with automatic verification once they propagate; save that for production. import os import requests BASE = " https://api.us.nylas.com " HEADERS = { " Authorization " : f " Bearer { os . environ [ ' NYLAS_API_KEY ' ] } " , " Content-Type " : " application/json " , } Step 1: provision the account POST /v3/connect/custom with "provider": "nylas" . No refresh token — just an email address on a registered domain: resp = requests . post ( f " { BASE } /v3/connect/custom " , headers = HEADERS , json = { " provider " : " nylas " , " settings " : { " email " : " test@your-application.nylas.email " }, }, ) resp . raise_for_status () grant_id = resp . json ()[ " data " ][ " id " ] print ( f " Agent Account live: { grant_id } " ) Save that grant_id — per the docs, you'll use it in every subsequent call. The mailbox works with every existing endpoint from this moment on. If you want policies or mail rules applied, add a top-level workspace_id to the same request body; the account inherits the workspace's limits, spam settings, and rules. Omit it and the account lands i

2026-06-16 原文 →
AI 资讯

Agent Accounts Quickstart in Node.js

Provisioning a working email mailbox from Node.js takes less code than the average OAuth callback handler. No consent screen, no token refresh job, no provider SDK — one fetch call returns a grant ID, and from there the mailbox sends, receives, and RSVPs to calendar invites. That's the pitch for Nylas Agent Accounts , hosted email-and-calendar identities you control entirely through the API. They're in beta, and the official quickstart promises a working account in under 5 minutes. The docs show it in curl; here's the same flow in JavaScript. What you need Two things: an API key, and a registered domain for the mailbox to live on. For testing, the zero-DNS path is a *.nylas.email trial subdomain registered from the Dashboard — addresses like test@your-application.nylas.email work immediately. For production you'd register your own domain (the Dashboard generates the MX and TXT records to publish, and verification is automatic once they propagate), but the trial domain is fine for this walkthrough. export NYLAS_API_KEY = "nyk_..." Create the mailbox The endpoint is POST /v3/connect/custom — the same Bring Your Own Auth route used for other providers — with "provider": "nylas" . Unlike OAuth providers, there's no refresh token in the body; just the address: const BASE = " https://api.us.nylas.com " ; const headers = { Authorization : `Bearer ${ process . env . NYLAS_API_KEY } ` , " Content-Type " : " application/json " , }; const res = await fetch ( ` ${ BASE } /v3/connect/custom` , { method : " POST " , headers , body : JSON . stringify ({ provider : " nylas " , settings : { email : " test@your-application.nylas.email " }, }), }); const { data } = await res . json (); const grantId = data . id ; // save this — every later call needs it That grantId is the whole handle. The mailbox behind it is live as soon as the response comes back, and it works with every existing endpoint — messages, drafts, folders, calendars, events, webhooks. One optional field deserves a menti

2026-06-16 原文 →
AI 资讯

Java Interface

today we discuss about Interface in Java. first we understand the concept with simple Analogy, Imagine you go to a shop and buy items. in a bill counter, the shop keeper care about only one thing. The customer paid the Money or not. The shopkeeper does NOT care about how you pay the money, UPI Debit Card Cash They only thing is payment paid in successfully. Here a interface acts like a Rule in billing counter. It only defines what must be done, not how it should be done. Different payment methods follow the same rule, but each one works in its own way. The shopkeeper does not need to change anything in the billing counter. No matter how the customer pays, the system works the same. so, i follow this analogy and using a example for this blog. What is Interface? (in GeeksforGeeks) An interface in Java is a blueprint that defines a set of methods a class must implement without providing full implementation details. It helps achieve abstraction by focusing on what a class should do rather than how it does it. Interfaces also support multiple inheritance in Java. A class must implement all abstract methods of an interface. All variables in an interface are public, static, and final by default. Interfaces can have default, static, and private methods first create a interface file Payment.java public interface Payment { void pay ( int amount ); } here we create a method but not defined that method This is the shop rule. “Anyone wants to pay must follow one rule → pay the amount.” The shop does not explain how you pay, only thing is you must pay. next we create another file for Different Customers, class CardPayment implements Payment { public void pay ( int amount ) { System . out . println ( "Paid ₹" + amount + " using Card" ); } } class UpiPayment implements Payment { public void pay ( int amount ) { System . out . println ( "Paid ₹" + amount + " using UPI" ); } } class CashPayment implements Payment { public void pay ( int amount ) { System . out . println ( "Paid ₹" +

2026-06-16 原文 →
AI 资讯

Bootcamp Grad Dives Into Google vs OpenAI API Pricing

Honestly, bootcamp Grad Dives Into Google vs OpenAI API Pricing When I finished my coding bootcamp three months ago, I thought I understood what an API did. I mean, you send a request, you get a response back, right? What I did not understand was how dramatically the cost could vary depending on which model you picked. I had no idea that a single line of code change could mean the difference between paying pennies and paying hundreds of dollars at scale. That is the rabbit hole I fell down last week, and I want to walk you through everything I learned. This is the post I wish I had read before I burned through my first $50 in API credits. Why I Started Looking At Pricing In The First Place I was building a small app that takes user reviews and summarizes them. Pretty straightforward. I figured I would just plug in the most popular model and call it a day. That model, if you have been paying attention to the news, is GPT-4o. So I wired it up, ran a few tests, and everything looked great. Then I did the math. GPT-4o charges $2.50 per million tokens on input and $10.00 per million tokens on output. I did not even know what a "million tokens" really meant in practice. So I tested my app with maybe 50 reviews and watched my credit balance drop. It was not catastrophic, but it was enough that I started wondering if there was a cheaper way. I was shocked when I found out how big the gap actually is. The Pricing Table That Changed My Whole Plan I stumbled onto a platform called Global API, and honestly, the pricing chart there blew my mind. They give you access to 184 different AI models, with prices ranging all the way from $0.01 to $3.50 per million tokens. Compare that to the GPT-4o output price of $10.00 per million tokens, and you start to understand why I panicked a little when I saw my early numbers. Here are the five models I ended up comparing side by side: Model Input Cost Output Cost Context Window DeepSeek V4 Flash $0.27 $1.10 128K DeepSeek V4 Pro $0.55 $2.20 20

2026-06-15 原文 →
AI 资讯

Why Is Your Kubernetes Bill So Confusing? Here’s How to Fix It

Simple Intro Your company gets one big cloud bill. It says $30,000. But which team spent it? Which app? Nobody knows. Kubernetes makes this worse because 100 small apps share the same computers. It’s like 10 families sharing one electricity bill. Let’s fix this in 5 easy steps Step 1: Put Nametags on Everything In Kubernetes, you can add "labels" to your apps. Example: team=sales , app=website , owner=pooja If you don’t add name tags, you can never track who spent what. It’s the most important step. Step 2: Check the Big Cost - Computers 70% of your bill is for CPU and RAM. That’s the “brain” and “memory” your apps use. The problem: Most people book a big computer but only use 20% of it. You pay for 100%, use 20%. You waste 80% money. Easy fix: Every month, check “How much did I book vs How much did I use?” Then book smaller next time. Step 3: Don’t Forget Hidden Costs Two things people forget: Storage: Like a hard disk. You deleted the app but forgot to delete the disk. It still charges you every month. Network: Moving data between countries or zones costs money. Check for old disks and big data transfers once a month Step 4: Share the Common Bill Fairly Some costs are for everyone. Like the main Kubernetes system or empty computers waiting for work. How to split it? Easy. If Team A uses 60% of the total computer power, they pay 60% of the common bill. Fair for everyone. Step 5: Use a Tool, Not Excel Doing all this in Excel will make you cry. It’s too much data. Use a tool that does it automatically. It connects to your Kubernetes, reads all the name tags, and tells each team: “You spent $2,340 this week.” Final Tip You can’t save money if you don’t know where it’s going. First, make the costs clear to everyone. Then the savings happen automatically. FAQ - In Simple Words Q1. Why can’t I just see costs in AWS bill? Because AWS only tells you “EC2 cost $10k”. It doesn’t tell you which of your 50 apps used that EC2. Kubernetes hides the details. Q2. What is the first

2026-06-15 原文 →
AI 资讯

Pagination records using JooqTemplate

Paginated queries with automatic total count calculation. Supports specifying result fields. public < E > LimitResult < List < E >, E > query ( Class < E > cls , LimitSelect limitSelect ) public < E > LimitResult < List < E >, E > query ( Class < E > cls , LimitSelect limitSelect , LimitRange range ) public < E > LimitResult < List < E >, E > query ( Class < E > cls , LimitSelect limitSelect , List resultFields ) public < E > LimitResult < List < E >, E > query ( Class < E > cls , LimitSelect limitSelect , LimitRange range , List resultFields ) Returns: LimitResult — contains getResult() (data list) and getTotal() (total count). Example: // Define pagination query LimitSelect limitSelect = new LimitSelect () { public SelectOrderByStep from ( SelectSelectStep select ) { return select . from ( T ( "user_table" )) . where ( jt . conditions ( "name%" , name , "birthday>=" , beginDate )); } public List < OrderField > orderBy () { return Arrays . asList ( F ( "birthday" ). desc ()); } }; // Mode 1: return all data, no total count LimitResult res1 = jt . query ( User . class , limitSelect ); // Mode 2: return limit rows, no total count LimitResult res2 = jt . query ( User . class , limitSelect , LimitRange . of ( 20 )); // Mode 3: paginate (offset starts at 0), calculate total count LimitResult res3 = jt . query ( User . class , limitSelect , LimitRange . of ( 20 , 0 )); // res3.getResult() returns data, res3.getTotal() returns total count // Mode 4: specify result fields LimitResult res4 = jt . query ( User . class , limitSelect , LimitRange . of ( 20 , 0 ), Arrays . asList ( "id" , "name" )); // LimitRange.all(): return all data, no total count LimitResult res5 = jt . query ( User . class , limitSelect , LimitRange . all ()); // Access results List < User > data = res3 . getResult (); int total = res3 . getTotal (); About the LimitSelect interface: // LimitSelect is a interface: public interface LimitSelect { // Build the FROM clause; the select parameter allows specifyi

2026-06-15 原文 →
AI 资讯

Run GLM-5.2 Locally: The Open Model Nobody Can Ban

On June 9, Anthropic shipped Claude Fable 5 — the most capable coding model the industry had ever seen. Three days later, the U.S. government ordered it offline for every user on Earth . No warning. No transition period. One directive, and the frontier vanished overnight. 📖 Read the full version with charts and embedded sources on ComputeLeap → The same week, Z.ai (Zhipu AI) released GLM-5.2 — a 744-billion-parameter coding model with a one-million-token context window, MIT-licensed open weights arriving within days. The timing was not lost on the developer community. ℹ️ The message landed clearly on Hacker News: as user Reubend put it, they're "grateful to Chinese labs for being open with their work" — especially after "the Fable 5 fiasco." Open weights aren't just a cost play anymore. They're insurance. This guide walks you through actually running GLM-5.2 on your own hardware — the VRAM you need, the quantization that fits, and the exact commands for llama.cpp, Ollama, and LM Studio. No API keys. No cloud dependency. No one can pull the plug. What GLM-5.2 Actually Is GLM-5.2 is the third major iteration in Z.ai's GLM-5 line, purpose-built for agentic coding and long-horizon software engineering . Here is what you are working with: Spec Value Architecture Mixture-of-Experts (MoE) Total Parameters 744 billion Active Parameters ~40 billion per token Context Window 1,000,000 tokens Max Output 131,072 tokens Training Data 28.5 trillion tokens License MIT (open weights) Thinking Modes High and Max The MoE architecture is the key to local viability. Only ~40 billion parameters fire per token — the rest sit idle. That is what makes aggressive quantization work: you are compressing 744B weights, but inference only touches a fraction of them at any given time. GLM-5.2 supports two thinking-effort presets: High and Max. Z.ai recommends Max as the default for coding work — it produces longer reasoning chains before generating output. The model launched on June 13 on Z.ai's C

2026-06-15 原文 →
AI 资讯

Making "files never leave your browser" verifiable with DevTools and CSP

"Files never leave your browser" is becoming standard copy for PDF tools, image editors, and document converters. But a trust claim and a verifiable fact are different things. Here's how to turn "zero upload" into something any user can audit in about two minutes, and how to enforce it at the browser level so it isn't just a promise. Step 1: Read the Network panel Open DevTools → Network, enable "Disable cache", reload. While processing a file, filter by "Fetch/XHR" and "Doc". A genuinely client-side tool should show only HTML/CSS/JS/WASM asset loads — no POST requests, no GETs carrying file content in query parameters. The non-obvious trap: third-party analytics, Google Fonts, and CDNs all show up as outbound requests. If you claim zero uploads, those count too. The honest move is to self-host fonts and scripts and drop analytics entirely, so the request list is genuinely short enough to eyeball. The Network panel is the human-readable check. The next part is what actually makes it hold. Step 2: Enforce egress with CSP connect-src This is the piece people get backwards, so it's worth stating precisely. CSP's connect-src is an egress allowlist the browser enforces before the request is sent . A fetch /XHR to an origin that isn't on the list is blocked by the browser and never leaves the machine. You'll see it fail in the console as a CSP violation, with no entry in the Network tab going out to that origin. This includes no-cors requests. no-cors is sometimes assumed to be an escape hatch, but it isn't one for this purpose. All no-cors does is let you issue a cross-origin request while making the response opaque (you can't read the body). It does not bypass connect-src : if the target origin isn't in your connect-src allowlist, the no-cors request is blocked exactly the same way — it never goes out. So you can't smuggle a file out to a third party with no-cors under a tight CSP. That's what makes CSP the actual proof, not just documentation. Tighten connect-src to 's

2026-06-15 原文 →