Skip to content

Instantly share code, notes, and snippets.

View dgouldin's full-sized avatar

David Gouldin dgouldin

  • Clara Labs
  • San Francisco, CA
View GitHub Profile
@dgouldin
dgouldin / noparse.py
Created October 19, 2010 16:43
Django template block tag {% noparse %} renders template syntax characters within the block as normal text.
from django import template
register = template.Library()
token_formats = {
template.TOKEN_TEXT: '%s',
template.TOKEN_VAR: '%s%%s%s' % (template.VARIABLE_TAG_START, template.VARIABLE_TAG_END),
template.TOKEN_BLOCK: '%s%%s%s' % (template.BLOCK_TAG_START, template.BLOCK_TAG_END),
template.TOKEN_COMMENT: '%s%%s%s' % (template.COMMENT_TAG_START, template.COMMENT_TAG_END),
}
@dgouldin
dgouldin / google_pycon_quiz.py
Created March 11, 2011 21:02
My entry to Google's PyCon Quiz: Count and sum all positive palindromic numbers up to a googol
def googol():
def palindromes(end):
for odd_length in (True, False):
left = 0
last_palindrome = 0
while last_palindrome < end:
left += 1
left_str = str(left)
right_str = left_str[::-1]
if odd_length:
@dgouldin
dgouldin / google_quiz.py
Created March 11, 2011 22:50
Google Quiz answer
def googol():
power = 100
count = sum([2*9*10**n for n in range(power/2)])
count_sum = sum([int(digit) for digit in str(count)])
return (count, count_sum)
@dgouldin
dgouldin / fixture_utils.py
Created September 7, 2011 22:47
Some simple django fixture utils
from django.core import serializers
from django.utils import simplejson
def add_to_fixture(qs, filename):
f = open(filename, 'r')
data_python_existing = simplejson.loads(f.read())
f.close()
data_json_unformatted = serializers.serialize('json', qs)
data_python_new = simplejson.loads(data_json_unformatted)
data_python_existing.extend(data_python_new)
@dgouldin
dgouldin / gist:1207636
Created September 9, 2011 23:49
Django templatetag to output the current page's querystring updated with the specified values.
from django import template
register = template.Library()
class UpdateQuerystringNode(template.Node):
def __init__(self, **kwargs):
self.kwargs = kwargs
def render(self, context):
query_dict = context['request'].GET.copy()
@dgouldin
dgouldin / incrdecr.py
Created October 10, 2011 21:19
At attempt at an atomic and bounded cache incr/decr function which handles key existence.
from django.core.cache import cache
def _incr_decr(key, incr=True, min=None, max=None, initial=None):
'''Incr/decr function which handles key creation as needed'''
# FIXME: min/max have rampant race conditions which could be fixed using
# memcache's "cas" feature, but current pylibmc + libmemcached causes a
# segfault when used.
initial = initial or min or 0
@dgouldin
dgouldin / rolling_rate_limit.py
Created October 12, 2011 01:09
Rolling window rate limit function decorator
from __future__ import division
import datetime
import hashlib
import inspect
import math
import pytz
import time
import urllib
from common.cache import incr, decr
@dgouldin
dgouldin / gist:1320358
Created October 27, 2011 18:17
Django model relation graph
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.db.models import loading
from django.db.models.fields.related import RelatedField
INDENT = ' '
for app_name in settings.INSTALLED_APPS:
print app_name
app_label = app_name.split(".")[-1]
try:
@dgouldin
dgouldin / gist:1411676
Created November 30, 2011 23:04
Abstract model class which validates on save using a default ModelForm
from django.db import models
from django import forms
from django.forms.models import modelform_factory
class ValidatingModel(models.Model):
class Meta:
abstract = True
def __init__(self, *args, **kwargs):
self.model_form_class = modelform_factory(self.__class__)
@dgouldin
dgouldin / gist:1411980
Created November 30, 2011 23:46
Chainable python "wrapper" for ImageMagick via subprocess
from __future__ import division
import os
import subprocess
try:
from cStringIO import StringIO
except ImportError:
from StringIO import StringIO