Skip to content

Instantly share code, notes, and snippets.

View jakelevi1996's full-sized avatar

Jake Levi jakelevi1996

View GitHub Profile
@jakelevi1996
jakelevi1996 / .Zipping and unzipping directories in Python using shutil.md
Last active March 1, 2021 15:58
Zipping and unzipping directories in Python using shutil

Zipping and unzipping directories in Python using shutil

Shown in zip_demo.py below is an example on how to zip and unzip directories in Python using shutil. The script will create a directory called zip_demo_dir containing a file called temp.txt, zip it up into a compressed file called zip_demo_output.zip, and then extract the contents of this zipped file into a directory called zip_demo_output_unpacked, which will contain a copy of the file temp.txt.

Note that it is also straightforward to unzip an archive using Python from the command line, as shown below, for example:

>>> import os, shutil
>>> os.listdir()
['example.tar.gz']
@jakelevi1996
jakelevi1996 / .Print timestamped exception information to a text file in Python.md
Last active June 25, 2021 12:03
Print timestamped exception information to a text file in Python

Print timestamped exception information to a text file in Python

Below is the Python code which demonstrates how to print timestamped exception information to a text file, followed by the output text file debug.txt. In order to append information to debug.txt (and create the file if it doesn't already exist) instead of overwriting the text file every time, replace the line debug_file = open("debug.txt", "w") with debug_file = open("debug.txt", "a").

import sys
from traceback import print_exception
from datetime import datetime

def do_something_bad():
@jakelevi1996
jakelevi1996 / Automatically opening serial connections to COM ports.md
Last active September 30, 2024 15:54
Automatically opening serial connections to COM ports

Automatically opening serial connections to COM ports

Below is a small Python script (putty_com.py) which can automatically open serial connections to COM ports using PuTTY, unless they have been specified as being occupied. The docstring contains instructions for how to further automate running this script, EG by adding a shortcut to the start menu. The script also has an argparse command-line interface, as explained in the docstring. This script has been tested using Python version 3.7.6, Pyserial version 3.4, and PuTTY version 0.73.

Note that an alternative to opening a PuTTY window in a subprocess is to read from the serial connection directly in Python using pySerial. The snippet below demonstrates a very basic yet functional example of how to read from a serial device (a more complete script containing some error handling, command line arguments, logging to file, and timestamps, is included in the [serial_log.py script below](https://gist.github.com/jakelevi1996/79f42f47f3885765b80bd6af6264978

@jakelevi1996
jakelevi1996 / .Making a pie chart of the current directory contents.md
Last active August 24, 2024 08:26
Making a pie chart of the current directory contents

Making a pie chart of the current directory contents

Below is a Python script, which can be used to calculate the sizes of all files and sub-directories of a given target directory, and plot the results in a pie chart. Some example output images are shown below.

A cache-file is used, so that the sizes of the same directories don't have to be calculated multiple times.

One simple way to use this script is to clone this Gist, change into the correct directory, and run python ./plot_dir_contents.py --target_dir TARGET_DIR, where TARGET_DIR is the name of the target directory whose contents should be calculated and plotted.

TODO: write file sizes to cache file repeatedly during the loop before writing them all again after the loop, to avoid exiting due to ctrl+c? Or catch signal and write it to disk before exiting?

@jakelevi1996
jakelevi1996 / Least common multiple and greatest common divisor.md
Last active July 29, 2020 15:31
Least common multiple and greatest common divisor

Least common multiple and greatest common divisor

Below is some code for calculating the least common multiple and greatest common divisor. This could be made more efficient in several ways, for example, using a prime number sieve (as demonstrated in one of my other Gists) instead of trial division to build up a prime factorisation:

from math import sqrt, log, exp
import numpy as np


def divides(factor, x):
@jakelevi1996
jakelevi1996 / .Pytest guide for unit testing in Python.md
Last active August 6, 2024 12:53
Pytest guide for unit testing in Python

Pytest guide for unit testing in Python

pytest is a Python module for performing unit tests, which can be installed with the commands pip install --upgrade pip and pip install pytest. This Gist demonstrates various features of pytest and other things which are useful when using pytest, including:

  • How to check that a function returns the values you expect it to return using an assert statement
  • How to check that a function raises the errors you expect it to raise using a with pytest.raises context manager
  • How to automate combinations of different input arguments using the @pytest.mark.parametrize decorator
  • How to define a decorator to automatically repeat a unit test multiple times with different random seeds
  • How to import source code from a parent directory
  • How to check how many times a function is called using unittest.mock.Mock
@jakelevi1996
jakelevi1996 / .Approximate log2(x) using integer arithmetic.md
Last active July 17, 2020 17:03
Approximate log2(x) using integer arithmetic

Approximate log2(x) using integer arithmetic

TODO 2020-07-17: tidy up this Gist. Binary search for size in bits adapted from source code for WebRTC project.

import numpy as np
import matplotlib.pyplot as plt

def log2Q10_xQ12(x_Q12):
    """
@jakelevi1996
jakelevi1996 / keras_cnn_mnist.py
Created July 10, 2020 14:02
Single script example of training a CNN on MNIST using tensorflow.keras
from time import perf_counter
import numpy as np
from tensorflow.keras import datasets, layers, models, losses
# Get training and test data
(x_train, y_train), (x_test, y_test) = datasets.mnist.load_data()
x_train = np.expand_dims(x_train, -1) / 255.0
x_test = np.expand_dims(x_test, -1) / 255.0
# Create model
@jakelevi1996
jakelevi1996 / . Record audio and plot spectrogram in Python.md
Last active July 8, 2020 21:42
Record audio and plot spectrogram in Python

Record audio and plot spectrogram in Python

Below is a Python script which demonstrates how to record audio in Python, calculate a spectrogram, and plot the spectrogram, followed by a few usage examples (me playing the opening bars of "Majorca" by Albeniz, and me whistling a major triad and then some random notes).