Skip to content

Instantly share code, notes, and snippets.

View toby-p's full-sized avatar

toby petty toby-p

View GitHub Profile
@toby-p
toby-p / hide_Jupyter_code.js
Created August 3, 2018 14:36
Hide code in an HTML download of a Jupyter notebook
// I always forget this so saving it here; taken from:
// http://chris-said.io/2016/02/13/how-to-make-polished-jupyter-presentations-with-optional-code-visibility/
// This script hides the code and leaves a button to toggle it on/off:
<script>
function code_toggle() {
if (code_shown){
$('div.input').hide('500');
$('#toggleButton').val('Show Code')
} else {
@toby-p
toby-p / random_string.py
Last active March 6, 2019 16:28
Function to generate unique random strings; mainly for use as a temporary column name in a Pandas DataFrame.
import string
import random
def random_str(l=100):
"""Return a random string of length `l` to use as a temporary unique
variable name or Pandas DataFrame column name."""
s = random.choice(string.ascii_letters) # 1st letter = alpha so can be used as var name.
return s+"".join(random.choice(string.ascii_letters+string.digits) for i in range(l-1))
@toby-p
toby-p / datetime_functions.py
Last active October 25, 2018 20:35
Helpful reusable functions for working with datetime objects
import datetime
import pytz
import dateutil
import os
def datetime_to_str(datetime_obj, date_format="%Y_%m_%d_%H_%M_%S"):
"""Convert a `datetime.datetime` object to a string in the desired format.
Reference for string formatting dates available here:
http://strftime.org/
@toby-p
toby-p / compound.py
Created October 25, 2018 20:34
Compound interest
def compound(initial, percent, years):
if years>0:
initial+=(initial*percent)
years-=1
return compound(initial, percent, years)
else:
return initial
@toby-p
toby-p / debug_print.py
Created October 29, 2018 15:30
Simple debug print statements
from datetime import datetime
import pytz
def debug_print(msg, timezone="US/Eastern"):
"""Print a time-stamped debug message."""
UTC_now = pytz.utc.localize(datetime.utcnow())
now = UTC_now.astimezone(pytz.timezone(timezone))
now_date = now.strftime("%Y_%m_%d")
now_time = now.strftime("%H:%M:%S")
print("[{} @ {}] : {}".format(now_date, now_time, msg))
@toby-p
toby-p / suppress_errors.py
Created December 18, 2018 19:44
Python decorator to suppress errors.
# Global variable to determine whether or not to raise errors.
SUPPRESS_ERRORS = True
def suppress_errors(func):
"""Decorator function to suppress errors."""
if not SUPPRESS_ERRORS:
return func
def suppressed(*args, **kwargs):
try:
return func(*args, **kwargs)
import math
def magnitude(x):
"""Get the order 10 magnitude of a float."""
return int(math.log10(x))
def mpl_y_scale(datamin, datamax, desired_n_steps=5, minmax_buffer=True):
"""Determine nicely spaced, nearest-decimal-rounded y-ticks, and y-axis
limits (with optional buffer) which centrally locate a line plot in a
Matplotlib figure axis.
@toby-p
toby-p / memory-usage.py
Created June 6, 2019 16:27
Function to track current memory usage.
import os, psutil
# Tool for tracking memory usage:
def usage():
process = psutil.Process(os.getpid())
print(process.memory_info()[0] / float(2 ** 20))
@toby-p
toby-p / search_strings.py
Created September 6, 2019 18:19
Search for strings in iterables and Pandas DataFrames
def str_search(*substrings: str, iterable, exact_match: bool = False) -> list:
"""Case-insensitive search of an iterable for substrings.
Args:
substrings (str): strings to search for in the iterable.
iterable (list, tuple, etc): iterable containing string objects to be
searched.
exact_match (bool): if True only return a single value that exactly
matches the substring supplied (therefore only works if 1 substring
arg is supplied). Otherwise returns list of all partial matches.
import traceback
import warnings
import sys
def warn_with_traceback(message, category, filename, lineno, file=None, line=None):
log = file if hasattr(file,'write') else sys.stderr
traceback.print_stack(file=log)
log.write(warnings.formatwarning(message, category, filename, lineno, line))