Skip to content

Instantly share code, notes, and snippets.

View sampsyo's full-sized avatar

Adrian Sampson sampsyo

View GitHub Profile
@sampsyo
sampsyo / gist:281277
Created January 19, 2010 20:42
fix for exception handler ordering in ASM
import java.util.Collections;
import java.util.Comparator;
import org.objectweb.asm.Label;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.tree.MethodNode;
import org.objectweb.asm.tree.TryCatchBlockNode;
/**
* Sorts the exception handlers in a method innermost-to-outermost. This
* allows the programmer to add handlers without worrying about ordering them
@sampsyo
sampsyo / subcommand.py
Created July 3, 2010 17:37
subcommand support for Python's optparse
"""A simple addition to Python's optparse module supporting subcommands
like those found in the svn or hg CLIs.
To use it, instantiate the Subcommand class for every subcommand you
want to support. Each subcommand has a name, aliases, a help message,
and a separate OptionParser instance. Then pass a list of Subcommands
to the constructor of SubcommandsOptionParser to make a subcommand-
aware parser. Calling parse_args on that parser gives you the
subcommand invoked, the subcommand's arguments and options, and the
global options all in one fell swoop. See the smoke test at the bottom
@sampsyo
sampsyo / enumeration.py
Created July 3, 2010 18:02
enumerated types for Python that really are types
"""A metaclass for enumerated types that really are types.
You can create enumerations with `enum(values, [name])` and they work
how you would expect them to.
>>> from enumeration import enum
>>> Direction = enum('north east south west', name='Direction')
>>> Direction.west
Direction.west
>>> Direction.west == Direction.west
@sampsyo
sampsyo / aliases.py
Created July 11, 2010 20:04
hack for argparse adding subcommand aliases
#!/usr/bin/env python
"""Aliases for argparse positional arguments."""
import argparse
class AliasedSubParsersAction(argparse._SubParsersAction):
class _AliasedPseudoAction(argparse.Action):
def __init__(self, name, aliases, help):
@sampsyo
sampsyo / empty.py
Created July 23, 2010 02:34
quick EC2 sandbox creator
#!/usr/bin/env python
"""Quickly get a temporary Ubuntu EC2 instance, SSH into it, and then
terminate the instance on logout.
"""
import boto
import subprocess
import time
# Set your AWS credentials.
EC2_ACCESS = ''
@sampsyo
sampsyo / runm.py
Created July 28, 2010 16:42
plot time data from runmeter with pychart
"""Plot time data from a Runmeter <http://www.abvio.com/runmeter/>
data export."""
import csv
import sys
from collections import defaultdict
import datetime
def runmeter_read(path):
doc = csv.reader(open(path))
@sampsyo
sampsyo / pipeline.py
Created August 1, 2010 02:25
multithreaded pipelines for Python coroutines
"""Simple but robust implementation of generator/coroutine-based
pipelines in Python. The pipelines may be run either sequentially
(single-threaded) or in parallel (one thread per pipeline stage).
This implementation supports pipeline bubbles (indications that the
processing for a certain item should abort). To use them, yield the
BUBBLE constant from any stage coroutine except the last.
In the parallel case, the implementation transparently handles thread
shutdown when the processing is complete and when a stage raises an
@sampsyo
sampsyo / fingerprinter-macports.diff
Created February 1, 2011 00:49
Fixes compilation of Last.fm fingerprinter under Mac OS X with libraries installed by MacPorts (correctly specifying the libraries that need to be linked).
diff -r 6a862c34b61f fplib/CMakeLists.txt
--- a/fplib/CMakeLists.txt Mon Jul 12 18:14:59 2010 +0100
+++ b/fplib/CMakeLists.txt Mon Jan 31 16:49:31 2011 -0800
@@ -19,6 +19,7 @@
IF(APPLE)
INCLUDE_DIRECTORIES(/opt/local/include/)
+LINK_DIRECTORIES(${LINK_DIRECTORIES} /opt/local/lib/)
ENDIF(APPLE)
@sampsyo
sampsyo / multijson.py
Created April 14, 2011 18:59
quick & dirty reading/writing of files containing multiple JSON objects
"""A couple of very simple utilities for reading and writing files
that contain multiple JSON values. Could be useful in situations where
you're generating a bunch of data for later processing and then, later,
you want to read it in an element at a time.
The json module doesn't really support streaming reads, though, so this
is limited by that. If you need real streaming, you probably want to use
something like ijson:
http://pypi.python.org/pypi/ijson/
"""
@sampsyo
sampsyo / gist:1137717
Created August 10, 2011 18:30
making MusicBrainz getters using templates
def _make_id_getter(entity):
def getter(id, **kwargs):
includes = []
for name in kwargs:
if not name.startswith('inc_'):
raise TypeError('got unexpected keyword argument...')
elif kwargs[name]:
includes.append(name[4:])
return _do_mb_query(entity, id, includes)
getter.__name__ = 'get_%s_by_id' % entity