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

标签:#tutorial

找到 370 篇相关文章

AI 资讯

From Zero to First PR: How I Contributed to an Open-Source AI Project as a Beginner

I stared at the GitHub page for what felt like forever. The repo had thousands of stars, hundreds of issues, and a long list of contributors who clearly knew what they were doing. Me? I had a few small personal projects, some half-finished tutorials, and a nagging feeling that I wasn’t “ready” to contribute to real open-source software. Especially not an AI project with fancy models, complex pipelines, and people publishing papers off the codebase. But I wanted in. I wanted to learn how real-world AI systems are built, to get feedback on my code, and to be part of something bigger than my local src/ folder. So I made a deal with myself: no more waiting until I feel “ready.” I’d go from zero to my first pull request (PR) in one focused push. Here’s exactly how I did it, what I learned, and what I’d tell anyone hesitant about contributing to an open-source AI or machine learning project for the first time. Step 1: Pick the Right Project (Not the Biggest One) The biggest mistake I almost made was aiming for the most famous AI repo I could find. Big projects are great, but they can be intimidating and slow for a first-timer. Instead, I looked for: Active maintenance : recent commits, issues being closed, maintainers responding. Clear contribution guidelines: a CONTRIBUTING.md or at least a solid README. Beginner-friendly issues: labels like good first issue, beginner, or help wanted. Scope I could understand: I didn’t need to grasp the entire codebase, just enough to fix one small thing. I ended up choosing a mid-sized open-source AI library : not unknown, not legendary. Perfect. If you’re searching now, try queries like: “awesome open source llm” “open source machine learning projects good first issue” “open source AI tools GitHub” Then scan their issues tab for beginner-friendly tasks. Step 2: Set Up the Project Locally (Without Panicking) Once I picked a project, the next hurdle was getting it to run on my machine. The repo had a typical structure: project/ README.md

2026-07-15 原文 →
产品设计

Dual role of * in C

Prerequisites Let's create a variable. int myNum = 5 ; Now, myNum refers to the value 5 . However, we can get its memory address using the & operator like this: &myNum . Role 1: Creating pointers A pointer holds a memory address. int * pointerToMyNum = & myNum ; Role 2: Modifying values using a pointer In this case, * works as the dereference operator. * pointerToMyNum = 10 ; Now, if we print myNum , the output will be 10 . Understanding that they are different in each context makes things much easier ✨ Note Both int ptr and int ptr are functionally identical in C.

2026-07-15 原文 →
AI 资讯

DeepSeek vs Qwen vs Kimi vs GLM: Which One Wins My Freelance Budget?

DeepSeek vs Qwen vs Kimi vs GLM: Which One Wins My Freelance Budget? Last Tuesday I spent two hours building a client dashboard that needed AI-powered text summarization. The client is a small e-commerce shop, they get maybe 500 product descriptions a week that need condensing into bullet points. Sounds simple, right? Except when I ran the numbers on my usual OpenAI setup, the bill was going to eat into my margin harder than I'd like. That's when I went down the rabbit hole of Chinese AI models. DeepSeek, Qwen, Kimi, GLM — I've been hearing about these for months from other devs in Discord, but I never actually committed to testing them because, honestly, who has the time? Well, apparently I do, because that Tuesday I decided to run all four head-to-head against my actual workload. Here's what happened. Why I Even Bothered (The Real Math) Before we get into the benchmarks and pricing tables, let me put this in perspective. My hourly rate as a freelance dev sits at $85. Every hour I spend wrestling with a subpar API that hallucinates or charges too much is an hour I'm not billing a client. The "free" model is never free — either it costs me time or it costs me money, and usually both. I was paying roughly $0.60 per 1M output tokens on GPT-4o for the summarization work. For 500 product descriptions, each averaging maybe 150 tokens output, that's about $0.045 per batch. Sounds tiny, right? But multiply that across multiple clients, and suddenly I'm watching $40-60 a month vanish into API costs that I can't really pass along without awkward pricing conversations. So I started shopping. And what I found genuinely surprised me. The Contenders at a Glance All four model families run through Global API's unified endpoint, which means I didn't have to maintain four different SDKs, four different auth setups, four different billing dashboards. Just swap the model name in the request and ship. For a one-person operation, that's huge. Here's the landscape I was working with: Di

