Skip to content

Instantly share code, notes, and snippets.

View johnberroa's full-sized avatar

John johnberroa

View GitHub Profile
import argparse
from typing import Any, Dict, List, Optional
class FillDict(argparse.Action):
"""Argparse action that fills in a dictionary with nargs.
General usecase:
Subclass this and set custom_keys and defaults (if there are any).
Set that subclass as the action of an argparse argument, with nargs="+".
@johnberroa
johnberroa / singelton.py
Created February 22, 2021 19:53
A Python singleton
import logging
LOG = logging.getLogger(__name__)
class Singleton:
"""Abstract class that forces only one instance of the child to be created."""
#: Singleton controller; True if an instance of this class has already been created
created = False
from copy import deepcopy
from typing import List
def propagate_color(matrix: List[List[str]], color: str) -> List[List[str]]:
"""Propagates color to all same colors that neighbor the color at [0,0]
Note: only works for square matrices!
"""
to_change: str = matrix[0][0]
@johnberroa
johnberroa / absorber.py
Last active October 11, 2019 15:05
Replace any class with this to essentially disable all references to it in code. Use this instead of many try/excepts or ifs.
class Disabled:
"""Class that absorbs all attribute and method calls on it"""
def __init__(self, *args, **kwargs):
pass
def __getattr__(self, item):
return self
def __call__(self, *args, **kwargs):
@johnberroa
johnberroa / extract_from_nested_dict.py
Created September 10, 2019 14:37
Dive into a dictionary given a key path separated by "/"
def dive_into_dict(path, dic):
path = path.split("/")
key = path[0]
result = dic[key]
if isinstance(result, dict):
result = dive_into_dict("/".join(path[1:]), result)
return result
@johnberroa
johnberroa / remove_umlauts.py
Created July 26, 2018 20:00
Remove umlauts from text in Python
def remove_umlaut(string):
"""
Removes umlauts from strings and replaces them with the letter+e convention
:param string: string to remove umlauts from
:return: unumlauted string
"""
u = 'ü'.encode()
U = 'Ü'.encode()
a = 'ä'.encode()
A = 'Ä'.encode()