Skip to content

Instantly share code, notes, and snippets.

jsbueno / arbitrarily_ordered_dict
Last active Mar 17, 2021
Python User Controlable Ordered Dictionary: one can actually control the item order.
View arbitrarily_ordered_dict
"""Class that represents an ordered dict over which
the user can actually control the item order, and
replace keys already in the dicionary in their
original insertion place.
It also does that in O[1]
If used intenselly, where memory leak of
items deleted might be a problem, the
".compact" method should be called from
jsbueno /
Created Oct 22, 2020
Pygame "Hello World"
import random
import pygame
class GameOver(Exception):
SIZE = 800,600
_sentinel = object()
def iter_check_last(iterable):
iterable = iter(iterable)
current_element = next(iterable, _sentinel)
while current_element is not _sentinel:
next_element = next(iterable, _sentinel)
yield (next_element is _sentinel, current_element)
current_element = next_element
jsbueno /
Last active Oct 15, 2020
Lazy sorter - an iterator that yields items in sorted order, lazily
from itertools import tee
def lazy_sort(v, key=lambda x: x):
v = iter(v)
pivot = next(v)
except StopIteration:
v_pre, v_pos = tee(v)
yield from lazy_sort((item for item in v_pre if key(item) < key(pivot)), key)
jsbueno /
Last active Sep 11, 2020
sample triangle class
class C:
def __init__(self, x, y):
self.x = x
self.y = y
def __repr__(self):
return f"({self.x}, {self.y})"
def __sub__(self, other):
return ((self.x - other.x) ** 2 + (self.y - other.y) ** 2) ** 0.5
jsbueno /
Created Jul 24, 2020
Example of Python code to run a slow call to several resources asynchronously and execute some callback function on return
import asyncio
def worker_that_waits_for_network_io(data, ...):
return result
def callback_hook(retrieved_data, ...):
jsbueno /
Created Jun 26, 2020
GIMP 2.10 plugin: redimensiona camada selecionada para tamanho da primeira camada
#!/usr/bin/env python2
# coding: utf-8
from gimpfu import *
def autoresize(img, drw):
new_width = base_width = img.layers[-1].width
new_height = base_height = img.layers[-1].height
jsbueno /
Last active Jun 2, 2020
One lines showing off what terminedia 0.3 can do
(globals().__setitem__("g", globals().__setitem__),g("i", __import__) ,g("TM", i("terminedia")),g("C", TM.Color),g("tt", TM.utils.get_current_tick),g("sc", TM.Screen()), g("t",TM.shape((80,5))), g("t2",TM.shape((40,10))), t.text[4].at((0,0), "Feliz Aniversário,"), t2.text[8].at((0,0), "Ikke!"), g("aa",,g("s2", aa(t2, active=True, pos=(0,16))), g("s", aa(t, active=True, pos=(5, 10))),g("a", lambda s, t: s.transformers.append(t)), g("T", TM.Transformer),a(s2, T(effects=(lambda pos, tick: TM.Effects.blink * ((tick // 5 + pos[0]) %2) * (pos[1] % 2)), foreground=(lambda pos, tick: C(("#ff0","#fa0")[pos.x %2]) + C((0,0,((tick * 10) % 256) * (pos.x%2)))), char=(lambda char, pos: char == " " and " " or "\u25cf\u25a0"[pos[0] % 2]))), a(s, TM.transformers.GradientTransformer(TM.utils.Gradient([(0, "white"), (.5, (0.3, 0.3, 1)), (1, "white")]))),[sc.update() for _ in (type("_", (),{"__iter__": (lambda s:s),"__next__": (lambda sl: setattr(s2, "pos", (tt() % 40, 16 - (tt() // 2 ) % 16) ))} )())])
jsbueno /
Created May 6, 2020
Auto assign decorator - eliminates attribute assignment boilerplate in __init__ functions
from inspect import signature, Parameter
from functools import wraps, partial
def autoassign(func=None, *, expand_kwargs=False):
if not func:
return partial(autoassign, expand_kwargs=expand_kwargs)
sig = signature(func)
def wrapper(*args, **kwargs):
jsbueno /
Created Apr 15, 2020
Decorator to enable a @DataClass to call __init__ on superclasses
#Decorator to enable a @dataclass to call __init__ on superclasses
from functools import wraps
def colaborative(cls):
if not hasattr(cls, "__dataclass_fields__") or not "__init__" in cls.__dict__:
return cls
cls._dataclass_init = cls.__init__
super_ = cls.__mro__[1]
def __init__(self, *args, **kw):