Skip to content

Instantly share code, notes, and snippets.

@lahwran
Created April 4, 2013 23:55
Show Gist options
  • Save lahwran/cd5b4861c1532dfb359b to your computer and use it in GitHub Desktop.
Save lahwran/cd5b4861c1532dfb359b to your computer and use it in GitHub Desktop.
a bunch of varyingly rushed hacks I've written over the past couple of years
# put on permanent pythonpath, add "import aprilfools" to sitecustomize.py
import datetime
d = datetime.date.today()
if d.month==4 and d.day==1 or __name__ == "__main__":
from itertools import cycle as J
from itertools import izip as K
import sys
class L(object):
def __init__(C,B):
C.A=J(range(31, 37))
C.B=B
isattr=lambda C:C.B.isatty()
write=lambda C,G:C.B.write(C.D(G))
writelines=lambda C,H:[C.write(I)for I in H]
__str__=lambda C:C.D(str(C.B))
__repr__=lambda C:C.D(repr(C.B))
D=lambda C,G:"".join(["\033[%02dm%s"%(E,F)for E,F in K(C.A, G)])
sys.stdout = L(sys.stdout)
sys.stderr = L(sys.stderr)
if __name__ == "__main__":
import code
code.interact()
import re
prefix = u"\u200a"
inp = raw_input("message: ")
h = inp.encode("hex")
numeric = int(h, 16)
octal = oct(numeric).replace("L", "")
print octal
encoded = prefix + u"".join(unichr(0x2002 + int(x)) for x in octal)
final = (u'*' + encoded + u'*').encode("utf-8")
print final
mapping = dict((unichr(0x2002 + x), str(x)) for x in range(8))
inp = raw_input("message: ").decode("utf-8").replace(u"*", u"")
x = re.compile(u".*?\u200a([\u2002\u2003\u2004\u2005\u2006\
\u2007\u2008\u2009]+).*")
match = x.search(inp)
if not match:
print "invalid:", repr(inp)
else:
inp = match.group(1)
inp = inp.replace(prefix, u"")
text = "".join(mapping[char] for char in inp)
print text
numeric = int(text, 8)
h = hex(numeric).replace('0x', '').replace("L", "")
print h.decode('hex')
# quickie timer that sleeps for 300 seconds and prints along the way
from twisted.internet import reactor
import time
def done():
reactor.stop()
print "done"
reactor.callLater(300, done)
done = time.time() + 300
def tick():
import time
print time.time(), "tick", done - time.time()
reactor.callLater(1, tick)
tick()
reactor.run()
# gives a general idea where in data space a string is
import sys
import math
import argparse
from StringIO import StringIO
parser = argparse.ArgumentParser()
parser.add_argument("-s", "--string", dest="file", type=StringIO)
parser.add_argument("-f", "--file", dest="file", type=argparse.FileType("r"))
args = parser.parse_args()
arg = args.file.read()
hex = arg.encode("hex")
integer = int(hex, 16)
precision = 50
stringed = str(integer)
length = len(stringed)
if length > precision:
prefix = stringed[:precision + 1]
pre_prefix = prefix[0]
post_prefix = prefix[1:]
stringed = "%s.%se+%d" % (pre_prefix, post_prefix, length)
print stringed
# markov chain toy
from collections import defaultdict
import random
import time
from twisted.python import log
start = object()
end = object()
def generate(chain):
result = [start]
while result[-1] != end:
result.append(random.choice(chain[result[-1]]))
line = " ".join([x for x in result if x not in (start, end)])
return line
def add(chain, line):
split = line.split(" ")
split = [start] + split + [end]
for index, x in enumerate(split[:-1]):
chain[x].append(split[index+1])
def main():
seed = random.randint(1, 10000)
random.seed(seed)
log.msg("random seed: %r" % seed)
chain = defaultdict(list)
while True:
line = raw_input("You: ")
log.msg("You: %r" % line)
add(chain, line)
her = generate(chain)
log.msg("Her: %r" % her)
print "Her:", her
if __name__ == "__main__":
log.startLogging(open("markov-log-%d.log" % time.time(), "w"), setStdout=False)
main()
# allow calling functions with the class statement
class Metaclass(type):
def __new__(cls, name, bases, dct):
if bases == (object,):
return type.__new__(cls, name, bases, dct)
del dct["__module__"]
if "_args" in dct:
_args = dct["_args"]
del dct["_args"]
else:
_args = ()
return bases[-1](*_args, **dct)
class Call(object):
__metaclass__ = Metaclass
class test(Call, raw_input):
_args = "hi! ",
print test
class ohgodwhy(Call, dict):
a = "1"
b = "c"
c = "x"
print ohgodwhy
# first get the numeral 1
_ = (()==())
__ = _ + _
_ = __ - _
# now build our list of characters
# "False"
__ = `()==[]`
# + "True"
__ = __ + `()==()`
# + "L"
____ = _ + _
___ = (((____ ** ____ ** ____ ** ____) ** ____) ** ____)
__ = __ + ((`___`)[-_])
# + "set"
__ = __ + ((`{_,_}`)[:_ + _ + _])
print __
height = 5
width = 5
cellwidth = 5
cellheight = 5
def print_row(is_head):
fill, mark = " ", "|"
if is_head:
fill, mark = " -", "+"
fill_wide = fill * cellwidth
borders = mark * (width + 1)
print fill_wide.join(borders)
print
for x in range(height):
for row in range(cellheight):
print_row(row == 0)
print_row(True)
# template for use teaching how functions can be used to generate an image
def wrap(): # ignore this line
import math
def ljiggle(amount, x):
x = x % (amount * 2)
if x > amount:
return amount - (x - amount)
return x
def generate(x, y):
return color_husl(math.sqrt(x**2 + y**2),49, 80)
# --------------------------------------
# ignore everything below this line (at least initially)
import sys
import pygame
import hashlib
import time
import itertools
import os
from collections import namedtuple
def memoize(func):
cache = {}
def wrap(*a):
try:
return cache[a]
except KeyError:
x = func(*a)
cache[a] = x
return x
wrap.cache = cache
return wrap
generate = memoize(generate)
@memoize
def color_husl(hue, saturation, value):
h,s,v = hue,saturation,value
import husl
fr, fg, fb = husl.husl_to_rgb(h, s, v)
return color_rgb(fr, fg, fb)
@memoize
def color_rgb(r, g, b):
color = pygame.Color(
int(r * 255.0),
int(g * 255.0),
int(b * 255.0)
)
return color
def _hashfile(filename):
with open(filename, "rb") as reader:
result = reader.read()
return result
_modulehash = _hashfile(__file__)
class Restarter(object):
def __init__(self):
self.should_restart = False
self.orig_cwd = os.path.realpath(".")
self.to_flush = [sys.stdout, sys.stderr]
self.args = sys.argv
def restart(self, args=None):
if args is not None:
self.args = [self.args[0]] + args
self.should_restart = True
def call(self, target, *args):
target(self, *args)
if self.should_restart:
os.chdir(self.orig_cwd)
sys.__stdout__.write("** restarting **\n")
for f in self.to_flush:
f.flush()
for f in self.to_flush:
os.fsync(f.fileno())
os.execv(sys.executable, [sys.executable] + self.args)
class PygameControllyThingy(object):
def __init__(self, width, height):
self.width = width
self.height = height
self.size = (width, height)
self.running = False
self.restarter = None
def run(self, restarter):
self.restarter = restarter
self.running = True
self.init_time = time.time()
self.tick_delta = 0.0
self.tick_time = 0.0
self.last_tick = 0.0
self.scale = 1
pygame.init()
self.display = pygame.display.set_mode(self.size)
while self.running:
self.attempt_reload()
for event in pygame.event.get():
if event.type == pygame.QUIT:
self.running = False
self.restarter.should_restart = False
if event.type == pygame.MOUSEBUTTONDOWN:
if event.button == 4:
self.scale *= 0.8
elif event.button == 5:
self.scale *= 1.25
pygame.display.set_caption(str(self.scale) + "x scale")
if self.running and self.tick_time == 0.0:
self.main()
self.tick_time = time.time() - self.init_time
self.tick_delta = self.tick_time - self.last_tick
remaining = 0.1 - self.tick_delta
if remaining > 0.0:
time.sleep(remaining)
self.last_tick = self.tick_time
def attempt_reload(self):
if _hashfile(__file__) != _modulehash:
self.restarter.restart()
self.running = False
def main(self):
pa = pygame.PixelArray(self.display)
for x, y in itertools.product(xrange(self.width),
xrange(self.height)):
pa[x][y] = generate((x - (self.width/2)) * self.scale,
(y - (self.height/2)) * self.scale)
pygame.display.flip()
if __name__ == "__main__":
restarter = Restarter()
controlly = PygameControllyThingy(640, 480)
restarter.call(controlly.run)
wrap()
class q(object):
def __nonzero__(self):
import inspect
import re
stack = inspect.stack()
matchy = re.compile("^if q: (.*)$")
parentframe = stack[1]
stackframe = parentframe[0]
text = parentframe[4][0].strip()
match = matchy.match(text)
assert match
code = match.group(1)
print code, "==", eval(code, stackframe.f_globals, stackframe.f_locals)
return False
q = q()
if q: 1 + 1
# parallelize random_brute_forcer.py
import subprocess
import itertools
import time
import signal
import sys
subprocesses = []
threads = 16
target = sys.argv[1]
try:
offset = sys.argv[2]
except:
offset = '0'
for i in range(threads):
proc = subprocess.Popen(["pypy", "random_brute_forcer.py", target, str(i), str(threads), "stopfile", offset])
subprocesses.append(proc)
# brute force random.choice() until it produces a word
import random
import sys
import os
import time
print list(enumerate(sys.argv))
random = random.Random()
target = sys.argv[1]
result = ""
thread = int(sys.argv[2])
offset = int(sys.argv[5])
seed = offset + thread
stopfile = sys.argv[4]
inc = int(sys.argv[3])
maxprint = int(1000000.0 / inc)
printat_ = int((float(thread) / float(inc)) * maxprint)
printat = printat_ / inc
startsleep = float(thread)/float(inc)
endsleep = (float(inc) - float(thread)) / float(inc)
time.sleep(startsleep)
print
print "startsleep:", startsleep
print "endsleep:", endsleep
print "totalsleep:", startsleep + endsleep
print "target:", target
print "thread:", thread
print "starting seed:", seed
print "inc:", inc
print "maxprint:", maxprint
print "print-at-:", printat_
print "print-at:", printat
print
time.sleep(endsleep)
print "starting"
try:
os.remove(stopfile)
except:
pass
start = 32 # ord(' ')
end = 90 # ord('Z')
while result != target:
seed += inc
random.seed(seed)
if (seed / inc) % maxprint == printat:
print seed
if os.path.exists(stopfile):
break
result = "".join([chr(random.randint(start, end)) for i in target])
if result == target:
print "seed: %r" % seed
random.seed(seed)
print "".join([chr(random.randint(start, end)) for i in range(10)])
w = open(stopfile, "w")
w.write("")
w.close()
# template for printing the brute forced random
import random
import sys
random.seed(476094213)
print "".join(chr(random.randint(32, 90)) for x in range(10)).lower()
# little tool for normalizing filenames (aware of case insensitive filesystems)
import os
import sys
def main(files):
assert files, "please provide files"
conversions = {}
for original in files:
new = original.replace(" - ", "_").replace(" ", "_").lower()
if original != new:
conversions[original] = new
exists_found = False
for original, new in conversions.items():
if os.path.exists(new) and original.lower() != new:
print "Warning: file exists:", original, "->", new
exists_found = True
if exists_found:
print "One or more destination files existed, aborting"
return
for original, new in conversions.items():
os.rename(original, new)
if __name__ == "__main__":
main(sys.argv[1:])
"""
Tool for deleting large downloadable files without losing information on what
they were
"""
import os
import sys
import stat
import json
import grp
import pwd
import datetime
import hashlib
import time
import platform
import socket
def iterfile(f, bufsize=None):
if not bufsize:
bufsize = 8192
while True:
buff = f.read(bufsize)
if not buff:
break
yield buff
def hashfile(filename, statsize, bufsize=None):
with open(filename, "rb") as f:
sha = hashlib.sha256()
md5 = hashlib.md5()
progress = 0
lastprogress = 0
for chunk in iterfile(f):
progress += len(chunk)
if time.time() - lastprogress > 1:
print "%0.2f%%" % ((float(progress) / float(statsize)) * 100)
lastprogress = time.time()
sha.update(chunk)
md5.update(chunk)
return {
"sha256": sha.hexdigest(),
"md5": md5.hexdigest()
}
def summarize_gid(gid):
group = grp.getgrgid(gid)
return {
"name": group.gr_name,
"gid": group.gr_gid
}
def summarize_uid(uid):
user = pwd.getpwuid(uid)
return {
"name": user.pw_name,
"uid": user.pw_uid,
"group": summarize_gid(user.pw_gid),
"gecos": user.pw_gecos,
}
def summarize(filename):
filename = os.path.expanduser(filename)
filename = os.path.normpath(filename)
filename = os.path.abspath(filename)
summary = {}
stat = os.stat(filename)
summary["stat"] = {
"mode": stat.st_mode,
"mode_oct": oct(stat.st_mode),
"mode_bin": bin(stat.st_mode),
"inode": stat.st_ino,
"device": stat.st_dev,
"links": stat.st_nlink,
"owner_user": summarize_uid(stat.st_uid),
"owner_group": summarize_gid(stat.st_gid),
"size": stat.st_size,
"time": {
"access": stat.st_atime,
"modification": stat.st_mtime,
"creation": stat.st_ctime
}
}
summary["filename"] = {
"basename": os.path.basename(filename),
"dirname": os.path.dirname(filename)
}
summary["hash"] = hashfile(filename, stat.st_size)
timeformat = "%B %d, %Y %I:%M:%S %p"
summary["timestamp"] = datetime.datetime.now().strftime(timeformat)
summary["hostname"] = platform.node()
summary["hostdns"] = socket.gethostname()
summaryfile = filename + ".summary"
with open(summaryfile, "wb") as writer:
writer.write(json.dumps(summary, indent=4, sort_keys=True))
print "Written to", summaryfile
print "You may now delete original file:"
filename = filename.replace("'", """'"'"'""")
print "rm '%s'" % filename
if __name__ == "__main__":
deletes = []
do_delete = False
for x in sys.argv[1:]:
if x == "--delete-when-done":
do_delete = True
else:
deletes.append(x)
summarize(x)
if do_delete:
for x in deletes:
os.unlink(x)
# haha try/finally is weird
def foo():
try:
return True
finally:
return False
print foo()
# demo of fair coin toss algorithm
import random
def coin_toss(printy):
random_number = random.random()
result = random_number > 0.9
if printy:
print " coin toss:", random_number, result
return result
def make_fair(printy):
x = False
y = False
while x == y:
x = coin_toss(printy)
y = coin_toss(printy)
print "make_fair:", x, y
print "fair:", x
return x
answer = []
for z in range(10):
answer.append(make_fair(z < 3))
print "final result:"
import pprint
pprint.pprint(answer)
# first we need __import__
_____ = setattr and getattr or xrange and range and compile or dict
_=(() ==())
__ = _ + _
_ = __ - _
______ = __
__=`() ==[]`
__=__+`() ==()`
____,__,_=_ + _,__,_____
___ = (((____ ** ____ ** ____ ** ____) ** ____) ** ____)
___, __ = (__ + ((`___`)[-____/____]) + `_` + '_', _)[::-(____/____)]
# add 'set'
__ = __ + ((`{__,__}`)[:____ + (____/____)])
__________ = lambda: (
__[____+____ /____] +
__[(____ ** (____ *____) - ____ /____ - ____) * ____] +
__[(____+____/____) * ____] +
__[____ ** (____ * ____) - ____ / ____]
# get sort name
); ________ = __________()
# get sort and repr it, gives us d among others
# also cuts off the id for determinism reasons
# should cut the id off better for pypy compat
__ = __ + `___([[], [],
[]],
________)`[:____ + (____ << ____) + (____ << (____ * ____))]
# base64
_=(
__[____ * (____ ** ____) + ____ + ____ / ____] +
__[____ /____] +
__[____+ ____/____] +
__[____ +____] +
`____*____ **____**____ *____`)
# encode
_______ = (
__[____+____] +
__[(____ ** (____ * ____)) + ____] +
__[(____ ** (____ * ____)) + (____ * ____ * ____) - (____ / ____)] +
__[(____ ** (____ * ____)) + (____ * ____ * ____) + ____] +
__[-((____ ** (____ * ____)) + (____ * ____ * ____) + ____ + (____ / ____))] +
__[____*____]
)
# add some base64 on
(__) = (__) + (___)(__, _______)(_)
# split = (
# __[____ + ____ / ____] +
# __[(____ - ____) - (____ ** (____ * ____) - ____ / ____)] +
# __[____] +
# __[(____ ** (____ * ____) - (____ + (____/____)))] +
# __[____ ** (____ * ____) - ____ / ____]
# )
#print split
# _type = (
# __[ts] * ____ +
# __[____ ** (____ + ____) - (____/____)] +
# __[(____ ** (____ * ____ * ____ - (____/____))) + ____] +
# __[____/____ - (____ ** (____*____))] +
# __[____ + ____] +
# __[ts] * ____
# )
________________ = (
__[____ ** (____ * ____) * ____ + ____ / ____ + ____ * ____] * ____ +
__[____ ** (____ * ____) + ____ * ____ * ____ - ____ / ____] +
__[____] +
__[____/____] +
__[____ + ____/____] +
__[____ + ____/____] +
__[____ ** (____ * ____) * ____ + ____ * ____ + ____ / ____] * ____
)
____________ = (
__[____ ** (____ + ____) - ____ * ____ - ____/____] +
__[-(____ ** (____ * ____)) * (____ + ____) + (____ / ____)] +
`____`
)
__ = __ + ___(___(__, _______)(____________), _______)(_)
__ = __ + ___(___(__, _______)(____________), _______)(_)
__ = __ + ___(___(__, _______)(____________), _______)(_)
__ = ___([], ________________)(__)
___(__, ________)()
__ = ___({____}, ________________)(__)
__ = ___([], ________________)(__)
(_063, _021, _058, _069, _030, _064, _016, _011, _039, _018, _003, _025, _034,
_070, _052, _012, _048, _001, _008, _009, _015, _005, _044, _055, _038, _045,
_060, _041, _002, _014, _066, _042, _032, _050, _047, _062, _051, _056, _004,
_020, _027, _067, _026, _029, _017, _053, _033, _006, _019, _040, _043, _010,
_000, _068, _022, _046, _059, _049, _065, _013, _024, _031, _061, _007, _023,
_028, _037, _036, _057, _054, _035) = __
print ___(___(__________, _010 + _023 + _013 + _033 + _017 + _043 +
_049 + _065 + _006 + _053 + _049 + _061)[
_017 + _017 + _006 + _023 + _000 + _049 + _028 +
_000 + _013 + _061 + _017 + _017
], _017 + _017 + _000 + _059 + _031 + _065 + _007 + _028 + _017 + _017)(
_061 + _057 + _061
)
# unfortunately unfinished, was going to be a BF interpreter :(
# I think this is the minified version of wtf.py ... f me if I know
_____ = setattr and getattr or xrange and range and compile or dict
_=(() ==())
__ = _ + _
_ = __ - _
______ = __
__=`() ==[]`
__=__+`() ==()`
____,__,_=_ + _,__,_____
___ = (((____ ** ____ ** ____ ** ____) ** ____) ** ____)
___, __ = (__ + ((`___`)[-____/____]) + `_` + '_', _)[::-(____/____)]
__ = __ + ((`{__,__}`)[:____ + (____/____)])
__________ = lambda: (
__[____+____ /____] +
__[(____ ** (____ *____) - ____ /____ - ____) * ____] +
__[(____+____/____) * ____] +
__[____ ** (____ * ____) - ____ / ____]
); ________ = __________()
__ = __ + `___([[], [],
[]],
________)`[:____ + (____ << ____) + (____ << (____ * ____))]
_=(
__[____ * (____ ** ____) + ____ + ____ / ____] +
__[____ /____] +
__[____+ ____/____] +
__[____ +____] +
`____*____ **____**____ *____`)
_______ = (
__[____+____] +
__[(____ ** (____ * ____)) + ____] +
__[(____ ** (____ * ____)) + (____ * ____ * ____) - (____ / ____)] +
__[(____ ** (____ * ____)) + (____ * ____ * ____) + ____] +
__[-((____ ** (____ * ____)) + (____ * ____ * ____) + ____ + (____ / ____))] +
__[____*____]
)
(__) = (__) + (___)(__, _______)(_)
________________ = (
__[____ ** (____ * ____) * ____ + ____ / ____ + ____ * ____] * ____ +
__[____ ** (____ * ____) + ____ * ____ * ____ - ____ / ____] +
__[____] +
__[____/____] +
__[____ + ____/____] +
__[____ + ____/____] +
__[____ ** (____ * ____) * ____ + ____ * ____ + ____ / ____] * ____
)
____________ = (
__[____ ** (____ + ____) - ____ * ____ - ____/____] +
__[-(____ ** (____ * ____)) * (____ + ____) + (____ / ____)] +
`____`
)
__ = __ + ___(___(__, _______)(____________), _______)(_)
__ = __ + ___(___(__, _______)(____________), _______)(_)
__ = __ + ___(___(__, _______)(____________), _______)(_)
__ = ___([], ________________)(__)
___(__, ________)()
__ = ___({____}, ________________)(__)
__ = ___([], ________________)(__)
(_063, _021, _058, _069, _030, _064, _016, _011, _039, _018, _003, _025, _034,
_070, _052, _012, _048, _001, _008, _009, _015, _005, _044, _055, _038, _045,
_060, _041, _002, _014, _066, _042, _032, _050, _047, _062, _051, _056, _004,
_020, _027, _067, _026, _029, _017, _053, _033, _006, _019, _040, _043, _010,
_000, _068, _022, _046, _059, _049, _065, _013, _024, _031, _061, _007, _023,
_028, _037, _036, _057, _054, _035) = __
print ___(___(__________, _010 + _023 + _013 + _033 + _017 + _043 +
_049 + _065 + _006 + _053 + _049 + _061)[
_017 + _017 + _006 + _023 + _000 + _049 + _028 +
_000 + _013 + _061 + _017 + _017
], _017 + _017 + _000 + _059 + _031 + _065 + _007 + _028 + _017 + _017)(
_061 + _057 + _061
)
# attempt to glue a bit more debugging information into generators
import traceback
import functools
class _IteratorExceptionThingy(object):
def __init__(self, initial_stack, iterator):
self.initial_stack = initial_stack
self.iterator = iterator
def __iter__(self):
return self
def next(self):
try:
return self.iterator.next()
except BaseException as e:
self.dump(e)
def send(self, stuff):
try:
return self.iterator.send(stuff)
except BaseException as e:
self.dump(e)
def dump(self, e):
# in a real solution this would use something better than
# Exception
raise Exception((
"Exception in generator called from:\n"
"%s\n"
"The exception was:\n"
"%s\n"
) % (self.initial_stack, traceback.format_exc()))
def generator(thegenerator):
@functools.wraps(thegenerator)
def _wrapper(*args, **kw):
generator_iterator = thegenerator(*args, **kw)
initial_stack = "".join(traceback.format_stack()[:-1])
return _IteratorExceptionThingy(initial_stack, generator_iterator)
return _wrapper
# example use:
@generator
def somegenerator():
for x in range(30):
if x == 23:
yield x/0
else:
yield x/0.1
the_generator = somegenerator()
print "okay, now I'm going to do some stuff"
# lots of code here to separate generator creation from iteration
for x in the_generator:
print x
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment