Skip to content

Instantly share code, notes, and snippets.

from collections import defaultdict
word_lists = defaultdict(list)
pairs = [('a', 1), ('b', 2), ('c', 3), ('a', 4), ('b', 5)]
for key, value in pairs:
word_lists[key].append(value) # Append value to list
print(word_lists.get('d', []))
@normanlmfung
normanlmfung / gist:a44a2797624c6f59e1c626fdbe060504
Created March 30, 2024 22:31
python_syntax_decorator_apiguard
# REST API guard: check api key (If incorrect API key, raise exception)
def check_api_key(api_key : str, request : Any, symmetric_key : str, kms_gizmo : Any):
def decorator(method):
headers = request.headers
encrypted_api_key_from_header = headers.get("X-Api-Key")
decrypted_api_key_from_header = encrypted_api_key_from_header
if kms_gizmo:
decrypted_api_key_from_header = kms_gizmo.decrypt(decrypted_api_key_from_header)
if symmetric_key:
decrypted_api_key_from_header = cipher_gizmo.decrypt(encrypted_text=decrypted_api_key_from_header, key=symmetric_key)
@normanlmfung
normanlmfung / gist:1665931c2eb94f2e02756a0dfd0f849a
Created March 30, 2024 22:30
python_syntax_decorator_timer
# timer (Simply log the duration of time the wrapped method took). Can also be extended to filter/modify parameters.
def timer(method):
def timed(*args, **kw):
start = time.time()
result = method(*args, **kw)
elapsed = (time.time() - start) * 1000
logger.info(f'@timer {method.__qualname__} returned in {elapsed} ms. {args_}')
return result
# Taken DIRECTLY from William's article https://realpython.com/python-interface/
import abc
class FormalParserInterface(metaclass=abc.ABCMeta):
@classmethod
def __subclasshook__(cls, subclass):
print("FormalParserInterface.__subclasshook__")
return (hasattr(subclass, 'load_data_source') and
callable(subclass.load_data_source) and
hasattr(subclass, 'extract_text') and
# https://docs.python.org/3/library/contextlib.html
from contextlib import contextmanager
class MessageWriter(object):
def __init__(self, filename):
self.file_name = filename
@contextmanager
def open_file(self):
try:
@normanlmfung
normanlmfung / gist:1765bd4dca5987c352f33304ad91e5f2
Created March 30, 2024 22:21
python_syntax_using_enter_exit
class MessageWriter(object):
def __init__(self, file_name):
self.file_name = file_name
def __enter__(self):
self.file = open(self.file_name, 'w')
return self.file
def __exit__(self, *args):
self.file.close()
@normanlmfung
normanlmfung / gist:9c293bc8c93c9be7b9ca9fd09c155195
Created March 30, 2024 22:19
python_syntax_yield_return_fibonacci
def fibonacci():
a, b = 0, 1
while True:
yield a
a, b = b, a + b
# Generate Fibonacci numbers up to a certain limit
def fibonacci_up_to(limit):
fib = fibonacci()
while True:
class square_all:
def __init__(self, numbers):
self.numbers = iter(numbers)
def __next__(self):
return next(self.numbers) ** 2
def __iter__(self):
return self
import numpy as np
from keras.models import Sequential
from keras.layers import Dense
X_train = np.array([[0, 0], [0, 1], [1, 0], [1, 1]])
y_train = np.array([[0], [1], [1], [0]])
model = Sequential()
model.add(Dense(2, input_dim=2, activation='relu'))
model.add(Dense(1, activation='sigmoid'))
import json
import pandas as pd
import numpy as np
import math
from datetime import datetime
from tabulate import tabulate
# Illustration 1. Array initialization: ones/zeros/arrange/linspace
np.arange(0, 10, 2) # array([0, 2, 4, 6, 8])
np.zeros(10)