Skip to content

Instantly share code, notes, and snippets.

View kissgyorgy's full-sized avatar

György Kiss kissgyorgy

View GitHub Profile
@kissgyorgy
kissgyorgy / parse_der_cert.py
Created July 2, 2022 17:20
Python: Parse X.509 DER certificate with extra data at the end
from pathlib import Path
from cryptography import x509
ASN1_SEQUENCE_TAG = 0x30
def get_der_cert_length(cert_bytes: bytes) -> int:
if cert_bytes[0] != ASN1_SEQUENCE_TAG:
raise ValueError("Not a DER certificate")
@kissgyorgy
kissgyorgy / sleep-sort.sh
Last active May 22, 2024 13:58
Bash: sleep sort
#!/bin/bash
function f() {
sleep "$1"
echo "$1"
}
while [ -n "$1" ]
do
f $1 &
shift
done
@kissgyorgy
kissgyorgy / structlog_lazy_field.py
Last active January 10, 2022 21:25
Python: lazily evaluate field for structlog
class LazyField:
"""Evaluates __repr__ lazily for heavy calculations.
Expects callable with args and kwargs of how to calculate the value.
"""
def __init__(self, func, *args, **kwargs):
self._func = func
self._args = args
self._kwargs = kwargs
self._value = ...
@kissgyorgy
kissgyorgy / waitforsocket.sh
Created August 14, 2021 20:37
bash: Wait for socket to became active
#!/bin/bash
# Wait for a socket on given host and port to became active.
# Will exit with statuscode 0 if succeeded, -1 otherwise.
# Originally got it from the blog post: https://developer.atlassian.com/blog/2015/03/docker-systemd-socket-activation/
host=$1
port=$2
tries=600
@kissgyorgy
kissgyorgy / async_loop_cancellation.py
Last active January 10, 2022 21:25
Python: Handle cancellation in an asyncio background task
import asyncio
import httpx
async def infinite_loop(backend_client):
while True:
try:
await asyncio.sleep(3)
except asyncio.CancelledError:
print("Cancelled")
import requests
import datetime
URI = 'https://gist.githubusercontent.com/jorin-vogel/7f19ce95a9a842956358/raw/e319340c2f6691f9cc8d8cc57ed532b5093e3619/data.json'
filename = datetime.date.today().strftime('%Y%m%d.csv')
def imperative():
with open(filename, 'w') as f:
f.write('Name,Credit Card\n')
@kissgyorgy
kissgyorgy / async_coro_close.py
Created May 4, 2021 08:49
Python: Handling closing of asynchronous coroutine properly
# https://www.python.org/dev/peps/pep-0525/
import asyncio
async def generate_numbers():
i = 0
while True:
try:
yield i
except GeneratorExit:
@kissgyorgy
kissgyorgy / print_diamond.py
Created April 3, 2021 13:12
Python: Print a diamond shape with as many lines as the input number.
# For example, if the input is 5, the shape should look like this:
# *
# ***
# *****
# ***
# *
import math
lines = int(input('How many lines? '))
@kissgyorgy
kissgyorgy / 1-before.py
Last active February 16, 2021 22:04
Python: calculate hash and save file at the same time
def _calculate_hash_and_save(uploaded_file, temp_file):
file_hash = hashlib.sha256()
for chunk in uploaded_file.chunks():
file_hash.update(chunk)
temp_file.write(chunk)
return file_hash.hexdigest()
@kissgyorgy
kissgyorgy / cpu_hog.py
Created September 23, 2020 14:08
Python: Makes your CPU sweat
from concurrent.futures import ProcessPoolExecutor, wait
WORKERS = 6
futures = []
def cpu_hog():
print("Starting computation")
return 2 ** 10000000000000000