Skip to content

Instantly share code, notes, and snippets.

View dmitric's full-sized avatar

Dmitri Cherniak dmitric

View GitHub Profile
@dmitric
dmitric / postlogin.py
Created September 26, 2011 06:14
Logging in a user, and using cookies
def post(self):
user = self.get_argument("username")
pwd = self.get_argument("password")
login_info = self.db.logins.find_one({'$or' : [{'username': user.lower() }, {'email': user }]})
if login_info is not None and bcrypt.hashpw(pwd, login_info['pwd_hash']) == login_info['pwd_hash']:
user = self.db.users.find_one({"user_id": login_info['user_id']})
self.set_secure_cookie(options.cookie_user, pickle.dumps(user))
self.redirect(self.get_argument("next","/"))
else:
self.set_secure_cookie(options.cookie_alerts, pickle.dumps([{'content': "Bad login", 'level': 'error'}]))
@dmitric
dmitric / basehandler.py
Created September 26, 2011 06:10
DLC's tornado.web.RequestHandler add on's
class BaseHandler(tornado.web.RequestHandler):
#lazy initializer of Connection reference
@property
def db(self):
if not hasattr(self, '_db'):
self._db = Connection(options.db_master, options.db_port)[options.db_name]
return self._db
#overriding the default get_current_user to use an encrypted, pickled python object
def get_current_user(self):
@dmitric
dmitric / linkify.py
Created September 12, 2011 04:36
linkify
def linkify(words, urls):
if isinstance(words, basestring) or not isinstance(words, (list, tuple)):
if isinstance(urls, basestring) or not isinstance(urls, (list, tuple)):
return linkify([words], [urls])
else:
return words
else:
html_links = ['<a href="{1}">{0}</a>'.format(word,url)
for word, url in zip(words, urls)
if word is not None and url is not None]
@dmitric
dmitric / gist:1176036
Created August 27, 2011 23:58 — forked from joerussbowman/gist:1176002
Tornado Twitter Stream
# not pretty, I quickly moved to another idea
# not involving the Twitter stream. Good starting
# point.
import re
import base64
import socket
import asyncmongo
from tornado import ioloop
from tornado import iostream
@dmitric
dmitric / ChessKnight.java
Created April 15, 2011 03:41
Dynamic programmings
public class ChessKnight {
//Possible moves
//for each possible way we can move in x, we have a corresponding y
int[] x ={-2,-2,-1,-1,1,1,2,2};
int[] y = {-1,1,-2,2,-2,2,-1,1};
double[][][] results;
private static final int BOARD_SIZE = 8;
public double probAfterNSteps(int x, int y, int n){
init_memoize(n); //initialize our memoization array
@dmitric
dmitric / api_call.py
Created March 27, 2011 19:49
A nice way to handle twitter API errors
def make_api_call(self,f,**kwargs):
if f is None:
raise ValueError("No function passed in!")
response = []
wait_period = 1
while True:
try:
#your api call
response = f(**kwargs)
break
@dmitric
dmitric / cumulativesum2D.py
Created March 21, 2011 07:43
A wrapper class for calculating simple statistics over various sub-arrays of an array in amortized O(1) time
class CumulativeSum2D:
"""A wrapper around 2D arrays to be able to quickly grab sums and averages of various sub-arrays of the array"""
def __init__(self,data):
self.cum_sum = self.__cumulify(data)
def __cumulify(self,data):
""" creates a 2D cumulative sum matrix"""
cum_sum_array = []
for j in xrange(len(data)):
cum_sum_array.append([])
@dmitric
dmitric / add.py
Created March 19, 2011 23:04
Some useful bit arithmetic
#addition, full adder style
def add(a,b):
if a == 0:
return b
elif b == 0:
return a
summed = a^b
carry = (a&b) << 1
return add(summed,carry)
from operator import mul
#find what numbers we are missing from an unordered list of size 1 to k, where numbers are bounded by n-k
def missing_n_prime(upto,missing_some):
product_1_to_n_primes = reduce(mul,[nth_prime(n) for n in xrange(upto)])
product_missing = reduce(mul, [nth_prime(n-1) for n in missing_some])
prime_factors = prime_factorize(product_1_to_n_primes/product_missing)
return [what_number_prime(i) for i in prime_factors]
#get prime factors of a number
def find_missing(n,missing_some):
check = [k+1 for k in xrange(n)]
for i in missing_some:
if i in check:
check.remove(i)
return check
def find_missing_using_sets(n,missing_some):
x = frozenset(frozenset([i for i in xrange(1,n+1)])-frozenset(missing_some))
return [i for i in x]