Skip to content

Instantly share code, notes, and snippets.

View bmispelon's full-sized avatar

Baptiste Mispelon bmispelon

View GitHub Profile
@bmispelon
bmispelon / months_html.py
Created April 17, 2024 20:37
Get a table of month names in various languages, using Django translation machinery
import django
django.setup()
from django.utils import translation
from django.utils.dates import MONTHS
def monthstr(i, lang):
translation.activate(lang)
return str(MONTHS[i])
@bmispelon
bmispelon / int_to_english.py
Created May 18, 2022 11:05
Convert an integer into english
import sys, unicodedata
def int_to_english(n: int) -> str:
"""
Convert the given integer into english (only works reliably for numbers between 1 and 31).
"""
return unicodedata.name(chr(13279 + n)).split()[-1]
if __name__ == '__main__':
@bmispelon
bmispelon / unicode_poetry.py
Created May 16, 2022 15:18
A poetry generator in 5 lines of python
import random as r, unicodedata
coolwords = [unicodedata.name(chr(119556+i)).split()[-1] for i in range(83)]
for w in r.sample(coolwords, r.randrange(9, 15)):
print(w, end=r.choice(' \n'))
print()
@bmispelon
bmispelon / find_templates.py
Created October 20, 2021 14:55
Exhaustively list all available templates in a Django project
from pathlib import Path
from django import template
def gen_all_templates():
"""
Generate the list of all available templates as tuples of 3 values:
- the template engine
@bmispelon
bmispelon / update.py
Created March 2, 2021 09:53
[Django ORM] Updating a JSONField based on the value of another field
"""
How to update JSONField based on the value of another field.
For example:
class MyModel(models.Model):
name = models.CharField(...)
data = models.JSONField()
How to update the MyModel table to store the `name` field inside the `data`
@bmispelon
bmispelon / checkchoices.py
Last active December 6, 2020 17:39
A Django management command to find model fields where the declared choices doesn't match what's in the database
"""
When a model field defines a `choices` attribute, Django doesn't actually
generate a database constraint for that, which means it's possible to insert
data that doesn't match the choices.
See https://adamj.eu/tech/2020/01/22/djangos-field-choices-dont-constrain-your-data/
This command scans your database to try and find which fields have mismatched
data.
By default it scans all fields of all models of all installed apps, doing one
@bmispelon
bmispelon / test_enums.py
Created October 27, 2020 18:17 — forked from hjwp/test_enums.py
Better string enums
import random
from enum import Enum, EnumMeta, IntEnum
class GoatEnumMeta(EnumMeta):
def __getitem__(cls, item):
if isinstance(item, int):
item = cls._member_names_[item]
return super().__getitem__(item)
@bmispelon
bmispelon / tuple.py
Created May 20, 2020 13:51
How to handle tuple creation in a generic way?
def my_tuple_function(t):
"""
Return a new tuple of the same length containing only zeroes.
"""
tuple_class = type(t)
return tuple_class(*(0 for _ in t)) # works for namedtuple
return tuple_class((0 for _ in t)) # works for plain tuple
# https://mobile.twitter.com/dabeaz/status/1199367834691932160
"""
As a oneliner:
ᚐ = type('ᚐ',(object,),{'ᚐ':{},'__getattr__':lambda s,a:s.ᚐ[a],'__setattr__':lambda s,a,v:s.ᚐ.__setitem__(a,s.ᚐ[a]+v)if a in s.ᚐ else s.ᚐ.__setitem__(a,v)})()
for ᚐ.i, ᚐ.s in [(600, 'sa'), (60, 'ta'), (6, 'n')]:
pass
@bmispelon
bmispelon / cooldigits.py
Created November 25, 2019 10:35
A script to convert boring ASCII digits in your strings. Try it with `./cooldigits.py $(date)`
import argparse
from functools import partial
import unicodedata
# based on https://www.fileformat.info/info/unicode/category/Nd/list.htm
ALPHABETS = {
'ARABIC-INDIC',
'EXTENDED ARABIC-INDIC',
'NKO',
'DEVANAGARI',