#Python

Cross-Model Audits of AI-Written Code — Process, Not Faith
After using AI to port a calculator from a 35-sheet engineering spreadsheet, how do I know it is correct? This article covers three independent audit rounds by an agent from another provider, the rules to set before starting, confidence levels that keep claims within the evidence, and the classes of errors AI kept making in every round.

Migrating an Old .aspx Site to a JSON Catalog and Filtering Images
The owner of an old .aspx site asked me to rebuild it, but more than a decade of content was in a database I could no longer access. I collected the pages from the site itself to build a JSON catalog that preserved every legacy_id, then wrote a three-layer image filter to keep stray QR codes from becoming article covers.

Scripting Government PDF Forms and Making Safer ID Copies
Government PDFs distributed as fillable forms often cannot actually handle Thai text. Subdivided fields let digits run over the borders, and tone marks collide with vowels above the line. This article covers listing field names first, filling the fields and flattening them into page content, drawing Thai text with a font that includes all the vowel marks, and making actual-size ID copies with purpose-specific watermarks.

Reverse Engineering Spreadsheet Constants into Formulas
A sheet has a criteria table sitting beside the calculations, but no VLOOKUP connects them. People read the table and type values into cells themselves, and mistakes go unnoticed. This article covers separating formula cells from manually entered cells, then reconstructing a single formula that matches all 16 values in a multiplier column.

Speed Up Screen Recordings While Keeping the Original Clock
How to make a timelapse from a screen recording by speeding up idle sections more than active sections, using split, trim, and setpts, then joining them with concat. The main trap is that drawtext must come before setpts for the clock to follow the original timeline instead of the accelerated one.

A 26-Page Bilingual Site: Why .php Broke Every Link
The production page displayed PHP tags as raw text because the web server served .html as static files. Changing all 26 pages to .php broke links across the site. Then, after adding clean URLs, subpages bounced back to .php because the rewrite and 301 setup was only half done. This article includes the full .htaccess, eight cases for $base, and scripts that handle the whole site in one pass.

Making 20,000+ API Calls That Resume Without Leaving Corrupt Files
Generating 26,850 files through an API limited to 20 calls per minute requires three pieces—a system-wide throttle, resuming from what is already on disk, and a separate file validator—because files interrupted by network failures still have the right extension and a nonzero size.

The Monitor That Hammered Devices Until the Whole Farm Went Down
A monitoring loop that runs every 30 seconds and tries to recover every device that fails a ping sounds useful, until one device hangs and gets hammered repeatedly until the whole bus goes down. This article walks through ruling out hardware, tracking what was accessing the devices, and the settings that fixed it.

Cannot Delete Faces from a Terminal: API Returns notSupport
The door's face recognition terminal advertises a command to delete faces from FDLib, but every variation I tried returned notSupport. People who had left could still scan their faces and get in. This article covers the dead ends, the approach that actually worked using UserInfo/Modify with the smallest possible body, and the two-way user registry sync that runs every night.

No kWh Meter? Estimate Daily Electricity Costs from Current
Notes on converting CT current readings into energy usage and daily time-of-use electricity costs, from the three-phase power formula and the sampling interval built into it, through skipping outages and separating peak from off-peak with epoch arithmetic, to a daily summary table that made the web page seven times faster.

Reading an Unknown Modbus Device: Verify Before Interpreting
My notes on tracking down an undocumented device on an RS485 bus, from scanning baud rates and addresses one combination at a time to proving which registers hold live values and which are dead, and the lesson that guessing a device's type from number patterns alone can lead to months of misinterpretation.

Registrar and Billing NS Mismatch: Audit All Three Sides First
A debugging log for "Wrong response from the server" when changing nameservers in a billing system, which failed only for domains with leftover glue IP data, followed by a three-way audit of the registrar, billing system, and actual DNS zones before I felt confident changing anything.

Moving JSON Time Series to Columns Without Changing the Dashboard
I stored entire device frames as JSON arrays at one row per second. After two weeks, the tables had grown to 183 MB at the endpoint and 625 MB on the server, with JSON_EXTRACT queries that could not use an index — here is how I moved the data into int columns and had the API rebuild a sparse array without changing a single line of the dashboard.

