AI 资讯
These startups are chasing the next big thing in LLMs
MIT Technology Review’s What’s Next series looks across industries, trends, and technologies to give you a first look at the future. You can read the rest of them here. Way back in the summer of 2017, AI researchers at Google put out a paper called “Attention Is All You Need,” in which they described a new…
AI 资讯
AI for science needs reasoning, not just data
Every few decades, someone announces that science has reached its end. In 1903, the revered physicist Albert Michelson wrote that the “facts of physical science have all been discovered.” In the 1980s, Stephen Hawking predicted that theoretical physics might be finished by the end of the century. With the explosive arrival of artificial intelligence, the…
AI 资讯
Build a React client intake form with file uploads
Client intake often requires two types of information: searchable answers and files for review. This Vite and React example collects both in the same response. You can try the form without an account. Ask only what you need The example asks for: the client's name; a work email address; the result they need; an optional target date; up to five briefs or reference files. Each answer should help someone prepare for the first call. Leave detailed discovery questions for the call. Define the form The form schema lives in the React app: import { createClient , defineForm , FilloForm } from " @usefillo/react " ; const intake = defineForm ({ id : " vite-client-intake " , title : " Tell us about your project " , description : " Tell us what you need, when you need it and which files will help us prepare. " , pages : [ { id : " intake " , blocks : [ { id : " name " , kind : " short_text " , label : " Your name " , required : true }, { id : " email " , kind : " email " , label : " Work email " , required : true }, { id : " outcome " , kind : " long_text " , label : " What result do you need? " , required : true , }, { id : " target-date " , kind : " date " , label : " Target date " }, { id : " documents " , kind : " file_upload " , label : " Briefs or reference files (PDF, DOCX, PNG or JPG) " , accept : [ " .pdf " , " .doc " , " .docx " , " .png " , " .jpg " , " .jpeg " ], maxFiles : 5 , }, ], }, ], settings : { submitLabel : " Send project details " }, }); Keep the form and field IDs after you collect the first response. Fillo uses them as stored answer keys. You can change labels and help text without changing the IDs. The React app controls the route, layout, styles and what happens after submit. Fillo handles the schema, validation, uploads and responses. The SDK renders React controls in the page. It does not use an iframe. Send files straight to storage The browser sends each file to the storage connected to the Fillo workspace. The Vite app does not proxy the file throu
AI 资讯
Nodes and Networks: How Blockchains Actually Stay Decentralized
When someone says "Bitcoin has over 15,000 nodes worldwide," they mean 15,000+ independent computers are each running Bitcoin software and each maintaining their own full copy of the blockchain. No server owns the truth. Every node checks it for itself. That single fact — every node independently verifies every transaction and block against protocol rules — is the reason blockchains don't need a central authority. If one node tries to cheat, the rest simply ignore it. There's no admin account to compromise because there's no admin. Not All Nodes Do the Same Job Full Node Downloads and stores the entire blockchain, every block since genesis, and independently validates everything against consensus rules. Highest security ~500 GB for Bitcoin ~1 TB for Ethereum This is the backbone of network security. A full node doesn't trust anyone's summary of the chain; it recomputes validity itself. Light Node (SPV) Stores only block headers, not full transaction data. Uses Merkle proofs and relies on full nodes to verify transactions. Low storage, ~50 MB Trusts full nodes for verification What most mobile wallets run Mining/Validator Node A full node that also participates in block creation. Miners (Proof of Work) solve computational puzzles; validators (Proof of Stake) stake cryptocurrency as collateral. Both earn rewards for securing the network. Creates new blocks Earns rewards Requires specialized hardware (PoW) or capital at stake (PoS) Archive Node Everything a full node stores, plus historical state at every block height. Complete history ~15+ TB for Ethereum Used by explorers, analytics platforms, and enterprise tooling Why Peer-to-Peer Instead of Client-Server A traditional web service is client-server: your browser requests data from a company's servers. If those servers go down, the service is unavailable. That's a single point of failure by design. Blockchain networks use peer-to-peer (P2P) architecture instead. Every participant is simultaneously a client and a serv
AI 资讯
Your Prompt Engineering Is Not the Bottleneck Anymore
I spend a lot of time in the AI space -- reading papers, building things, talking to engineers who are actually shipping. And there is a gap between what the demos show and what production systems actually look like that nobody is being fully honest about. So here is my honest take on where things actually are. The Problem With How We Talk About AI Agents Everyone is calling everything an "agent" right now. A function that calls a tool? Agent. A chatbot with memory? Agent. A script with a loop? Agent. This dilution is not just semantic. It is causing real engineering mistakes. When you do not have a precise definition for what you are building, you end up over-engineering simple pipelines and under-engineering genuinely complex ones. I have seen teams spend weeks adding "agentic" orchestration to workflows that would have been fine as a single well-structured prompt. Here is the definition I keep coming back to: an agent is a system that has an objective, not just an instruction. It decides what to do next. It handles failure. It knows when it is done. Everything else is just a fancy function call. 🟢 If your system needs a human to tell it each step, it is not an agent. It is a chat interface. 🔵 If your system can recover from a failed tool call and try a different approach, you are getting somewhere. ✅ If your system can decompose a goal into subtasks and delegate them, that is the real thing. What Is Actually Happening in Production Right Now The honest picture from teams I follow and talk to: Most real agent deployments are narrow. They do one thing well. Customer support triage. Document extraction. Code review on a specific codebase. They are not general-purpose reasoning engines. They are purpose-built pipelines with some intelligence in the decision layer. The teams getting good results are not chasing the latest model release. They are obsessing over: ☑️ Tool design -- what can the agent actually call, and how clean is the interface ☑️ Failure handling -- wh
开发者
Geo-Blocking: Block Malicious Traffic from Specific Countries (2-Minute Setup)
Why Geo-Block? Not every country needs to reach your server. If you run a local business in Brazil, you don't need traffic from North Korea. If you serve customers in the EU, you probably don't need visitors from 150 other countries hitting your login page. Geo-blocking at the WAF level stops unwanted traffic before it ever reaches your application. No CPU spent. No database queries wasted. No bandwidth consumed. The Numbers from My Server After 30 days of logging, I checked where attacks came from: Traffic Source % of Total Requests % of Attacks Target countries (where my customers are) 23% 8% Non-target countries 77% 92% 77% of my traffic came from countries I don't serve, and 92% of attacks originated from those countries. Geo-blocking the non-target regions would eliminate the vast majority of malicious traffic with zero impact on real users. Setting Up Geo-Blocking in SafeLine Step 1: Go to IP Groups -> Geo Blocking in the dashboard. Step 2: Choose your approach: Option A: Allow-list mode (strictest) Block everything, then whitelist specific countries. Block : ALL Allow : United States , Canada , United Kingdom , Germany , France , Netherlands Option B: Block-list mode (targeted) Allow everything, then block specific high-noise regions. Block : Russia , China , Vietnam , North Korea , Iran Step 3: Apply the rule. Done. What Happens to Blocked Visitors Blocked IPs see a 403 Forbidden page. They can't reach your application at all — the WAF drops the connection at the proxy layer. Your app server never sees these requests. SafeLine logs every geo-blocked request to Attack Logs. You'll see: Which country the IP was from What URL they tried to access The exact timestamp Which Countries to Block Based on my 30-day log analysis and common community reports: Almost always safe to block: North Korea — 0 legitimate traffic for 99.9% of sites Iran — heavy scanner activity, minimal legitimate traffic (for non-Iranian sites) High scanner volume, consider blocking if not yo
AI 资讯
How to Set Up Rate Limiting on Any Web App (Free, No Code Changes)
The Problem Your login page, search endpoint, or contact form is getting hammered. Rate limiting is the fix — but implementing it in application code means finding every endpoint, writing middleware, choosing a storage backend, and deploying changes. On a WAF, you set it once and it applies everywhere. Why WAF-Level Rate Limiting Is Better Approach Code-Level WAF-Level Setup time Hours to days 5 minutes Code changes Required None Applies to One endpoint at a time All routes with one rule Storage Redis/Memcached needed Built into WAF Performance impact Hits your app server Blocked at proxy Updates Deploy new code Change a rule in dashboard Step-by-Step: Rate Limit Setup 1. Log into SafeLine Dashboard Go to https://<your-ip>:9443 . Navigate to Rules -> Add Rule -> Rate Limiting. 2. Create Your First Rule — Login Protection Name: Login brute force protection Match: URL contains /login OR /wp-login.php OR /auth Limit: 5 requests per minute per IP Action: Block (return 429 Too Many Requests) Block duration: 15 minutes This stops credential stuffing cold. An attacker who tries 5 wrong passwords in 60 seconds gets blocked for 15 minutes. That's a maximum of 480 attempts per day — vs unlimited without rate limiting. 3. Search Endpoint Protection Name: Search rate limit Match: URL contains /search OR /query Limit: 30 requests per minute per IP Action: Challenge (JS captcha) Search endpoints are expensive. A single user running a script can do 1,000+ queries per minute and degrade performance for everyone. 30/min is generous for humans but stops scripts. 4. Global Baseline Name: Global request limit Match: /* Limit: 300 requests per minute per IP Action: Throttle Catches anything that slips through specific rules. 300/min = 5/sec, which is more than any human needs. What Happens When a Limit Is Hit SafeLine logs every rate limit trigger to the Attack Log. You'll see: Which IP triggered it Which endpoint they were hitting Time of the trigger Whether they got blocked, challenge
AI 资讯
Stop Slouching! Build a Real-Time Spine Posture Monitor using MediaPipe and Python
We’ve all been there: hunched over a keyboard at 3 AM, neck craned forward like a turtle, debugging a race condition. "Tech neck" isn't just a meme; it’s a productivity killer. As developers, our spine is our most underrated hardware. In this tutorial, we are going to build a Real-Time Spine Posture Monitor . We will leverage real-time human pose estimation and MediaPipe Python libraries to track your posture via your webcam. By the end of this guide, you'll have a system that detects when you're slouching and sends a system notification to keep your ergonomics in check. This project is perfect for those looking into OpenCV computer vision and developer ergonomics solutions. The Architecture 🏗️ The logic is straightforward: we capture video frames, process them through a pre-trained neural network to find body landmarks, and apply some basic geometry to determine if your posture is healthy. graph TD A[Webcam Feed] --> B[OpenCV Frame Processing] B --> C[MediaPipe Pose Landmark Detection] C --> D{Extract Shoulder & Ear Coordinates} D --> E[Calculate Neck Inclination Angle] E --> F{Angle > Threshold?} F -- Yes --> G[Trigger System Notification] F -- No --> H[Continue Monitoring] G --> B H --> B Prerequisites 🛠️ Before we dive into the code, ensure you have the following installed: Python 3.9+ MediaPipe : Google’s framework for cross-platform ML. OpenCV : For video stream handling. PyObjC : (For macOS) to trigger native system alerts. pip install mediapipe opencv-python pyobjc Step 1: Initialize the Pose Engine MediaPipe makes pose estimation incredibly easy. We’ll use the Pose solution, which provides 33 3D landmarks for the human body. import cv2 import mediapipe as mp import math # Initialize MediaPipe Pose mp_pose = mp . solutions . pose pose = mp_pose . Pose ( static_image_mode = False , model_complexity = 1 , enable_segmentation = False , min_detection_confidence = 0.5 ) mp_drawing = mp . solutions . drawing_utils Step 2: Calculating the "Slouch" Angle 📐 To detect
AI 资讯
How to stop a Claude Code agent writing outside a directory
When you're sitting in front of an agent, "don't touch anything outside src/ " is enforced by you noticing. Unattended, it has to be enforced by something that runs whether or not anyone is watching. Claude Code gives you two mechanisms for that, and they are not interchangeable. One is declarative and can't express what you probably want. The other can, but is structurally blind to a whole category of writes. Here's what each one actually does, and the code for the second. Why permissions.deny isn't enough Permission rules live in settings.json and take the form Tool(specifier) : { "permissions" : { "deny" : [ "Read(./.env)" , "Read(./.env.*)" , "Write(./.github/**)" , "Write(//etc/**)" ] } } Paths are gitignore-style. A leading // means absolute, ~ means home, and anything else is relative to the settings file. deny beats ask , which beats allow , and rules merge across scopes rather than override — so a deny in project settings still applies even when your personal ~/.claude/settings.json allows the same thing. That precedence is the useful part: a deny rule is hard to undo by accident. The problem is shape. What you want for an unattended agent is an allow-list — only these directories, nothing else. What deny gives you is a block-list, and you cannot build the first out of the second. The obvious trick of denying everything and allowing back the exceptions fails on exactly the precedence rule that makes deny valuable: Write(**) in deny outranks every allow you pair it with, so the agent can write nothing at all. Claude Code does have one allow-list-shaped boundary — the project root, plus whatever you list in additionalDirectories . That stops an agent wandering into /etc . It says nothing about which directories inside your project it may write, which is usually the interesting question. Nobody's real worry is that a scheduled agent edits /etc/hosts . It's that the agent tasked with writing articles decides to fix its own scheduling config. So for anything fin
AI 资讯
Topic selected: Option A – Purely Technical: "Building a Secure AI Proxy for Browser Tools
This is the strongest choice. It teaches a tangible, highly demanded skill (API key security) with actual code, making the backlink to AfriWidget feel like a natural, neutral citation rather than a sales pitch. Here is the article, rewritten to be strictly technical, objective, and genuinely useful for dev.to readers. Stop Exposing Your AI API Keys: Build a Secure Proxy with Cloudflare Workers We have all seen it. You open the browser's DevTools on a "cutting-edge" AI startup's landing page, check the Network tab, and find a direct POST request to api.openai.com containing a plaintext API key in the headers. It is one of the most common—and dangerous—mistakes in modern web development. Exposing your LLM API key client-side is an open invitation for abuse, leading to stolen credits, hefty bills, and potential account suspension. The standard solution is the Backend-for-Frontend (BFF) proxy pattern. But how do you implement it practically, cheaply, and securely without spinning up a heavy Express server? In this guide, I will walk you through building a lightweight, serverless AI proxy using Cloudflare Workers to securely call Groq (or OpenAI) APIs from your browser-based calculators and tools. The Architecture: How It Works Instead of your frontend talking directly to the AI provider, we introduce a stateless middleware layer: Browser App → Cloudflare Worker (Proxy) → Groq/OpenAI API ↑ ↑ (No API Key) (API Key stored securely in Worker env vars) The Worker's responsibilities: Receive the sanitized calculation context from the frontend (numbers, not PII). Attach the secret API key via environment variables. Forward the request to the LLM provider. Stream or return the generated insight back to the client. Step 1: Scaffolding the Cloudflare Worker We will use the new create-cloudflare CLI. Make sure you have Node.js installed. npm create cloudflare@latest ai-proxy Choose "Hello World" worker and TypeScript. Once inside the directory, install the Groq SDK: npm install gr
AI 资讯
Why a 24 GB GPU Does Not Give Your Local LLM 24 GB
I keep seeing the same local LLM sizing mistake: "The model file is smaller than my GPU, so it should fit." That is only the first check. A 24 GB GPU does not give your model a clean 24 GB memory budget. The display stack, runtime, temporary buffers, model weights, and KV cache all compete for the same space. Here is the worksheet I use before I download a model or rent a GPU. 1. Start with the weight floor The simplest weight estimate is: weight_memory_gib = parameters * bits_per_parameter / 8 / 1024^3 For a simple 4-bit estimate: Model size Weight floor 7B 3.3 GiB 13B 6.1 GiB 70B 32.6 GiB These are floors, not promises. Real quantized files can also contain scales, metadata, and layers stored at higher precision. If you know the exact checkpoint size, use that instead of the simple bits-per-parameter estimate. Also use total parameters for a sparse mixture-of-experts model unless your runtime really offloads inactive experts. Active parameters describe compute per token. They do not automatically describe how many weights must be stored. 2. Reduce the physical capacity to a usable budget I normally start with 90 percent usable VRAM for planning: usable_vram = physical_vram * usable_fraction For a 24 GB card: 24 * 0.90 = 21.6 GiB usable The exact reserve depends on the OS, display use, driver, runtime, graph capture, allocator behavior, and other processes. The important part is to stop treating the number on the box as fully available. 3. Add the KV cache The KV cache is where context length and concurrency become expensive. A useful planning formula is: kv_cache_bytes = 2 * layers * kv_heads * head_dimension * context_tokens * concurrent_sequences * bytes_per_kv_value The factor of two stores keys and values. Take a model with: 32 layers 8 KV heads 128 dimensions per head 8,192 cached tokens 1 concurrent sequence 16-bit KV values, which use 2 bytes The KV cache is about 1 GiB. Raise the context to 32,768 tokens and it becomes about 4 GiB. Keep that context and ru
AI 资讯
Voice-to-code 100 % local : Whisper + Claude Code, zéro octet au cloud
Coder à la voix avec ChatGPT, ça marche. Le hic tient en une ligne : chaque mot que tu dictes part chez OpenAI. Depuis le 23 juillet 2026, Codex se pilote à la voix — il ouvre une pull request, cherche l'origine d'un bug, tout ça dans une phrase. Pratique pour un side-project. Rédhibitoire quand le code appartient à un client. On voulait le même confort sans la fuite. Le résultat est un pipeline 100 % local : faster-whisper pour la transcription, Claude Code et sa commande /voice pour l'agent. Rien ne sort de la machine — ni la voix, ni le contexte, ni le code. Voici la config exacte, la latence qu'on mesure sur un M2, et les deux bugs qui nous ont coûté une demi-journée. Pourquoi pas simplement Codex vocal ? Parce que « coder à la voix » cache deux choses qu'on confond tout le temps. Le mode vocal de ChatGPT est fait pour converser : il répond, il temporise, il reformule. Dicter du code, c'est l'inverse — tu veux une transcription fidèle et muette, qui ne discute pas, ne reformule pas et n'ajoute rien à ce que tu dis. Deux gestes opposés. Le vrai stack n'est donc jamais « ChatGPT vocal seul ». C'est un outil de dictée précis d'un côté, un agent de code de l'autre. Codex vocal fait les deux dans le cloud pour 20 €/mois ; un setup local sépare les deux briques et garde tout sur ta machine. Le tour d'horizon complet — prix, outils, cas d'usage — est dans le guide de référence ; ici, on reste sur le terrain technique. Le chemin le plus court : /voice Depuis mars 2026, Claude Code embarque un mode vocal. Tu tapes /voice dans le terminal, tu tiens la barre d'espace, tu parles, tu relâches. La transcription passe par un Whisper local, pas par une API distante. > /voice [hold space to talk · release to send] Pour 90 % des cas, ça suffit. Tu dictes une intention, l'agent écrit le code, tu relis. Si tu veux garder la main sur le modèle, la langue et le vocabulaire technique, il faut descendre d'un cran et brancher ta propre transcription. Le pipeline DIY, brique par brique T
开发者
This ‘adversarial’ pattern can prevent surveillance cameras from detecting you
A security researcher has designed an algorithm that can create computer-generated patterns capable of hiding people, faces, and vehicles from detection by surveillance cameras.
AI 资讯
These AI Barons Are Ready to Give Away Their Fortunes
A new generation of philanthropists made rich by artificial intelligence are preparing to give away their vast wealth. What should we make of a multi-billion-dollar pinky promise?
AI 资讯
Stripe Uses Graph Search and State Machines to Automate Database Remediation
The engineering team at Stripe recently described how they automated database incident recovery by modeling their global infrastructure as a graph. Using graph search algorithms together with state machines, the team computes and executes remediation plans automatically. By Renato Losio
AI 资讯
Surviving the AI Bubble With Two Pieces of Junk From Amazon
Everyone is building agents. You should build escape hatches. We are living through the most expensive group hallucination in tech history. Every SaaS now has a chatbot stapled to it. Every CEO is an "AI thought leader" on LinkedIn. Every startup pitch deck is just the words "autonomous," "agentic," and "10x" in different fonts. NVIDIA could buy a small country. OpenAI burns through more cash in a quarter than NASA did getting to the moon. And for what? So you can generate slightly worse emails, slightly faster? Look, I love AI. I actually build with it. But I have been around long enough to know what a bubble smells like. It smells like free credits, unearned confidence, and a thousand wrappers around the same API call. The bubble will pop. Not in a dramatic, newspapers falling from the sky way. It will pop quietly. Credits will dry up. Models will get paywalled behind enterprise tiers. The cloud bill you have been ignoring will finally show up. And all those beautiful, cloud-dependent workflows you built will start blinking red. So while everyone else is trying to figure out how to make their AI agent book a flight, I have been asking a different question. What do you build when you assume the internet will get worse, the cloud will get more expensive, and you will need actual skills that survive a downturn? The answer, annoyingly, is two pieces of junk from Amazon that cost less than your last Uber Eats order. Piece of Junk #1: The $25 Router That Sees Everything It is not sexy. It is called the GL.iNet GL-MT300N-V2. Everyone calls it the Mango. It looks like a little yellow box that should have come free with your ISP in 2014. You can buy it on Amazon for about twenty six dollars when it is on sale. Sometimes twenty. Inside it is a tiny Linux computer running OpenWrt. It has two ethernet ports, a USB port, and just enough RAM to be dangerous. Most people buy it to get free WiFi in hotels. I bought it to spy on my own network. Because here is the dirty secret of
AI 资讯
Local LLMs in 2026: What Actually Runs Well on a Laptop Now
Two years ago, "run a language model locally" meant a weekend of compiling, a graveyard of CUDA errors, and a model that answered like it had a concussion. In 2026, you can install one tool, type one command, and have a genuinely useful assistant running on a laptop with no internet connection. Here's an honest map of what works, what doesn't, and where the sharp edges still are. Why bother running locally at all Three reasons keep pulling developers back to local inference: Privacy. The prompt never leaves your machine. For code you can't paste into a cloud box, or personal data, that's non-negotiable. Cost and offline. No per-token bill, no rate limits, and it works on a plane. Latency and control. No network round-trip, and you pin the exact model version forever — no silent upgrades changing your outputs. The catch has always been quality-per-watt. That's the number that moved. The hardware tiers, honestly 8 GB RAM / integrated GPU: You can run 3–4B parameter models at 4-bit quantization. Good for autocomplete, summarizing, simple Q&A. Don't expect deep reasoning. 16 GB RAM: The sweet spot for most developers. 7–9B models run comfortably and are genuinely helpful for coding assistance and drafting. 32 GB+ or a discrete GPU with 16–24 GB VRAM: Now you're running 20–30B models, or bigger models at aggressive quantization, with real reasoning ability. Apple Silicon (unified memory): Punches above its weight. A machine with 32–64 GB of unified memory runs models that would need an expensive discrete GPU on other platforms, because the CPU and GPU share the same memory pool. Quantization: the trick that makes it possible The reason a 7B model fits in 16 GB is quantization — storing weights at 4 bits instead of 16. The common format you'll see is GGUF, and the common recipe is 4-bit (often labeled Q4). The quality loss from full precision to 4-bit is surprisingly small for most tasks, while the memory savings are 4x. Below 4-bit (2–3 bit) the model starts to degrade n
AI 资讯
X replaces its revenue-sharing program with ‘Original Content Rewards’
X is ending its controversial revenue-sharing program for content creators, which has seen numerous revisions under Elon Musk's reign. In its place, it's launching a new Original Content Rewards program on September 8th. To be eligible, creators must have at least 500 verified followers and at least 500,000 Home Timeline impressions from verified users in […]
AI 资讯
Build map guidance that follows the user without blocking pinch-to-zoom
A navigation map should help the user move through the world, not fight every gesture they make. I recently hit a deceptively simple bug while building field guidance in a React Native / Expo app: the route rendered correctly and the camera followed the current position, but users could not meaningfully zoom or pan while walking. They could pinch the map, but the next location update snapped the camera back to a fixed zoom. The map looked active. The experience felt broken. The cause: two camera owners The implementation combined two useful features: followsUserLocation={true} on the native map. animateCamera(...) after every location update, using a fixed walking zoom and pitch. Each feature was reasonable on its own. Together, they gave the camera two automatic owners and the user none. A pinch gesture changed the zoom for a fraction of a second. Then a GPS update arrived and our effect applied the navigation camera again. On iOS, native user-follow behavior added another layer of camera control. A better model: follow mode and explore mode The fix was not to stop navigation. Route progress, distance, bearing, breadcrumb recording and off-route detection should all continue regardless of what the user does with the map. Only the camera behavior should change. We now keep a small piece of local UI state: const [ cameraFollowing , setCameraFollowing ] = useState ( navigationActive ); useEffect (() => { if ( ! navigationActive || ! cameraFollowing || bearing == null ) return ; mapRef . current ?. animateCamera ( walkingCamera ( currentCoordinate , bearing ), { duration : 480 }, ); }, [ currentCoordinate , bearing , navigationActive , cameraFollowing ]); The native follow prop uses the same state: < MapView showsUserLocation followsUserLocation = { navigationActive && cameraFollowing } onTouchStart = { () => { if ( navigationActive ) setCameraFollowing ( false ); } } /> As soon as the user touches the map, the camera enters explore mode. Pinch, pan and rotation work n
AI 资讯
Cuando tu clasificador parpadea: histéresis para señales que oscilan
Tienes una señal que a cada observación te dice en qué estado estás: un monitor de salud que dice OK o CAÍDO , un detector de conectividad, un clasificador de modo. Y cerca del umbral oscila : OK, CAÍDO, OK, CAÍDO, OK . Cada cambio dispara algo —una alerta, un failover, entrar o salir de una posición— y de repente tu sistema está temblando por ruido, no por una transición real. Es el mismo problema que resuelve el termostato de tu casa desde hace un siglo, y la solución tiene nombre: histéresis . No cambies de estado hasta que el nuevo se haya sostenido. La regla, en una frase Un estado nuevo solo se confirma tras repetirse N observaciones consecutivas. Si el candidato cambia o revierte antes de llegar a N , la cuenta se reinicia. El estado vigente se mantiene estable; los parpadeos se ignoran. Lo empaqueté como librería — hysteresis-state , Python puro, sin dependencias— porque lo reescribía una y otra vez: from hysteresis_state import HysteresisState estado = HysteresisState ( " OK " , confirmations = 3 ) for lectura in stream : # "OK" / "CAIDO" actual = estado . update ( lectura ) # solo cambia tras 3 lecturas seguidas if estado . changed : # ¿esta lectura provocó la transición? alertar ( actual ) Aliméntalo con OK, CAÍDO, OK, CAÍDO, OK y no pasa nada: ningún candidato se sostuvo. Hacen falta tres CAÍDO seguidos para que el cambio se confirme. El detalle que casi siempre falta: histéresis asimétrica Un umbral único tiene un problema sutil. Si exiges 3 confirmaciones para entrar en fallo, también tardas 3 en salir — y a veces quieres justo lo contrario: caer rápido a lo seguro, volver despacio a lo arriesgado . Es el comportamiento de un disyuntor eléctrico: salta a la primera, se rearma con cautela. Se resuelve dejando que el umbral dependa de la transición: # 1 confirmación para caer a "CAIDO", 5 para volver a "OK" conf = lambda desde , hacia : 1 if hacia == " CAIDO " else 5 estado = HysteresisState ( " OK " , confirmations = conf ) estado . update ( " CAIDO " )