Skip to content

Instantly share code, notes, and snippets.

View rldotai's full-sized avatar

Brendan Bennett rldotai

View GitHub Profile
@rldotai
rldotai / get_comments.py
Created September 12, 2022 19:24
Get comments in the supplied Python code
import io, tokenize
def extract_comments(code: str | io.TextIOBase) -> str:
"""
Extract comments from a piece of Python code, returning a string of
*just* the comments.
Example:
>>> extract_comments(r'''
@rldotai
rldotai / rename_files.py
Created September 14, 2021 16:02
Bulk renaming files with Python to make them more consistent/easier to type. Not especially difficult, but it comes up surprisingly often.
"""
Renaming files to make them more consistent/easier to type.
"""
import unicodedata
import re
from pathlib import Path
# You can use whatever function you prefer, but Django's slugify is pretty slick
def slugify(value, allow_unicode=False):
@rldotai
rldotai / getter.py
Created February 7, 2021 06:24
A `getter` that brings JavaScript-style danger to Python.
import operator
from functools import reduce
def get(obj, key):
"""Get the item within `obj` corresponding to `key`.
If `obj` is subscriptable, return `obj[key]`, otherwise assume `key`
refers to an attribute and return `obj.key` instead.
"""
if hasattr(obj, '__getitem__'):
@rldotai
rldotai / get_jupyter_columns.html
Last active February 7, 2021 04:42
Get the number of columns in a Jupyter notebook output cell, from within the notebook itself.
%%html
<canvas id="canvas"></canvas>
<script>
/* A function that reports the width of a Jupyter notebook cells */
function reportWidth() {
/* Get an output area element */
let el = document.querySelector("div.output_subarea.output_text.output_stream.output_stdout > pre");
/* Determine the width of the output area, in pixels */
let output_width = el.clientWidth;
@rldotai
rldotai / colorama_demo.py
Created February 6, 2021 03:51
Demo of colorama's different output stylings
from colorama import Fore, Back, Style
foregrounds_dark = {
i: Fore.__dict__[i]
for i in dir(Fore)
if not (i.startswith("_") or i.startswith("LIGHT") or i.startswith("RESET"))
}
foregrounds_light = {
@rldotai
rldotai / distinct_floats.py
Created July 22, 2020 02:46
Calculate the number of distinct floats between two numbers.
"""
Calculate the number of distinct floats between two numbers via bit packing and
unpacking.
--------------------------------------------------------------------------------
>>> distinct_floats(1, 0)
4607182418800017408
>>> distinct_floats(-1, 0)
4616189618054758400
>>> distinct_floats(0, float('inf'))
9218868437227405312
@rldotai
rldotai / fixedmidpointnorm.py
Created July 11, 2020 04:44
A Matplotlib Norm with a Fixed Midpoint
import numpy as np
from matplotlib.colors import Normalize
class FixedMidpointNorm(Normalize):
def __init__(self, vcenter):
"""
Normalize data with a set center.
For plotting diverging colormaps around a particular value, at the
@rldotai
rldotai / minimal_plot.py
Last active January 18, 2020 23:42
Convert a matplotlib plot to its most minimal form (no text, labels, titles, legends)
"""
********************************************************************************
Matplotlib can create some great plots, although it is often a hassle to
customize said plots after their creation, particularly if you're creating a
large number of them, or regenerating them for minor changes (e.g. scaling)
is inconvenient.
I've been experimenting with generating "minimal" plots, which contain only the
actual representation of the data.
Insofar as I can add titles/labels in LaTeX, this allows me to embed the plots
@rldotai
rldotai / save_legend.py
Last active September 15, 2023 08:09
Saving a legend separately with matplotlib
"""
Here we imagine that you've plotted some things, added a legend, and now
want to be able to save that legend separately.
Perhaps you want to rescale things later, or maybe you've plotted a bunch
of similar graphs and want to have a common legend for all of them, which
can be awkard to do in matplotlib.
Here is one method for doing this:
0. Plot some things, set up a legend
1. Get information about the legend, in particular its bounding box
@rldotai
rldotai / ndenum.py
Last active January 7, 2019 04:31
Convert objects (including iterables of objects) to dictionaries mapping `sympy` symbols to the objects values.
import itertools
def is_iterable(x) -> bool:
"""Return `True` if `x` is iterable."""
try:
iter(x)
return True
except TypeError:
return False