Skip to content

Instantly share code, notes, and snippets.

@ValentaTomas
ValentaTomas / must.go
Created March 23, 2024 00:29
Go utility for ensuring a proper value that panics otherwise
func Must[T any](obj T, err error) T {
if err != nil {
panic(err)
}
return obj
}
@ValentaTomas
ValentaTomas / ttl_cache.py
Last active January 8, 2024 11:39
Generic Python TTL cache that uses threads
import threading
import time
from typing import Callable, TypeVar, Generic, Any, Dict, Tuple, List
T = TypeVar("T")
class TTLCache(Generic[T]):
def __init__(
@ValentaTomas
ValentaTomas / stopwatch.py
Created December 22, 2023 14:04
Measure execution time of a function
def stopwatch():
def decorator(func):
def wrapper(*args, **kwargs):
start_time = time.time()
result = func(*args, **kwargs)
end_time = time.time()
elapsed_time = end_time - start_time
print(f"time taken {elapsed_time: 2f}")
return result
@ValentaTomas
ValentaTomas / hash.ts
Last active October 13, 2023 20:13
Hash files
import * as crypto from 'crypto'
const delimiter = '\0'
export function getFilesHash(files: { name: string; content: string }[]) {
const shasum = crypto.createHash('sha1')
files.forEach(({ name, content }) => {
shasum.update(name)
// Add delimiter to hash to prevent collisions between files where the join of the name and content is the same
@ValentaTomas
ValentaTomas / random.sh
Last active August 14, 2023 16:01
Generate random string (the chars are only hex, not the full alphanumeric!)
node -e "console.log(require('crypto').randomBytes(64).toString('hex'))"
@ValentaTomas
ValentaTomas / id.py
Created August 4, 2023 14:26
Random alphanumeric id generator
import random
import string
characters = string.ascii_letters + string.digits
def id(length: int):
return "".join(random.choices(characters, k=length))
@ValentaTomas
ValentaTomas / deferred_future.py
Last active December 20, 2023 20:20
Deferred future for controlling async flow (there are existing asyncio features for doing this)
import asyncio
import json
from typing import TypeVar, Generic, List
T = TypeVar("T")
class DeferredFuture(Generic[T]):
def __init__(self):
@ValentaTomas
ValentaTomas / useAsyncResource.ts
Created June 2, 2023 21:50
Simple wrapper for useEffect and useState hook to execute and store results of async operations.
import { useEffect, useState } from 'react'
export function useAsyncResource<T>(fetchResource: () => Promise<T>) {
const [data, setData] = useState<T>()
const [error, setError] = useState<any>()
useEffect(function getResource() {
fetchResource()
.then(setData)
.catch(setError)
@ValentaTomas
ValentaTomas / wait.ts
Created May 29, 2023 20:36
Promisified setTimeout
export async function wait(ms: number) {
return new Promise(resolve => setTimeout(resolve, ms))
}
@ValentaTomas
ValentaTomas / useQueryTab.ts
Last active April 20, 2023 11:00
Save and retrieve page tab information with query string in Next.js
import { useRouter } from 'next/router'
import { useCallback } from 'react'
type Base = Record<string, string | number>
interface SetTab<T> {
(tab: keyof T): void
}
function compareTabsCaseInsensitive<T extends Base>(tabs: T, tab?: string) {