Contents

A memory efficient nonce system

Linux compose key sequences

Here.

How to remap the buttons of the Kensington Expert Mouse

Save the following file to /etc/udev/hwdb.d/70-trackball-remap.hwdb

evdev:name:Kensington Expert Mouse:*
 KEYBOARD_KEY_90001=btn_middle
 KEYBOARD_KEY_90002=btn_right
 KEYBOARD_KEY_90003=btn_left
 KEYBOARD_KEY_90004=btn_side

Then run as root

systemd-hwdb update
udevadm trigger

Important notes

Render "GitLab Flavored Markdown"

Obtain an access token (look in your user preferences on GitLab for access tokens).

When you have one, copy it to ~/.gitlab-access-token

Then create this file in an location in your PATH, e.g., ~/bin/render-glfm

#!/bin/bash
[ -z $GITLAB_ACCESS_TOKEN ] && GITLAB_ACCESS_TOKEN=$(< ~/.gitlab-access-token)
TMP="$(mktemp -u)"
python3 -c '
import json
d=dict()
with open("'"$1"'","r") as fd:
    d["text"]=fd.read()
d["gfm"]="true"
with open("'"$TMP"'","w") as fd:
    json.dump(d,fd)
'
curl --request POST --header "PRIVATE-TOKEN: $GITLAB_ACCESS_TOKEN" \
     --header "Content-Type:application/json" \
     -T "$TMP" \
     "https://gitlab.com/api/v4/markdown" \
     | python3 -c 'import sys; import json; print(json.loads(sys.stdin.read())["html"])'

You can now render markdown by doing

render-glfm path/to/your/file.md > path/to/result.html

Out of source builds with make

See the source code package here.

Simpler dependency generation with make

Courtesy of the Embedded Artistry course.

.PHONY: all test clean

LIB_DIR=src
TEST_DIR=test
CPPFLAGS=-std=c++11 -Wall

# These flags generate dependency files at compile-time
DEPFLAGS = -MT $@ -MMD -MP -MF $*.d

INCLUDES=\
    -I$(LIB_DIR)\
    -I$(TEST_DIR)

