Skip to content

Instantly share code, notes, and snippets.

@cutthroat
cutthroat / gist:4957198
Created February 14, 2013 23:02
Heap's method for generating permutations
// Heap's method, see Sedgewick (1977)
function eachPerm(a, callback, target) {
var n = a.length;
var c = new Array(n);
var j = n;
while (j--) { c[j] = 0; }
var m = 0;
callback.call(target, a, m++);
var i = 1;
do {
@cutthroat
cutthroat / split.lua
Created January 28, 2013 16:02
Split strings in Lua, the Python way
function string.split(s, pattern, init, plain)
local function f(s, init)
local n = #s + 1
if init > n then return nil end
local i, j = s:find(pattern, init, plain)
if i == nil then
return n + 1, init, n - 1
else
return j + 1, init, i - 1
end
@cutthroat
cutthroat / gist:4620655
Created January 24, 2013 12:00
A (possibly incorrect) way to get non-blank input from STDIN
sub non_blank_or_prompt {
my $input = shift;
if (length($input // '') < 1) {
# Check for tty. However, consider IO::Interactive
-t STDIN and -t STDERR
or die "Input required";
for (;;) {
print STDERR "Enter something: ";
defined ($input = <STDIN>)
or die "\nInput required";
@cutthroat
cutthroat / amd64_sysv.h
Created October 11, 2012 15:57
Simple C coroutines on AMD64/SysV
#pragma once
/* Each coroutine is represented by a pointer to its stack bottom. */
typedef void *co_coro;
/* The coroutine procedure takes the calling coroutine as its first argument. */
typedef void (*co_proc)(co_coro back);
/* Switch to new coroutine. The stack top must be 16 byte aligned.*/
@cutthroat
cutthroat / dis.py
Created June 16, 2011 18:11
disassemble python byte code
# i got my 9 millimeter at my waist, papa
# i got my shotgun in the escalade, papa
from opcode import HAVE_ARGUMENT, EXTENDED_ARG, opname, opmap, cmp_op
from opcode import hasconst, hasfree, hasname, hasjrel, hasjabs, haslocal, hascompare
haspair = [opmap[x] for x in ('UNPACK_EX', 'CALL_FUNCTION')]
# global convention:
# i - position of the opcode in the byte stream
@cutthroat
cutthroat / pickle_list.c
Created December 21, 2010 00:40
basic linked list serialization
#include <stdlib.h>
#include <stdio.h>
/* list in core */
/* node in our linked list */
struct node {
struct node *link;
long data;
@cutthroat
cutthroat / gist:647786
Created October 26, 2010 20:58
cartesian product of array valued hash
def product(h)
k = h.keys
v = h.values_at(*k)
p = v.shift.product(*v)
p.map { |v| Hash[k.zip(v)] }
end
{- how to eval Icon pure integer-expressions -}
{- values -}
data D = DNull | DInt Int
deriving (Show, Eq)
newtype V = V { runV :: [D] }
deriving (Show)
@cutthroat
cutthroat / avltree.c
Created May 21, 2010 15:41
simple avl tree implementation
#include <stdlib.h>
#include <errno.h>
#include <stdio.h>
#include "avltree.h"
struct node {
struct node *left, *right;
int diff;
key_t key;
};