2026-07-15 原文 →
开发者

You Don't Need Node.js to Learn Web Development

I see this every week. Someone decides to learn web development. They Google "how to start web development" and within 20 minutes they're installing Node.js, npm, VS Code, and five extensions they don't understand. They haven't written a single line of code yet. But they've already spent an hour configuring their "environment." Then they get stuck. Node version conflicts. npm permission errors. VS Code extensions that break their syntax highlighting. They think they're not smart enough for programming. They are. They just started with the wrong step. The Problem Learning web development has three core technologies: HTML, CSS, and JavaScript. That's it. Everything else — Node.js, npm, webpack, Vite, React — is extra. It's not the starting point. But most tutorials assume you already have Node.js installed. They say "open your terminal" and "run npm install." Beginners follow along, copy the commands, and have no idea what any of it means. Here's what actually happens: You install Node.js (200MB+) You install VS Code (another 300MB+) You install 5-10 extensions You create a project folder You open terminal and run npm init -y You run npm install live-server You run npx live-server You finally see your HTML page in a browser That's 8 steps before you write Hello World . The Solution You don't need any of that. Not yet. Here's what you actually need to learn HTML, CSS, and JavaScript: A browser (you already have one) A text editor (Notepad works) That's it Open Notepad. Write this: <!DOCTYPE html> <html> <head> <title> My First Page </title> </head> <body> <h1> Hello, World! </h1> <p> This is my first web page. </p> </body> </html> Save it as index.html. Double-click the file. It opens in your browser. You just built your first web page. No terminal. No npm. No Node.js. No configuration. When Should You Actually Learn Node.js? Node.js becomes useful when you need: Server-side code (backend development) Package management (npm packages) Build tools (webpack, Vite) Framew

2026-07-15 原文 →
AI 资讯

# Building a Lightweight Product Filter with Vanilla JavaScript