Too Many Alerts Mean No Alerts: Tuning a Bot People Will Read
In one day, 28 events became 56 messages, and 57 percent of all events were repeat alerts every 30 minutes. This article covers recipient tiers, merging overlapping cycles, state that survives restarts, and why you must not add keepalive to a chat app session.

SketchUp Drawing Sheets with Automatic Labels and Dimensions
A finished model is not ready for submission yet. What the authorities accept is a set of paper sheets with building numbers, dimension lines, a north arrow, and a scale. This article covers extracting geometry from the model as numbers, rendering a top ortho view as black lines on white, and letting a script place numbers and dimension lines without overlaps, with overrides for individual items.

Mapping a Building by Phone and Finding True North with GNSS
ARCore gives room-corner coordinates in meters accurately enough to use, but its world frame has an unknown orientation, so the resulting plan is always rotated by some angle. The fix is to collect pairs of (AR position, GNSS reading) while working, then fit a rotation using weighted 2D Kabsch, with weights based on each fix's accuracy, to find both north and the origin's coordinates.

Rebuilding an Off-Scale PDF Plan at Real Dimensions
Presentation plans are often drawn block by block, with different scales for the x and y axes and different scales again for each room. Calibrating the whole page once and tracing it gets everything wrong. This article covers extracting coordinates from paper into metres by recalculating the scale for every room, counting objects with colour-blob BFS instead of by eye, and drawing them back into a model at their real dimensions.

News Stuck for Three Days Because the Feed Wasn't Sorted by Date
The news site's homepage showed the same day's stories for three days straight, even though scheduled jobs ran, translations finished, and every step reported success. The causes were an RSS feed sorted by relevance rather than date, string sorting of pubDate that actually sorted by weekday name, and requesting too few stories, leaving nothing after filtering before the rest even got a look.

Sending Automated Job Files to Telegram and the Bot API's 50 MB Limit
Set up a small local service that takes files from scripts and sends them to me on Telegram, with outbound delivery only, no polling, and no incoming commands, along with the actual Bot API limits to know before writing it, including 50 MB per file, images over 10 MB that must be sent as documents, and the Thai text trap in curl on Windows.

CDP Still Responds but Commands Fail After Chrome Updates Itself
I run several automation jobs on one machine that need a real browser, and ran into two problems at once — jobs fighting over tabs and getting each other's results, and Chrome overwriting its own files during an update while the process was still running, leaving the port responsive but Runtime.evaluate unusable. This article covers how I isolate jobs, detect the failure, and repair it automatically.

A 25-Hour Power Outage Left Scheduled Jobs Missing
The machine running my automated jobs lost power three times in three days, with the longest outage lasting 25 hours. When it came back, I found that jobs scheduled directly through Task Scheduler had skipped their runs entirely, while jobs managed by a dispatcher that checked the time itself had all caught up. This article covers the setting to enable, what to avoid during recovery, and the traps that led me to misread the status.

Automated Image Uploads Stopped for 4 Days: ssh Chosen by PATH
Write subprocess.run(["ssh", ...]) and leave the system to choose the binary from the caller's PATH. One day the caller changes, and the binary changes with it. File transfers fail silently for 4 days while reporting success every time. This article covers how I tracked it down, a helper that probes the actual binary before using it, and a completeness check before declaring the job done.

Managing Site Switches Remotely with UniFi's Cloud Connector Proxy
My workstation is in a different location from the site, with no VPN and no inbound ports open, but I still need to change VLANs per port, reserve fixed IPs, and track down failing cables. This article explains how Site Manager's connector proxy reaches the legacy API for both reads and writes without requesting a CSRF token, and the discipline needed when holding a key this powerful.

Set VLANs on a Hikvision Switch Using Its Web UI API
A smart managed switch whose Switch ISAPI endpoints return 403 can still be scripted if you inspect what its web UI sends. This article turns that API into a VLAN configuration script with a dry-run before apply, covering the traps I actually hit, including different field names for reads and writes, CCTV mode forcing 10 Mbps, and a calculated PoE load that exceeds the switch's budget.

