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

标签:#programming

找到 1319 篇相关文章

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 资讯

Building an Offline AI Note-Taking App with WebGPU

For the last few months, I’ve been obsessed with a specific problem: the friction between privacy and utility in modern AI tools. Most "private" AI solutions still rely on a local LLM running on your CPU or GPU via a heavy desktop application. They require installation, constant background processes, and often struggle with performance on older hardware. I wanted to see if we could do better. I wanted to see if we could run a capable language model entirely within the browser, using only the device’s hardware acceleration, with zero data leaving the machine. The result is PrivateScribe, a tool I built to handle note summarization, email drafting, and rewriting. But more importantly, it’s an experiment in what’s possible when you treat the browser not just as a display layer, but as a compute engine. The Wedge: WebGPU and True Offline The core constraint that drove this project was simple: nothing leaves the device. In the current landscape, "on-device AI" often means "installed on your device." This is fine for desktop apps, but it creates silos. You can’t easily share a workflow across a Chromebook, a Windows machine, and an iPad without installing three different native applications. By leveraging WebGPU, PrivateScribe runs entirely in the browser. This unlocks a few critical advantages: Zero Installation: Users open a URL and start working. No downloads, no permission dialogs for file system access beyond what’s needed for the session. Hardware Acceleration: WebGPU allows the browser to tap directly into the GPU. This is crucial for inference speed. A small model that runs in your browser can process text significantly faster than a CPU-bound implementation, especially on modern laptops with integrated graphics. True Offline Capability: Because the model weights are loaded locally via WebAssembly and the inference happens on-device, the app works completely offline. If you lose your internet connection in the middle of drafting an email, the AI doesn’t stop. It c

2026-07-13 原文 →
AI 资讯

Breeze Framework: Rethinking What a Modern Go Framework Can Be ⚡

The web has changed . Applications are no longer simple HTTP servers. Today we build real-time dashboards, AI-powered services, multiplayer systems, APIs, microservices, and applications that need to handle thousands of connections with minimal overhead. But our frameworks are still mostly designed for yesterday's problems. So we asked a simple question: What if a * Go * framework was built from the ground up for modern workloads? Meet Breeze . A high-performance Go framework designed around one idea: Performance should not come at the cost of developer experience. Why Breeze ? Go already gives us incredible performance. But the framework layer often becomes the bottleneck. Too much abstraction. Too many allocations. Too much hidden complexity. Breeze takes a different approach: ⚡ High-performance networking powered by gnet 🔥 Real-time WebSocket architecture built in 🧩 Modular middleware system 📚 Automatic Swagger/OpenAPI generation 🎨 Built-in SPA template engine 🚀 Optimized worker pool architecture 🗄️ BreezeORM for efficient database operations Everything you need to build production-grade applications — without assembling dozens of unrelated tools. The Future Is Real-Time Modern applications are moving toward instant experiences: Live collaboration Trading platforms AI assistants Gaming backends Monitoring systems Real-time analytics Breeze is designed for this world. Instead of adding real-time capabilities later, Breeze treats them as a first-class citizen. Less Glue Code. More Building. A common problem in backend development: You start with a simple API... Then suddenly you need: Authentication Documentation WebSockets Background workers Database optimization Frontend integration Your stack becomes a collection of disconnected pieces. Breeze tries to bring these pieces together into one coherent ecosystem. Built With Go Philosophy Go was created around simplicity, performance, and reliability. Breeze follows the same principles: Simple APIs. Predictable behavi

2026-07-13 原文 →
AI 资讯

10 Free Facts, Jokes & Name APIs With No Key (2026)

