Skip to content

Instantly share code, notes, and snippets.

View cameronp98's full-sized avatar

Cameron Phillips cameronp98

  • Nottingham / Leeds
View GitHub Profile
@cameronp98
cameronp98 / slugify.py
Last active January 2, 2016 18:19
convert strings to standard format
import re
import unittest
from unicodedata import normalize
# http://en.wikipedia.org/wiki/Clean_URL#Slug
def slugify(string, delim="-"):
string = normalize("NFKD", string).lower()
return re.sub(r"\W+", delim, string).strip(delim)
class TestSlugify(unittest.TestCase):
@cameronp98
cameronp98 / factory.py
Created January 9, 2014 22:04
Singleton-esque one instance factory(?) in Python
class Factory(object):
inst=None
@classmethod
def get(self):
if self.inst == None:
# new instance of self
self.inst = self # instantiate() to run __init__
self.inst.__init__(self)
# apply @classmethod to all methods
for name,attr in self.__dict__.items():
@cameronp98
cameronp98 / fib.py
Created January 9, 2014 22:05
Python fibonacci number generator
def fib(n):
x,y = 1,1
for i in range(n):
yield x
x,y = y, x+y
def main():
for i in range(1,10):
print(fib(i))
@cameronp98
cameronp98 / flatten.py
Last active January 2, 2016 18:19
Generator to flatten nested lists in Python. (Only works in 3.3+ w/ 'yield from' syntax)
def flatten(seq):
for item in seq:
if hasattr(item, "__iter__"):
yield from flatten(item)
else:
yield item
@cameronp98
cameronp98 / human_format.py
Created January 9, 2014 22:09
Generate suffixes for large numbers in Python (e.g. 1,000,000 = "1M", 10,000 = "10K" etc.)
from random import randint
from math import log10, floor
def human_format(num, ends=["", "K", "M", "B", "T"]):
# divides by 3 to separate into thousands (...000)
return ends[int(floor(log10(num))/3)]
if __name__ == '__main__':
for i in range(10):
x = randint(1,10**i)
@cameronp98
cameronp98 / contextmanager.py
Created January 9, 2014 22:09
Random crap w/ contextlib.contextmanager
from contextlib import contextmanager
from shutil import rmtree
from tempfile import mkdtemp
import unittest
import os
@contextmanager
def working_directory(path):
current_dir = os.getcwd()
os.chdir(path)
import re
def slugify(string, delim="-"):
return re.sub(r"\W+", delim, string.lower())
class Provider(object):
""" A provider holds its publishers alongside their
subscribers and can run the published content to
the appropriate subscribers"""
@cameronp98
cameronp98 / template.py
Created January 9, 2014 22:15
Almost useful template 'engine' in Python
import re
import hashlib
class TemplateError(Exception):
pass
class Template(object):
pattern = r"(\{[a-zA-Z0-9-_\|\.]+\})"
def __init__(self, string):
@cameronp98
cameronp98 / randomly-nested-sequence.py
Created January 9, 2014 22:18
Randomly nested list generator in Python
from random import randint
def sequence(length=3, depth=0, max_depth=2):
for i in range(1,length):
if randint(0,1) and depth <= max_depth:
yield list(sequence(3, depth+1))
else:
yield randint(1,9)
if __name__ = "__main__":
@cameronp98
cameronp98 / defaultdict-examples.py
Created January 9, 2014 22:20
Some brief example implementations of collections.defaultdict
from collections import defaultdict
#------------------------
# $COUNTING
#------------------------
names = ["tom", "dick", "harry", "harry", "dick", "tom", "tom", "dick", "harry"]
d = defaultdict(int)
for name in names: