Skip to content

Instantly share code, notes, and snippets.

from math import log10
from typing import Sequence
def print_numbered_list(items: Sequence, fmt='{num}. {item}') -> None:
"""Display as a numbered list where the items are left aligned.
items:
A list of printable items.
fmt:
@bpeterso2000
bpeterso2000 / print_table.py
Last active February 18, 2023 02:25
Display a list of lists as a simple text table with rows, columns and an optional header.
from math import log10
from typing import Sequence
def print_table(rows: Sequence[Sequence], hdr=True, rownums=True) -> None:
"""Display as a simple text table; rows, columns & optional header.
rows:
Rows & columns where each cell object is a string or can be
converted into a string.
import shlex
import subprocess
import sys
def bash(cmd):
print(cmd)
try:
res = subprocess.run(shlex.split(cmd), capture_output=True, check=True)
except subprocess.CalledProcessError as e:
print(res.stderr, file=sys.stderr)
~/w/rest-client-boilerplate   *…  restclient  cat ratelimiter.py
"""
Key-based Rate limiter
======================
Rate limiter for API keys & resource ID's.
Not thread-safe; use something like redis for that.
"""
import threading
import json
import sys
import click
import click._termui_impl
class JSONFile(click.File):
name = 'JSON.load'
@bpeterso2000
bpeterso2000 / jsoncrawl.py
Created October 10, 2017 13:56
JSON Node Visitor
from itertools import repeat
from collections import Mapping, Sequence, deque, namedtuple
from treecrawler._compat import string_type, text_type, binary_type
DONT_ITER_TYPES = string_type, text_type, binary_type
Node = namedtuple('Node', ['keys', 'val'])
def get_children(node, element_char, mappings=True, sequences=False,
from random import randint
# --- Base Solution ---
def base_sum_diags(n, rows):
ldiag = [row[i] for i, row in enumerate(rows)]
rdiag = [list(reversed(row))[i] for i, row in enumerate(rows)]
print(ldiag)
print(rdiag)
@bpeterso2000
bpeterso2000 / slugs_funct.py
Created April 26, 2017 00:38
Slugify tokens
import re
from collections import Counter
from unidecode import unidecode
from toolz import curry, pipe
WHITESPACE = re.compile(r'\s+')
NONALPHANUM = re.compile(r'[^\w_-]')
@bpeterso2000
bpeterso2000 / get_all_nested_keys.py
Last active December 29, 2016 21:51
Get pointers to all unique top-level and nested keys
import collections
def get_keys(d, keys=None, pointer=None, sep='.', prefix=''):
if keys is None:
keys = set()
if pointer is None:
pointer = []
"""
JSON Keys.
A simple command-line utility that allows the user to quickly:
1. Set the root level of JSON data by using a JSON pointer.
2. Select items to pull from each object in a JSON array.
3. Drop items from objects in a JSON array.
It is not uncommon for an API to return a JSON array of objects containing
much more detail than is needed. This tools is designed to allow the user to