On July 12, 2026 I asked a free API to guess the age of someone named Xzqwlptv. It answered in a few milliseconds: HTTP 200, valid JSON. # runnable, read-only: no key needed curl -s "https://api.agify.io?name=Xzqwlptv" {"count":0,"name":"Xzqwlptv","age":null} # HTTP 200 OK Status 200. The JSON parses. The age key is present, exactly where a schema says it belongs. Its value is null . Every guard I usually reach for passes this response: if resp.ok , if "age" in data , even a JSON Schema that requires an age property. The null walks straight past all of them and into the dataset. My earlier keyless-API posts kept circling one idea from different angles. HTTP 200 does not mean the read worked, because the body can be empty. HTTP 201 Created does not mean a write happened, because the read-back returns 404. This post moves the lie one level deeper than either of those. Here the status is 200, the body arrives, it parses, it matches your schema, and the field you came for is sitting right there. The value is just empty. The null that passes your schema check. A free fun or facts API here means a public endpoint that returns a joke, a fact, or a guess about a name, with no API key, no signup, and no credit card. A URL you can paste into a terminal right now. Ten of them clear that bar, and I re-verified every response below with a live curl on July 12, 2026: real HTTP code, real body, trimmed but never reworded. One scope note first, so the numbers stay honest. I curl-verified all ten APIs on July 12, 2026. I have not run any of them in production. My 2,190 production scraper runs (962 of them on a single Trustpilot scraper) are a different domain, and I cite them for one reason only: they are why I read a field's value and its confidence instead of its status line. That number is not a claim about these ten endpoints. # API What it returns Example call The empty success to watch 1 agify.io Age guess from a first name GET api.agify.io?name=Xzqwlptv 200 with age: null 2 g

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 资讯

How Python's Import System Works and Why It Matters for Debugging

Module caching, execution order, and circular imports explained by tracing what actually happens. How Python's Import System Works and Why It Matters for Debugging The import system is one of the least understood parts of Python and one of the most practically important for debugging production issues. Circular import errors, unexpected code execution, and module state bugs all stem from not understanding what happens when Python encounters an import statement. What Happens on the First Import When Python executes import mymodule for the first time: Python checks sys.modules for mymodule . If found, returns the cached module object immediately. If not found, Python locates the module file. Python creates a new module object and adds it to sys.modules under the module name. Python executes the module file's code in the new module's namespace. The name mymodule in the importing module is bound to the module object. Step 3 happens before step 4. This is critical for understanding circular imports. The Module Cache import sys import os print ( " os " in sys . modules ) print ( sys . modules [ " os " ] is os ) Output: True True Every imported module is cached in sys.modules . Subsequent imports return the cached object without re-executing the module code. Module-Level Code Executes on Import # config.py print ( " config module loading " ) DEBUG = True print ( f " DEBUG is { DEBUG } " ) # main.py import config import config # second import print ( config . DEBUG ) Output: config module loading DEBUG is True True The print statements in config.py run exactly once — when the module is first imported. The second import returns the cached module object without re-executing the code. Circular Import Behavior # module_a.py print ( " loading module_a " ) from module_b import b_function def a_function (): return " from a " # module_b.py print ( " loading module_b " ) from module_a import a_function def b_function (): return " from b " When you import module_a , Python starts exe

2026-07-13 原文 →
AI 资讯

Engineering a Structured Database for Floating-Point Anomalies and Software Quirks: A Deep Dive into Modeling IEEE 754 and RLS Security at the Edge

Hey everyone, We talk a lot about documenting clean architectures and robust APIs, but software engineering history is uniquely shaped by its failures. Documenting these bugs globally usually results in scattered StackOverflow threads or unindexed GitHub issues. I wanted to explore how to build a highly structured, community-driven database dedicated exclusively to tracking software bugs, their deep technical root causes, and multi-language solutions. Here is a technical breakdown of the architectural challenges, data modeling decisions, and security implementations behind building this engine. 1. The Data Modeling Challenge: Structuring the Unstructured Bugs are notoriously hard to normalize in a relational database. A classic logic bug looks nothing like a memory leak or a floating-point precision error. To solve this, we modeled the schema around a strict "Bug DNA" structure using PostgreSQL: Categorization & Multi-Runtime Target: Mapping a single bug to multiple language runtimes dynamically (e.g., how the 0.1 + 0.2 anomaly propagates across V8 JavaScript, CPython, and JVM identically due to hardware constraints). The Diagnostic Timeline: Instead of a generic description text, we structured a linear, time-stamped array to track state changes during the replication phase. 2. Deep Dive: Representing IEEE 754 at the Schema Level Our inaugural entry into the database was the infamous base-2 fractional conversion problem ($0.1 + 0.2 = 0.30000000000000004$). To make this data educational, the challenge was handling how the processor truncates infinite binary fractions: $$0.1_{10} = 0.0001100110011001100110011001100110011001100110011001101..._2$$ We decoupled the storage mechanism so that the raw precision error is stored as a literal string to prevent the database layer (PostgreSQL float types) from auto-correcting or rounding the very bug we are trying to document. 3. Edge Security: Row-Level Security (RLS) Without a Middleware Backend Since the application runs on a

2026-07-13 原文 →