AI 资讯
Mutation Testing as a Merge Gate for Agent-Written Tests
An agent patch that passes its own tests is a baseline, not a verdict. The same model wrote the code and the tests, so both share the same blind spots. Mutation testing scores the tests themselves: inject a fault, run the suite, and see whether it notices. In practice, the first mutant often survives. Previous rounds on this account established three gates before merge: property checks, fixtures, and a freeze on flaky tests. This round adds a fourth gate that runs after the suite is green. It answers a different question — not "does the patch work?" but "would the tests catch it if it didn't?" Why green tests from an agent are weak evidence Code coverage measures execution, not detection. A test can execute a line and still miss the bug on it. A suite that only checks is_even(2) and is_even(4) runs both lines, passes both assertions, and stays blind to a mutation that flips == to != . Agents produce this shape of test by default. They follow the happy path, mirror the implementation, and rarely probe boundaries. The result is a suite that is green, fast, and weak for regression. Mutation testing converts that intuition into a number. For each small fault, rebuild and rerun. If the tests fail, the mutant is killed. If they pass, it survived — and you found a hole in the suite, not in the code. A minimal harness The harness below applies one mutation at a time to the implementation file, compiles it together with an unchanged test file, runs the resulting binary, and records the outcome. It is deliberately small: regex-based, two files, no dependencies beyond a compiler. #!/usr/bin/env python3 # mutate.py — score a test binary against source mutations. import re import subprocess import sys import tempfile from pathlib import Path MUTATIONS = [ ( " eq_to_neq " , r " == " , " != " ), ( " lt_to_le " , r " < " , " <= " ), ( " add_to_sub " , r " \+ " , " - " ), ( " zero_to_one " , r " return 0; " , " return 1; " ), ] def mutate_once ( src : str , pattern : str , replaceme
AI 资讯
The Agent's Tests Passed. Mutation Testing Showed 2 of 4 Faults Survived.
The agent patch passed the gates I ran on it. Its unit tests were green, fixtures matched, nothing was flaky. Then I seeded four faults into the implementation, one at a time. Two survived. That gap is what this article is about. A green suite is a claim, not a measurement. Mutation testing turns it into a measurement: introduce a fault, run the suite, and see whether the suite notices. I now run this loop before merging any agent-written patch, and the whole thing costs a few rebuilds. Why green tests lie A passing test proves one thing only: the test and the implementation agree on the inputs the test exercised. When an agent writes both the patch and the tests, the tests inherit the patch's assumptions. If the implementation encodes a wrong assumption, the test encodes the same one. The suite is green because it is blind, not because the code is right. The patch in this article came from a free model on MonkeyCode's free model access. Disclosure: This article was prepared as part of MonkeyCode's product outreach. The model wrote a bounded queue and a test file. The test file was not wrong. It was blind in exactly the place the implementation was wrong. The method: five steps Mutation testing is easy to describe and awkward to skip: Freeze flaky tests first. A flaky test fails at random, so it makes every mutation look like a kill. The signal is garbage. This is the flaky freeze from the gates post; without it, the numbers mean nothing. Select the functions the patch touched. Mutating untouched code measures someone else's tests. Generate mutations. Each mutation is one small fault: drop a modulo, flip a comparison, change an increment. Run the suite against each mutation. Rebuild, run, record. Gate on the kill rate. A surviving mutation means the suite cannot detect that fault class. Send the patch back with the survivor list as evidence. The artifact A minimal bounded queue, the agent's test, and a small Python driver. The queue: // bounded_queue.h #pragma once
AI 资讯
Building a Modular C++ Static Library: Clean Architecture, Encapsulation, and Safe Input Handling
As C++ codebases scale, housing utility routines, state management, and primary execution logic inside a single main.cpp file inevitably leads to technical debt. Code duplication increases, compilation times degrade, and testing isolated features becomes virtually impossible. Modular architecture solves this problem by enforcing a strict separation of concerns. By decoupling function declarations from their definitions and compiling utility modules into reusable static libraries, developers can achieve clean abstraction boundaries, simplify unit testing, and eliminate memory corruption vulnerabilities associated with unvalidated inputs. In this tutorial, you will learn how to build a production-grade C++ utility module from scratch, complete with boundary guards and static compilation. Prerequisites Before diving in, ensure you have: A modern C++ compiler supporting C++17 or higher (GCC, Clang, or MSVC). Basic familiarity with header files ( .h ) and translation units ( .cpp ). A Code Editor or IDE such as Visual Studio Code or Visual Studio . Project Structure To keep boundaries clean, we structure our workspace by isolating public headers from implementation units: text ModularCppLib/ ├── include/ │ ├── ArrayUtils.h │ └── ValidationUtils.h ├── src/ │ ├── ArrayUtils.cpp │ └── ValidationUtils.cpp ├── main.cpp └── README.md Phase 1: Structural Abstraction and Memory-Safe API Design Separating Interfaces from Translation Units In production C++ engineering, headers ( .h ) serve as explicit architectural contracts. They declare what operations are available without leaking how those operations are executed. All utility routines are scoped inside the explicit CoreUtils namespace to prevent global namespace pollution: namespace CoreUtils { // Contract: Accepts array pointer and length, // returns calculated mean safely double CalculateAverage ( const int * arr , std :: size_t size ); // Formats and prints array content void PrintArray ( const int * arr , std :: size_t si
AI 资讯
Shipping Stock CLIs as Subprocess Instead of Static-Linking SDKs
I'm building yyzTools, which bundles 9 third-party engines (OpenSSL, FFmpeg, ImageMagick, pdfcpu, Aria2, 7-Zip, RapidOCR, Everything...). I chose to spawn them as subprocesses rather than static-link their SDKs. Here's why—and the cost. The conventional approach When your app needs OpenSSL crypto, FFmpeg video processing, ImageMagick image ops—you reach for the SDK. Link libssl, link libav*, link libMagick. One binary, no external deps, fast function calls. It's the textbook answer. I did the opposite. yyzTools ships the stock CLI binaries (openssl.exe, ffmpeg.exe, magick.exe, pdfcpu, aria2c, 7z) and spawns them as subprocesses. The C++ layer is a thin loop: build args → CreateProcess → read stdout → wrap as JSON → return. It doesn't know what -gravity southeast or sm4-cbc means. It just passes the algorithm name through. Why I went this way Upgrades without recompiling This is the big one for a desktop app. OpenSSL ships a CVE, or adds sm2/sm3/sm4 support in 3.x. If you've static-linked, you recompile the whole app, run full regression, re-release, and every user reinstalls. With the subprocess model, I drop in a new openssl.exe. Zero C++ changes. The update is a few-MB delta, not a full reinstall. For a product where users won't tolerate reinstalling for a library bump, this is the deciding factor. No symbol conflicts OpenSSL, zlib, libpng—multiple libraries want to own these symbols. Static linking them all into one binary is a recipe for "which inflate did I just call?" With subprocess CLIs, each tool brings its own dependencies in its own process. No conflict. Transparent supply chain openssl version, ffmpeg -version—auditing which version of each tool is live is trivial. It's an independent binary. Far easier than digging symbols out of a statically-linked blob. Free crash isolation If ffmpeg.exe misbehaves, it exits non-zero and my host wraps that as an error. My main process keeps running. A static-linked bug can take down the whole app. The process boundary
开发者
Fixing a Snapcraft Build that had been Broken for Two Years
As I stated in my introduction , the first piece of work I did on Packet Sender was fix the Snapcraft build. What is Snapcraft? It has been a while since I've worked with Ubuntu, so I wasn't up to speed with how Ubuntu was now doing things like package management. As I understand it, apt and/or apt-get is still a thing, but Snapcraft is the new shiny. Snapcraft is more than just an app repository, though. It's a build system, dependency manager and a packager. Ergo, the vertical integration means you don’t have to keep multiple tools in sync. The Problem When building Packet Sender with Snapcraft, the product would build, link and run. But as soon as you ran it, it would crash with the following error message: /snap/packetsender/49/usr/local/bin/packetsender: error while loading shared libraries: libpxbackend-1.0.so: cannot open shared object file: No such file or directory .dll(s) and .so(s) I grew up in the '90s. This meant that, unfortunately, I grew up in the age of Microsoft, meaning I started on PCs. While I remember Windows 3.1's UI, I didn't really start using computers until Windows 95. My first machine was a Windows 98 box. I tell you this so you know that I grew up knowing what a .dll is because I grew up using Windows. Simply put, a .dll is a shared library . The idea was that instead of having to compile common libraries into executables and thus bloat the size of executables and the amount of memory they needed, vendors could deliver a shared library that would be loaded into memory once and could be called at run time by any running process that needed them. Of course, Microsoft being Microsoft, this was poorly engineered . .so s 1 are the same idea but on *nix. Thankfully, they had time to learn from Microsoft's mistakes. What does the error message mean? Simply put, what the error message was trying to tell us was that when the code was compiled, we assumed the .so files would be in a given place, but they weren't. One common way to fix this is with
AI 资讯
Case Study: A Free Model Wrote a C++ Tree Hasher. The Reference Oracle Found Three Bugs.
Conclusion first: a free model drafted a working C++17 directory hasher in one pass. The draft compiled, ran, and was still wrong. A differential test against standard system tools found three real bugs before the tool ever touched a production cache. Generation was the cheap part. Verification was the deliverable. Background I needed a deterministic hash of a directory tree. The use case was cache invalidation for a small build pipeline: if any file content, name, or symlink target changes, the cache key must change. If nothing changes, the key must stay identical across machines and across checkouts. Hand-writing the tool is maybe 200 lines of std::filesystem code. The happy path is easy. The risk lives in ordering, symlinks, and metadata leaking into the hash. I turned the task into an experiment. MonkeyCode's free model access and free server option meant the model ran on a remote server while I kept verification on my laptop. Disclosure: This article was prepared as part of MonkeyCode's product outreach. The plan: let the model write the first version, then prove or disprove it against a reference oracle. The Contract The goal was not "a tool that compiles." The goal was a tool that matches a reference implementation on every input I could generate. I wrote the contract in three sentences: Same tree → same hash, on any machine. Different content, name, or symlink target → different hash. File metadata (mtime, inode) must not affect the hash. Implementation Step 1: the prompt. I gave the model the contract, the C++17 standard, and one constraint: a single file with no dependencies beyond the standard library. Step 2: the draft. The model returned one .cpp file in a single response. It compiled on the first try. That is the exact moment where most workflows stop. This one did not. Step 3: the reference oracle. Instead of reviewing the code line by line, I built a harness that compares the tool against a shell pipeline: find " $tree " -printf '%P\0' | sort -z | wh
AI 资讯
Why Your Generated Tone Clicks, and How an Envelope Fixes It
If you have generated a pure tone in code and played it back, you may have noticed a small click at the start, the end, or both. The tone itself is clean, but the edges are not. That click is not a bug in your sine wave. It is a real and well understood artifact, and the fix is a technique you will reuse in every sound you ever synthesize: an envelope. This piece builds directly on generating a basic tone from scratch . We take a tone that clicks, look at the actual sample values to see why, and apply an envelope to smooth it. Everything is plain C++ with no libraries, and every number here is captured from a real run of the code. Where the click comes from A tone is a list of samples tracing a sine wave. A speaker turns those samples into sound by physically moving: the sample value sets the position of the speaker cone at each instant, where 0 is its resting position and larger values push it further forward or pull it back. Playing the tone moves the cone in and out 44,100 times a second to recreate the wave. When playback starts, the cone is at rest, at position 0. But the first sample of the tone is usually not 0. It is wherever the wave happens to be at that instant, and if that value is far from zero, the cone has to move from rest to that position in a single sample step, about 22 microseconds at this sample rate. That near instant movement is the click. A cone moving gradually pushes the air smoothly and produces a smooth sound. A cone forced to a distant position in one sample makes a sharp, abrupt movement of the air, which your ear hears as a click or pop. You can see it directly in the numbers. Here are the first six samples of a plain 440 Hz tone at half amplitude: n=0 raw=0 n=1 raw=1026 n=2 raw=2048 n=3 raw=3063 n=4 raw=4065 n=5 raw=5051 The wave leaves zero and climbs fast. Between the silence before playback and sample 1, the signal jumps by 1026 in one step. The same thing happens at the end: if the tone stops while the wave is partway through a cy
AI 资讯
What Building a C++ Benchmarking Suite Taught Me About "Simple" Data Structures
We all know the Big-O complexity of basic data structures. Arrays are O(n) for search. Hash maps are O(1). Linked lists are... well, complicated. But when I set out to build hashbrowns — a C++17 benchmarking suite comparing arrays, linked lists, and hash maps — I discovered that theory and practice are very different beasts. Here's what I learned building this project from scratch, and why you should probably benchmark before you optimize. 🎯 The Goal Was Simple (Ha!) I wanted a clean, educational project that would: Implement dynamic arrays, linked lists, and hash maps from scratch Benchmark insert, search, and remove operations Find the "crossover points" where one structure beats another Export everything to CSV for analysis Sounds straightforward, right? Four months later, I had written a custom memory tracker, implemented multiple hash map strategies, added statistical bootstrapping for confidence intervals, and learned more about CPU caches than I ever wanted to know. 📚 Lesson 1: Polymorphism Has a Price (But It's Worth It) My first architectural decision was creating a common DataStructure interface: class DataStructure { public: virtual void insert ( int key , const std :: string & value ) = 0 ; virtual bool search ( int key , std :: string & value ) const = 0 ; virtual bool remove ( int key ) = 0 ; virtual size_t memory_usage () const = 0 ; virtual std :: string type_name () const = 0 ; // ... }; This made benchmarking elegant — I could write generic code that tested any data structure: for ( auto & structure : structures ) { timer . start (); structure -> insert ( key , value ); timer . stop (); } But virtual function calls have overhead. In tight loops, that vtable lookup adds up. I spent a whole weekend convinced my hash map was slower than expected... until I realized I was measuring the cost of polymorphism, not the data structure itself. The fix? I kept the clean interface for the benchmarking harness but used templates internally where performance-cri
AI 资讯
Design Notes for a Deterministic C++ Simulation Framework
“Same inputs, same result” sounds like a simple requirement. In a multithreaded simulation, it is an architectural constraint that touches data layout, scheduling, physics, randomness, floating-point behavior, serialization, and debugging. Determinism is valuable for replays, lockstep networking, regression tests, and reproducing hard failures. It does not happen automatically. Define the determinism boundary Start by stating what must match. Do two runs on the same executable and machine need identical results? Across different compilers? Across CPU architectures? Across operating systems? Those are increasingly difficult guarantees. A framework should document the supported boundary rather than using “deterministic” as a universal adjective. Control time Do not feed variable wall-clock deltas directly into a deterministic simulation. Use a fixed simulation step and decide how the renderer catches up or interpolates. Record inputs by simulation tick. If the system pauses or falls behind, handle that condition explicitly instead of silently changing the rules. Make randomness replayable Every pseudorandom decision needs a known generator, seed, and consumption order. A global generator shared by many systems is fragile because adding one random call in an unrelated feature shifts the sequence everywhere. Prefer scoped streams or deterministic derivation by system, entity, and tick where appropriate. Record seeds in test and replay artifacts. Schedule parallel work deliberately Multithreading introduces nondeterministic execution order. If two jobs write shared state, results may depend on timing even when data races are technically avoided. A robust job graph should make read and write sets visible, separate independent phases, and define deterministic merge or reduction rules. Avoid relying on thread completion order. Parallelize work whose outputs can be combined predictably. Keep entity iteration stable Entity-component systems often use dense arrays and swap-rem
AI 资讯
# Why I’m Rewriting a PHP Extension in C23, Not C++
I forked the DataStax Cassandra driver when it stopped compiling on PHP 8 and most of its maintainers had already moved on. My first instinct was to write the new parts in C++. I built a Zend wrapper class, used RAII throughout, and put smart pointers around zval s—the whole modern setup. It introduced memory bugs that took me days to track down, and I did not get a meaningful benefit in return. So the driver is being rewritten in C23. I want to explain why, because “just use C++; it’s safer” is the reflexive answer. For a PHP extension, I no longer think it is the right one. This is not an argument that C++ is a bad language. In an application where I own the allocator, error model, and object lifetimes, std::vector and std::unique_ptr earn their keep. A PHP extension is different: the Zend Engine owns those rules, and its rules are written in C. The problem is not that C++ cannot call the Zend API. Plenty of extensions do. The problem is impedance: each abstraction has to be taught PHP’s lifetime rules, and the teaching code can become more complicated than the work it was meant to simplify. These are the four places where that cost me real debugging time. PHP owns the allocator PHP has its own memory manager. Request-scoped memory is allocated with functions such as emalloc , ecalloc , and safe_emalloc , then released with efree . Zend tracks that memory and normally reclaims what remains at request shutdown. Persistent allocations use a separate API because they have a different lifetime. Plain malloc and free —and therefore ordinary new and delete —sit outside that request-memory model. The moment I put a std::vector<zval> in an extension, its backing storage uses the C++ allocator unless I replace it. The obvious fix is a custom allocator: template < class T > struct PhpAllocator { using value_type = T ; template < class U > PhpAllocator ( const PhpAllocator < U >& ) noexcept {} PhpAllocator () noexcept = default ; [[ nodiscard ]] T * allocate ( std :: size_t
AI 资讯
ESP32 HTTP Client Sem Dores de Cabeça: Consuma REST APIs com Zero Alocação de Memória
Consumindo REST APIs no ESP32 sem Estourar a Memória: Conheça o ESP32-HTTP-Client Se você já desenvolveu projetos IoT no ESP32 que se comunicam com APIs REST (seja para enviar dados de sensores para a nuvem, consultar status de serviços ou integrar com Firebase e AWS), provavelmente já enfrentou um destes problemas clássicos: Fragmentação e estouro de heap: O combo padrão HTTPClient + ArduinoJson precisa carregar todo o payload HTTP na RAM como String antes de desserializar o JSON. Em payloads médios ou grandes, isso gera Out of Memory ou travamentos intermitentes. Lentidão em requisições consecutivas: O HTTPClient padrão refaz o handshake TLS/TCP repetidamente, adicionando centenas de milissegundos a cada chamada. Código verboso e boilerplate excessivo: Mais de 15 a 20 linhas de código para instanciar clientes, extrair buffers, checar erros e navegar em nós JSON. Para resolver esses gargalos de forma elegante e moderna, foi criada a biblioteca ESP32-HTTP-Client . O que é o ESP32-HTTP-Client? O ESP32-HTTP-Client é um cliente HTTP/REST moderno, fluente e orientado a objetos para ESP32, projetado especificamente para sistemas embarcados de alta eficiência. Em vez de "fazer download da resposta, guardar na memória e depois processar", ele utiliza Direct Memory Binding (injeção direta) e Stream Parsing : os dados do JSON são lidos diretamente do stream da rede e injetados direto nas suas variáveis ou struct s em C++, sem armazenar o payload inteiro na RAM . // Uma linha. Zero strings intermediárias. Injeção direta em memória. client . get ( "/sensor" ). getBody ( "temperature" , & myFloatVariable ); Benchmark: ESP32-HTTP-Client vs Abordagem Tradicional Em testes controlados com 100 requisições HTTP consecutivas contendo payloads JSON (usando o endpoint /users do JSONPlaceholder), os resultados comprovam a economia de recursos: Métrica / Recurso HTTPClient + ArduinoJson (Padrão) ESP32-HTTP-Client Diferencial Heap alocado por requisição ~58.2 KB ~0.0 KB (15 bytes) ~99.9%
开发者
Fast & Lightweight Online CRC Calculator
Hi everyone, I built a simple, fast, and lightweight online CRC calculator tool for embedded systems and developers. URL: https://crc-calc.com Features: Supports standard CRC polynomials (CRC-8, CRC-16, CRC-32, etc.) Custom polynomial & bit reflection settings No signup required I'd love to hear your feedback or suggestions!
AI 资讯
Ctrl+S said "Saved." The file was 0 bytes.
This is a submission for DEV's Summer Bug Smash: Smash Stories powered by Sentry . Written with the help of AI (Claude). The bug, the fix, the validation setup, and every claim below are mine, and were verified against the real codebase and a real full disk. The report Someone lost a Magic: The Gathering decklist. They were playing on Cockatrice — the open-source MTG client — with their decks on a drive that had quietly filled up while Oracle pushed an update in the background. They added a card, hit Ctrl+S, and Cockatrice said it saved. The debug log agreed: [2026-05-28 22:31:42.031 I] Saved deck to "G:/cockatrice300/data/decks/edh-b2-gitrog-reanimate.cod" with format 1 - true - true . Success. The file was 0 bytes. The deck was gone. That was issue #6952 , filed by Mekkiss. The steps to reproduce are four lines long and completely damning: Have a full disk. Open a deck on the full disk Add one card to it Save the deck (ctrl+s) Observe that the deck is now a 0 byte file. Three ways to be wrong at once The save path lived in DeckLoader::saveToFile() . Stripped down, it looked like this: QFile file ( fileName ); if ( ! file . open ( QIODevice :: WriteOnly | QIODevice :: Text )) { qCWarning ( DeckLoaderLog ) << "Could not create or open file:" << fileName ; return std :: nullopt ; } bool success = false ; switch ( fmt ) { /* ... saveToFile_Native / saveToFile_Plain ... */ } file . flush (); file . close (); qCInfo ( DeckLoaderLog ) << "Saved deck to " << fileName << "with format" << fmt << "-" << success ; There are three independent failures stacked on top of each other here, and you need all three to lose data: 1. WriteOnly truncates on open. The instant open() succeeds, the existing deck is 0 bytes. Not after a successful write — at open time . The old deck is already destroyed before a single byte of the new one is written. On a full disk, open() still succeeds: truncating a file doesn't need free space. It frees space. 2. The serializers always returned true . sa
AI 资讯
🚀 Mastering OOP for Interviews : Understanding Abstraction from First Principles (C++)
Series: Master OOP for Software Engineering Interviews Introduction Ask ten beginner developers: "What is abstraction?" Most answers sound like this: "Abstraction is the process of hiding implementation details and showing only essential information." Technically, that's correct. But if I ask the next question: "Why was abstraction invented?" or "Can you explain abstraction using an Inventory Management System?" or "How is abstraction different from encapsulation?" many candidates struggle. That's because they memorized the definition instead of understanding the idea behind it. In this article, we'll learn abstraction the way experienced software engineers think about it—not by memorizing definitions, but by understanding why it exists, what problem it solves, and how it appears in every modern software system. 🎯 Learning Goals After reading this article, you should be able to: Explain abstraction without memorizing a textbook definition. Understand why abstraction exists. Identify abstraction in everyday life. Recognize abstraction in software systems. Confidently answer beginner interview questions. Build a strong mental model that makes future OOP concepts easier. Before We Learn Abstraction... Let's ask an important question. Why do programming languages even provide OOP? Imagine writing software for an e-commerce company. The system contains: Products Customers Orders Warehouses Payments Delivery Partners Notifications Discounts Reviews Thousands of features. If every developer had to understand every implementation detail before writing code, software development would become impossible. We need a way to reduce complexity. That solution is called abstraction. The Problem Abstraction Solves Imagine buying a new car. You sit inside. You: Press the accelerator. Turn the steering wheel. Shift gears. Press the brake. Simple. But underneath the hood, hundreds of complex operations happen every second. The engine burns fuel. The pistons move. The gearbox changes tor
AI 资讯
Python vs C++ for Embedded Systems: When to Use Each
When you first step into the world of embedded systems, one of the earliest and most consequential decisions you will face is choosing a programming language. Two names come up more than any others: Python and C++. Both are powerful, both have passionate communities, and both are genuinely useful — but for very different reasons and in very different contexts. This article is not about declaring a winner. It is about understanding why each language exists in this space, what trade-offs you are actually making, and how to make a confident, informed decision for your next project. Understanding the Fundamental Difference Before comparing features, it helps to understand why these two languages feel so different at a deeper level. C++ is a compiled, statically-typed, systems-level language . When you write C++, you are writing code that gets translated directly into machine instructions. You manage memory manually. You control exactly when objects are created and destroyed. The hardware does precisely what you tell it to, nothing more and nothing less. This directness is both its superpower and its source of complexity. Python, by contrast, is an interpreted, dynamically-typed, high-level language . A Python runtime sits between your code and the hardware, managing memory automatically through garbage collection, resolving types at runtime, and handling a lot of bookkeeping so you don't have to. This makes Python wonderfully expressive and fast to write, but it introduces overhead that matters enormously on constrained hardware. The mental model to hold onto is this: C++ gives you control, Python gives you speed of development . Both are valuable. The question is which one your project needs more. Where C++ Shines in Embedded Systems 1. Bare-Metal and Resource-Constrained Environments If you are programming a microcontroller like an STM32, an AVR ATmega, or an ESP32 running its native SDK, C++ is almost always your primary language. These devices often have kilobytes —
AI 资讯
MCP Explained: How It's Different from Traditional APIs
Imagine you are planning a surprise birthday party. You need invitations, food, decorations, and a cake. You call different places to get these things. You tell each one exactly what you need. "I need 20 red balloons." "I need a chocolate cake for 10 people." This is how many computer programs talk to each other. They use something called an API (Application Programming Interface). An API is like a menu. You pick what you want. You get exactly that. It works well for simple tasks. But what if your party plans change? What if you decide on a theme mid-conversation? Traditional APIs can feel a bit rigid then. They don't always remember your past requests. They don't understand the bigger picture. Now, imagine talking to a super-smart party planner. You start by saying, "I'm planning a party." The planner asks, "For how many people?" You say, "About 20." Then you mention, "It's for a birthday." The planner instantly suggests a cake size. It recommends decorations based on your earlier answers. This smart planner remembers everything you said. It understands your overall goal. It uses something like MCP (Model Context Protocol). MCP is a new way for computers to talk. It's like having a real conversation. It's much smarter than a simple menu order. You will soon understand why this difference is a game-changer. Traditional APIs: The Fixed Menu Approach Let's start with what you might already know. Many apps you use every day rely on APIs. An API is like a waiter in a restaurant. You look at the menu. You tell the waiter your exact order. "I want a cheeseburger with fries." The waiter takes your order to the kitchen. The kitchen prepares only that specific meal. Then the waiter brings it back to you. This is how most apps work together. One app sends a very specific request. It asks for a certain piece of information or to perform a specific action. The other app performs that task. It sends back a very specific response. Think of ordering from an online store. You click
AI 资讯
Capturing Attributes in Execution Calculations
Note: If you're new to execution calculations, I'd recommend starting with my previous post which covers them in detail, then coming back here. What is attribute capturing and why would you use it Attribute capturing refers to directly exposing certain attributes to your execution calculation from attribute sets, to be used in execution calculations. Capturing attributes lets you handle things like damage in a more complex way. So for example, you could have advantages and weaknesses against certain damage types, or an attribute like armor that should reduce incoming damage. This is just two use cases, but once you learn how to do it, you should naturally be able to see in what other ways they can be used. In this example, I will show how to get attribute magnitude from captured attributes and using them in calculations, which is the most common way of using captured attributes. Capturing attributes Defining the struct, declaring and defining attribute capture definitions In this post, I will show how to use a static struct to access all your captured attributes, as a good performance-aware solution. You are also free to choose not to use the struct. For the struct approach, the first step is to go to the .cpp of the execution calculation, and define your struct there. In the struct, we first use the DECLARE_ATTRIBUTE_CAPTUREDEF() macro, passing in the name of your attribute. After that, we make the constructor of the struct, and in the constructor we use the DEFINE_ATTRIBUTE_CAPTUREDEF() macro, passing in the attribute set that has the attribute, the attribute from it, whether the attribute from the Target or Source should be used (the Target is the ASC the ExecCalc is outputting its result to, and the Source is the ASC that called it), and a bool for if the captured attribute should be snapshotted (if the attribute should be frozen at ExecCalc GE application (snapshotted) or if the value should be read at execution time). In my case, I will show 2 examples of non-
AI 资讯
A small C++ library for sending structured commands and telemetry between devices — no schema files, just add your parameters and serialize
If you've ever tried to build a simple command/telemetry protocol between a PC and a fleet of SDR receivers, sensors, or embedded devices, you know the usual options aren't great: Roll your own binary format — fast, but you end up writing and maintaining custom serialization code for every device type, and debugging mismatched structs across machines is painful. Protobuf / FlatBuffers — robust, but require you to define your message layout in a schema file upfront, run a code generator as part of your build, and commit to a fixed structure. Adding a new device type or a new parameter means editing the schema, regenerating, recompiling everything. JSON over the wire — easy to debug, but heavy for anything real-time or bandwidth-constrained. I ran into this while working on a multi-SDR receiver system and ended up writing MessageFrame — a small C++17 library that lets you build structured messages dynamically, without any schema files or code generation. The basic idea Instead of defining a struct for each device type, you address each parameter with two strings — a device name and a parameter name — and the library handles the rest: // One message, multiple devices, assembled at runtime msgframe :: MessageFrame msg ( MSG_TELEMETRY , TYPE_PERIODIC , src = 1 , tgt = 2 ); msg . add ( "sdr_1" , "rx_gain" , VALUE ( 30.0 )); msg . add ( "sdr_1" , "center_freq" , VALUE ( 915'000'000.0 )); msg . add ( "sdr_1" , "sample_rate" , VALUE ( 2'000'000.0 )); msg . add ( "sdr_2" , "rx_gain" , VALUE ( 25.0 )); msg . add ( "sdr_2" , "lock_status" , VALUE ( true )); msg . add ( "psu_1" , "voltage" , VALUE ( 12.04 )); msg . add ( "psu_1" , "temp_c" , VALUE ( 47.3 )); // Attach raw IQ data alongside the parameters std :: vector < uint8_t > iq_buffer = { 0x01 , 0x02 , 0x03 , 0x04 }; msg . add_attachment ( "raw_iq" , std :: move ( iq_buffer )); // Serialize into a buffer, send over whatever transport you use std :: vector < uint8_t > out ; msg . serialize ( out ); send_udp ( out . data (),
AI 资讯
Three Small Shell Scripts That Make HackerRank/DevSkiller C++ Take-Homes Way Less Painful
If you've ever done a timed C++ coding assessment on a platform like HackerRank or DevSkiller, you know the friction isn't really the algorithm — it's the loop . Download a zip with a weird filename, unzip it, hunt for the project root, configure CMake, build, run GTest, fix one failing test, repeat... and somewhere in there you've burned ten minutes of your one-hour window just fighting the harness instead of writing code. These platforms' in-browser editors are fine for quick problems, but for anything involving multiple files (headers, sources, a real test suite), I'd rather work in my own terminal and editor. The catch is that you still have to get the project out of the browser sandbox, build it locally with the exact same toolchain (CMake + GTest), and then package it back up in a way the grader will accept. So I wrote three small bash scripts to remove that friction entirely. Sharing them here in case they save someone else the same ten minutes. The workflow Download the project archive from the platform (zip or tar.gz, filename is whatever the platform gives you — often randomized) Extract it — script 1 handles this regardless of filename or archive type Iterate — script 2 configures CMake once, then repeatedly builds and runs GTest, optionally watching for file changes Package — script 3 strips build artifacts and any local helper scripts, then zips it back up under a name that won't collide with the original download, ready to re-upload Script 1: extract_and_setup.sh Most of these platforms hand you an archive with an unpredictable filename. This script extracts whatever you point it at ( .tar , .tgz , .tar.gz , or .zip ), figures out which directory it unpacked to by diffing the folder listing before and after, and drops the build script into it automatically. #!/usr/bin/env bash # extract_and_setup.sh # Extracts $fname (tar, tgz, tar.gz, or zip) into the CURRENT folder, # then copies run_build.sh into the directory that was created. # # Usage: # ./extrac
AI 资讯
The Introduction
Operating system, a thing that everybody uses but no one talks about. While reading Operating Systems: Three Easy Pieces (OSTEP), my background in C and C++ fueled a growing fascination with memory allocation, virtualization, scheduling, and the intricate mechanics of operating systems. This would be a series of article, the number i am not sure, it will be the amount of content that someone might comfortably read in a 10 min Article. Keeping each piece to a solid 10-minute read is the perfect sweet spot for a developer to read over a cup of coffee. It gives you enough runway to explain a core concept, show the math, and link a practical C/C++ experiment without making their eyes glaze over. Why this Article ? We are often warned against “reinventing the wheel.” However, I firmly believe that building and optimizing modern software is impossible without a fundamental grasp of virtualization, memory allocation, and concurrency. Consider Docker: it functions almost entirely on OS-level virtualization features like Namespaces, cgroups, and isolated filesystems. Similarly, the highly optimized Memory Manager in PostgreSQL only works because it leverages the robust memory management systems already written into the OS kernel. This article aims to bring the core concepts of OSTEP to life through practical experimentation. By accompanying the theory with an open-source repository, my goal is to provide a clear, interactive learning experience that demystifies operating systems. I am not an operating system guru or a Principal Engineer with years of experience, but I hope to become one someday (assuming AI doesn’t replace me first… HeHe ). What I can do is dive in, explore, and try to understand these concepts by actually building things. Because of that, my goal here is to present the findings and experiments I explore rather than giving strong opinions — I’ll leave the comment section for those! Any support, feedback, or contributions from the community will be incredibly