Skip to content

Instantly share code, notes, and snippets.

@CatChenal
Last active October 24, 2024 17:09
Show Gist options
  • Save CatChenal/cc4e41f1f44241f4f7581059ef7a2cee to your computer and use it in GitHub Desktop.
Save CatChenal/cc4e41f1f44241f4f7581059ef7a2cee to your computer and use it in GitHub Desktop.
Cell0 in all Jupyter notebooks

The following code appears as 'Cell0' in all my Jupyter notebooks (because I use JupyterLab Templates).
It loads the most usual functions I use:

from IPython.core.interactiveshell import InteractiveShell
# to get multiple outputs from a cell (with or without using print):
InteractiveShell.ast_node_interactivity = "all"

from IPython.display import Markdown, Image
# for presentations:
#display(HTML("<style>.container { width:100% !important; }</style>"))

import matplotlib as mpl
from matplotlib import pyplot as plt
plt.ion()
plt.style.use('seaborn-v0_8-muted')

import numpy as np
import pandas as pd
#pd.set_option("display.max_colwidth", 200)
from pathlib import Path
from pprint import pprint as ptp
import sys
import time


print("Today: ",time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
print(f"Python ver: {sys.version}\nPython env: {Path(sys.prefix).name}")
print(f"Pandas ver: {pd.__version__}")
print(f"Currrent dir: {Path.cwd()}\n")


def add_to_sys_path(this_path, up=False):
    """
    Prepend this_path to sys.path.
    If up=True, path refers to parent folder (1 level up).
    """
    if up:
        newp = str(Path(this_path).parent)
    else:
        newp = str(Path(this_path))
    if newp not in sys.path:
        sys.path.insert(1, newp)
        print('Path added to sys.path: {}'.format(newp))


def fdir(obj, start_with_str='_', exclude=True):
    """Filtered dir() for method discovery."""
    return [d for d in dir(obj) if not d.startswith(start_with_str) == exclude]


def despine(which=['top','right']):
    """Remove plot borders.
    which ([str])): 'left','top','right','bottom'.
    """
    ax = plt.gca()
    for side in which:
        ax.spines[side].set_visible(False)
    return


def md_width_comment(w:int=120) -> str:
    """Width guide for composing md documents."""
    return f"<!-- dotted line width = {w}\n{'.'*w}-->"


def get_elapsed_time(start_t:time, message :str=None) -> str:
    elapsed = time.time() - start_t
    if message is None:
        return f"Elapsed time: {elapsed:,.2f} s ({elapsed/60:,.2f} min)."
    return f"{message} {elapsed:,.2f} s ({elapsed/60:,.2f} min)."


# autoreload extension
%load_ext autoreload
%autoreload 2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment