Interactive Turing patterns in WebGPU
2024-05-29
WebGPU hello world in 2024
2024-05-25
What is Monte Carlo integration?
2024-04-24
How to escape JavaScript for a script tag
2024-04-24
On that flickering blur in Chrome
2024-04-23
What is the Metropolis algorithm?
2024-04-18
Automatic differentiation with dual numbers
Differentiation asks: how does tweaking the inputs change the output? To accurately differentiate an arbitrary function, perhaps the simplest way is using âdual numbersâ. 2024-04-02
What is numerical differentiation?
Differentiation asks: how does tweaking the inputs change the output? Numerical differentiation is a simple, general way to do this. But itâs not very accurate, and itâs inefficient when there are many inputs. 2024-04-01
Tell the LLM the business context
Tell LLM why its task is needed and how the output will be used. Youâll get better results, but programmers often donât do this because itâs anti-modular. 2024-03-30
Auto-summarizing my blog posts
Summarizing my blog posts using Claude Haiku. The benefits of providing business context. The benefits of iterating. 2024-03-26
It might not need a label
Often, content is self-labelling. Removing its label can make the content more scannable. Programmers often over-label. 2024-03-20
How can I capture all crashes in a web page?
Including uncaught errors, unhandled promise rejections, image load failures, Content Security Policy violations, and console.error
calls. 2024-03-14
How do errors in a web page reach the dev console?
Errors in JavaScript cause an ErrorEvent
on window
. Preventing the default action blocks console output. Resource errors follow the capture-bubble event model. 2024-03-13
A formula for responsive font-size
Try setting the root font-size to calc(1rem + 0.25vw)
instead of using media queries with fixed breakpoints. 2024-03-12
Setting font-size based on viewing distance
Estimating viewing distance from screen size to set optimal font-size, but other factors like user mobility, long-sightedness, and short-sightedness complicate the ideal font-size calculation. 2024-03-11
How does HotJar record your screen?
âSession replayâ tools record user interactions by capturing DOM changes, external resources, and viewport state, using efficient techniques like the MutationObserver API. 2024-03-09
The golden rule of PR reviews
The âgolden ruleâ of code reviews is to approve improvements. Approve pull requests that fix bugs, even if the implementation isnât ideal. 2023-10-07
Letâs get calibrated! A workshop
A workshop to show the importance of estimation, and teach self-calibration using facts about your company. 2023-09-13
How ForumMagnum builds communities of inquiry
2023-09-04
Build norms, not features
A primary feature of a collaborative product is its social norms. I look at LessWrong, a forum product, and show how it builds its social norms. 2023-08-28
Proving 1+1=2 and other advanced theorems
Lean is used to define and prove the commutativity of addition on natural numbers. 2023-06-14
Proofs about programs: an interactive tutorial
2022-12-14
Riceâs theorem: an interactive tutorial
2022-11-02
Gödelâs first incompleteness theorem: an interactive tutorial
2022-10-17
Differential equations: an interactive tutorial
2022-10-13
Email providers should be regulated
2022-09-10
Time series: an interactive tutorial
2022-09-08
A/B Testing: an interactive look at Thompson sampling
2022-07-15
The quadratic formula: an interactive tutorial
2022-02-24
The halting problem: an interactive tutorial
2022-02-09
Imputation: an interactive tutorial
2022-01-17
How to export a model for TensorFlow.js
Exporting a TensorFlow model, converting it to the TensorFlow.js format, and running it in the browser with interactive input. 2021-03-09
TensorFlow 2 âhello worldâ
A TensorFlow 2 program that learns the cost per gram of chocolate by training a linear model on example chocolate bar weights and prices. 2021-02-17
What is a Single-Shot Multibox Detector?
A neural network architecture that can output bounding boxes. It uses a fixed set of âanchor pointsâ and predicts offsets and sizes for each anchor. 2021-02-16
How to run a pre-trained model in TensorFlow.js
Load the model, convert the input to a tensor, preprocess the tensor to match the modelâs expected format, run inference with .predict()
, and decode the prediction tensor. 2021-02-15
How to replace GIF with HTML video in 2021
To replace a GIF with an HTML <video>
element in 2021, use a long list of attributes disable unwanted browser behaviors. 2021-01-19
Measuring audio volume in JavaScript
A demo of real-time microphone volume measurement using the Web Audio APIâs AnalyserNode
. 2021-01-18
MP4 can encode superwhite and superblack, thanks to analog TV
Screen recording accidentally encoded superwhite/superblack due to obsolete yuv420p(tv)
color space; rescaling fixes it. 2021-01-13
NPM addon package hello world
How to create an NPM addon package from C++ code using the node-gyp
tool and a binding.gyp
file, with a JavaScript wrapper module for a more idiomatic API. 2020-12-07
Homogeneous coordinates in 3D
I implement homogeneous coordinates in 3D, including rotation, scaling, translation, and projection matrices, and use them to create an animated 3D house scene. 2020-11-29
Homogeneous coordinates in 2D, from scratch
Homogeneous coordinates enable a matrix to translate points. I show a six-line JS library. 2020-11-28
A matrix library in 5 lines of code
A 5-line matrix library, and how to derive it without rote memorization. 2020-11-27
How do classes work in JavaScript?
JavaScript class
syntax is just syntactic sugar over the traditional prototype-based inheritance. Deconstructing a simple class
reveals the underlying constructor functions, prototype assignment, and use of super
to call the superclassâs constructor. 2020-11-03
How do JavaScript prototypes work?
JavaScript has two different âprototypeâ concepts: an own property with the string key âprototypeâ, and a parent slot. Donât confuse the two! 2020-11-02
What does the dot do in JavaScript?
foo.bar
, foo.bar()
, or foo.bar = baz
- what do they mean? A deep dive into prototypical inheritance and getters/setters. 2020-11-01
The many sizes of a video element
A playground to explore the various widths and heights of a <video>
element, as reported by different browser APIs, when displaying a webcam stream with dynamically adjustable constraints. 2020-10-23
Why is my WebGL texture upside-down?
WebGLâs texImage2D
function expects pixels in bottom-to-top order, while browsers provide them top-to-bottom. UNPACK_FLIP_Y_WEBGL
fixes this behavior. 2020-10-22
Use varyings for texture2D coordinates!
Using a varying
to pass the texture coordinates to the fragment shader avoids the need to perform divisions in the fragment shader, improving performance. 2020-10-21
How do JavaScript async iterators work?
Async iterators use the Symbol.asyncIterator
method to define the iteration protocol. 2020-10-19
MediaRecorder hello world
The MediaStream Recording API converts a MediaStream to a Blob of compressed video and audio. A demo where you can record a 5-second clip. 2020-10-17
Babel JS from the ground up
Babel is a JavaScript compiler that transforms JavaScript code. Here I use its API programmatically. 2020-10-16
How does require
work in Electron?
require
in Electron works like Node.js, allowing you to load modules, but each Renderer process has its own isolated module state. Relative module resolution depends on whether you use loadFile
or loadURL
. 2020-10-15
The Electron process architecture is the Chromium process architecture
An Electron instance is basically a Chromium instance. It just has some Node.js integration. 2020-10-14
WebRTC group chat hello world
A WebRTC-based group chat application that uses Ablyâs publish-subscribe system for signaling. Clients connect directly via peer-to-peer data channels, with Ably facilitating the initial connection. 2020-10-13
A head in a box with BlazeFace
A method for calculating a bounding circle around a head, using facial landmarks from BlazeFace. Plus a live demo that you can run on your own face. 2020-10-12
Head tracking with BlazeFace
A method for calculating a bounding circle around a head, using facial landmarks from BlazeFace. Plus a live demo that you can run on your own face. 2020-10-11
How to self-host a TensorFlow.js model
Involves downloading the model manifest file and associated binary weight files, to avoid downloading large models every application launch. 2020-10-07
How to make a floating head
Creating a âfloating headâ effect using WebGL and the BodyPix machine learning model to segment the face from a webcam feed. 2020-10-06
How does the Node.js REPL display previews?
Node.js REPL uses the inspector
module to safely evaluate expressions as you type, using V8âs evaluation with throwOnSideEffect: true
to avoid executing harmful code. 2020-10-05
What are UMD modules? One final module system to rule them all (except ES modules which are a different thing)
UMD modules are a way to write JavaScript code that can be used in any module system (e.g. CommonJS, AMD, or as a global variable). 2020-10-04
What are AMD modules? Fetch your sick bag
âSimplified CommonJS wrappingâ feature is a hacky attempt to support synchronous require
calls by using regexes. Itâs gross. 2020-10-03
Executables in npm?
NPM packages can contain executables, not just Node.js modules. NPM provides features to help distribute and run these executables, such as the bin
field in package.json
and the npm run-script
command. 2020-10-02
How to publish an npm package
Publishing an npm package @jameshfisher/numsyslib
with a stringifyRoman
function that converts a number to a Roman numeral. 2020-10-01
What is npm?
NPM is Node.jsâs package system, allowing installation of arbitrary stuff, not just Node.js modules. Packages are folders, tarballs, URLs, or version identifiers published to the NPM registry. 2020-09-30
How do ECMAScript modules work in Node.js?
ECMAScript modules and CommonJS modules in Node.js are interoperable. Node.js looks at file extensions and package.json
fields to determine the module type. ECMAScript modules can only use import
, while CommonJS modules can only use require
. 2020-09-29
JavaScript live bindings are just concatenation
ES modules are just concatenated source files, with some error checking and variable renaming. Live bindings are an illusion - theyâre just ordinary variables at the top-level scope. 2020-09-28
What does the require
function do in Node.js?
The require
function in Node.js loads modules, either local files or external packages. I show the algorithm that searches node_modules
directories and package.json files. 2020-09-27
What are JavaScript source maps?
Source maps map generated JavaScript to original source files, allowing debugging of the original code in the browserâs dev tools. 2020-09-26
JavaScript modules for grumpy developers from 2005
JavaScript modules enable better dependency management and scoping. A guide for developers like me who still use <script>
tags everywhere. 2020-09-25
Using BodyPix segmentation in a WebGL shader
A WebGL shader that uses BodyPix segmentation to set the alpha channel. 2020-09-24
Running BodyPix on a video stream
Applying the BodyPix machine learning model to a video stream for real-time person segmentation, with separate render and segmentation loops to optimize performance. 2020-09-23
Resizable boxes in pure CSS!
The CSS resize
property allows any element to be resized, not just <textarea>
! But there are some gotchas. 2020-09-22
BlazeFace hello world
A demo that uses the BlazeFace model from TensorFlow.js to detect faces in a webcam stream, and draws the detected landmarks on the video. 2020-09-21
Step-away background removal
A step-away background removal technique using WebGL, which compares both chrominance and luminance differences between the webcam feed and a captured background image to create a transparent mask. 2020-09-20
Edge detection with Sobel filters
A WebGL fragment shader that implements the Sobel filter, a method for detecting edges in an image. A demo processes your webcam video stream. 2020-08-31
BodyPix hello world
BodyPix is a TensorFlow model for person segmentation. A demo of BodyPix in the browser. 2020-08-16
Why does my WebGL alpha-transparency look wrong?
WebGL alpha-transparency may appear wrong because of premultiplied alpha. Fix it by setting premultipliedAlpha: false
when creating the WebGL context. 2020-08-12
Production-ready green screen in the browser
A green screen implementation in the browser using WebGL and chroma key. Includes a live demo. 2020-08-11
How to implement green screen in WebGL
An green screen implementation in the browser using WebGL and a chroma key shader. Includes a demo that replaces sufficiently green pixels with magenta. 2020-08-10
How to implement green screen in the browser
A green screen implementation in the browser using WebGL and chroma key. Includes a live demo. 2020-08-09
Smear phishing: a new Android vulnerability
Trick Android to display an SMS as coming from any contact. Convincing phishing vuln, but still unpatched. 2020-08-06
What is the order of NSWindow
levels?
The order of NSWindow
levels is defined by the CGWindowLevelKey
constants, with lower numerical values being behind higher ones. The NSWindow.Level
enum provides a more limited set of semantic level names, with some levels overlapping. 2020-08-03
devices(for:) was deprecated in macOS 10.15: Use AVCaptureDeviceDiscoverySession instead
Use AVCaptureDeviceDiscoverySession
instead of the deprecated AVCaptureDevice.devices(for:)
to discover video capture devices. 2020-07-31
Why is the contentRect
of my NSWindow
ignored?
Calling setFrameAutosaveName
on an NSWindow
causes its size and position to be saved to user defaults, overriding the contentRect
passed to the constructor. To avoid this, do not call setFrameAutosaveName
. 2020-07-10
A probabilistic pub quiz for nerds
A âtrue or falseâ quiz where you respond with your confidence level, and the optimal strategy is to report your true belief. 2020-04-26
How to resolve âthe app shows no response upon launchâ in App Review
To resolve âthe app shows no response upon launchâ in App Review, identify and handle potential sources of fatal errors, such as uncaught exceptions, force-unwrapping nil values, unsafe downcasts, and out-of-bounds array access. Display a helpful error message instead of crashing. 2020-04-24
Time is running out to catch COVID-19
Simulation shows itâs rational to deliberately infect yourself with COVID-19 early on to get treatment, but after healthcare capacity is exceeded, itâs better to avoid infection. Includes interactive parameters and visualizations. 2020-03-14
How to record a canvas to video
Using the MediaRecorder
API to record a canvas element as a WebM video file, allowing the user to download the recorded video. 2020-03-13
Simulating epidemics in WebGPU
Simulating an epidemic in WebGPU using a direct index into an array of cells, avoiding the issues encountered with the previous WebGL implementation that used a texture. 2020-03-12
Game of Life in WebGPU
Implementing Conwayâs Game of Life in WebGPU, a 2D cellular automaton simulation. Uses compute shaders to update the game state and render the cells. 2020-03-03
Rule 110 in WebGPU
A WebGPU-powered simulation of the Rule 110 cellular automaton, rendering a dynamic image on a canvas. 2020-03-02
How to write an ArrayBuffer to a canvas
I write an ArrayBuffer to a canvas by interpreting the buffer as pixel data and using ImageData to provide the dimensions. 2020-03-01
When in doubt, donât blur it out
Blurring sensitive information in images may not effectively protect privacy, as the original content can often be recovered using deblurring techniques. 2020-02-29
Simulating epidemics with WebGL
A spatial SIR model for simulating epidemics, implemented using WebGL fragment shaders. Tracks susceptible, infected, and recovered populations in a 2D grid. 2020-02-23
Why does this RNA virus look like DNA?
RNA genomes of viruses like COVID-19 are often sequenced as complementary DNA (cDNA) for practical reasons, though the actual genome is made of RNA with uracil instead of thymine. 2020-02-16
Simulating epidemics
An interactive simulation showing how disease characteristics and human behavior can significantly impact the spread of an epidemic. 2020-02-15
Diffing coronaviruses
Comparing the genome sequences of the Wuhan coronavirus and a bat coronavirus using diff
and NCBI BLAST reveals an 89% similarity. 2020-02-09
Is there a route between these two nodes in this directed graph?
An algorithm in Haskell using a breadth-first search to find the reachable set of nodes. 2020-01-24
How to check if a binary tree is balanced
An O(n) algorithm to check if a binary tree is balanced, by passing up the height from recursive calls. 2020-01-23
How to sort a stack using one additional stack
We can model âinfinite tapeâ using two stacks. Then we can navigate the list in both directions. This lets us bubble-sort the list in O(n^2) time. 2020-01-22
Implementing a queue using two stacks
Implement a queue using two stacks, with one stack for the back of the queue and one for the front. Reverse the back stack onto the front stack when dequeuing to maintain the queue order. 2020-01-21
Towers of Hanoi in Haskell
A Haskell solution to the classic Towers of Hanoi problem. 2020-01-20
A stack with minimum element
A stack with a min
operation that runs in O(1) time. Store the current minimum alongside each element, or use run-length encoding to compress the stack of minimums. 2020-01-19
Implementing a queue using a linked list
The head is the front of the queue, allowing efficient dequeue. The tail is the back of the list. To enqueue efficiently, we keep a reference to the tail. 2020-01-18
Implementing a stack using a linked list
The head of the list is the top of the stack. 2020-01-17
How to check whether a linked list is a palindrome
Find the middle node of the linked list using the ârunnerâ trick. Reverse the first half, then compare the nodes pairwise from the middle outwards. Restore the list to its original state before returning. 2020-01-16
How to find the middle of a linked list
A trick to find the middle of a linked list by using two pointers, slow
and fast
, where fast
moves twice as fast as slow
. 2020-01-15
How to reverse a linked list
Reverse a linked list by treating it as a stack, popping elements and pushing them onto a new list. An implementation in C without a separate stack. 2020-01-14
How to partition a linked list
A C function to partition a linked list around a value x
, running in optimal time and space. 2020-01-13
How to delete a node from the middle of a linked list
To delete a node from the middle of a linked list, copy the value and next pointer of the next node to the current node, then free the next node. 2020-01-12
How to find kth last node of a linked list
Use the ârunnerâ technique with two pointers - one leading by k nodes - to find the kth last element of a singly linked list without knowing the list length in advance. 2020-01-11
How to remove duplicates from an unsorted linked list
To remove duplicates from an unsorted linked list with no extra memory, use a nested loop to check each node against all others, removing duplicates as you go. Time complexity is O(n^2). 2020-01-10
How to rotate a square matrix in-place
An in-place algorithm to rotate a square matrix by 90 degrees. The key is to rotate 4 corresponding points using a formula, applying this to all points in the top-left corner. 2020-01-09
Run-length encoding in C
Compresses a string by replacing consecutive repeated characters with the character and its count. The solution requires two passes to first calculate the length of the compressed string, then generate it. 2020-01-08
How to percent-encode strings in-place
A C function to replacing spaces with "%20"
in-place, by iterating from the end, preserving true string length. 2020-01-07
Determine whether one string is a permutation of the other
A C function to determine if one string is a permutation of another, using a character distribution representation for optimal time and space complexity. 2020-01-06
How to reverse a string in C
An in-place string reversal function in C, starting by swapping the first and last characters, then iterating towards the middle. 2020-01-05
Determine if a string has all unique characters
A recursive algorithm to determine if a string has all unique characters, with an analysis of its time complexity. 2020-01-04
How does Glitch refresh my app?
Glitchâs âShow in a new windowâ feature uses the window.open
API to open a new window, and then manipulates the contents of that window by updating its location
property when the source code is edited. 2020-01-01
Browsing my genome
Exploring my 23andMe genome data - a text file of single nucleotide polymorphisms, not a full DNA sequence, requiring a reference genome to interpret. 2019-12-30
What are CSS percentages?
CSS percentages have varying meanings depending on the property. They can refer to the containing blockâs width/height, the elementâs own font size, or other specific measurements. 2019-12-29
Les Aventures De Toupac - a pixel art game
A pixel art game developed over Christmas, with code on GitHub and development on Glitch. 2019-12-28
What are CSS variables?
CSS variables, also called custom properties, allow defining and using dynamic values in CSS. They cascade and inherit like other CSS properties, with the var()
function used to reference them. 2019-12-21
Summary of âZero to Oneâ, Chapter 9: Foundations
Startups must get the foundations right from the start. Choose co-founders carefully, keep the board small, hire full-time employees, and compensate with equity over high salaries, even for the CEO. 2019-10-07
How to name a product with reduplication
Product names often use reduplication, like âTic Tacâ or âFit Bitâ, to mimic the babbling sounds of babies. This creates a sense of familiarity and simplicity. 2019-10-06
What is simulated annealing?
Simulated annealing is a variation of trial-and-error optimization that generates mutations of the current best guess, and gradually reduces the magnitude of the mutations over time, similar to how metals cool. 2019-05-28
What is a McCulloch-Pitts neuron?
A mathematical model where the neuron is a function that takes binary inputs and produces a binary output based on a threshold. The model can implement basic logic gates like AND and OR, but not more complex functions like XOR. 2019-05-27
I can see your local web servers
Script detects and exposes your local web servers on localhost
and your local network. 2019-05-26
JavaScript generators are also consumers!
Generators in JavaScript can act as both producers and consumers of data. An example Metric
generator batches and sends data using the yield
keyword. 2019-05-18
What is function*
in JavaScript?
JavaScriptâs function*
defines a generator function, which can be used to generate and consume data. 2019-05-17
What are symbols in JavaScript?
Symbols are a new fundamental data type in JavaScript, introduced in 2015. They are used to create unique object property keys that wonât clash with other properties. 2019-05-16
How to remember stopping distances for the Highway Code
Formulas to calculate stopping distances for different speeds, using thinking and braking distances, instead of memorizing a table. 2019-05-15
How do JavaScript iterators work?
JavaScript iterators are objects that implement a specific protocol, providing a way to iterate over a sequence of values. The for...of
loop is syntactic sugar for manually creating and using an iterator. 2019-05-10
Browser webcam hello world
Demo of the userâs webcam in a <video>
element, using the navigator.mediaDevices.getUserMedia()
API. 2019-05-06
How can I add tags to a Jekyll blog?
A plugin to create tag pages on a Jekyll blog, and a minimal layout for those tag pages. 2019-05-05
Does Redis Pub/Sub work with master-slave replication?
Redis Pub/Sub works with master-slave replication, allowing messages published on the master to be replicated to the slave and received by subscribed clients on the slave. 2019-05-04
The inception bar: a new phishing method
A new phishing technique that displays a fake URL bar in Chrome for mobile. A key innovation is the âscroll jailâ that traps the user in a fake browser. 2019-04-27
Node.js addon hello world
I create a native Node.js addon called addon
in C++ using node-gyp
. The addon exports a hello()
function. 2019-04-20
Electron hello world
Installing Electron, creating an HTML web page, and writing the main entry point script to load the page. 2019-04-19
VĂ©los, vins et vassaux dans la Loire
Cycling tour of Franceâs Loire Valley, visiting chateaux, wineries, and medieval attractions over 5 days, from Tours to Nantes. 2019-04-09
What is matched betting?
Matched betting exploits differences in odds between betting exchanges to guarantee a profit, by betting on both sides of a proposition. 2019-04-02
What is a prediction market?
Prediction markets allow people to bet on the outcome of future events, with the traded share prices reflecting the marketâs probability estimate for those events. 2019-04-01
What is a betting exchange?
Betting exchanges like Betfair allow users to act as bookmakers, offering bets at their own chosen odds. This contrasts with traditional bookmakers who set the odds. 2019-03-31
Probability notation for odds
Different notations for betting odds, including fractional, decimal, and probability. Probability notation is shown to be the most transparent, revealing the bookmakerâs expected positive gain. 2019-03-30
The hacker hype cycle
I got started with simple web development, but because enamored with increasingly esoteric programming concepts, leading to a âtrough of hipster technologiesâ before returning to more productive work. 2019-03-23
Why canât I set the font size of a visited link?
CSS visited link styles are limited for security reasons, as they could reveal a userâs browsing history. Color can be changed, but getComputedStyle
will lie about it. 2019-03-08
Project C-43: the lost origins of asymmetric crypto
Bob invents asymmetric cryptography by playing loud white noise to obscure Aliceâs message, which he can cancel out but an eavesdropper cannot. This idea, published in 1944 by Walter Koenig Jr., is the forgotten origin of asymmetric crypto. 2019-02-16
Summary of âZero to Oneâ, Chapter 8: Secrets
Valuable businesses are built on secrets - things that are hard but still doable. Look for secrets by thinking contrarily and exploring outside the mainstream. When you find a secret, share it only with the people you need to. 2019-01-27
How Hacker News stays interesting
Hacker News buried my post on conspiracy theories in my family due to overheated discussion, not censorship. Moderation keeps the site focused on interesting technical content. 2019-01-26
My parents are Flat-Earthers
For decades, my parents have been working up to Flat-Earther beliefs. From Egyptology to Jehovahâs Witnesses to theories that human built the Moon billions of years in the future. Surprisingly, it doesnât affect their successful lives very much. For me, itâs a fun family pastime. 2019-01-20
How to fix âActivating bundler (< 2) failedâ error in your jekyll build
Jekyll build breaks due to Bundler 2 incompatibility. Fixed by removing Bundler 1 version from Gemfile.lock. 2019-01-09
How to run Redis Sentinel
Redis Sentinel provides high availability for Redis. We start a Redis master, then three Redis Sentinel instances. They discover each other, then we trigger a failover. 2019-01-08
How to make a webserver with netcat (nc)
Use nc
(netcat) to create a web server that returns custom HTTP responses. 2018-12-31
How I start Jekyll blog posts
I use a custom blogpost
command to quickly create new blog post files with the current date and post title. 2018-12-30
How to draw sprites on an HTML canvas
I demonstrate animating a cat walk cycle on an HTML canvas using a sprite sheet image and the drawImage
method. 2018-12-29
A cat walk cycle
A pixel art animation of a âwalk cycleâ, created using GIMP, for use in a retro game. 2018-12-28
What is document.cookie?
Cookies are client-side storage that get sent with every HTTP request. A cookie is scoped to a domain suffix, a path prefix, and a time range. The API is old and weird. 2018-12-22
A history of time in 40,000 pixels
A visualization of how frequently different years are referenced in writing over time, showing patterns in how the past and future are viewed. 2018-12-18
How does a Morris approximate counter work?
The Morris approximate counter is incremented probabilistically. 2018-12-17
What is the API for Google Ngram Viewer?
The Google Ngram Viewer API is undocumented, but can be accessed by replacing the graph
in the URL with json
. This returns a JSON response with the frequency of the searched phrase over time. 2018-11-25
How to count at scale at Redis Day London 2018
2018-11-15
Strava route builder API
How to use the undocumented Strava Route Builder API to get routes between two points, including a JavaScript example. 2018-10-13
Summary of âZero to Oneâ, Chapter 7: Follow the money
The power law distribution is key in venture capital, companies, and careers. Focus on finding and growing the few with vast potential, rather than trying to fix failures. 2018-09-23
Summary of âZero to Oneâ, Chapter 6: You are not a lottery ticket
The USA believes in the future is unpredictable but will get better. A false contradiction. Success is not random, as evidenced by serial entrepreneurs who have founded multiple billion-dollar businesses. 2018-09-19
Summary of âZero to Oneâ, Chapter 5: Last mover advantage
To build a lasting monopoly, focus on proprietary technology, network effects, economies of scale, and branding. Start small, sequence your markets, and aim to be the last mover in your industry. 2018-09-17
Summary of âZero to Oneâ, Chapter 4: The ideology of competition
Competition is often destructive and distracting. Wise companies either diverge into new space or merge into a monopoly, rather than imitate each other through competition. 2018-09-16
Summary of âZero to Oneâ, Chapter 3: All happy companies are different
Profitable companies are monopolies, not competitors. Competition drives down prices but also wages and quality. Monopolies are not permanent, as new markets and products can create new monopolies. 2018-09-15
Summary of âZero to Oneâ, Chapter 2: party like itâs 1999
The dot-com bubble showed that conventional wisdom is often wrong. Lessons learned, like being âleanâ and avoiding new markets, prevent bold visions and are the opposite of what companies like Google and PayPal needed. 2018-09-14
Donât say âsimplyâ, at Write the Docs 2018, Prague
2018-09-13
Month of Jack Robinson
Jack Robinson is an instant messaging app where your message is shared as you type, with no âsubmitâ button, reducing finger-to-eye delay compared to traditional chat apps. 2018-07-29
How is the Redis sorted set implemented?
Redis sorted sets are implemented using a hash table for efficient key-value lookups and a skip list for efficient score-based ordering. I show a Haskell implementation that uses a forward map for keys and a reverse map for scores. 2018-04-22
The dots do matter: how to scam a Gmail user
Gmailâs âdots donât matterâ feature lets scammers create an account on, say, Netflix, with your email address but different dots. Results in convincing phishing emails. 2018-04-07
A summary of Managing Oneself by Peter Drucker
Discover your strengths, work styles, and values through feedback analysis. Align your career and relationships with your unique characteristics. 2018-04-01
What are /dev/stdout
and /dev/stdin
? What are they useful for?
/dev/stdin
, /dev/stdout
, and /dev/stderr
are special files in the /dev
directory that represent the standard input, output, and error streams of a process. They can be used to connect processes in a shell pipeline without creating temporary files. 2018-03-31
Rounding up to the next power of two in C
An efficient algorithm to round up to the next power of two in C, using bitwise operations and compiler intrinsics for constant-time performance. 2018-03-30
What is HTTP keep-alive? What is HTTP request pipelining?
HTTP keep-alive allows reusing the same TCP connection for multiple requests, avoiding the overhead of opening a new connection. HTTP request pipelining sends multiple requests without waiting for their responses. 2018-03-27
How to create an SSH certificate authority
Creating and using an SSH certificate authority, an alternative to the default âtrust on first useâ model. 2018-03-16
A lambda calculus interpreter in Haskell
A lambda calculus interpreter in Haskell, using de Bruijn indexing and lazy evaluation, with simple integer literals added. 2018-03-15
Hello world in Linux x86-64 assembly
An x86-64 program that writes to stdout and exits. 2018-03-10
Writing a parser in Haskell
I write a parser for JimScript, an imperative programming language, in Haskell. The parser goes through three stages: tokenization, nesting, and parsing. 2018-03-09
An interpreter in Haskell
An interpreter for an imperative language in Haskell, featuring integers, operators, global variables, control flow, and I/O primitives. 2018-03-06
Creating a UDP connection with netcat
nc
can create UDP connections. UDP connections are established when the first data packet is sent, and terminated when the server becomes unreachable. ICMP messages notify the client of an unreachable server. 2018-03-04
How does network address translation work?
NAT allows multiple devices in a local network to share a single public IP address. Routers modify IP and port information in network packets, and manage a translation table. 2018-03-02
What does Linux do with a lost TCP connection?
Linux uses exponential backoff to retry dropped TCP connections, with a configurable retry limit. 2018-02-27
What are TCP sequence numbers?
TCP uses sequence numbers to map unordered IP packets to an ordered byte stream. The sequence number field is 32 bits, but wraps around to 0 after reaching the max value. The sender chooses a random âinitial sequence numberâ during the connection handshake. 2018-02-24
Running tcpdump
on a TCP connection
tcpdump
captures network traffic. Capture and analysis of a TCP connection, including the 3-way handshake and message exchange. 2018-02-23
How does swapping stdin and stderr work?
The magic shell string 3>&2 2>&1 1>&3-
swaps stdout and stderr. It does with the dup2
system call to swap file descriptors. 2018-02-22
Hello world in C inline assembly
A C program that writes âhello, world!â to the console using inline assembly instead of standard library functions, demonstrating direct system call invocation. 2018-02-20
How to make a system call in C
Replacing printf
with write
, and finally directly using the syscall
function with inline assembly. 2018-02-19
Diary writing prompts
Struggling with mundane diary entries, I implement random writing prompts to reinvigorate the process. 2018-02-17
What is the routing table in Linux?
When a packet arrives, Linux determines which network interface should handle it. It uses the first rule in the routing table that matches the destination address. Surprisingly, all 127.0.0.0/8
addresses go to the loopback interface. 2018-02-12
How does an IP address get translated to a MAC address?
IP addresses are mapped to MAC addresses using the Address Resolution Protocol (ARP). The OS maintains an ARP cache to store these mappings. 2018-02-11
What is a subnet?
Subnets divide the IP address space hierarchically using bitstring prefixes. We check if an IP address is in a subnet using C. 2018-02-10
How does reverse DNS lookup work?
Reverse DNS lookup maps an IP address to a domain name by querying PTR
records. The mapping is not always consistent with the forward DNS lookup. 2018-02-09
Run-length encoding in C
A C implementation of run-length encoding, a compression scheme that works well on inputs with consecutive repeated characters. 2018-02-08
How does ping
work?
ping
uses ICMP, or âInternet Control Message Protocolâ, to send âecho requestâ packets and receive âecho replyâ packets. 2018-02-07
What is DHCP?
DHCP dynamically assigns IP addresses to hosts, using a client-server protocol over UDP. It involves a sequence of DORA (Discover, Offer, Request, Acknowledge) messages to obtain and configure a network lease. 2018-02-06
Donât use nscd
nscd
, a local DNS resolver within glibc
, is non-standard. Instead, use a local DNS server like named
or dnscache
. 2018-02-05
What does getaddrinfo
do?
getaddrinfo
ostensibly does DNS lookups. Sounds simple, but it uses more than 100 system calls! Letâs trace the crazy path of address lookup on Linux. 2018-02-03
What is tcpdump
?
tcpdump
captures and displays network traffic. An example inspecting DNS requests and responses. 2018-02-01
Donât say âsimplyâ, at Write The Docs London
2018-01-23
A hex compiler in C
A compiler that converts a text file containing hex codes and comments into a binary output file. 2018-01-21
Bootstrapping a C compiler
I propose BootstrapCC, a project to build a C compiler from a tiny handwritten program, avoiding the trust problem in Thompsonâs âReflections on Trusting Trustâ. 2018-01-11
What is a random oracle?
A random oracle is an idealized model of a hash function, where each call queries a global server that returns a true random value. This models important properties of real-world hash functions like collision resistance. 2018-01-10
How to hash multiple values
Methods for hashing multiple values, including hash-then-XOR, concat-then-hash, and serialize-then-hash. The only method thatâs collision-resistant is serialize-then-hash! 2018-01-09
Making a stream cipher
A stream cipher in Go that generates an infinite keystream from a shared key using SHA-256. 2018-01-01
osquery: UNIX as a SQL database
osquery
allows querying a UNIX system using SQL. 2017-12-11
What is open addressing?
An open addressing hash table implementation in C, which resolves collisions by finding alternative buckets for elements using linear probing. 2017-12-10
What is a TTY?
Terminals in Unix are files in the filesystem, identified by names like /dev/ttys008
. Processes have standard input, output, and error streams that can be connected to terminals. The terminal a process is attached to can be inspected and manipulated. 2017-12-09
What is modular arithmetic?
Modular arithmetic involves operations like addition, subtraction, multiplication, and exponentiation that âwrap aroundâ a fixed modulus. This is useful for cryptography like RSA. 2017-12-08
Inline quizzes
Inline quizzes make reading more engaging by requiring readers to participate in the content. 2017-12-07
Linking to external posts from Jekyll
Using an external_url
property for linking to external blog posts from a website built with Jekyll, allowing a comprehensive directory of all posts regardless of platform. 2017-12-06
Nativité 2017: creating a Facebook Messenger bot
Creating a Facebook Messenger bot for a Christmas game âNativitĂ©â, switching from expensive SMS notifications. The bot is hosted on Heroku and Netlify, with Pusher for real-time updates. 2017-12-05
How less works: the terminalâs alternative buffer
less
uses the terminalâs âalternate screenâ feature to clear the screen and display the contents of a file, and then restores the previous screen when exiting. 2017-12-04
An encrypted diary using OpenSSL
Generate a master keypair. Encrypting each diary entry with a one-time shared secret. Encrypt the shared secret with the public key. Decrypt entries using the private key and the shared secret. 2017-12-03
The sorry state of OpenSSL usability
OpenSSLâs inadequate documentation, confusing key formats, and deprecated interfaces make it difficult to use, despite its importance. 2017-12-02
What is ASN.1?
ASN.1 is a data format used to encode structured data like RSA private keys and certificate signing requests. Using openssl asn1parse
to reveal its structure. 2017-11-30
UNIX free
: used
does not mean what you think it means
The used
metric in free -m
includes memory used for caching, not just application memory. The true memory usage is lower, calculated as used minus buffers/cache. 2017-11-29
Diff views in GitHub-Flavored Markdown
GitHub-Flavored Markdown supports âdiff viewsâ with +
and -
prefixes. While it loses syntax highlighting, itâs a quick and easy way to show changes. 2017-11-27
Nativité, a pastoral Christmas game
A Christmas game where sisters compete to move their toy sheep closer to the Christ Child by doing good deeds, played out in real-time through a web app with an admin interface for the parents. 2017-11-26
DNS resolution procedure
DNS resolution is a recursive procedure involving different record types like A, CNAME, and NS. Resolving a domain name can require multiple DNS queries to different nameservers. 2017-11-25
Adding blog tags
I start using tags to categorize blog posts, enabling audience-specific features like subreddit auto-posting, customizable RSS feeds, and push notifications. 2017-11-24
Diff views as instructions
A proposal to use âdiff viewsâ in technical writing to clearly differentiate code under discussion from contextual information, similar to the format of version control diffs. 2017-11-23
What is Swiftâs @NSApplicationMain
annotation?
The @NSApplicationMain
annotation in Swift automatically sets up the applicationâs entry point, including creating the NSApplication
instance and assigning the AppDelegate
class. 2017-11-13
Moving pictures
Replaced static image on this site with a looped video. Experimenting with subtle motion to mimic images at first glance. 2017-11-12
SaaS price models: cost-based pricing vs. value-based pricing
Cost-based pricing sets prices to cover costs plus profit, while value-based pricing sets prices based on customer willingness to pay. The optimal SaaS pricing model uses value-based inputs like user count that approximate customer value. 2017-11-11
Adding a blog header
Added a header to the blog with a photo that links to the homepage, as people expect a header for navigation. 2017-11-10
How PHP and Composer find your code
Composerâs autoloader uses PSR-4 to map namespaces to directories, allowing you to load classes without explicit require
statements. 2017-11-09
I hate telephones
I hate telephones. Some rational reasons: lack of authentication, no spam filtering, forced synchronous communication. But also just a visceral fear. 2017-11-08
A JavaScript Promises implementation
Implementing a Promise API in JavaScript, including handling asynchronous callbacks, promise chaining, and automatically wrapping non-promise values. 2017-11-07
How do I release a PHP Composer package?
To release a PHP Composer package, create a GitHub repo, add a composer.json
file, submit the package to Packagist.org, and tag a stable version. Then Composer users can require your package. 2017-11-06
What are promises in JavaScript?
Promises in JavaScript represent future values. They provide a way to handle asynchronous operations, allowing chaining of callbacks. Promises can be fulfilled or rejected, with callbacks handling each case. 2017-11-05
Adding Open Graph meta tags to jameshfisher.com
Added Open Graph meta tags to improve how blog posts appear when auto-posted to Facebook. 2017-11-04
Asymmetric encryption with the Web Cryptography API
Generating ECDH keys and deriving a shared AES key. 2017-11-03
Symmetric encryption with the Web Cryptography API
Generating a key, encrypting and decrypting text, and explaining the implementation. 2017-11-02
Signing a string with HMAC using the Web Crypto API
A web page that allows you to sign a string using the HMAC algorithm with SHA-256, implemented using the Web Crypto API. 2017-10-31
Hashing a string with the Web Cryptography API
The Web Cryptography API provides low-level crypto primitives in JavaScript, including hashing strings using SHA-256. 2017-10-30
Guest writers
Setting up guest writers on a Jekyll blog. Marking authors in the metadata. Storing author information in a YAML file. 2017-10-29
WebGL shading: both diffuse and specular
A WebGL shader that combines diffuse and specular lighting, allowing the user to adjust the relative contribution of each using keyboard controls. Guest post by LuĂs Fonseca. 2017-10-28
Forward secrecy with hash ratchets
A âhash ratchetâ ensures that a compromise of the current key does not allow decryption of past messages. Each messageâs encryption key is derived from the previous key using a hash function. 2017-10-27
The Three Ts of Time, Thought and Typing: measuring cost on the web
Businesses often tout âfreeâ services, but the real costs come in terms of time, thought, and typing required from users. Reducing these âThree Tsâ is key to improving sign-up flows and increasing conversions. 2017-10-26
Group chat with end-to-end encryption
Group chat with end-to-end encryption can use âclient-side fan-outâ where the sender encrypts the message separately for each recipient, or âserver-side fan-outâ where the sender encrypts the message once using a shared secret, then the server distributes the ciphertext to the group. 2017-10-25
Web Push API in Firefox
Differences between the Web Push API in Google Chrome and Firefox. Firefox uses the Mozilla Push Service, enabling push notifications without Googleâs GCM/FCM. 2017-10-24
Giant Game of Life
Implements a 1024x1024 grid of Conwayâs Game of Life using WebGL fragment shaders. 2017-10-23
Game of Life implemented with a fragment shader
A Conwayâs Game of Life simulation implemented using WebGL fragment shaders, with rendering to texture and a Gosper Glider Gun initial state. 2017-10-22
Drawing a cube in WebGL
Rendering an animated 3D cube in WebGL using a vertex shader, face color uniforms, and matrix transformations for rotating the cube. 2017-10-21
Generated normal-mapped ripples
Generating dynamic normal-mapped ripple effects using WebGL, with the mouse position controlling the light source. 2017-10-20
GLSL varying variables
GLSL varying
allows vertex shader outputs to be passed to fragment shaders. A WebGL demo with colors interpolated between vertices. 2017-10-19
Generating a normal map in WebGL
Generates a normal map of a cone in WebGL dynamically, without needing to load a static file. Using a rotation matrix and color conversion functions to create the normal map. 2017-10-18
Multiple textures in WebGL
Combining two textures in a WebGL fragment shader, using texture units and uniform locations to access the textures. 2017-10-17
WebGL shaders with color
WebGL shaders that respond to mouse movement, using normal maps and color maps to simulate diffuse and specular lighting on a rockface texture. 2017-10-16
One-dimensional Perlin noise
Random slopes are interpolated to create a smooth, wiggly line. More realistic noise is achieved by combining multiple octaves. 2017-10-15
macOS OpenGL hello world using GLFW
A program to create a cyan window on macOS using C and the GLFW library. 2017-10-14
WebAssembly hello world
A WebAssembly program that prints 42
to the console, demonstrating the structure and usage of WebAssembly. 2017-10-13
WebGL shading: diffuse vs. specular
Contrasting diffuse and specular shading models in WebGL, with live demos showing matte vs. shiny surface renderings. 2017-10-12
WebGL Lambertian shading
Interactive WebGL demo that shows Lambertian shading, with a fragment shader that calculates lighting based on a normal map and mouse position. 2017-10-11
WebGL matrix visualization
A WebGL-powered matrix visualization tool that lets you interactively edit a 4x4 transformation matrix and see the effects on a 3D cube render. 2017-10-10
WebGL clipspace point visualization
A WebGL visualization of a point in 4D homogeneous clip space. Explore the effects of the x, y, z, and w components. 2017-10-09
WebGL canvas size vs. CSS size vs. viewport vs. clipspace vs. world space
WebGL has several spaces that need to be properly managed to display content correctly. 2017-10-08
Drawing a clock face with WebGL
A WebGL clock face with moving hands that updates every second, using a vertex shader to convert polar coordinates to 3D positions. 2017-10-07
How to load an image in WebGL
Using WebGL to load an image and swap its RGB channels with a fragment shader. 2017-10-06
WebGL fragment shader animation
A WebGL fragment shader that animates a pulsating colored square by updating a time-based uniform
in the shader. 2017-10-05
Textures in WebGL shaders
A WebGL demo that creates a 2x2 checkerboard texture, uploads it to the graphics driver, and samples from it in the fragment shader to display a blurred checkerboard pattern. 2017-10-04
WebGL shader uniforms
Shader uniforms in WebGL are global variables that allow passing data from the JavaScript application to the shader. A demo shows how to update a uniform representing the mouse position and use it to generate a dynamic pattern. 2017-10-03
WebGL fragment shader
A demo WebGL fragment shader that draws concentric circles, with a live editor to experiment with the shader code. 2017-10-02
Drawing a triangle with WebGL
A WebGL example that draws a cyan triangle on a pink canvas by creating shaders, a program, a vertex buffer, and rendering using gl.drawArrays()
. 2017-09-30
Unicode is only for plaintext
The Unicode Consortium rejected proposals for encoding a âexternal link signâ character, citing that it is not âan element of plain textâ. This precedent makes it unlikely that a proposal for a Unicode feed icon would be approved. 2017-09-29
Where is the Unicode feed icon?
Lack of a standard Unicode feed icon despite its widespread use. I plan to submit a proposal for its inclusion. 2017-09-28
WebGL hello world
A WebGL demo that creates a green square in a canvas element, showing the difference between 2D canvas and WebGL contexts. 2017-09-27
IndexedDB hello world
How to create an IndexedDB database, add an object store, and read/write data. 2017-09-26
lldb
hello world
Compiling a C program with debugging flags, then using lldb
to set breakpoints, step through the code, and observe output. 2017-09-25
LocalStorage hello world
LocalStorage allows web apps to store key-value pairs locally in the browser, with storage scoped to the origin. Comes with a free demo. 2017-09-24
How can I store things on the browser?
Browsers offer various storage options, including cookies, localStorage, sessionStorage, IndexedDB, CacheStorage, WebSQL, and AppCache, each with its own tradeoffs in terms of use case, persistence, and support. 2017-09-23
Adding an RSS feed to a Jekyll blog
Adding an RSS feed to a Jekyll blog using the jekyll-feed
gem, configuring _config.yml
, and adding links to the HTML template. 2017-09-22
How can I encrypt data in the Web Push API?
Browser generates keys, shares public key; server encrypts data with it; browser decrypts push payload. 2017-09-21
Web Notification API onclick
notificationclick
service worker event lets the web app open a webpage via clients.openWindow
. 2017-09-20
What is the web Push API?
Web applications can âsubscribeâ for notifications via PushSubscription
endpoint, but thereâs poor interoperability between different browsersâ push services. 2017-09-19
Per-IP rate limiting with iptables
2017-09-19
ICFP: Ode on a Random Urn
An efficient way to represent and sample from a discrete probability distribution, using a balanced binary tree data structure called the âurnâ. 2017-09-18
Hello world in Rust
I install Rust, create a âHello Worldâ program, and compare it to the equivalent C program. The Rust binary has additional dependencies beyond the standard C library. 2017-09-17
Coping with depression
Depression involves negative cycles of repression, guilt, and reclusiveness. Coping strategies include getting out, making healthy meals, reading, and talking about it. 2017-09-16
Why are there 21 million bitcoins?
The 21 million bitcoins limit was chosen to ensure the smallest unit, the satoshi, would have a reasonable value if Bitcoin were the worldâs exclusive currency. 2017-09-15
What is a Web App Manifest?
A web app manifest is a JSON file that provides metadata about a web app, such as its name, icons, and display mode, enabling features like adding it to a homescreen. 2017-09-14
What is the web Background Sync API?
The Background Sync API lets service workers execute tasks even when the client page is not active. It queues jobs that run as sync
events, which can trigger desktop notifications. 2017-09-13
new Notification(...)
is deprecated
Deprecated new Notification()
replaced with ServiceWorkerRegistration.showNotification()
. 2017-09-12
Service worker hello world
A service worker that responds to a âpingâ message with âpongâ, and a client-side script that registers the service worker and sends it the âpingâ message. 2017-09-11
What are service workers?
Service workers are scripts that run outside the browser context, allowing web apps to perform tasks like caching, network requests, and offline functionality. 2017-09-10
How could Bitcoin fail?
Bitcoin could fail due to theoretical inferiority, lack of practicality, bans, critical bugs, centralized control, or technological collapse. 2017-09-09
Publication notifications for static sites
Using a service worker to monitor the sitemap and display updates via browser notifications. 2017-09-08
What is the web Notification API?
The web Notification API allows web apps to display system-level notifications, requiring user permission. It has two key parts: requesting permission and creating notifications. 2017-09-07
Array vs. dictionary pagination
Paginate an API with either array indexing (?page_number=
) or dictionary indexing (?first_word=
). Array indexing suffers from shifting page boundaries, but is easier to parallelize. Dictionary indexing requires ordering, but handles dynamic ordering better. 2017-09-06
Worst interview
Disastrous interview experience. Unable to enter building. Was this a test to weed out the idiots? Ran away and never came back. 2017-09-05
How to write an essay
Guidelines for writing compelling yet substantively questionable essays, focused on rhetorical techniques over truth. 2017-09-04
Running a Laravel+Pusher workshop at work
Internal workshop on Laravel+Pusher. Structured approach with checkpoints helped keep everyone on track. 2017-09-03
What makes a good blog post title? 5 steps to going VIRAL!
To write a viral blog post title, use a question format, focus on a single topic, and employ clickbait tactics to pique readersâ curiosity. 2017-09-02
August review
After a long blogging hiatus, Iâm back. Iâve been giving conference/meetup talks, and have moved my blog to a permanent home at jameshfisher.com. In August, I wrote about C and DNS, and did marketing work on Vidrio. For September, Iâm focusing on understanding and investing in cryptocurrencies. 2017-09-01
Post-driven permanent blog pages
Permanent blog pages are now generated from tagged blog posts, providing automatic updates, separate URLs, and chronological ordering. 2017-08-31
How do I make a full-width iframe
with fixed aspect ratio?
Use CSS padding-top and position properties to create a full-width iframe with fixed 16:9 aspect ratio. 2017-08-30
Securing my Bitcoin
Old Bitcoin wallet on a sketchy 2012 laptop. Block database corrupted but wallet.dat found. 2017-08-29
A calendar view for this blog
An updated calendar-based homepage, highlighting gaps in posting. 2017-08-29
What is an extern
function in C?
In C, function declarations are implicitly extern
, meaning they have external linkage. The static
keyword can be used to give a function internal linkage instead. 2017-08-28
What is extern
in C?
extern
declares a variable without defining it, allowing the linker to find the definition elsewhere. This is useful when a variable is declared in one file but defined in another. 2017-08-27
What is static linking in C?
Static linking in C involves compiling a library and main program separately, then linking the object files together into an executable. 2017-08-26
What system calls does dlopen
use?
The dlopen
API uses open
, mmap
, close
, and munmap
to load a shared object file into memory, without requiring any special syscalls. 2017-08-25
How to make plugins with dlopen
Dynamically load and unload shared libraries using dlopen
, dlsym
, and dlclose
. 2017-08-24
Sentence wrap
Sentence-wrap is a text-wrapping approach that inserts newlines between sentences. Diffs are easier to read, and sentences more apparent. Reminiscent of poetry. 2017-08-23
How to inspect Mach-O files
Using otool
to see dynamic library dependencies, and nm
to see function symbols. 2017-08-22
What is C include
?
#include
in C does not import functionality, but rather inserts the preprocessed text of the included file. The actual implementation of the included functions, like fprintf
, is provided through linking. 2017-08-21
What is an authoritative DNS server? What is a recursive DNS server?
Authoritative DNS servers provide definitive responses for their domains, while recursive DNS servers consult other servers to serve responses, caching results to reduce load on authorities. 2017-08-20
Does C have generics?
Câs _Generic
is not true generics. It requires manual implementation of concrete type cases, unlike generics that automatically generate code for any type. 2017-08-19
What is stdatomic in C?
stdatomic
provides atomic operations like atomic_fetch_add
to ensure thread-safe access to shared variables. 2017-08-18
Golangâs realtime garbage collector at GolangUK
2017-08-17
How do Reddit thumbnails work?
Embedly respects Open Graph og:image
meta tag for thumbnail selection. Adding it to vidr.io
enables Reddit thumbnail. 2017-08-16
Greater-than is redundant
>
is redundant; <
alone suffices for all comparisons. I prefer it because it aligns with the number line. 2017-08-15
How to distribute a MacOS .dmg
Distributing Vidrio outside the Mac App Store with a signed .app in a .dmg, and creating custom download badges to comply with Appleâs guidelines. 2017-08-13
How to build a .dmg to distribute MacOS apps
Package a macOS app for distribution outside the Mac App Store by archiving it in Xcode, exporting it with a Developer ID signature, then creating a .dmg disk image. 2017-08-12
How do peer-to-peer programs discover each other?
Peer-to-peer programs use centralized discovery mechanisms like BitTorrent trackers and Bitcoin DNS seeds to find peers, as a purely decentralized approach would require an impractical brute-force search. 2017-08-11
How to trace a DNS lookup
Tracing a DNS lookup for ws-mt1.pusher.com
using dig +trace
reveals the iterative process of resolving the domain name, starting from the root name servers and following referrals to the top-level domain and authoritative name servers. 2017-08-10
What is the rel=canonical
tag?
<link rel="canonical" href="..."/>
specifies the preferred URL of a page duplicated across domains. Search engines use this to determine which page to recommend. 2017-08-09
How to move your GitHub pages blog to Netlify
Moved GitHub Pages blog to Netlify, using custom domain, HTTPS, and redirects from the old site. 2017-08-08
This site is now on jameshfisher.com
Moved blog from jameshfisher.github.io
to jameshfisher.com
, with CNAME setup and GitHub custom domain settings. Switching to Netlify for HTTPS hosting. 2017-08-07
Instance DNS in multi-tenant services
Pusher could use runtime DNS lookup to identify the cluster for each app instance, instead of hardcoding the cluster. This allows more flexibility, and easier changes, at the cost of some lookup overhead. 2017-08-06
How to let your users sign in with Google, from scratch
Implemented Google Sign-In for a web app, handling the authentication flow and verifying ID tokens to authorize access to a private diary feature. 2017-08-05
How to write a DNS server in Go
A DNS server in Go that responds to A queries for a hardcoded set of domain-to-IP mappings, using the miekg/dns
package. 2017-08-04
How can I do DNS lookup in Go?
Using the Go "net"
package to look up IP addresses for a given domain name, using either the C stdlib or a pure Go DNS resolver. 2017-08-03
How to implement malloc/free
A malloc/free implementation that maps allocations directly to mmap/munmap, with the allocation size stored before the returned pointer. 2017-08-02
How to watch system calls with dtruss
dtruss
allows tracing system calls on macOS. It shows the syscall, arguments, return value, and errno. 2017-08-01
How to cut out the CA middleman
Eliminate Certificate Authorities by storing the public key for a domain directly in the DNS, allowing browsers to verify the identity of a server without relying on a third-party CA. 2017-07-30
Are concurrent fwrite
s atomic? No!
Concurrent fwrite
s are not atomic and can lead to interleaving of characters, invoking undefined behavior. POSIX does not specify behavior of concurrent writes to a file, so applications should use concurrency control. 2017-07-29
Notes from Minsk
Spoke with Will about the Go garbage collector at GoWayFest in Minsk, Belarus. Orderly city. Software engineering scene surprisingly big. 2017-07-25
Golangâs realtime garbage collector at GoWayFest, Minsk
Presented âGo garbage collectorâ talk at GoWayFest in Minsk, met fellow Gophers, and did some tourism around Belarus and Ukraine. 2017-07-21
The Fisher Tree at The Realtime Guild
A talk about the Fisher Tree, a data structure, with slides and code. 2017-07-05
Pattern jokes via WordNet/NLTK
A chatbot that generates âpattern jokesâ by replacing a word in a phrase with a related word from the same category, using WordNet and NLTK. 2017-06-25
Long calendar
A long-term personal calendar that captures life goals, plans, and trajectories rather than daily schedules. Focuses on broad life stages and scenarios rather than precise event planning. 2017-06-06
Defining the sine function as an oscillator
The sine function can be defined as the oscillation of an object on a spring, which can be simulated with a simple iterative function. This provides an intuitive definition of sine beyond the standard trig-based one. 2017-06-04
Granddad died today
Granddad died. The unspoken practice of death-by-dehydration in the NHS. The Liverpool Care Pathway. Assisted dying in the UK. The importance of planning in end-of-life care. 2017-05-19
Donât trust cat
!
cat
can hide malicious content behind terminal control sequences, so you should not trust its visual output. Use less
or hexdump
to inspect files instead. 2017-05-07
What is the clear
program?
The clear
program clears the terminal screen using the escape sequence \033c
, where \033
is the ASCII code for âescapeâ and 'c'
is the command to clear the screen. 2017-05-06
What is CIColorKernel
?
CIColorKernel
is a type of CIKernel
optimized for pixel-wise image transformations, with input as pixel samples instead of image samplers. 2017-05-03
How to make a Core Image kernel program running on the CLI
A Swift CLI program that applies a Core Image kernel to image files, allowing operations like averaging two images. 2017-05-02
How to pass multiple inputs to a CIKernel
A CIKernel
in Swift can have multiple inputs, including image samplers and other data types. Example: an alpha-compositing kernel. 2017-04-30
How to write a webcam app in Swift on macOS
A macOS app that displays a webcam preview in a floating panel, using the AVFoundation framework. 2017-04-29
What are samples in a Core Image kernel?
Kernels in Core Image operate on output pixels, using samplerCoord
to find corresponding input pixels. sample
then retrieves the color of the input pixel. Kernel can apply transformations by modifying the samplerCoord
expression. 2017-04-28
How to make a custom CIFilter in Swift
Using a CIFilter
using a GLSL kernel to swap the red and green components of an image. 2017-04-27
How to apply a CIFilter
to an image in Swift
Using CIFilter
to apply a sepia tone filter to an NSImage
and save the result to a file. 2017-04-26
How to write âhello worldâ in TensorFlow
Two ways to calculate the cost per gram of chocolate: one without machine learning, and another using TensorFlow to learns a linear model. 2017-04-23
What is the simplest neural network? One neuron
A neural network with one neuron that classifies binary-encoded natural numbers. We can decide whether the number is even, or whether itâs greater/less than 5. 2017-04-22
What is a .app?
A .app is a macOS application bundle, a directory structure containing the executable and supporting files. The .app directory contains the real program binary, but cannot be directly executed. 2017-04-21
How to run Swift from the CLI
Run Swift scripts from the command line using swift hello.swift
, or compile them to an executable with swiftc hello.swift
. 2017-04-20
How to write an OpenCL âhello worldâ on macOS
A program that squares an array of floats on the GPU, using the OpenCL API on macOS. 2017-04-19
How to write a TCP chat server in 55 lines of Golang
A TCP chat server in Go, where each client message is broadcast to all other connected clients. Uses the net
package and goroutines to manage multiple connections. 2017-04-18
What company information is public? Whatâs on Companies House?
Companies House is the UK company register. It provides public information about registered companies, including their registration details, officers, business activities, and financial statements. 2017-04-17
What is a business? What is a company?
Businesses can take different legal forms, such as companies, sole traders, and partnerships. Companies are unique in that they are considered âlegal personsâ with their own finances and liabilities, distinct from their directors and shareholders. 2017-04-16
How to create a public-key infrastructure
I demonstrate creating a public-private key pair, distributing the public key, and using a trusted third party (CA) to vouch for the public key. 2017-04-15
How can I do elliptic curve crypto with OpenSSL?
Generate ECC private key with openssl ecparam
, extract public key from it using openssl ec
, derive shared secret using openssl pkeyutl
. 2017-04-14
Playing with Stripe
Investigating Stripe as a payment processor for Vidrio. Trying out the client-side and server-side integration, creating a simple Go server to handle the Stripe token and charge the user. 2017-04-10
Product key server as a service
I want a service to manage product keys for software monetization, including key generation, signing, distribution, and verification, with optional machine or user licensing restrictions. 2017-04-09
How to implement a âfree trialâ for macOS apps
Implementing a âfree trialâ for macOS apps involves a license-generation system on a server and a license-verification system in the app, plus storing the license data in the appâs preferences file. 2017-04-08
Multiplexing by looping over nonblocking sockets
A TCP server that multiplexes multiple clients without select
by looping over non-blocking sockets, maintaining a shared counter of total bytes received. 2017-04-07
What is go tool trace
?
A screencast about go tool trace
, a profiling tool for Go applications. 2017-04-06
rxi/vec - a simple C vector library
rxi/vec provides dynamic arrays in C, including push, pop, and iteration, without the need to manage array resizing and length. 2017-04-06
How do I set a socket to be non-blocking?
To set a socket as non-blocking, use fcntl
to mark it with the O_NONBLOCK
flag. This allows the socket to fail gracefully instead of blocking when no data is available. 2017-04-05
What is the viewport
meta tag? How can I display my website on mobile?
Mobile browsers magically scale pages to fit mobile screens. Setting width=device-width
disables this, but it requires the website to be designed for small screens. 2017-04-04
How to run go tool trace
A screencast about go tool trace
, a profiling tool for Go applications. 2017-04-03
What is âsequencing marketsâ?
A strategy for growing a product by starting with an extremely specific target market and gradually expanding to broader markets. 2017-04-02
Monthly review: 2017-03
Completed Vidrio release in March, but fell short on other goals. Focused heavily on Vidrio development and marketing, rather than technical learning. Plans to continue Vidrio work and study OpenSSL, iptables, NAT, OAuth, and payment systems in April. 2017-04-01
Replay with sound
A âReplay with soundâ button to control a muted video, implemented using the YouTube Iframe API. 2017-03-30
How to prevent autoplay on mobile
Prevent annoying video autoplay on mobile by detecting mobile devices and serving a manual play button instead. 2017-03-29
Varying navbar for mobile and desktop
Using CSS media queries to re-word navbar elements based on screen width. 2017-03-28
How to use keycastr
Keycastr is a tool that displays your keystrokes on the screen during screencasts, but has some issues like not displaying over maximized windows, fixed positioning, and using obscure key symbols. 2017-03-27
Study of framer.com promo video
An analysis of the Framer.com promo video, highlighting its engaging music, timed animations, and succinct text slides. 2017-03-25
Your password is the private key. So what is the public key?
Asymmetric cryptography uses public and private keys. The private key can be derived from a password using a secure PRNG, avoiding the need to store the private key. 2017-03-24
How to get your point across with spaced repetition
Repetition is key for effective communication. Spaced repetition throughout the text, not just in the intro and conclusion, helps readers remember the main point. 2017-03-23
How do I do public-key signatures with openssl
?
Using openssl genrsa
, openssl rsa
, openssl rsautl -sign
, and openssl rsautl -verify
. 2017-03-22
How do I do public-key encryption with openssl
?
Generating RSA keys, extracting the public key, encrypting with the public key, and decrypting with the private key. 2017-03-21
How is MainMenu.xib
found in Cocoa?
NSApplicationMain
loads the MainMenu.xib
file to create the applicationâs main menu and window. It first looks for the NSMainNibFile
key in the Info.plist
file, and if not found, it falls back to the first nib/xib file in the main bundle. 2017-03-20
What is NSApplication
? How is it instantiated? What is NSApp
?
NSApplication
is the core of a Cocoa application. It is typically instantiated via NSApplicationMain
or by calling NSApplication.shared()
. NSApp
is a global variable that holds the singleton instance of NSApplication
. 2017-03-19
What is Swiftâs @NSApplicationMain
annotation?
The @NSApplicationMain
annotation in Swift is a macro that calls NSApplicationMain(...)
to set up the Cocoa applicationâs UI event loop. 2017-03-18
How to make a Cocoa application without a .xib
file
To create a Cocoa app without a .xib
file, remove the NSMainNibFile
key from the Info.plist
, and replace the @NSApplicationMain
annotation on your AppDelegate
class with a custom main.swift
file that manually sets up the application and its delegate. 2017-03-17
Donât say âit will take five minutesâ
Avoid claiming unrealistic time estimates like â5 minutesâ for product onboarding or tutorials. Realistic estimates like âa couple hoursâ are more honest and set appropriate expectations. 2017-03-14
How do I create a message digest using openssl
?
Create message digests using the openssl dgst
command, specifying the hash algorithm (e.g. -sha512
) and optionally signing with a shared password using -hmac
. 2017-03-13
How do I hash a password with openssl
?
The openssl passwd
command hashes passwords using the outdated crypt algorithm, with truncation to 8 characters - a poor choice for secure password hashing. 2017-03-12
How do I fetch a serverâs SSL certificate using openssl
?
Use the openssl s_client
command to fetch a serverâs SSL certificate chain, including the root certificate. 2017-03-11
How do I generate random bytes with openssl
?
Generate random bytes with openssl rand
, which uses a PRNG seeded with entropy from ~/.rnd
. 2017-03-10
Golangâs realtime garbage collector at Not On The High Street Conference
Discussed Goâs real-time garbage collector at an internal conference, after presenting the same talk at The Realtime Guild. 2017-03-10
How do I encrypt text with openssl
?
Encrypt and decrypt text using the openssl enc
command with a password and AES-256 cipher. The encrypted text is base64-encoded. 2017-03-09
How to add a developer account to XCode
Xcode uses âteamsâ to manage developer identities, and revoking a certificate on one device may require regenerating provisioning profiles. 2017-03-03
How to submit an app build to iTunes Connect
To submit a macOS app build to iTunes Connect, archive the app in Xcode, enable App Sandbox, then upload the build. 2017-03-02
How do I create the AppIcon for my app?
To fix misconfigured App Icons, create properly-sized PNG files and update the Contents.json
file to reference the correct image files. 2017-03-01
Redis Pub/Sub under the hood
Examines Redisâs source code to understand how it tracks subscriptions, handles disconnections, and implements pattern subscriptions, highlighting potential pitfalls and attack vectors. 2017-03-01
Justifying posts
A technique to improve blogging focus by including a justification for each post, referring back to monthly targets. Allows room for off-the-wall posts. 2017-03-01
Monthly review: 2017-02
Focused on learning C, UNIX, and networking fundamentals. To avoid becoming a neckbeard, Iâll keep my projects grounded in real-world applications. March will be dedicated to Vidrio. 2017-03-01
Installing and running ebe
Install ebe
assembler with a one-liner, but be wary of the SourceForge installation script. 2017-03-01
What is the Apple Store release process?
1) Enroll in the Apple Developer Program. Create an âApp Recordâ in iTunes Connect. Upload the app. Submit it for review. 2017-03-01
How to write a TCP server with the pthread
API
A TCP server that uses pthread
to serve multiple clients concurrently, with an âechoâ server for each connection. 2017-02-28
What are the domain
and type
arguments to the socket
system call?
The domain
and type
arguments to socket()
describe the protocol family and socket type, respectively. The protocol
argument specifies the actual protocol to use, which may be inferred from the domain
and type
. 2017-02-27
What is UTF-8?
UTF-8 is a character encoding that can represent the entire Unicode character set. Itâs variable-length, self-synchronizing, and an extension of ASCII. 2017-02-26
How to write a TCP server using the fork
syscall
A TCP server that uses the fork
system call to create a new child process for each accepted connection, allowing it to handle multiple clients concurrently. 2017-02-25
Should I go paperless?
Going paperless by scanning, shredding, and storing documents digitally in Google Drive can solve issues with physical clutter and document management, while carefully considering the tradeoffs of legal weight, fidelity, sentiment, independence, and privacy. 2017-02-25
What is mode_t
in C?
mode_t
is a bitfield type in C that represents file permissions, including read, write, and execute permissions for the owner, group, and other classes. It provides symbolic constants to set and check these permissions. 2017-02-24
How do I print bits in C?
A program in C that prints the individual bits of various data types, showing how they are represented in memory. 2017-02-23
What is ssize_t
in C?
ssize_t
is a signed version of size_t
, used to represent return values from system calls that may need to indicate error with -1
. 2017-02-22
Donât use the word âsimplyâ
Avoid using the word âsimplyâ as it can come across as insulting to the reader by implying the task is easy or the reader is stupid. Instead, rephrase to be more objective and avoid comparatives like âsimplyâ or âjust.â 2017-02-22
What is a a FIFO, or ânamed pipeâ? What is mkfifo
in C?
A FIFO is a special file that allows inter-process communication. The mkfifo
system call creates a FIFO, enabling processes to read from and write to it. 2017-02-21
How to write an assembly âhello worldâ on macOS
A âHello, world!â program in x86-64 assembly for macOS, using the NASM assembler and system calls for writing to stdout and exiting. 2017-02-20
What is lsof
?
lsof
lists open system resources, including pipes, sockets, and yes, files. It shows their type, owner, and location. 2017-02-20
How to generate Intel and AT&T assembly with clang
Generate Intel and AT&T assembly with clang
, demonstrating the difference in syntax between the two styles. 2017-02-19
What are setjmp
and longjmp
in C?
setjmp
and longjmp
in C bypass normal function call and return flow, allowing a function to return to a previously saved state. setjmp
saves the current execution context, and longjmp
restores it. 2017-02-18
How do I call a program in C, setting up standard pipes?
A C function to create a new process, set up its standard input/output/error pipes, and return a struct containing the process ID and pipe file descriptors. 2017-02-17
How do I close a file descriptor in C?
To close a file descriptor in C, use the close
system call. Multiple descriptors can reference the same underlying file or pipe. The pipe is only closed when all references are closed. 2017-02-16
Golangâs realtime garbage collector, at The Realtime Guild
A talk given with Will Sewell. Overview of Goâs concurrent garbage collector. 2017-02-15
How do I duplicate a file descriptor in C?
Use the dup
system call to duplicate a file descriptor in C, allowing two references to the same underlying pipe. 2017-02-15
UNIX as a SQL database
UNIX represents various system components, like processes, file descriptors, and memory, using in-memory data structures that can be modeled as relational database tables. 2017-02-14
French preposition examples
French preposition examples for common spatial relationships like behind, in front of, next to, under, on, above, in, and between. 2017-02-13
What are Lamport timestamps?
Lamport timestamps measure time and causality in distributed systems. Timestamps are assigned to events, with the property that if event A happened-before event B, then Aâs timestamp is less than Bâs. 2017-02-12
Are processes and messages different?
Processes and messages can be unified - processes are just very slow messages, and message passing can be seen as splitting and fusing atoms. 2017-02-11
What is the happened-before relation?
The happened-before relation models time in distributed systems, where events at different locations may not have a total order. It defines time using causality. 2017-02-10
How to wake up earlier
To wake up earlier, set a physical alarm in a location away from the bed, and schedule early meetings to create firm deadlines for your day. 2017-02-09
How can I wake up earlier?
Reassessing daily routine - shifting sleep, work, and commute times to wake up earlier, improve sleep quality, and align with daylight hours. 2017-02-08
How does GeoDNS work?
GeoDNS uses geo-IP to locate clients and connect them to the nearest server, reducing latency. 2017-02-08
How do I call a program from C?
To call a program from C, use `fork` then `execve`. There is no more direct way! 2017-02-07
How do I use fork
in C?
fork
duplicates the current process. It returns 0
in the child process. In the parent process, it returns the childâs new process id. 2017-02-06
How do I use execve
in C?
execve
replaces the current process with a new one. It takes a path, an argument array, and an environment array. The process never returns unless execve
fails. 2017-02-05
FOSDEM: The Challenges and Secrets of the Realtime World
Realtime apps use protocols like HTTP streaming, long polling, WebSocket to enable live updates. Scaling pub/sub requires distributed servers and routing clients to the closest server. 2017-02-04
WebRTC - low barrier to entry, low barrier to exit?
WebRTC has many challenges - browser API inconsistencies, protocol ambiguities, infrastructure requirements, and lack of built-in âbusiness logicâ. Not as easy as it seemed at first. 2017-02-04
What are the stages of C compilation?
C compilation involves 6 stages: preprocessing, parsing, AST generation, LLVM IR production, assembly generation, and linking to produce the final executable or shared library. 2017-02-04
How do I generate assembly from a C file?
Compiling with the -S
flag generates assembly. 2017-02-03
How do I access environment variables in C?
Access environment variables in C by using the global environ
variable, which points to an array of string pointers representing the environment. 2017-02-02
Monthly review: 2017-01
Reviewing January 2017 - covered networking, C/UNIX, WebRTC, and electronics. Plans to learn fundamentals of circuits, C compilation, UNIX process management, and WebRTC protocols. 2017-02-01
What system calls does macOS have?
All system calls on macOS 10.12, categorized by the functionality they provide, such as process management, file operations, memory management, etc. 2017-01-31
How do I read man
pages?
The man
command is used to access the UNIX manual pages, which are organized into numbered sections. man
searches a predefined path to find the relevant manual page. 2017-01-30
Cloning Spaceteam
A multiplayer web-based version of the cooperative game Spaceteam, using Pusher for real-time communication between players. 2017-01-30
In what ways can processes communicate?
Processes can communicate via files, pipes, signals, sockets, message queues, semaphores, and shared memory. 2017-01-29
How can I write a file with mmap
in C?
To write to a file, open the file, mmap
the file descriptor, then write to memory. 2017-01-28
How can I read a file with mmap
in C?
Use mmap
to map a file into memory, then read and write the memory directly. 2017-01-27
What is mmap
in C?
mmap
is a system call in C that allows programs to manipulate underlying hardware resources, such as physical memory or files, using ordinary memory manipulation. 2017-01-26
What is Coulombâs law?
Coulombâs law describes the force between charged particles, which is proportional to the product of their charges and inversely proportional to the square of the distance between them. 2017-01-25
Quickly checking for a zero byte in C using bitwise operations
How to check if a 64-bit word contains a zero byte. A step-by-step example and a proof of correctness. 2017-01-24
How to subtract in binary
To subtract in binary, we use carry bits and twoâs complement representation. 2017-01-24
What is the type of a constant in C?
Integers in C are int
by default, while suffixes like L
and U
denote long
and unsigned
types. Floats are double
without a suffix. 2017-01-23
What is the difference between C constants and C literals?
Literals are lvalues with addresses, while constants are rvalues without addresses. In C, only string literals are literals; other âliteralsâ like numbers and characters are constants. 2017-01-22
What are lvalue and rvalue in C?
âlvalueâ either means âexpression which can be placed on the left-hand side of the assignment operatorâ, or means âexpression which has a memory addressâ. ârvalueâ is defined as âall other expressionsâ. 2017-01-21
What is the UINT64_C
macro in C?
The UINT64_C
macro appends the ULL
suffix to a 64-bit unsigned integer literal, converting it to the appropriate type. 2017-01-20
What is electric current?
Electric current measures the change in electric charge across a boundary, like a wire. It is measured in amperes (coulombs per second) and reflects the net movement of electrons and protons from one side of the boundary to the other. 2017-01-19
What is electric charge?
Electric charge is the number of electrons minus the number of protons in an object. 2017-01-18
How does reliability work in RTCDataChannel
?
The RTCDataChannel
API lets us configure the delivery guarantees, including the ordered
, maxPacketLifeTime
, and maxRetransmits
properties. 2017-01-17
How to write a âhello worldâ serverless WebRTC app
Including setting up the RTCPeerConnection
, creating a data channel, handling ICE candidates, and generating an offer to be shared with the remote peer. The signaling channel is copy-paste! 2017-01-16
What is STUN?
STUN is a protocol that allows clients to discover their public IP address and port, enabling peer-to-peer connections in WebRTC. 2017-01-15
How do C signals interact with the stack?
C signal handlers reuse the same call stack as normal functions, but can optionally use a special signal stack instead. 2017-01-14
What is sigaction
in C?
sigaction
says what to do when a signal is received. signal
is a simplified interface to sigaction
. 2017-01-13
Doing something n
times in C with while
and decrement
Executing do_something()
N times in C using a while
loop and post-decrement operator. 2017-01-12
How do I unregister a signal
handler in C?
To unregister a signal
handler in C, use signal(signum, SIG_DFL)
to reset the disposition to the default, or signal(signum, SIG_IGN)
to set the disposition to ignore the signal. 2017-01-11
What does the C signal
function return?
signal
returns the old signal handler pointer for given signal number. 2017-01-10
What are âsignalsâ in C?
Signals in C are software interrupts that allow programs to respond to events. The signal.h
header provides functions to register signal handlers and send signals. 2017-01-09
How does differential signaling work in USB?
USB uses âdifferential signalingâ where the sender transmits two signals, D+
and D-
, and the receiver interprets the difference D+ - D-
. This cancels out electromagnetic interference that affects both wires equally. 2017-01-08
How does the USB power wire work?
The four wires in a USB cable are power (black, red) and data (white, green). One can power devices by connecting the ground and +5V wires, ignoring the data wires. 2017-01-07
What is the Ivy Lee method?
1) At end of day, list 6 tasks for tomorrow, ranked; 2) Next day, work through the list in order; 3) Discard the old list before making a new one. 2017-01-06
Error URLs (addressable errors)
Using unique error codes with linkable documentation improves error reporting. Provide a central error page URL with each error message. 2017-01-05
What are âbitfieldsâ in C?
Bitfields in C allow compact bit packing in structs, avoiding manual bitwise operations for greater safety and clarity, at the cost of some language complexity. 2017-01-04
What is a union
in C?
A union
in C allows one variable to hold different data types, where the storage is shared. The size of a union
is at least the size of its largest member. Fields in a union
have the same byte offset. 2017-01-03
How do I pack bits in C? (An answer using masks)
Efficient packing of game player data into 16 bits using bitwise operations on a uint16_t
type. 2017-01-02
How fast does an IP packet travel?
IP packets travel at ~20% the speed of light, with most time spent in routers rather than on the wire. 2017-01-01
What do DNS datagrams look like?
The structure and contents of a DNS request datagram, including the header, question section, and how to represent it in C. 2016-12-31
What are âstatement expressionsâ in GCC?
GCCâs âstatement expressionsâ allow inserting statements into expression positions. Behavior is unspecified. 2016-12-30
Pointer to middle of allocation, part 1
Redis uses length-prefixed strings with pointers into the middle of the allocation, allowing C-string operations on the string data. 2016-12-28
How do I put an array in a struct in C?
C allows a single array field of incomplete type (char []
) at the end of a struct definition. The size of the struct is determined by the size of the fixed fields, and the dynamic-sized array is allocated separately. 2016-12-27
How do I measure program execution time in C? How do I use the times
function?
Use the times()
system call in C to measure the CPU time used by a process, distinguishing between time charged to the process itself and time charged to the kernel on its behalf. 2016-12-26
How to write an array literal in C (with explicit indexes)
C array literals can use explicit indexes. The array length is determined by the largest explicit index. 2016-12-25
What is perror
in C?
perror
in C prints a human-readable description of the last error that occurred, as stored in the global errno
variable. 2016-12-24
What are âprotocol numbersâ in IP?
An IP packet contains a âprotocol numberâ that identifies the protocol (e.g. TCP, UDP) running over IP. The kernel uses this to determine how to handle the packet. 2016-12-23
How do I print bytes in C?
Useful to show how C represents various data types. 2016-12-22
What is htons
in C?
htons
and htonl
convert values between host and network byte order, where network order is big-endian. ntohl
and ntohs
are the inverse functions. 2016-12-21
How to write a âhello worldâ HTTP server in C
A C program that creates an HTTP server that responds with âHello, world!â to every request. 2016-12-20
What syscalls does a UDP server need?
The syscalls needed for a simple UDP echo server are socket
, bind
, recvfrom
, sendto
, and close
. 2016-12-19
How to write a TCP server with the kqueue
API
Kqueue is a more efficient alternative to select
for managing multiple TCP connections, providing a publish-subscribe model for tracking events in the kernel. 2016-12-18
What is fdset
in C?
fdset
in C is a data structure that represents a set of file descriptors. The FD_SET
, FD_CLR
, FD_ISSET
, and FD_ZERO
macros are used to manipulate and inspect these sets. 2016-12-17
How to write a TCP server with the select
syscall
The select
syscall allows a process to sleep and wake up when a file descriptor is ready for reading, writing, or has an exceptional condition. This enables a TCP server to handle multiple clients concurrently. 2016-12-16
What is a âfile descriptorâ, really?
File descriptors should be called âresource descriptorsâ. They represent various system resources, not just regular files. The operations you can perform depend on the specific resource. 2016-12-15
What syscalls does a TCP server need?
A minimal TCP server in C uses the socket
, bind
, listen
, accept
, recv
, send
, and close
syscalls to manage connections. 2016-12-14
What is errno
in C?
errno
lets you access error codes from system calls. Itâs a global int
. 2016-12-13
What are static
functions in C?
static
functions in C are only callable within the translation unit they are defined in, not across the whole program. 2016-12-12
How can I do modulo with a bitmask in C?
Use i & (n-1)
to compute i % n
, when n
is a power of two. This avoids the modulo operation. 2016-12-10
What are âmacro functionsâ in C?
Macros in C can define token replacements or function-like replacements. 2016-12-09
What is âarray decayingâ in C?
Arrays in C can âdecayâ to pointers, but are not inherently pointers. The size of an array is lost during decay. 2016-12-08
What are automatic variables (dollar variables) in a Makefile
?
Automatic variables in a Makefile, like $@
for the target and $^
for the dependencies, reduce repetition in rules. 2016-12-07
What is a âbinary-safeâ string?
C strings use null-terminated byte arrays, which cannot represent arbitrary binary data. Binary-safe strings explicitly store the length, allowing them to represent any sequence of bytes. 2016-12-06
How do I set the C compiler in a Makefile
?
Set the C compiler in Makefile
using predefined variable $(CC)
, which defaults to cc
and can be redefined. 2016-12-05
What is FILE
in C?
A FILE
is a C data type that represents an open file. It contains metadata about the file, such as its file descriptor and buffers. 2016-12-04
What does the restrict
keyword mean in C?
The restrict
keyword in C is a type qualifier that indicates a pointer parameter points to an object not accessed through any other pointer in the functionâs scope. This allows the compiler to make optimizations. 2016-12-03
What does const
mean in C?
const
is a type qualifier in C that makes a variable unassignable, except during initialization. 2016-12-02
Does C have booleans?
C99 introduced the stdbool.h
header, providing bool
, true
, and false
for boolean values, building on the _Bool
type. 2016-12-01
What is realloc
in C?
realloc
resizes an allocated memory block, copying contents if necessary. 2016-12-01
Where is the C programming language defined?
C is defined in several places, including âThe C Programming Languageâ by Kernighan and Ritchie, and a series of ISO C standards (C89, C99, C11). 2016-11-30
Does C allow pointer arithmetic?
Computing a pointer to unowned memory invokes undefined behavior, even without dereferencing! 2016-11-30
How do I write a multi-line string literal in C?
Use concatenated string literals with newline characters to define multi-line string literals in C. 2016-11-30
Can I put comments in string literals in C?
C string literals can contain comment-like characters, which are treated as literal text, not as comments. 2016-11-30
What do array subscripts mean in C?
C array subscripts are defined as pointer arithmetic, where a[b]
means *(a+b)
. This means a[b]
is the same as b[a]
! 2016-11-30
How do I find out which preprocessor my C compiler uses?
To find out which preprocessor your C compiler uses, run the compiler with the -print-prog-name=cpp
flag, which shows the path to the preprocessor subprogram it calls. 2016-11-29
What is size_t
for? How do I iterate over an object in C?
size_t
is used to represent the size of objects in memory. It is commonly used for array indexing. 2016-11-29
What type should I use to count objects in C?
Use uintptr_t
to count objects in C, as it can represent the largest possible pointer value. 2016-11-29
What is static
in C?
static
in C can modify variable declarations inside and outside a function body, and function parameters. 2016-11-28
What does void
mean as a function parameter in C?
void
in a C function parameter list means the function takes no arguments, whereas an empty list allows for an unspecified number of arguments. 2016-11-27
What is void
in C?
void
in C has multiple meanings: as a return type to indicate no return value, as a parameter type to indicate no parameters, and as a pointer type to indicate a pointer to an unknown type. 2016-11-27
What is K&R style function definition in C?
The âK&R-styleâ function definition in C uses an initializer list to declare parameters, unlike the more common parameter type list. This old-style definition has significant semantic differences and should be avoided due to its potential for undefined behavior. 2016-11-27
Bike front derailleur
The front derailleur (Shimano FD-2203) is incompatible with the triple crankset, causing shifting issues. A compatible front derailleur like Shimano FD-5603 may be needed to resolve the problem. 2016-11-27
Donât use the word âitâ
Avoid using ambiguous pronouns like âitâ in technical writing. Refer to specific referents explicitly to improve clarity. 2016-11-25
A C typedef convention for complex types
A convention for expressing complex C types using typedef
and a âreverse Polish notationâ syntax to improve readability. 2016-11-24
How is the stack laid out in C?
The stack layout in C includes function arguments, return address, and local variables. Addresses decrease as you go through the arguments, and the stack grows downward with each function call. 2016-11-24
How do varargs work in C?
Variadic functions in C use the ...
syntax to accept an arbitrary number of arguments. The stdarg.h
library provides va_start
, va_arg
, and va_end
to access the arguments. 2016-11-23
How does a stream cipher work?
A stream cipher works like a one-time pad, but uses a pseudorandom âkeystreamâ from a PRNG seeded by a secret key and nonce, preventing attacks based on pad disclosure or reuse. 2016-11-21
Should I buy Huel or Joylent?
Comparing meal replacement options Huel and Joylent, I choose Joylentâs vegan version. 2016-11-20
What is symmetric cryptography?
Symmetric cryptography uses a shared secret key for both encryption and authentication, providing confidentiality and integrity. We look at the API, HMAC, and Authenticated Encryption. 2016-11-19
How do I change the resolution on macOS?
To get more screen real-estate, go to System Preferences > Displays, and select âMore Spaceâ . 2016-11-18
What is an .xcworkspace
file?
An .xcworkspace
file is a directory that contains a workspace configuration for Xcode projects. 2016-11-17
What is an .xcodeproj
file?
The .xcodeproj
âfileâ is actually a directory that contains a project.pbxproj
file, which is a text file that stores the settings of an Xcode project, including information about the files, build configurations, targets, and dependencies. 2016-11-17
How do I write a UDP server in Go?
A UDP server that listens for packets and prints the received messages. A UDP client that sends âhelloâ to the server. 2016-11-17
How do I replace target/action with callbacks in Swift?
Use a CallbackWrapper
object to associate a closure with an NSControl
, setting the target
and action
properties to enable callback-based event handling. 2016-11-17
Summary of âZero to Oneâ, Chapter 1: the challenge of the future
Progress comes from either copying or creating. Global progress since 1971 has been copying via globalization, except for computing. Startups create, not copy, because small groups, not large, can think anew. 2016-11-17
Learning vim (a short adventure)
I try Vim. I give up after discovering that the cursor cannot sit at the end of a line. 2016-11-16
How do I serialize JSON in Swift?
Serialize JSON in Swift with JSONSerialization.data(withJSONObject:options:)
. 2016-11-16
Post every day
Daily blogging pledge; punishment for failure TBD. 2016-11-16
A summary of âOn-the-Fly Garbage Collection: An Exercise in Cooperationâ
A concurrent garbage collection algorithm that keeps synchronization constraints between the mutator and collector processes as weak as possible. It uses node markings (white, grey, black) to ensure reachable objects are not incorrectly collected. 2016-11-16
Should I get a cleaner?
Hired a cleaning service that takes a third of the hourly rate. 2016-11-16
128 byte of CSS is enough
Limiting CSS to 128 bytes prevents bloat and distractions, allowing focus on content. 2016-11-15
How does tricolor garbage collection work?
Golangâs garbage collector uses a âtricolorâ algorithm, dividing heap objects into black, white, and grey sets. The algorithm can run concurrently with the program, and the âtricolorâ invariant ensures no pointers go directly from the black set to the white set, allowing the white set to be cleared. 2016-11-11
Forging web security by escaping the browser viewport
2016-08-10
Low latency, large working set, and GHCâs garbage collector: pick two of three
Large working sets and low latency are incompatible with GHCâs stop-the-world garbage collector, which optimizes for throughput instead of latency. The collectorâs pause times scale linearly with working set size. 2016-05-12
Wikipedia needs an IDE, not a WYSIWYG editor
2014-10-25
Software developers are not depressed (but everyone else is)
2014-10-23
Your first-class functions donât make you functional
2014-10-11
The price model shapes the product
2014-10-06
I want problems, not solutions!
2014-10-04
Nix by example, Part 1: The Nix expression language
Nix is a functional programming language used for package management. We see the Nix expression language, including strings, primitives, operators, functions, let expressions, and conditionals. 2014-09-28
Git log spelunker (A proposal)
2014-09-14
Documentation for free, or, in-wiki issue tracking
2014-09-13
A semantic wiki in Prolog
Prolog as a better alternative to âsemantic triplesâ and SPARQL. 2014-08-24
Hide your hyper-links, or, dealing with depth-first syndrome
2014-08-21
Use a repository as your CI database
2014-08-19
Documentation black holes: things we write that donât get read
Documentation often ends up in black holes - internal documents, issue trackers, test cases, conversations, commit messages, and wikis - where it goes unread. Focus on writing documentation that people will actually read, like product names, homepages, and inline help. 2014-08-13
Does a branch identify a commit, or does a commit identify a branch?
2014-08-10
Why canât I see my phone screen in sunlight?
Phone screens have low contrast in sunlight because the reflected sunlight overpowers the screenâs own light output, reducing the effective contrast ratio. 2014-08-09
Estimates are not deadlines
The difference between estimates and deadlines, and why conflating the two can cause problems in project management. 2014-07-27
Your syntax highlighter is wrong
Syntax highlighters make value judgments about code. Most highlighters judge that comments are cruft, and try to hide them. Most diff viewers judge that code deletions are bad. 2014-05-11
Alan Turingâs âroyal pardonâ is absurd
2014-05-10
On the absence of energy and time in the virtual world of applications, or, the misconception of the âdistraction-freeâ mode
Physical books and board games require energy and time to access, which creates a sense of focus. Virtual applications lack these constraints, leading to constant distraction. 2014-05-04
A proof that the Halting problem is undecidable, using JavaScript and examples
A JS function to decide the Halting Problem will always have a logical contradiction. 2013-12-24
TODO DAG
A task management system using a directed acyclic graph (DAG) to represent task dependencies and priorities, allowing for more nuanced organization than a flat to-do list. 2013-12-19
Where is the Firefox application shortcut?
Firefox still lacks a built-in feature to create application shortcuts, unlike Chrome, despite the rise of web apps over the past decade. 2013-11-19
Un-biasing a biased coin
Flip a biased coin twice to get an unbiased outcome. Use HT and TH as the outcomes, ignoring HH and TT. 2013-11-16
Visualizing world population
2012-10-30
Is a crime an occupation?
2012-04-15
Boycotting for the masses: a web solution
2012-04-08
A proposal for visual pure functional programming
A visual programming language inspired by Haskell. 2012-02-27
The Thatcher effect in typography
2010-02-10
Page margins in principle and practice
2010-01-25
Redundant information in unordered lists: fundamental?
2010-01-19
Normally, I hand craft my images using vim
2010-01-19
The long road from HTML to PDF
2010-01-17
To what extent did the trial of Giordano Bruno set a precedent for that of Galileo?
The trials of Giordano Bruno and Galileo were connected, not because Bruno was a proto-Galileo, but because the Inquisition associated Galileoâs Copernicanism with Brunoâs condemned Hermeticism and theological heresies, creating a precedent for condemning Galileo. 2008-02-15
Do not ask if I had a good holiday
A disastrous start to a holiday in Turkey, involving a naked midnight run, injured toes, heat exhaustion, and a serious bacterial infection, leading to an unpleasant but unforgettable trip. 2007-07-27
Tetra Pak: Faithful Friend, Silent Hero, and Protector of All Things Good
An ode to the Tetra Pak carton. 2007-05-23
What were the principal factors governing state formation in the early modern period?
Humanism, the Reformation, centralized administration, the decline of feudalism, and the rise of national identity. 2007-03-10
In what ways might natural magic be seen to have contributed to the emergence of modern scientific method?
Natural magic and scientific method share commonalities, but only scientific method distinguished correlation from causation. The Scientific Revolution arose from internal technological developments, the link between knowledge and political power, and the destruction of absolute truth from the Renaissance and Reformation. 2007-02-09
âA liberal revolution that was blown off courseâ. Is this an adequate description of what happened in France?
The French Revolution, far from being a âliberal revolutionâ, was defined by violence from the start, with the Terror and subsequent instability being a logical continuation, not a deviation, from the events of 1789. 2006-12-11