Skip to content

Instantly share code, notes, and snippets.

View thelonecabbage's full-sized avatar

Justin Alexander thelonecabbage

  • Bluevine, Inc
  • Modi'in, Israel
View GitHub Profile
@thelonecabbage
thelonecabbage / sample.py
Created September 17, 2018 07:47
Integer Only Sampling Class
class Sample():
def __init__(self, values=None, *args, **kwargs):
self.reset(values)
def reset(self, values=None):
values = values or (0, 0, None, None, None, 0)
(self._total, self._cnt, self._min, self._max, self._first, self._ex2) = values
def append(self, value):
# self._all.append(value)
@thelonecabbage
thelonecabbage / README.md
Last active September 13, 2022 12:22
django, current user

(cliped from http://stackoverflow.com/a/21786764/117292)

The least obstrusive way is to use a CurrentUserMiddleware to store the current user in a thread local object:

current_user.py

from threading import local

_user = local()
@thelonecabbage
thelonecabbage / setter_django.py
Created November 24, 2015 17:24
How to create a setter in djano models that doesn't mess up the admin or .filter queries!
class MyModel(models.Model):
foo = models.CharField(max_length=20)
bar = models.CharField(max_length=20)
def __setattr__(self, attrname, val):
setter_func = 'setter_' + attrname
if attrname in self.__dict__ and callable(getattr(self, setter_func, None)):
super(MyModel, self).__setattr__(attrname, getattr(self, setter_func)(val))
else:
super(MyModel, self).__setattr__(attrname, val)
@thelonecabbage
thelonecabbage / api.py
Created October 2, 2013 14:40
Using decorators to simplify declaring actions on Tastypie Resources
from utils.api import action, actionurls
from tastypie.resources import ModelResource
from tastypie.authorization import Authorization
class NoteResource(ModelResource):
class Meta:
object_class = Note
queryset = Note.objects.all()
authorization = Authorization()
@thelonecabbage
thelonecabbage / gist:6484336
Created September 8, 2013 12:21
Using CSRF in jQuery
function create_task(title) {
return $.ajax({
url: '/api/v1/task/',
dataType: "application/json",
data: JSON.stringify({
title: title
}),
type:'POST',
contentType:'application/json',
@thelonecabbage
thelonecabbage / gist:6484328
Last active December 22, 2015 14:18
CSRF Tokens with AngularJS
// note the $httpProvider
// must be called AFTER login (ie ajax login)
function($httpProvider, $http) {
$httpProvider.defaults.headers.post['X-CSRFToken'] = (document.cookie.match(/csrftoken=([0-9a-zA-Z]*)/) || ['']).pop();
};
//alternately, dont' forget to install angular-cookies.js
@thelonecabbage
thelonecabbage / recursive.tojson for backbone
Created March 12, 2012 08:31
Recursive toJSON for Backbone.js
Data.Model = Backbone.Model.extend({
toJSON: function(){
var clone = _.clone(this.attributes);
_.each(clone, function (attr, idx) {
if(attr.toJSON){
clone[idx] = attr.toJSON();
}
});
return clone;
}