Skip to content

Instantly share code, notes, and snippets.

View mbarkhau's full-sized avatar
💭

mbarkhau

💭
  • Cyberspace
View GitHub Profile
class Memoizer(object):
"""Memoizer for pure functions with positional hashable arguments.
Eviction from cache is done more or less at random, which
in practice is surprisingly close to a LRU strategy.
"""
def __init__(self, func, maxsize=10000):
self.func = func
self.maxsize = maxsize
@mbarkhau
mbarkhau / redict.py
Last active December 18, 2015 12:49
Limited size dictionar with Random Eviction
from random import randint
class REDict(dict):
def __init__(self, maxsize, *args, **kwargs):
self._maxsize = maxsize
self._keys = []
self._evict_cb = kwargs.pop('_evict_cb', None)
dict.__init__(self, *args, **kwargs)
@mbarkhau
mbarkhau / freshfile.py
Last active December 20, 2015 15:59
Class which will always give the fresh contents of a file
import codecs
from os.path import getmtime
from time import time
class FreshFile(object):
def __init__(self, filename, mode='r', encoding='utf-8', process_func=None,
max_age=0):
self._filename = filename
def eval_sexpr(sexpr):
fn = sexpr[0]
args = sexpr[1:]
args = tuple(eval_sexpr(e) if isinstance(e, tuple) else e for e in args)
return fn(*args)
import operator as op
eval_sexpr((op.add, (op.mul, 3, 4), (op.mul, 2, 5)))
@mbarkhau
mbarkhau / gen_wallet_seed.py
Last active May 5, 2022 23:35
Snippet to create electrum seed from rolls of a six sided dice and a secret passphrase.
#!/usr/bin/env python
"""Electrum Wallet Seed Generator (use at own risk).
Usage:
-h --help
-s --seed-bits=<bits> Size of the wallet seed in bits
[default: 256]
-i --iterations=<iterations> Number of pbkdf2 iterations
[default: 500000]
@mbarkhau
mbarkhau / lazy.py
Created March 4, 2014 00:21
LazyObject and decorator
# "Of being lazy" February 2, 2013 by Paul Masurel
# http://fulmicoton.com/posts/lazy/
class LazyObject(object):
__slots__ = [ "_recipe", "_result", "_evaluated" ]
def __init__(self, recipe):
object.__setattr__(self, "_recipe", recipe)
object.__setattr__(self, "_result", None)
@mbarkhau
mbarkhau / safe_eval.py
Last active August 29, 2015 14:04
safe python eval
try:
import builtins
except ImportError:
# PY2 compat
import __builtin__ as builtins
import re
import math
from functools import partial
@mbarkhau
mbarkhau / multisort.py
Created September 5, 2014 12:32
Sort items in a list by multiple fields
from operator import itemgetter
def multisort(vals, sort_spec, in_place=False):
comparers = []
for i, spec in enumerate(sort_spec):
if isinstance(spec, tuple):
key, polarity = spec
elif isinstance(spec, (str, unicode)):
key = spec.replace("-", "", 1)
polarity = 1
@mbarkhau
mbarkhau / pp_timeit.py
Last active August 29, 2015 14:15
Pretty print replacement for timeit
# coding: utf-8
"""
Pretty print replacement for timeit
pp_timeit.auto_timeit runs a statement and automatically
determines the number of repetitions required to gain
satisfactory accuracy (similar to timeit.main).
pp_timeit uses auto_timeit and prints the result so that the
different magnitudes of results are visible by their alignment.
@mbarkhau
mbarkhau / getarg.py
Last active April 1, 2022 14:24
mimimal arg parsing
import sys
def getarg(argname, args=sys.argv[1:]):
long_arg = '--' + argname
short_arg = '-' + argname[:1]
for idx, arg in enumerate(args):
if arg.startswith(long_arg):
if arg == long_arg:
# check for parameter