Building a Lightweight Product Filter with Vanilla JavaScript While building a small e-commerce project, I wanted users to filter products instantly without refreshing the page. Instead of relying on a frontend framework, I opted for a simple solution using HTML data attributes, vanilla JavaScript, and a little CSS. The goal was straightforward: let visitors filter items by size while keeping the interface fast, responsive, and easy to maintain. HTML Structure Each product card stores its information in data-* attributes. This keeps the markup clean and makes filtering straightforward. <div class= "filters" > <button class= "filter-btn" data-filter= "all" > All </button> <button class= "filter-btn" data-filter= "small" > S </button> <button class= "filter-btn" data-filter= "medium" > M </button> <button class= "filter-btn" data-filter= "large" > L </button> </div> <div class= "product-grid" > <div class= "product-card" data-size= "medium" data-style= "cargo" > Cargo Shorts </div> <div class= "product-card" data-size= "large" data-style= "chino" > Chino Shorts </div> <!-- More product cards --> </div> Using data attributes means you can add new filter categories later without changing your overall structure. JavaScript Filtering Logic The filtering logic listens for button clicks and simply shows or hides product cards based on the selected size. const filterButtons = document . querySelectorAll ( " .filter-btn " ); const productCards = document . querySelectorAll ( " .product-card " ); filterButtons . forEach (( button ) => { button . addEventListener ( " click " , () => { const filterValue = button . dataset . filter ; productCards . forEach (( card ) => { const cardSize = card . dataset . size ; if ( filterValue === " all " || cardSize === filterValue ) { card . classList . remove ( " hidden " ); } else { card . classList . add ( " hidden " ); } }); filterButtons . forEach (( btn ) => btn . classList . remove ( " active " )); button . classList . add ( " active "

2026-07-15 原文 →
AI 资讯

An Introduction to Neural Networks

Hi guys ! I'm a new developer who's interested in data science and artificial intelligence. To showcase what I learnt thus far, I've started writing articles, with my first one being published here ! One of the most difficult parts of getting into machine learning was the overload of terminology that tutorials had, even when explaining basic concepts such as how a neural network itself would function. Because of this, I've written an article (see above) that simplifies it while ensuring the main concepts are sufficiently explained; it requires no mathematical background and will only take less than 5 minutes to read ! I hope you find it informative and well written, and I highly welcome any suggestions or corrections that might be suggested to improve my future articles !

2026-07-15 原文 →
AI 资讯

Seven things to check before a WordPress major upgrade — before "patch what breaks after" becomes a disaster

WordPress major version upgrades (5.x → 6.x, and eventually 6.x → 7.x) are a different animal from minor releases. Minor releases (like 6.4.1 → 6.4.2) are mostly bug fixes with low compatibility risk. Majors land API deprecations, raised PHP minimum requirements, and core block replacements all at once — and those things hit operations hard. The " just hit Update in the admin and patch whatever breaks " workflow can survive on a single personal site, but it tends to fall apart under multi-site maintenance — simultaneous failures across sites overwhelm root-cause triage. This post collects the things worth verifying before you run a major upgrade, as a seven-item checklist . 1. Has the minimum PHP version been raised? Major WordPress releases sometimes raise the minimum supported PHP version (6.6 lifted it to PHP 7.2.24, and a future 7.0 will very likely require PHP 8.x). What matters operationally isn't just the server's PHP version and WordPress's stated minimum — it's the intersection with the PHP versions your plugins and themes actually run on . You can usually upgrade your server's PHP, but older themes and plugins not running on new PHP isn't rare. A subtle failure mode here: traps like PHP 8.2+ deprecated warnings leaking into older WP-CLI JSON output , where nothing visibly errors but your operational tooling silently breaks. Before upgrading, run wp plugin list --format=json on the production PHP environment and verify you're getting clean JSON. That one check catches a lot of post-upgrade pain. 2. Audit "Tested up to" for every plugin Each plugin's readme.txt carries a Tested up to: X.X line — the developer's declaration of the highest WordPress version they've actually tested against . It's the first signal for major-upgrade compatibility audits. WP-CLI gives you the inventory in one shot: wp plugin list --fields = name,version,update_version,update --format = table Plugins where "Tested up to" is old AND no updates in the last year deserve scrutiny. Acti

2026-07-15 原文 →
AI 资讯

Adaptive Thinking Killed My Token Budget Code: Migrating Off budget_tokens

I had a tidy little helper that computed a thinking budget based on input size. Something like "give the model 30% of the context as thinking room." It worked great on Opus 4.5. Then I tried to point it at Opus 4.8 and got a 400. The whole concept I had built around is gone in the current models. Here is what replaced it and how I migrated. What broke The old pattern looked like this: // Opus 4.5 and earlier const response = await client . messages . create ({ model : " claude-opus-4-5 " , max_tokens : 16000 , thinking : { type : " enabled " , budget_tokens : 8000 }, messages , }); On Opus 4.7, 4.8, and Fable 5, thinking: { type: "enabled", budget_tokens: N } returns a 400. The fixed token budget is dead. The replacement is adaptive thinking, where the model decides how much to think, plus an effort knob that controls overall token spend. // Opus 4.8 const response = await client . messages . create ({ model : " claude-opus-4-8 " , max_tokens : 16000 , thinking : { type : " adaptive " }, output_config : { effort : " high " }, // low | medium | high | xhigh | max messages , }); Why this is actually better (after I got over it) My old budget code was a guess dressed up as a calculation. I had no real basis for "30% of context." I picked it because it felt reasonable and the outputs looked fine. Adaptive thinking moves that decision to the model, which sees the actual problem. The mental model shift: budget_tokens controlled how much the model could think. effort controls how much it thinks and acts . They are not the same axis, so there is no clean 1:1 mapping. I stopped trying to translate "8000 tokens" into an effort level and instead picked based on the workload. How I chose effort levels After running my own evals, here is where I landed: Workload Effort Notes Classification, routing low Fast, scoped, not intelligence-sensitive Most app traffic medium to high The balance point Coding and agentic loops xhigh Best for these; it is the Claude Code default Correctness

2026-07-14 原文 →
AI 资讯

Build a Local LLM Chatbot with Ollama and Python

Build a Local LLM Chatbot with Ollama and Python Build a Local LLM Chatbot with Ollama and Python Imagine typing a question into your chatbot and getting a response in milliseconds, completely offline, with zero data leaving your machine. No API keys, no monthly subscription fees, and no privacy concerns about your data being sent to a cloud server. This isn’t a futuristic dream—it’s the reality of running a Local Large Language Model (LLM) on your own computer. With the rise of tools like Ollama , building a private AI chatbot in Python has become as simple as installing a few packages and writing a short script. Let’s dive in and build one together. Why Go Local? Before we write any code, it’s worth understanding why running an LLM locally is a game-changer. Cloud-based AI services like OpenAI or Anthropic are powerful, but they come with trade-offs: you pay per token, your data is processed on their servers, and you’re dependent on their uptime. A local LLM flips this model. You download the model once, run it on your hardware, and you have full control. Ollama is the engine that makes this accessible. It’s a lightweight, open-source tool that simplifies running LLMs like Llama 3, Phi 3, or Mistral on macOS, Linux, and Windows. It handles model downloads, memory management, and inference, exposing a simple API that Python can easily interact with [1][2]. Step 1: Install Ollama and Pull a Model The first step is getting Ollama on your machine. Visit ollama.com , click Download , and install the version for your operating system [2]. Once installed, verify it’s working by opening your terminal or Command Prompt and running: ollama --version If you see a version number, you’re ready to go. Next, you need a model. Ollama supports dozens of open-source models, but for a beginner-friendly chatbot, Llama 3.2 is a great choice. It’s small, fast, and surprisingly capable. To download it, run: ollama pull llama3.2 This command fetches the model and stores it locally. Depen

2026-07-14 原文 →
AI 资讯

I Wish I Ran the Numbers on Open Source AI APIs Sooner

I Wish I Ran the Numbers on Open Source AI APIs Sooner Three months ago I would have told you self-hosting was the obvious move. "Open source means free, right?" I said that to a client while quoting them $3,500 for a GPU server setup. They smiled politely and went with someone else. That rejection sent me down a rabbit hole I wish I'd started years earlier, because the actual math — not the vibes-based math freelancers like me tend to do — completely flips the script. If you're running a solo practice or a tiny shop, you probably bill every minute of GPU babysitting straight out of your own pocket. That's time you could be shipping features, pitching clients, or — if we're being honest — sleeping. So let me walk you through what I learned the hard way, with all the pricing left exactly where it belongs. The Open Source Lineup That Actually Matters Right Now When I started this research, I assumed "open source AI API" was an oxymoron. If you're calling an API, somebody owns the server, so what's even the point of being open? Turns out the point is massive: open-weight models accessible through an API give you the pricing transparency of self-hosting without the DevOps funeral you're planning for your weekends. Here's the pricing matrix I put together from Global API's public rates. These are output token prices (input is usually cheaper), and yes — they're shockingly low compared to GPT-4o territory. Model License Output Price Self-Host Range DeepSeek V4 Flash Open weights $0.25/M $500-2,000/mo DeepSeek V3.2 Open weights $0.38/M $800-3,000/mo Qwen3-32B Apache 2.0 $0.28/M $400-1,500/mo Qwen3-8B Apache 2.0 $0.01/M $200-800/mo Qwen3.5-27B Apache 2.0 $0.19/M $300-1,200/mo ByteDance Seed-OSS-36B Open weights $0.20/M $500-2,000/mo GLM-4-32B Open weights $0.56/M $400-1,500/mo GLM-4-9B Open weights $0.01/M $200-800/mo Hunyuan-A13B Open weights $0.57/M $300-1,000/mo Ling-Flash-2.0 Open weights $0.50/M $300-1,000/mo Look at Qwen3-8B and GLM-4-9B at $0.01/M output tokens. A mi

2026-07-14 原文 →
AI 资讯

My MCP Server Kept Crashing. Here's the Error Recovery Pattern That Saved It.

I spent three days wondering why my MCP server would just... stop. No crash logs. No error messages. Clients connected fine, then after a few hours, every tool call returned silence. Turns out the Model Context Protocol (MCP) spec doesn't force you to handle errors — it assumes you will. But the reference implementations are minimal. Your server starts healthy, then bit by bit, things go wrong. A network blip. A malformed tool argument. An external API timeout. And suddenly your AI agent is staring at a blank response. Here's the pattern I ended up with. It's not clever. It just works. The Fix Start with a wrapper around your tool handlers. Every MCP server framework has some kind of tool registration — this works for the official Python SDK, the TypeScript SDK, and most community frameworks: from mcp.server import Server from mcp.types import ErrorData , INTERNAL_ERROR , INVALID_PARAMS import traceback import json class ResilientMCPServer ( Server ): """ An MCP server that doesn ' t silently die. """ async def call_tool ( self , name : str , arguments : dict ): try : result = await super (). call_tool ( name , arguments ) return result except ( ConnectionError , TimeoutError ) as e : # Network-level issues — reconnect and retry self . _reconnect () return self . _error_response ( f " Connection lost while executing { name } : { e } " ) except ValueError as e : # Bad arguments from the client — tell them clearly return self . _error_response ( f " Invalid arguments for { name } : { e } " , code = INVALID_PARAMS ) except Exception as e : # Everything else — log, don't crash traceback . print_exc () return self . _error_response ( f " Tool { name } failed: { e } " , code = INTERNAL_ERROR ) def _error_response ( self , message : str , code : int = INTERNAL_ERROR ): return { " content " : [{ " type " : " text " , " text " : f " ERROR: { message } " }], " isError " : True } def _reconnect ( self ): """ Reset transport layer without restarting the server. """ # Your recon

2026-07-14 原文 →
AI 资讯

Python Redis: Caching and Fast Data Structures

Python Redis: Caching and Fast Data Structures Redis is an in-memory data store used for caching, session storage, pub/sub messaging, leaderboards, rate limiting, and more. With redis-py 's async client, it integrates cleanly into any asyncio application. Installation pip install redis[hiredis] # hiredis is a C parser — 2-5× faster protocol parsing Connect and Verify import asyncio import redis.asyncio as aioredis from datetime import timedelta import json REDIS_URL = " redis://localhost:6379/0 " async def get_redis () -> aioredis . Redis : client = aioredis . from_url ( REDIS_URL , encoding = " utf-8 " , decode_responses = True , socket_connect_timeout = 5 , socket_timeout = 5 , retry_on_timeout = True , ) pong = await client . ping () print ( f " Redis connected: { pong } " ) return client Strings — Basic Cache with TTL async def cache_set ( r : aioredis . Redis , key : str , value : str , ttl : int = 300 ) -> None : await r . set ( key , value , ex = ttl ) async def cache_get ( r : aioredis . Redis , key : str ) -> str | None : return await r . get ( key ) # Cache-aside pattern async def get_user_profile ( r : aioredis . Redis , user_id : int , db ) -> dict : cache_key = f " user:profile: { user_id } " cached = await r . get ( cache_key ) if cached : print ( f " Cache HIT for user { user_id } " ) return json . loads ( cached ) print ( f " Cache MISS for user { user_id } — querying DB " ) user = await db . fetch_user ( user_id ) # your DB call if user : await r . set ( cache_key , json . dumps ( user ), ex = 600 ) return user or {} # Atomic counter async def increment_page_views ( r : aioredis . Redis , page : str ) -> int : key = f " views: { page } " count = await r . incr ( key ) await r . expire ( key , 86400 ) # reset counter after 24 h return count Hashes — Structured Objects async def save_session ( r : aioredis . Redis , session_id : str , data : dict , ttl : int = 3600 ) -> None : key = f " session: { session_id } " await r . hset ( key , mapping = data )

2026-07-13 原文 →
AI 资讯

🍪 Cookies and CORS — When Are Cookies Actually Sent?

In the previous article , we briefly discussed the relationship between Cookies and CORS . In this article, we'll take a closer look at how browsers decide whether a Cookie should be included in a Cross-Origin request. One of the most common misconceptions is that once CORS is configured correctly, Cookies are automatically sent with every request. In reality, that's not how browsers work. 📌 Default Browser Behavior When a Cross-Origin request is made using fetch() or XMLHttpRequest , browsers do not send Cookies, Authorization headers, or other credentials by default. For example: fetch ( " https://api.example.com/profile " ) Even if the user is already logged into api.example.com , the browser will not include any Cookies with this request. This default behavior helps prevent authentication data from being unintentionally leaked across different Origins. 📌 How Can We Send Cookies? If you want the browser to include Cookies in a Cross-Origin request, you must explicitly use the credentials option. For example: fetch ( " https://api.example.com/profile " , { credentials : " include " }) Using credentials: "include" does not guarantee that Cookies will be sent. Instead, it tells the browser: "If there are any Cookies that are eligible to be sent with this request, include them." 📌 What Makes a Cookie Eligible? Even with credentials: "include" , the browser still evaluates the Cookie before sending it. Some of the most important checks include: Domain Path SameSite For example: If the Cookie's Domain doesn't match the request destination, it won't be sent. If the request path doesn't satisfy the Cookie's Path attribute, it won't be sent. If the Cookie's SameSite policy blocks Cross-Site requests, it won't be sent. In other words, credentials is only the first requirement , not the final decision. 📌 Server Configuration Matters Too If your application expects JavaScript to access the response while using Cookies, the server must also be configured correctly. For exampl

2026-07-13 原文 →
AI 资讯

JavaScript Event Loop Explained: The Complete Guide

You've written setTimeout(fn, 0) expecting it to run "immediately." It didn't. A Promise.then() you scheduled a line later ran first, and somewhere a for loop of 50,000 iterations froze your UI for a full second despite every function being "async." None of this is a bug. It's the JavaScript event loop doing exactly what it always does — you just haven't seen the mechanism yet. What you'll learn By the end of this guide you'll be able to: Explain, precisely, why microtasks (Promises) always run before macrotasks ( setTimeout , setInterval ) — even at a zero delay Predict the exact console output order of any mix of synchronous code, setTimeout , and await Diagnose a frozen UI as a blocked call stack, not a "slow async function" Choose correctly between queueMicrotask , setTimeout(fn, 0) , and requestAnimationFrame for a given timing need Avoid the two most common event-loop bugs: microtask starvation and accidental serial await s in a loop Who this is for: you've written async / await and used setTimeout , but you want the model that makes their interaction predictable instead of memorized. Contents Why the JavaScript event loop exists The mental model Stage 1: the call stack and blocking code Stage 2: Web APIs and the macrotask queue Stage 3: Promises and the microtask queue Stage 4: async/await is sugar, not magic Stage 5: rendering, and Node's extra queues Edge cases and gotchas Best practices FAQ Cheat sheet Key takeaways Why the JavaScript event loop exists JavaScript runs on a single thread. One call stack, one thing executing at a time, no parallel function calls in the same realm. That's a deliberate design — it means you never need locks or mutexes to protect a shared variable — but it creates an obvious problem: how does a single-threaded language do anything concurrent, like waiting on a network response, without freezing the entire page while it waits? Here's the naive expectation, and why it would be a disaster if JavaScript worked this way: console . l

2026-07-13 原文 →
AI 资讯

Improve Performance by Loading Videos Only When They're Needed

Videos are one of the heaviest assets you can add to a web page. Loading videos too early can significantly impact your application's performance. The good news is that modern browsers are starting to support lazy loading for video elements , allowing you to defer loading until users are likely to watch them. However, there's one important thing to know: 👉 This feature is not yet part of the Baseline web platform , so browser support is still limited. At the time of writing, lazy loading for <video> elements is supported in Chromium-based browsers such as Google Chrome , Microsoft Edge , and Opera , while browsers like Firefox and Safari do not yet support it natively. In this article, we'll explore: What lazy loading videos is Why it's important for web performance How to implement it Browser support considerations Best practices for optimizing video loading Let's dive in. 🤔 What Is Lazy Loading for Videos? Lazy loading means delaying the loading of a resource until it's actually needed. Instead of downloading every video immediately during page load, the browser waits until the video is close to entering the viewport. This helps reduce: initial network requests bandwidth usage page load time memory consumption Especially on pages with multiple videos, the difference can be significant. 🟢 What Problem Does It Solve? Imagine an e-commerce page with several product videos. Without lazy loading: every video starts downloading immediately bandwidth is consumed even for videos users never watch page rendering may become slower This negatively impacts; Largest Contentful Paint (LCP), Time to Interactive (TTI), and overall user experience. Most visitors won't watch every video on the page. So why load them all? Lazy loading ensures videos are fetched only when they're actually needed. 🟢 How to Lazy Load a Video The easiest approach is using the loading="lazy" attribute. Example: <video controls loading= "lazy" poster= "/preview.jpg" > <source src= "/video.mp4" type= "vide

2026-07-13 原文 →
AI 资讯

I Tested Direct Provider APIs vs Aggregators — Here's the Truth

I Tested Direct Provider APIs vs Aggregators — Here's the Truth Six months ago I was staring at a $48,000 invoice from an AI provider that shall not be named. We had committed to a six-month contract because the sales rep promised "priority routing" and "negotiated rates." What we got instead was a rate hike, an outage during our biggest product launch, and a support team that took 72 hours to respond. That was the moment I decided to stop signing contracts with AI providers entirely. This is the playbook I wish someone had handed me on day one — the architecture decisions, the math, and the code that lets a small team punch way above its weight class without betting the company on a single vendor. The Trap Most Startups Fall Into When I started my last company, I did what every founder does. I read the docs, got an API key, shipped a feature. The model worked, the demo went well, the investors nodded. Then we hit production traffic and the bills started arriving like clockwork. Here's what nobody tells you about going direct to a model provider as a startup: The pricing page you see on the website is the retail price. The actual cost of running production workloads includes rate limits you didn't anticipate, caching you forgot to implement, context windows that blow up your token count, and prompt engineering iterations that look cheap per call but compound fast. I watched one team burn $20K in a single weekend because they were streaming completions without setting a max_tokens guardrail. Direct providers also lock you into their ecosystem. Their SDK, their tools, their prompt format, their authentication scheme. The moment you want to A/B test a different model — which you will, probably next quarter — you're rewriting integration code instead of shipping features. And then there's the geopolitical mess. Some of the best models in 2026 come from providers that don't accept US credit cards. I've personally lost an afternoon trying to sign up for an account that re

2026-07-13 原文 →
AI 资讯

SQL: Data Constraints

Introdução Validar dados é uma responsabilidade que pode ficar na aplicação, no banco de dados, ou em ambos. Deixar tudo na aplicação é arriscado: diferentes sistemas podem acessar o mesmo banco, migrações podem rodar diretamente, um bug pode deixar passar um valor inválido. Constraints são regras definidas no próprio banco de dados — uma camada de proteção que age independente de quem está escrevendo os dados. PRIMARY KEY A chave primária identifica cada linha de forma única. Ela combina duas restrições implicitamente: NOT NULL e UNIQUE . Nenhuma linha pode ter o mesmo valor de chave primária, e nenhuma pode tê-la nula. CREATE TABLE clientes ( id INT PRIMARY KEY , nome VARCHAR ( 100 ) NOT NULL ); Quando a chave primária envolve mais de uma coluna, ela é declarada separadamente: CREATE TABLE matriculas ( aluno_id INT , curso_id INT , PRIMARY KEY ( aluno_id , curso_id ) ); Na maioria dos bancos, é comum usar uma chave primária auto-incremental para não precisar gerenciar os IDs manualmente: -- PostgreSQL id SERIAL PRIMARY KEY -- MySQL id INT AUTO_INCREMENTPRIMARY KEY -- SQL padrão (suportado por ambos) id INT GENERATED ALWAYS AS IDENTITY PRIMARY KEY FOREIGN KEY A chave estrangeira garante integridade referencial : um valor só pode existir numa coluna se ele existir como chave primária na tabela referenciada. É o que torna os relacionamentos entre tabelas confiáveis. CREATE TABLE pedidos ( id INT PRIMARY KEY , cliente_idINT REFERENCES clientes ( id ) ); Tentar inserir um pedido com cliente_id = 99 quando não existe cliente com esse id resulta em erro imediato. O banco rejeita a operação antes mesmo de ela chegar ao disco. O comportamento quando o registro referenciado é deletado pode ser configurado: CREATE TABLE pedidos ( id INT PRIMARY KEY , cliente_id INT REFERENCES clientes ( id ) ON DELETE CASCADE -- deleta os pedidos junto com o cliente ON UPDATE CASCADE -- atualiza o cliente_id se o id do cliente mudar ); As opções disponíveis são: Opção Comportamento RESTRICT

2026-07-13 原文 →
AI 资讯

SQL: Aggregate Queries

Introdução Consultas individuais respondem perguntas como "qual o email do cliente 42?". Mas as perguntas mais valiosas em qualquer sistema são de outro tipo: "qual o produto mais vendido?", "qual a receita média por pedido?", "quantos clientes se cadastraram esse mês?". Para responder isso, o SQL oferece as funções de agregação — operações que recebem um conjunto de linhas e devolvem um único valor resumido. Para os exemplos a seguir, considere esta tabela: pedidos: | id | cliente | produto | categoria | quantidade | valor | |----|------------|-------------|--------------|------------|--------| | 1 | Ana Lima | Notebook | Eletrônicos | 1 | 3500.00| | 2 | Ana Lima | Mouse | Periféricos | 2 | 80.00| | 3 | Bruno Melo | Teclado | Periféricos | 1 | 150.00| | 4 | Bruno Melo | Notebook | Eletrônicos | 1 | 3500.00| | 5 | Carla Nunes| Monitor | Eletrônicos | 2 | 1200.00| | 6 | Carla Nunes| Mouse | Periféricos | 1 | 80.00| As Funções de Agregação COUNT Conta o número de linhas — ou de valores não nulos em uma coluna específica. -- Total de pedidos SELECT COUNT ( * ) AS total_pedidosFROM pedidos ; -- Resultado: 6 -- Clientes distintos que fizeram pedidos SELECT COUNT ( DISTINCT cliente ) AS clientes_unicosFROM pedidos ; -- Resultado: 3 COUNT(*) conta todas as linhas, incluindo as que têm nulos. COUNT(coluna) conta apenas as linhas onde aquela coluna não é nula. COUNT(DISTINCT coluna) conta valores únicos — útil para saber quantos clientes, produtos ou categorias distintos aparecem no resultado. SUM Soma os valores de uma coluna numérica. -- Receita total SELECT SUM ( valor ) AS receita_total FROM pedidos ; -- Resultado: 8510.00 -- Total de itens vendidos SELECT SUM ( quantidade ) AS itens_vendidos FROM pedidos ; -- Resultado: 8 AVG Calcula a média aritmética dos valores. -- Valor médio por pedido SELECT AVG ( valor ) AS ticket_medio FROM pedidos ; -- Resultado: 1418.33 AVG ignora valores nulos automaticamente — calcula a média apenas sobre os registros que têm valor preenchid

2026-07-13 原文 →
AI 资讯

Using WebSockets to Convert BTC to USD and Reais (BRL)

If you need real-time BTC conversion (USD and BRL), polling an API every few seconds is usually not enough. A better approach is streaming quotes with WebSockets and calculating conversions as events arrive. Why WebSockets for BTC conversion? With WebSockets, your app keeps one open connection and receives new prices instantly. Benefits: Lower latency than polling Fewer HTTP requests Better user experience for real-time values Trade-offs: You must handle reconnects Need heartbeat/health checks Must validate and normalize incoming messages Real-time conversion model For BTC conversion, a common model is: Stream BTC/USD Stream USD/BRL Calculate BTC/BRL = BTC/USD × USD/BRL This avoids waiting for a separate BTC/BRL endpoint and keeps conversion logic transparent What is a “tick”? A tick is one market update event. Example: BTCUSD changed to 64210.50 at timestamp t . In this article, each tick has: pair : market identifier ( BTCUSD , USDBRL ) price : latest value for that pair ts : event timestamp Why this matters: conversion state should always be derived from the latest ticks . Minimal WebSocket client (TypeScript) This client only transports responsibilities: Connect Receive messages Parse and normalize into a consistent shape Notify listeners Reconnect on disconnect type MarketTick = { pair : string ; // e.g. "BTCUSD" or "USDBRL" price : number ; ts : number ; }; class WsFeedClient { private ws ?: WebSocket ; private listeners : Array < ( tick : MarketTick ) => void > = []; constructor ( private readonly url : string ) {} connect () { this . ws = new WebSocket ( this . url ); this . ws . onopen = () => console . log ( " [ws] connected " ); this . ws . onmessage = ( event ) => { try { const data = JSON . parse ( String ( event . data )); // Normalize external payload into internal contract const tick : MarketTick = { pair : String ( data . pair ), price : Number ( data . price ), ts : Number ( data . ts ), }; // Basic guard if ( ! tick . pair || Number . isNaN ( tick

2026-07-13 原文 →