Using an NVR to Reach Inaccessible Cameras with ISAPI and SDK
The cameras sit behind the NVR's second interface, and none are directly reachable. This article works through what the NVR's ISAPI can actually do, with 26 of 38 tested endpoints working, retrieves CCTV snapshots and RTSP through the NVR, finds when each channel last recorded, and falls back to HCNetSDK through ctypes to read device logs when ISAPI runs out of options.

Every Layer Reported Success While the Output Was Garbage
In one day, four layers of the same automated pipeline failed together, but every layer reported success without a single error line. The person who caught it was a user who said the site was not updating. These are the rules I wrote afterward so that failing stages could speak up for themselves.

Generating Thai PDF Quotes with Chromium and the Pitfalls I Hit
Building a system to generate PDF quotations from HTML with Chromium for multiple companies in a group and multiple templates, from an Executable doesn't exist error caused by looking for the wrong headless shell, to A4 layout and pagination, sanitizing Thai filenames, and a token-based document numbering system where an accidental slash broke the path.

Decoding a Bluetooth Label Printer Protocol from btsnoop
My Bluetooth label printer only had a mobile app and no way to connect it to my own system, so I enabled HCI snoop logging on my own phone, peeled away HCI/ACL/L2CAP/RFCOMM one layer at a time with a short Python parser, and compared the results with open-source libraries until I could read the commands and print directly from a script.

Auditing CCTV Directly with ISAPI and ffprobe RTSP, Bypassing the NVR
The NVR screen only tells you a camera is online. It does not tell you its model, how old its firmware is, or the actual stream resolution. In this article, I write a script to query ISAPI deviceInfo on each camera directly, then use ffprobe to read values from the actual RTSP stream to build an inventory and check the health of the camera system I maintain.

Planning 2.4GHz WiFi Channels 1/6/11 and Multi-Floor Heatmaps
A five-story building with seven APs per floor needs a 2.4GHz channel plan that avoids overlap both horizontally and vertically. This article covers the 1/6/11 principle, per-floor channel tables, the actual Tx power and RSSI threshold settings, and a Python script that labels floor plans with channels using PIL before a walkthrough survey to create a heatmap.

Inventory Switch and AP Ports with SNMP Walk and MAC Tables
You can build your own Layer 2 inventory without a controller or NMS. Write an SNMP walk with pysnmp asyncio to retrieve sysDescr, ifTable, and the bridge FDB, then convert OID indexes back into MAC addresses to find which device connects to which port on which switch.

Read Device Uptime Without SNMP/SSH/API Using TCP Timestamps
Many IP cameras, door controllers, and embedded devices have no SNMP, SSH, or API for querying uptime. But if they return TCP timestamps, I can read their boot time remotely without logging in even once.

My Firewall Permanently Banned Googlebot and Hid Sites from Search
I investigated why sites disappeared from search results and found Googlebot in my own firewall's permanent ban list. 408 of 500 entries came from the counter tallying WAF false positives. How I lifted the bans, wrote a script to fetch official bot IP ranges into the ignore list daily, and dealt with a grep trap and the side effects of blocking entire countries.

Repairing a Claude Code Session .jsonl File Too Large to Open at 38 MB
A single session stretched over 8 days grew to 38.61 MB / 11,537 records until the UI could no longer open its history. I wrote a Python script to process it line by line, trimming only the parts that were already unreadable to humans, bringing it down to 17.41 MB while preserving all 8,171 message uuid values in their original order, with no orphans.

Thai Data Migration Traps: VARCHAR, Idempotency, and OCR Vowels
Lessons from importing and migrating hundreds of thousands of Thai data rows — undersized VARCHAR columns silently truncating synthetic keys into collisions, idempotency requiring DELETE before INSERT to stop totals reaching 200%, collation treating su001 and SU001 as equal while storing both, and Thai vowels corrupted by OCR that need a normalization map before insert

