Skip to content

Instantly share code, notes, and snippets.

View malcolmgreaves's full-sized avatar

Malcolm Greaves malcolmgreaves

View GitHub Profile
@malcolmgreaves
malcolmgreaves / descent_torchscript_iterating.py
Last active February 21, 2023 21:01
descent_script: A function that recursively expands a model's children and TorchScripts everything, making it easy to identify which network parts are and are not TorchScript compatible.
import traceback
from abc import ABC, abstractmethod
from dataclasses import dataclass
from typing import Iterator, Sequence, Union
import torch
from core_utils.common import type_name
__all__: Sequence[str] = (
"descent_script",
@malcolmgreaves
malcolmgreaves / canceling_asyncio_tasks_101.py
Created February 14, 2023 01:47
Simple example showing how to safely cancel a heartbeat task.
async def heartbeat(interval=5):
while True:
await asyncio.sleep(interval)
async def safe():
loop = asyncio.get_running_loop()
h = loop.create_task(heartbeat())
await asyncio.sleep(1)
@malcolmgreaves
malcolmgreaves / keep_process_alive.py
Last active December 21, 2022 23:06
Python process watchdog: monitors a process for termination and restarts it as necessary.
import os
import sys
from multiprocessing import Process
from typing import Callable, Optional, Sequence
def make_logger():
import logging
log_level = logging.INFO
@malcolmgreaves
malcolmgreaves / calculate_greast_common_subpath.py
Last active October 15, 2022 19:34
Provides a function `calculate_greatest_common_subpath` which accepts a `Sequence[Path]` and finds the deepest common parent among them.
import os
from collections import Counter
from pathlib import Path
from typing import Iterator, List, Sequence, Tuple
def calculate_greatest_common_subpath(files: Sequence[Path]) -> Path:
"""Find the longest common subpath amongst a collection of files."""
if len(files) == 0:
raise ValueError("Must input at least one file!")
@malcolmgreaves
malcolmgreaves / lazy.py
Last active October 5, 2022 21:42
A function / method wrapper to lazily evaluate a function ONCE.
def cache_once(func):
"""Decorator that caches the result of a unary function or method.
REQUIREMENTS: The decorated function must be **referentially transparent**. I.e. the same arguments
result in the same output result, **every time**. With this guarantee, it is safe to
cache the value of a unary function from a single execution. If your funciton has any
side effects, it is not referentially transparent. Avoid any dependencies on mutable
state, I/O, etc.
To use, you simply wrap an existing function:
@malcolmgreaves
malcolmgreaves / fast_http_utils.py
Last active September 28, 2022 23:00
Massively concurrent HTTP request sending with Python.
import logging
import threading
import time
import traceback
from concurrent.futures import FIRST_COMPLETED, Future, ThreadPoolExecutor, wait
from contextlib import ExitStack
from dataclasses import dataclass
from time import sleep
from typing import Any, Callable, ContextManager, List, NamedTuple, Optional, Sequence, Set
@malcolmgreaves
malcolmgreaves / fixed_thread_pool_executor.py
Created September 26, 2022 21:32 — forked from tliron/fixed_thread_pool_executor.py
Python fixed thread pool exuector
from threading import Thread, Lock
from Queue import Queue
import itertools, traceback, multiprocessing
class FixedThreadPoolExecutor(object):
"""
Executes tasks in a fixed thread pool.
Makes sure to gather all returned results and thrown exceptions in one place, in order of task
submission.
@malcolmgreaves
malcolmgreaves / execute_bash_script_from_python_helper.py
Last active August 9, 2022 14:00
Function to execute an arbitrary-length BASH script from Python; always returns a CompletedProcess object.
# Uses `strip_margin` defined here:
# https://gist.github.com/malcolmgreaves/7c9ec3407a02a3eb6d4b898bc16dc902
import subprocess
def exec_bash_script(
script_contents: str, *, prepend_bash_shebang_if_needed: bool = True
) -> subprocess.CompletedProcess:
script_contents = script_contents.strip()
@malcolmgreaves
malcolmgreaves / strip_margin_from_multiline_string.py
Last active August 9, 2022 13:56
Strings the whitespace margin from each line of a multiline string.
from typing import List
def strip_margin(long_multiline_string: str) -> str:
bits = long_multiline_string.strip().split('\n')
stripped: List[str] = []
for b in bits:
for i in range(len(b)):
c = b[i]
@malcolmgreaves
malcolmgreaves / reproduce_dataclass_field_override_inherit_bug.py
Last active June 17, 2022 19:34
Bug report: adding a type annotation to a field, *when the parent is a `@datalcass`*, makes overriding that field with different values in extending classes impossible.
from dataclasses import *
from abc import *
from pathlib import Path
from typing import TypeVar, Optional, Union, Type, Any, Generic
ServiceClass = TypeVar("ServiceClass")
T = TypeVar("T")