Skip to content

Instantly share code, notes, and snippets.

@zhangzhhz
zhangzhhz / resize_img_save_to_pdf.py
Last active September 7, 2019 14:51
A way to reszie images and save them to one pdf file using Python package Pillow (PIL fork)
from PIL import Image
from glob import glob
# assumed ".jpg" files
def resize_images(files, width, height):
for f in files:
img = Image.open(f).resize((width, height)) # Note: this won't keep aspect ratio
img.save(f.replace('.jpg', '_resized.jpg'))
def save_to_pdf(files, pdf_file_name):
@zhangzhhz
zhangzhhz / whoami.py
Created December 29, 2019 05:49
Get the name of the function that is running
def whoami():
'''
To be used within a function.
Returns the name of the function whoami() is called in.
'''
import sys
return sys._getframe(1).f_code.co_name
@zhangzhhz
zhangzhhz / python_logging.md
Last active January 18, 2021 08:35
SoOme notes on python logging module

logging.basicConfig() configures the root logger. The default log level of basicConfig() is logging.WARNING or 30 (try print(logging.getLogger().level) or print(logging.root.level)).

logging.getLogger(), logging.getLogger(None) and logging.root returns the same root logger.

In [26]: logging.getLogger().level
Out[26]: 30
In [27]: logging.getLogger(__name__).level
Out[27]: 0
In [28]: logging.root is logging.getLogger(), logging.root is logging.getLogger(None)
Out[28]: (True, True)
@zhangzhhz
zhangzhhz / python_logging_example_2.py
Last active December 29, 2019 08:36
Using python logging module, one can change logging level of a imported module that also uses python logging. In this snippet, the last line (commented out) disables MSAL DEBUG logs.
import msal
# Optional logging
formatter = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
# logging.basicConfig(format=formatter, level=logging.DEBUG) # Enable DEBUG log for entire script
logging.basicConfig(format=formatter) # initialte logging
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
# logging.getLogger("msal").setLevel(logging.INFO) # Optionally disable MSAL DEBUG logs
@zhangzhhz
zhangzhhz / ffmpeg_commands.txt
Last active March 16, 2021 19:24
Some ffmpeg commands
Convert videos to mp4:
Move MOOV atom to the beginning so that the video can be streamed:
ffmpeg -i orig.mp4 -movflags faststart -c copy out.mp4
ffmpeg -i S04E04.1080p.mkv -c:a copy -c:v libx264 -preset faster -f mp4 -s hd720 -hide_banner S04E04A.720p.mp4
# to specify profile and level for h264 coding:
# to output 8bit, use `-pix_fmt yuv420p`
ffmpeg -i video.mkv -c:a copy -c:v libx264 -profile:v high -level:v 4 -preset faster -pix_fmt yuv420p -f mp4 -s hd720 -hide_banner output.mp4
def pack_file(file_name, outfile_name, no_of_bytes_to_prefix=100):
file_name_encoded = bytes(file_name, encoding='utf-8')
file_name_length = len(file_name_encoded)
if file_name_length > no_of_bytes_to_prefix:
raise Exception('file name after utf-8 encoding is too long')
prefixed_bytes = bytearray(no_of_bytes_to_prefix)
prefixed_bytes[0:file_name_length] = file_name_encoded
chunk_buffer = 4096
with open(file_name, 'rb') as infile, open(outfile_name, 'wb') as outfile:
import hashlib, binascii, os
def hash_password(password):
"""Hash a password for storing."""
salt = hashlib.sha256(os.urandom(60)).hexdigest().encode('ascii')
pwdhash = hashlib.pbkdf2_hmac('sha512', password.encode('utf-8'),
salt, 100000)
pwdhash = binascii.hexlify(pwdhash)
return (salt + pwdhash).decode('ascii')
const crypto = require('crypto');
const util = require('util');
const randomBytes = util.promisify(crypto.randomBytes);
async function hashPassword(password) {
// Hash a password for storing.
try {
const buf = await randomBytes(64);
const salt = crypto.createHash('sha256').update(buf.toString('hex')).digest('hex');
const fs = require('fs');
function packFile(filename, outfilename, noOfBytesToPrefix = 100) {
const filenameEncoded = new Buffer.from(filename, 'utf8');
const filenameLength = filenameEncoded.length;
if (filenameLength > noOfBytesToPrefix) {
throw new Error("file name after utf-8 encoding is too long");
}
let prefixBuffer = new Buffer.allocUnsafe(noOfBytesToPrefix).fill(0);
Perl:
print "$^V\n"; # 5.26.1
print "$]\n"; # 5.026001
Python:
import sys
print(sys.version) # 3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:59:51) [MSC v.1914 64 bit (AMD64)]
print(sys.version_info) # sys.version_info(major=3, minor=7, micro=0, releaselevel='final', serial=0)
import platform
print(platform.python_version()) # 3.7.0