Skip to content

Instantly share code, notes, and snippets.

@JordanReiter
JordanReiter / split_by_language.py
Created May 9, 2019 17:13
Given a block with mixed languages, split into individual sections by language
'''
requires langdetect, available on pypi (pip install langdetect)
https://github.com/Mimino666/langdetect
'''
import langdetect
def split_by_language(content, delimiter='\n', joiner='\n',
languages=None, fail_silently=True):
'''
@JordanReiter
JordanReiter / s3_file_field.py
Last active March 27, 2019 15:17
File field for files stored in S3 that provides easy access to previous versions
'''
Adds access to previous versions to a model's file field.
Requires django-storages, and you must either be using S3Boto3Storage
by default, or you must specify it as the storage class in the field
definition.
class SampleModel(models.Model):
file = S3FileField(upload_to='path/to/dir')
@JordanReiter
JordanReiter / django_context_placeholder.py
Last active April 10, 2019 15:33
Django template context placeholder
import uuid
import datetime
import itertools
import re
import inflection # requires python library inflection (pip install inflection)
class ContextPlaceholder:
counter = itertools.count()
DEFAULT_VALUES = {
@JordanReiter
JordanReiter / signal_testcase.py
Last active March 4, 2019 20:21
Simple TestCase Mixin for testing whether signals are fired, and testing for specific signal values
from contextlib import contextmanager
from django.dispatch.dispatcher import Signal
class SignalTestMixin(object):
'''
Add this as a mixin to any Django TestCase
that needs to add testing for signals.
@JordanReiter
JordanReiter / clean_base64.py
Created April 6, 2018 21:24
This function can be used to process text that may or may not be base64 encoded
# This function can be used to process text that may or may not be base64 encoded
# In general, if you use base64 decode on normal text, you end up with random bytes
# that don't resemble a standard encoding. This function makes use of the chardet
# library to recognize decoded text that matches an expected encoding.
# Note that it tends to fail for very short inputs.
import binascii
import base64
@JordanReiter
JordanReiter / login-template.js
Last active November 1, 2017 14:57
Automatic sign-in for already-authenticated users for SSO based on django-cas-provider
window.CASLogin = window.CASLogin || (function () {
var action = "{{ action|safe }}",
ticket = {% if ticket %}"{{ ticket.ticket }}"{% else %}null{% endif %},
logged_in = {{ logged_in|lower|default:"false" }},
username = {% if request.user.is_authenticated %}"{{ request.user.username }}"{% else %}null{% endif %},
email = {% if email %}"{{ email }}"{% else %}null{% endif %};
function authenticate() {
if (!logged_in) {
window.location.href = action;
@JordanReiter
JordanReiter / input-month-polyfill.js
Last active January 25, 2023 08:55
Polyfill for input type="month" with no dependencies.
(function() {
var monthInputs = document.querySelectorAll('input[type="month"]'),
checkDateInput = document.createElement('input'),
dateSupported = false,
months = [],
lang = document.documentElement.lang || navigator.language,
DEFAULT_SPAN = 5;
if (monthInputs[0].type === 'month') {
// browser supports month input; no need for polyfill
@JordanReiter
JordanReiter / management_email_admins.py
Created March 28, 2017 21:08
Use the EmailAdminsOnErrorCommand class instead of BaseCommand so that your Django management commands send error emails to admins
# This file provides a base Command class that handles sending errors via mail_admins
# Make sure to adjust the LOGGING variable in settings
# Credit to Abdulla Diab: https://mpcabd.xyz/make-django-management-commands-send-errors-email-admins/
import sys
import logging
from django.core.management import BaseCommand
logger = logging.getLogger('management.command')
@JordanReiter
JordanReiter / crontab
Last active July 11, 2023 10:39
Remind yourself of what you did over the past day and week by reading a summary of all of your git commits.
0 22 * * 1,2,3,4,5 /path/to/git_changes.sh /path/to/projects/ # Sends 5 PM EST if server time is UTC
0 21 * * 5 /path/to/git_changes.sh -w /path/to/projects # Sends Friday @ 4PM EST if server time is UTC
@JordanReiter
JordanReiter / get_dotted_value.py
Created September 30, 2015 19:29
Access values from an object using dot notation.
def get_dotted_value(obj, attr=None):
"""Access values from an object using dot notation.
Can be attributes, keys, or indices.
>>> class SampleObject():
... def __repr__(self):
... return repr(sorted(self.__dict__.items()))
...
>>> zoo = SampleObject()