Last active
August 13, 2022 20:08
-
-
Save davidbgk/b5989d129dabebea1ce8d253d4b7a6c7 to your computer and use it in GitHub Desktop.
Let's start to reference some Python utils
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def neighborhood(iterable, first=None, last=None): | |
""" | |
Yield the (previous, current, next) items given an iterable. | |
You can specify a `first` and/or `last` item for bounds. | |
""" | |
iterator = iter(iterable) | |
previous = first | |
current = next(iterator) # Throws StopIteration if empty. | |
for next_ in iterator: | |
yield (previous, current, next_) | |
previous = current | |
current = next_ | |
yield (previous, current, last) | |
import fnmatch | |
import os | |
def each_folder_from(source_dir, exclude=None): | |
"""Walk across the `source_dir` and return the folder paths.""" | |
for direntry in os.scandir(source_dir): | |
if direntry.is_dir(): | |
if exclude is not None and direntry.name in exclude: | |
continue | |
yield direntry | |
def each_file_from(source_dir, pattern="*", exclude=None): | |
"""Walk across the `source_dir` and return the matching `pattern` file paths.""" | |
for filename in fnmatch.filter(sorted(os.listdir(source_dir)), pattern): | |
if exclude is not None and filename in exclude: | |
continue | |
yield source_dir / filename | |
import hashlib | |
def generate_md5(content): | |
return hashlib.md5(content.encode()).hexdigest() | |
# https://github.com/pyrates/minicli | |
from minicli import cli, run, wrap | |
@cli | |
def blah(): | |
... | |
@wrap | |
def perf_wrapper(): | |
start = perf_counter() | |
yield | |
elapsed = perf_counter() - start | |
print(f"Done in {elapsed:.5f} seconds.") | |
if __name__ == "__main__": | |
run() | |
# There has to be a better way. | |
import time | |
import date from datetime | |
def iso8601toEpoch(iso8601): | |
return time.mktime(date(*[int(part) for part in iso8601.split('-')]).timetuple()) | |
iso8601toEpoch('2021-07-11') => 1625976000.0 | |
# To extract images from a commonmarkdown file: | |
MD_IMAGE_PATTERN = re.compile( | |
r""" | |
!\[ # regular markdown image starter | |
(?P<alt>.*?) # alternative text to the image | |
\]\( # close alt text and start url | |
(?P<url>.*?) # url of the image | |
(?:\s*\"(?P<title>.*?)?\")? # optional text to set a title | |
\) # close of url-part parenthesis | |
""", | |
re.VERBOSE | re.MULTILINE, | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Moved and updated here: https://code.larlet.fr/python/