Skip to content

Instantly share code, notes, and snippets.


James JamesTheAwesomeDude

View GitHub Profile
JamesTheAwesomeDude / shell.bat
Last active September 18, 2023 17:50
Open a CMD window directly in a Python venv
View shell.bat
@echo off
REM After creating a venv via py -m venv "%USERPROFILE%\.venvs\MYVENVNAMEHERE"
REM Save this as %USERPROFILE%\.venvs\MYVENVNAMEHERE\Scripts\shell.bat
REM This script is OK to call from another folder, such as %USERPROFILE%
@echo on
REM Try python -m idlelib
cmd /k "%~dp0\activate.bat"
JamesTheAwesomeDude /
Last active June 23, 2023 15:45
tee into multiple "for" loops in parallel without async, threading, or subprocess
import greenlet
def teeinto_lockstep(
it: 'Iterable[TypeVar("Y")]',
*consumer_callables: 'Callable[[Iterable[TypeVar("Y")]], TypeVar("R")]'
) -> 'Tuple[TypeVar("R"), ...]':
"""tee iterable *it* into multiple non-`async def` consumers, in constant memory, without `threading`.
The consumer callables must take 1 argument, which is a normal (synchronous) iterable object.
JamesTheAwesomeDude /
Last active June 14, 2023 23:56
SortedList-based Multiset
"""Multiset implementation.
__all__ = ["Multiset"]
from sortedcontainers import SortedList #
from collections import Counter, deque
JamesTheAwesomeDude /
Last active July 7, 2023 13:23
groupby multiple iterables in parallel
def joint_groupby(*iterables, key=None, ordered=True):
"""Like itertools.groupby, but iterates through a collection of iterables.
If the value type (or the return type of key) is not comparable, you MUST pass ordered=False.
Example: [(x, tuple(sum(1 for _ in group) for group in groups)) for x, groups in joint_groupby(...)]"""
if key is None:
key = lambda x: x
iterables = [iter(it) for it in iterables]
stop = object()
buffer = [next(it, stop) for it in iterables]
JamesTheAwesomeDude /
Last active June 6, 2023 18:55
extended euclidean algorithm python
def xgcd(a, b):
x, x_ = 1, 0
y, y_ = 0, 1
while b:
q, b, a = *divmod(a, b), b
x, x_ = x_, x - q*x_
y, y_ = y_, y - q*y_
#assert a0*x + b0*y == math.gcd(a0, b0)
return x, y
JamesTheAwesomeDude /
Last active June 6, 2023 18:50
Wrapper function to ease generator-driven query-response pattern
def _ez_generator_interface(g):
"""Handy wrapper for generator-driven program flows.
Example usage:
def g(questions=[("What's 3 + 3?", 6), ("What's 9 + 10?", 19)]):
"Example generator function that yields queries expecting a reply"
for question, correct_answer in questions:
answer = yield question # <- KEY LINE
if int(answer) != correct_answer:
JamesTheAwesomeDude /
Last active June 15, 2023 15:54
parse POST data without cgi module, for Python 3.11+
import email.message, email.parser, email.policy
import urllib.parse
import re
from collections import namedtuple
from resource import getpagesize
except ImportError:
import mmap
def getpagesize():
return mmap.PAGESIZE
JamesTheAwesomeDude /
Last active June 9, 2023 18:40
Get the last element of a sequence matching some predicate
def last_qualified(predicate, iterable, /, return_if_exhausted=True):
Consumes iterable or sequence `iterable` until finding an item
not satisfying `predicate`, or until exhausted, then returns the last item
which satisfied `predicate`.
Raises ValueError if `iterable` is empty.
Raises ValueError if the first item from `iterable` does not satisfy `predicate`.
JamesTheAwesomeDude /
Last active March 24, 2023 14:39
Normalize function inputs before LRU cache
import functools
@(lambda t: lambda f: functools.wraps(f)(lambda x: f(t(x))))(NORMALIZE_FUNC)
def f(x):
JamesTheAwesomeDude / createxmldoc.js
Last active February 21, 2023 15:30
Firefox/Chrome DOM stdlib: create XML document from scratch, including declaration
View createxmldoc.js
// example: createXMLDocumentWithDeclaration('', 'gpx', null, 'version="1.0" standalone="yes"')
function createXMLDocumentWithDeclaration(namespaceURI, qualifiedNameStr, documentType=null, declarationData='version="1.0"') {
const document = new Document().implementation.createDocument(namespaceURI, qualifiedNameStr, documentType);
document.insertBefore(document.createProcessingInstruction("xml", declarationData), document.firstChild);
return document;