Skip to content

Instantly share code, notes, and snippets.

@aprell
aprell / rm.sh
Created September 17, 2013 10:06
Remove everything in a directory except certain files
ls | grep -E -v 'file1|file2|file3' | xargs rm -rf
@aprell
aprell / tagged.c
Last active December 24, 2015 07:59
Tagged pointer basics
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <assert.h>
#define TAG_BITS 4
#define TAG_MASK 0xF
#define TAG_INT 3
#define bit(p, n) (((uintptr_t)(p) & (1 << (n))) != 0 ? 1 : 0)
@aprell
aprell / stmtexp.c
Created October 2, 2013 09:34
Statement expressions: "Blocks that return values"
#include <stdio.h>
typedef struct T {
int i, j;
float f;
} T;
int main(void)
{
T a = { 1, 2, 3.14 };
@aprell
aprell / unless.c
Created October 3, 2013 15:10
when/unless statements
#include <stdio.h>
#define and &&
#define or ||
#define not !
#define when(exp) if (exp)
#define unless(exp) if (not (exp))
static void open_and_read(int files, char *filenames[])
{
@aprell
aprell / coro.lua
Created October 10, 2013 12:52
Full asymmetric coroutines in Lua
function pingpong(n)
n = n or 3
coro = coroutine.create(function (msg)
for i = 1, n do
io.write(msg, " ")
msg = coroutine.yield("pong")
end
end)
local _, msg = coroutine.resume(coro, "ping")
for i = 1, n do
@aprell
aprell / corowrap.lua
Created October 10, 2013 12:58
coroutine.wrap in Lua
function count(s, e)
s = s or 0
e = e or s + 10
--[[
coro = coroutine.create(function ()
for i = s, e do
coroutine.yield(i)
end
end)
--]]
@aprell
aprell / wrapup.sh
Last active December 25, 2015 06:59
Quickly backup files and directories
#!/bin/bash
BACKUPDIR=$HOME/backups
if [ $# -eq 0 ]; then
echo "Usage: $(basename "$0") FILE..."
exit 0
fi
if [ ! -d $BACKUPDIR ]; then
@aprell
aprell / array.sh
Last active December 30, 2015 14:39
Arrays in Bash
#!/usr/bin/env bash
read -a files <<< $(echo *.{lua,go})
echo "Read ${#files[@]} files:"
for f in "${files[@]}"; do
echo " $f"
done
@aprell
aprell / associative_array.sh
Created December 7, 2013 14:58
Associative arrays in Bash 4
#!/usr/bin/env bash
declare -A table
table[foo]=1
table[bar]=2
table[baz]=3
for i in "${!table[@]}"; do
echo "$i: ${table[$i]}"
@aprell
aprell / clone.lua
Last active December 30, 2015 14:59
Prototype-based objects in Lua
function clone(o, ...)
assert(type(o) == "table", "clone works on objects (tables) only")
local c = setmetatable({}, {__index = o})
if c.init ~= nil then
c:init(...)
end
return c
end
local o1 = {a = 1, b = 2, n = "o1"}