SRCS=\
    $(wildcard $(LIB_DIR)/*.cpp)\
    $(wildcard $(TEST_DIR)/*.cpp)
OBJS=$(SRCS:.cpp=.o)
DEPFILES=$(SRCS:.cpp=.d) # Generate depfile names for use in Make prerequisites

all: clean test

%.o: %.cpp
    $(CXX) $(CPPFLAGS) $(DEPFLAGS) $(INCLUDES) -c $< -o $@

test: run_test
run_test: $(OBJS)
    $(CXX) $(CPPFLAGS) $(DEPFLAGS) $(INCLUDES) -o run_test $(OBJS)
    ./run_test

clean:
    $(RM) $(OBJS)
    $(RM) $(DEPFILES)


$(DEPFILES): # Each dependency is made a target so that make doesn't fail if the file doesn't exist

# You will need to include the dependency files. We usually keep this at the bottom of a Makefile
include $(wildcard $(DEPFILES))

Useful tmux commands

List windows in current session

tmux choose-tree -f '#{==:#{session_id},'$(tmux display -p '#{session_id}')'}'

Track git repos with Make

# gitdeps.mk (suggested name for this included Makefile, see below)

# Routines for having git repositories checked out to particular commits as Make
# dependencies.
# This avoids submodules.


# call this to generate a file name where the commithash will get stored
# things that depend on the repo need to depend on $(call git-dep-commit-hash-file,$(path_to_repo))
git-dep-commit-hash-file = $1.commithash

# In the following function, we have
# $1 is repo path
# $2 are dependencies for repo path
# $3 is repo URL
# $4 is the hash of the commit we want to pin to
#
# Add a git repository commit ($4) in $1 as a dependency for a
# target
#
# How it works:
# (this is based on tracking checksum changes of files instead of their
# modification times:
# https://www.cmcrossroads.com/article/rebuilding-when-files-checksum-changes)
# The target is made to depend on a file containing the hash of the commit we
# want to pin to ($1.commithash).
# The filter-out function uses the contents of this file (the empty string if
# the file doesn't exist) to compare with the current commit hash
# ($4) and the
# desired commit hash. If either of these don't equal the contents of the file,
# the git repo fetches new commits (from $3) checks out the desired commit and stores
# that in the commit hash file. Note that ($if ...) enters the clause if its
# argument is a non-empty string.
#
# To update the commit that we depend on, just change
# $4 in the Makefile. The next time
# $1.commithash is used as a dependency and files are
# built using the Makefile, it will be seen as different from
# $4 and the repo will get checked out to the proper
# commit. This rule will always run because of the FORCE prerequisite (the
# commit hash will always get checked).
#
# Note that this should be called using $(eval $(call git-dep, ... )) because we
# want the Makefile to read in the resulting rules (using eval)
define git-dep =
$1 : $2
    git clone $3 $$@

$$(call git-dep-commit-hash-file,$1): FORCE $1
    $$(if $$(filter-out $$(shell cat $$@ 2>/dev/null),\
            $$(shell git -C $1 log HEAD^..HEAD --format='%H')\
            $$(shell echo $4)),\
        git -C $1 fetch && \
            git -C $1 \
                checkout $4 && \
            git -C $1 log HEAD^..HEAD --format='%H' > $$@)
endef

Example usage

# To have something depend on a repo checked out to a specific commit, we
# usually want an untracked directory where the repos are cloned to, we need
# to include the functions defined above, we need a dependency on the file
# containing the hash, and we need to call $(eval $(call git-dep ...)) with
# the proper arguments.

MAKEDEPS=.makedeps

$(MAKEDEPS):
    mkdir -p $@

-include gitdeps.mk

REPO=$(MAKEDEPS)/repo
REPO_URL ?= git@zombo.com:me/repo.git
REPO_COMMITHASH=283d01dac9f66d9ad85ab5eb0ce9e52a45bebcd5

# Note that $(MAKEDEPS) is supplied as an order-only prerequisite (using '|',
# its modification time is not checked, only if it exists or not) because any
# modifications to stuff in that directory changes its modifcation time. But we
# only want it created if it doesn't exist because it is just a directory.
$(eval $(call git-dep,$(REPO),| $(MAKEDEPS),$(REPO_URL),$(REPO_COMMITHASH)))

clonegitdeps: $(call git-dep-commit-hash-file,$(REPO)) ... # add other hashes here as needed

# then things can have it as a dependency
all: ... clonegitdeps
    ...

# To add another repo in the same project, you only need to do
# $(eval $(call git-deps,$(ANOTHER_REPO),| $(MAKEDEPS), $(ANOTHER_REPO_URL),$(ANOTHER_REPO_COMMITHASH)))
# (with those variables defined somewhere of course)

Dependency generation with Make

Includes how it can work with generated headers.

Download example.

File Encrpytion

Import and export keys with GPG

Encrypt and decrypt a file with SSH keys

Recursive allocation in C

Kind of sketchy maybe and wastes space

#include <stddef.h>
#include <stdio.h>

struct list {
    struct list *next;
    size_t id;
};
typedef struct list list_t;

size_t list_alloc(size_t n_nodes, void *start_addr, list_t *prev)
{
    if (n_nodes > 0) {
        list_t node = {.next = NULL, .id = n_nodes};
        prev->next = &node;
        return list_alloc(n_nodes - 1, start_addr, &node);
    } else {
        char dummy;
        void *p = &dummy;
        // stack grows downward in addresses
        return start_addr - p;
    }
}

void list_print(const list_t *node)
{
    if (node) {
        printf("id: %lu\n",node->id);
        list_print(node->next);
    }
}

int main (void)
{
    size_t len;
    list_t head = {.id = 999 };
    char dummy;
    char buf[len = list_alloc(10,&dummy,&head)];
    list_print(&head);
    printf("len: %lu vs %lu\n",len,sizeof(list_t)*10);
    return 0;
}

atoi in bash

#!/bin/bash

[ -z $PRECISION ] && PRECISION=32
[ -z $ENDIAN ] && ENDIAN=little
x=$1
if [[ $x -lt 0 ]]; then
    x=$(( 2**$PRECISION + $x ))
fi

r=''
while [[ $x -gt 0 ]]; do
    case $ENDIAN in
        little)
            r=$r$(printf '\\x%02x' $(( $x & 0xff )))
            ;;
        big)
            r=$(printf '\\x%02x' $(( $x & 0xff )))$r
            ;;
        *)
            echo "Bad endianness $ENDIAN" >&2
            exit -1
            ;;
    esac
    x=$(( $x >> 8 ))
done

echo -ne "$r"

Example

$ ENDIAN=big /tmp/atoi.sh -12345 | od --endian=big -t d4
0000000      -12345
0000004

atoi.sh

A lookup function in pure bash

# lookup.sh
lookup () 
{
    # create selector string
    s=$(seq -s' ' 0 $(($1 + 1)))
    s="${s/$1/x}"
    s="${s//[[:digit:]]/_}"
    while read $s; do echo -n "$x"; done
}

Example

$ source /tmp/lookup.sh && wc /tmp/lookup.sh | lookup 0