Porting Excel Formulas to the Web: Floating-Point Traps
Porting engineering formulas from an Excel file to a web calculator produced differences around 1e-13 — not a math bug, but differences in how JS and Excel evaluate floating-point powers and multiplication order, with a method for reading formulas and values separately using openpyxl and building fixtures that actually catch regressions.

Inferring Cold Room Defrost Timing from Temperature Slopes
A cold room used to dehydrate glass noodles has no humidity sensors, but frost on the coil always flattens the temperature drop slope (dT/dt). This article uses the lumped-capacitance equation and time constant τ to detect frost and trigger demand defrost with working Python code, along with calculations for R404A COP and water removed per cycle.

Government ICT Computer Price Criteria + DIY Builds with Scripts
The December 2568 government ICT reference price criteria clearly define specifications for 20,000 baht office computers and 24,000 baht processing computers. In this article, I read the actual criteria item by item, then write a Python script to pull Advice prices and put together DIY builds to compare how much better the value is than buying prebuilt machines.

reCamera + Gimbal: RISC-V Cross-Compilation, CAN, and Node-RED
reCamera is an AI camera on a RISC-V chip mounted on two brushless axes, with rotation controlled over CAN bus at a resolution of 0.01 degrees. This article covers cross-compiling C for riscv64 musl, uploading to the device with scp, the CAN frame structure for motor control, reading back the 15-bit encoder, finding motor zero using current, a Node-RED dashboard + PID + auto-track, and STP files for 3D-printing the housing.

Control TP-Link Omada OC200 via REST API with Python
A practical guide to logging into an OC200 controller through REST API v2 with Python — handling CSRF tokens, self-signed certs, fetching sites/devices/SSIDs/DHCP/port-forward rules, and writing back with PATCH, including the read-only fields that cause a nonzero errorCode

Network-as-code on MikroTik RouterOS
A network-as-code approach for MikroTik — save /export output as a file, strip secrets with a sanitize script before sharing, split it into sections, then generate configs for multiple sites from Jinja2 templates + one set of variables

Reading a DTSU666 3-Phase Meter with Raspberry Pi over Modbus RS485
Notes on connecting a DTSU666 Smart Power Sensor to a Raspberry Pi over RS485, reading 3-phase electrical measurements from multiple meters using Modbus RTU, decoding 32-bit floats correctly, and storing them in SQLite/MySQL before exporting through MQTT and a REST API, including a negative-value bug I ran into myself

Screenshot Multiple Domains Directly from Origin, Bypassing Cloudflare
Need screenshots of dozens of domains for inspection, or want to confirm that the origin server (not the CDN cache) renders correctly — but Chrome's screenshot flag has been broken since version 132, and AV reverts hosts edits? This article uses Playwright to override DNS at the process level, solving both problems.

Reading Modbus RTU over an RS485 Gateway Without Phantom Values
Connecting multiple Modbus RTU meters/sensors on an RS485 bus through a serial-to-Ethernet gateway can produce phantom values, incorrect readings, or devices that do not actually exist — because a transparent gateway uses RTU-over-TCP, which requires assembling frames and calculating CRC yourself, and validating every reply. This article covers the rules I learned from doing it.

Create .ppk Files for plink/pscp on Windows Without Opening puttygen
puttygen.exe on Windows is GUI-only and cannot batch-convert OpenSSH to .ppk (it returns unrecognised option) — this article writes PPK v3 files directly with Python, including the hard-to-find HMAC-SHA-256 MAC formula, ready to use with plink/pscp/WinSCP.

Generate PromptPay QR (EMVCo) in Pure Python — No External Libraries
Want to generate PromptPay payment QR codes in your own POS/web system without calling a bank API? In this article, I build the EMVCo TLV string + CRC16 myself in pure Python, producing a payload that matches the Thai QR specification and can be scanned for payment by any banking app, along with the pitfalls that stop apps from reading it.

Recovering Old Website Images with Wayback Machine CDX API + Python
A website over a decade old had broken images throughout because it hotlinked to a dead CDN — I wrote a Python script to list images from the Wayback Machine CDX API and restore them to their original paths without touching a single character of HTML, with the full script I actually used.