Skip to content

Instantly share code, notes, and snippets.

View mgd020's full-sized avatar

mgd020 mgd020

View GitHub Profile
@mgd020
mgd020 / template.py
Created October 29, 2019 02:14
python template engine
import re
example = """
one
two
three
{% if 1 %}{% end %}
{{
dance(
var image_nes_filter = (function() {
var PIXEL_SIZE = 4;
dither = (function() {
// Floyd–Steinberg dither
var ERROR_DIFFUSION_1_16 = 1 / 16,
ERROR_DIFFUSION_3_16 = 3 / 16,
ERROR_DIFFUSION_5_16 = 5 / 16,
ERROR_DIFFUSION_7_16 = 7 / 16,
@mgd020
mgd020 / fairqueue.py
Created April 23, 2019 10:56
Fair Queueing implementation for Python multiprocessing
"""A multiprocessing Queue but is "fair" to every flow/session/channel.
See https://en.wikipedia.org/wiki/Fair_queuing.
"""
import sys
import time
from multiprocessing.queues import Queue
@mgd020
mgd020 / onetomanyfield.py
Created March 21, 2019 11:21
Adds OneToManyField django model field
from django.db import models
from django.db.models.fields.related import ManyToManyRel, ReverseOneToOneDescriptor
from django.utils.translation import gettext_lazy as _
class OneToManyRel(ManyToManyRel):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.multiple = False
@mgd020
mgd020 / set_tags.py
Created February 21, 2019 05:01
Add `set` like twigs to django templates
from django import template
from django.template.base import token_kwargs
register = template.Library()
class SetBlockNode(template.Node):
def __init__(self, name, nodelist):
self.name = name
@mgd020
mgd020 / choices.py
Created September 19, 2018 13:50
nice choices class for
"""
Example usage:
# declare
class Color(Choices):
RED = 'Red'
GREEN = 'Green'
BLUE = 'Blue'
# use on model
@mgd020
mgd020 / binary_json.py
Created August 27, 2018 23:08
An example implementation of binary json
import struct
import sys
"""
encoding is little endian
header details: (lsb to msb)
int7 1
length 7 bits of int [-64, 63]
@mgd020
mgd020 / util.js
Last active June 2, 2018 12:32
basic javascript utils
function element(tagName) {
/*
create an element
arguments: tagName, [attributes], children...
*/
// help the minifier out a bit
var args = arguments
var doc = document
@mgd020
mgd020 / cached_property.py
Created March 12, 2018 02:49
Method decorator which extends regular property to cache the value.
class cached_property(object):
"""Decorator that converts a method with a single self argument into a property cached on the instance."""
def __init__(self, func):
self._get = func
self.__doc__ = getattr(func, '__doc__')
self._name = '_cached_' + func.__name__
@staticmethod
def _set(obj, value):
raise AttributeError("can't set attribute")
# Turn an integer into a nice base64 encoded string
# E.g. 4095 -> D_8
# requires python 3
import base64
def encode(n):
return base64.urlsafe_b64encode(n.to_bytes((n.bit_length() + 7) // 8, 'big')).rstrip(b'==')