Skip to content

Instantly share code, notes, and snippets.

@nwjlyons
nwjlyons / blocks.py
Last active June 26, 2018 16:02
Wagtail NonFieldErrors for Blocks
class NonFieldErrors:
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.non_field_errors = []
self.meta.form_template = 'struct.html'
def get_form_context(self, value, prefix='', errors=None):
context = super().get_form_context(value, prefix, errors)
context['non_field_errors'] = self.non_field_errors
return context
@nwjlyons
nwjlyons / benchmarks.py
Created September 18, 2018 07:44
Redis v SQL benchmarks
import timeit
from django.core.cache import cache
from django.contrib.auth.models import User
def benchmark_redis(n=1):
for _ in range(n):
cache.get("blank")
@nwjlyons
nwjlyons / docker-rm-stopped-containers.sh
Created May 30, 2019 12:59
Delete stopped containers
docker rm $(docker ps -a -q)
@nwjlyons
nwjlyons / keyword_arg.py
Last active June 18, 2019 10:16
Python 2/3 add keyword arg
# python 2
class Person(object):
def __init__(self, name, age):
self.name = name
self.age = age
class Employee(Person):
def __init__(self, *args, **kwargs):
self.job_title = kwargs.pop('job_title')
@nwjlyons
nwjlyons / preload_redirect_middleware.py
Last active September 30, 2019 14:14
Django preload redirect
from django.http import HttpResponseRedirect, HttpResponsePermanentRedirect
def preload_redirect_middleware(get_response):
def middleware(request):
response = get_response(request)
if isinstance(response, (HttpResponseRedirect, HttpResponsePermanentRedirect)):
@nwjlyons
nwjlyons / concurrent.ex
Created January 24, 2020 13:36
Playing with concurrency in Elixir
defmodule Math do
@doc """
Calculate the square of a integer
This function simualtes an expensive operation by sleeping for x seconds
"""
def square(x) when is_integer(x) do
Process.sleep(x * 1_000)
x * x
end
@nwjlyons
nwjlyons / template.erb
Last active February 20, 2020 11:24
Embedded Ruby
<h1><%= @answer %></h1>
@nwjlyons
nwjlyons / storage.go
Last active July 18, 2020 11:10
Adaptor pattern in Go
package main
import "fmt"
type StorageAdaptor interface {
Save(string)
Delete(string)
}
@nwjlyons
nwjlyons / storage.ex
Last active July 18, 2020 12:35
Adaptor pattern in Elixir with compile time config checking
defmodule Storage do
defmacro __using__(opts) do
quote bind_quoted: [opts: opts] do
@adaptor Keyword.fetch!(opts, :adaptor)
@config @adaptor.check_config(opts)
def save(io_device), do: @adaptor.save(io_device, @config)
def delete(path), do: @adaptor.save(path, @config)
end
end
@nwjlyons
nwjlyons / irrational_numbers.ex
Last active August 17, 2020 09:59
Taking the square root of each number from 1 to 100, which of them are irrational
Enum.reject 1..100, fn i ->
square_root = Decimal.sqrt(i)
remainder = Decimal.rem(square_root, 1)
Decimal.eq?(remainder, 0)
end