Skip to content

Instantly share code, notes, and snippets.

import re
import sys
from collections import defaultdict
from pathlib import Path
import inspect
def run(f, argv = None, *, converters = None):
"""
Usage:
@valtron
valtron / assembler.py
Created September 2, 2017 07:28
Hack machine language assembler
import re
from pathlib import Path
def main():
dir = Path('.')
for pi in dir.glob('**/*.asm'):
po = Path(str(pi).replace('.asm', '.hack'))
assemble(pi, po)
def assemble(pi, po):
@valtron
valtron / t.py
Last active April 1, 2017 19:03
Aaronson's Sentence
# Aaronson's Sentence
# https://oeis.org/A005224
import re
import collections
from num2words import num2words
l = 1
q = collections.deque()
def emit(txt):
@valtron
valtron / fsconv.py
Last active February 19, 2017 20:18
"""
Filter sharing convolution: https://arxiv.org/abs/1612.02575
Excl. bias, has MNP+PS parameters (vs. MNS for regular conv).
"""
import functools
from keras import backend as K
from keras import activations, initializations, regularizers, constraints
from keras.engine import Layer, InputSpec
@valtron
valtron / capture_queries.py
Created February 25, 2014 18:56
Context manager for collecting queries executed in a Django environment.
class CaptureQueries(object):
"""
Context manager that captures queries executed by the specified connection.
Mostly copied from django.test.utils.CaptureQueriesContext.
"""
def __init__(self, connection = None):
if connection is None:
from django import db
connection = db.connection
@valtron
valtron / list_urls.py
Created August 8, 2013 17:44
Lists full url regexes that are matched by a django urlconf in a standardized form.
from project import urls
def main():
for x in sorted(map(combine, list_urls(urls.urlpatterns))):
print x
def list_urls(urllist):
for entry in urllist:
if hasattr(entry, 'url_patterns'):
for x in list_urls(entry.url_patterns):
@valtron
valtron / gist:5688638
Last active January 24, 2017 23:53
typescript-unsound-generics.ts
class Box<T> { constructor(public value: T) {} }
class A {}
class B { foo() {} }
var bb : Box<B> = new Box<B>(null);
// This typechecks (it shouldn't; T is used both in a co- and contra-variant position, so it's invariant)...
var ba : Box<A> = xb;
ba.value = new A();
@valtron
valtron / caching.py
Created March 10, 2013 21:46
Shows the effect of regex caching in python.
from re import _MAXCACHE, _cache
from timeit import timeit
setup = '''
from re import compile
def create_regex(n):
return compile(r'^(a*b*|a+c*|b*|c*)a*b*c*(a*|(b*|c*)){:03}$'.format(n))
def run(n):
@valtron
valtron / bug.py
Last active December 14, 2015 08:58
Replicates concurrency bug described in https://github.com/mitsuhiko/jinja2/issues/8 using two threads. `MyLRUCache` implements a fix using a lock. The first commandline argument is the amount of time to sleep between accesses to the cache. If set to 0, it triggers the bug almost right away. If set to 0.001 (the smallest nonzero value sleep will…
from threading import Thread
from time import sleep, time
from random import choice, random
from jinja2.utils import LRUCache
class MyLRUCache(LRUCache):
def __getitem__(self, key):
self._wlock.acquire()
try:
@valtron
valtron / rationals.py
Created February 27, 2013 22:37
Script to enumerate rational numbers
from itertools import izip, imap
from fractions import Fraction, gcd
def main():
for x in rationals():
print x
def rationals():
yield Fraction()