Skip to content

Instantly share code, notes, and snippets.

@justinfay
justinfay / requests_xpath.py
Created May 16, 2012 22:41
A xpath response hook for requests using lxml
from lxml import etree
def xpath(response):
response.xpath = etree.HTML(response.content).xpath
return response
if __name__ == "__main__":
import requests
r = requests.get('http://example.com', hooks=dict(response=xpath))
r.xpath('//h1/text()')
@justinfay
justinfay / redisbucket.py
Created August 20, 2012 13:01
redis token bucket
import redis
from redis import WatchError
import time
RATE = 0.1
DEFAULT = 100
TIMEOUT = 60 * 60
DEBUG = False
@justinfay
justinfay / elo.py
Created October 18, 2012 15:56
Simple function to calculate elo ranking of a non drawing game
def elo_ranking(winners_rank, losers_rank, k=20):
expected_winner = 1 / (1 + 10 ** ((losers_rank - winners_rank) / 400))
expected_loser = 1 / (1 + 10 ** ((winners_rank - losers_rank) / 400))
winners_rank += k * (1 - expected_winner)
losers_rank += k * (0 - expected_loser)
return winners_rank, losers_rank
// Set the aliases for the libraries used in the application
require.config({
paths: {
jquery: 'libs/jquery-min',
underscore: 'libs/underscore-min',
backbone: 'libs/backbone-min',
request: 'libs/XMLHttpRequest',
mustache: 'libs/mustache-min',
templates: '../templates',
collapse: 'libs/bootstrap-collapse',
>>> class PopulableForm(forms.Form):
... def populate(self, other):
... for k, v in self.cleaned_data.items():
... if hasattr(other, k):
... setattr(other, k, v)
... else:
... try:
... other[k] = v
... except TypeError:
... continue
from flask import Flask
app = Flask(__name__)
app.config['SERVER_NAME'] = 'flasksubs.local:5000'
app.config['SUB_DOMAINS'] = {
'good': 'good sub domain',
'ok': 'ok sub domain'
}
app.config['NO_SUB_DOMAIN_MSG'] = 'no sub domain found'
@justinfay
justinfay / python
Created June 20, 2013 09:54
stupidly unpythonic methodcaller example
>>> from operator import methodcaller
>>> from random import randint
>>> class Foo(object):
... def __init__(self):
... self.number = randint(0, 10)
... def get_number(self):
... return self.number
...
>>> lfoos = [Foo() for i in xrange(10)]
>>> for foo in lfoos:
var Game = (function() {
var settings = {
// payout which is a multiple.
payout: 2,
// probability of getting a payout represented fraction.
probability: .50,
};
var init = function(options) {
for (var key in options) {
import importlib
IMPORT_CACHE = {}
def cache_import(path):
"""Import an object from a specified `path`."""
mod, imp = path.rsplit('.', 1)
if mod in IMPORT_CACHE:
return getattr(IMPORT_CACHE[mod], imp)
mod_ = importlib.import_module(mod)
@justinfay
justinfay / autoreload
Created December 18, 2013 14:49
enabling autoreload in ipython
%load_ext autoreload
%autoreload 2