Skip to content

Instantly share code, notes, and snippets.

@dmwyatt
dmwyatt / filetype_types.py
Last active February 21, 2024 21:18
A Union of all file types in `filetype` package
frofrom typing import Union
from filetype.types import application, archive, audio, document, font, image, video
ImageFileType = Union[
image.Dwg,
image.Xcf,
image.Jpeg,
image.Jpx,
image.Apng,
@dmwyatt
dmwyatt / temp_backup.py
Last active October 25, 2023 22:09
[temporarily replace file] Sometimes when testing I want to replace a file with a test file. This context manager does that. #testing
import contextlib
import shutil
from pathlib import Path
@contextlib.contextmanager
def replace_file(orig, replace_with):
if not replace_with.is_file():
raise ValueError("{} does not exist.".format(replace_with))
if orig.is_file():
@dmwyatt
dmwyatt / check_if_executable.py
Last active October 25, 2023 22:09
[Check if file is executable.]
def is_exe(filepath):
return os.path.isfile(filepath) and os.access(filepath, os.X_OK)
@dmwyatt
dmwyatt / hash_dir.py
Last active October 25, 2023 22:09
[hash directory and capture filename data]
import os
import hashlib
def hash_dir(path):
"""
Create a hash out of a directory that handles renamed files.
A hash of the contents of a file will not capture a hash of the filename.
This function will add filenames to the hash so that we can know if a
@dmwyatt
dmwyatt / model_diff_mixin.py
Last active October 25, 2023 22:08
[ModelDiffMixin: compare previous values to new values] lets you compare previous values to new values when saving Django model #django
from django.forms.models import model_to_dict
class ModelDiffMixin(object):
"""
A model mixin[1] that tracks model fields' values and provide some useful api
to know what fields have been changed.
[1] http://stackoverflow.com/questions/1355150/django-when-saving-how-can-you-check-if-a-field-has-changed
"""
@dmwyatt
dmwyatt / register_app_routes.py
Last active October 25, 2023 22:08
[auto drf url registration] Using Django Rest Framework's DefaultRouter to build an API Root for urls.py files located in individual apps. #django #drf
# urls.py
def register_routes(router, apps):
"""
Register DRF router routes from urls.py in the provided apps.
>>> router = routers.DefaultRouter()
>>> register_routes(router, ['app1', 'app2', 'app3])
"""
for app in apps:
urls = importlib.import_module(app+".urls")
@dmwyatt
dmwyatt / dict_differ.py
Last active October 25, 2023 22:07
[dict diff]
class DictDiffer(object):
"""
Calculate the difference between two dictionaries as:
(1) items added
(2) items removed
(3) keys same in both but changed values
(4) keys same in both and unchanged values
http://stackoverflow.com/questions/1165352/fast-comparison-between-two-python-dictionary/1165552#1165552
"""
@dmwyatt
dmwyatt / show_urls.py
Last active October 25, 2023 22:07
[Pretty print urls] Print indented list of urls configured in a django project #django
def show_urls(urllist: list, indent_depth: int = 0, indent_char: str = " "):
"""
Prints a list of urls for this project.
:param urllist: A list of url patterns. Typically `urlpatterns` imported from `urls.py`
:param indent_depth: How far to indent for each sub-level of urls
:param indent_char: The charcter to use to indent.
"""
for entry in urllist:
print(indent_char * indent_depth, entry.regex.pattern, end="")
@dmwyatt
dmwyatt / remove_chrome_other_search_engines.js
Last active October 25, 2023 22:07
[Remove chrome "other search engines"] #chrome
// 1. open chrome://settings/searchEngines
// 2. press Ctrl-Shift-J to open console
// 3. paste the following code
// note: you may have to run it multiple times to get rid of all of them
// If you have search engines you want to use add the text "(KEEP)" to their name
// and by name i mean the "Search engine" field when you add/edit one of the search engines
settings.SearchEnginesBrowserProxyImpl.prototype.getSearchEnginesList()
.then(function (val) {
@dmwyatt
dmwyatt / update_function_param_values.py
Last active October 25, 2023 22:05
[arg updater] A function that takes a function, the args and kwargs for that function, and updated values for those args and kwargs. It then applies the updated values to the original args and kwargs and returns the updated args/kwargs.
import abc
import inspect
from collections import OrderedDict
from typing import Any, Mapping, Tuple, Union, Callable, MutableMapping, Sequence
class ValueUpdater(abc.ABC):
"""Base class for functions that update the value of another functions arguments.
For usage with :func:`update_parameter_value`.