Skip to content

Instantly share code, notes, and snippets.

Avatar

Joao S. O. Bueno jsbueno

View GitHub Profile
@jsbueno
jsbueno / helloworld.py
Created Oct 22, 2020
Pygame "Hello World"
View helloworld.py
import random
import pygame
class GameOver(Exception):
pass
SIZE = 800,600
View iter_check_last.py
_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
jsbueno / lazyquicksort.py
Last active Oct 15, 2020
Lazy sorter - an iterator that yields items in sorted order, lazily
View lazyquicksort.py
from itertools import tee
def lazy_sort(v, key=lambda x: x):
v = iter(v)
try:
pivot = next(v)
except StopIteration:
return
v_pre, v_pos = tee(v)
yield from lazy_sort((item for item in v_pre if key(item) < key(pivot)), key)
@jsbueno
jsbueno / triangle.py
Last active Sep 11, 2020
sample triangle class
View triangle.py
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
jsbueno / async_run_example.py
Created Jul 24, 2020
Example of Python code to run a slow call to several resources asynchronously and execute some callback function on return
View async_run_example.py
import asyncio
def worker_that_waits_for_network_io(data, ...):
...
return result
def callback_hook(retrieved_data, ...):
...
@jsbueno
jsbueno / autoresize.py
Created Jun 26, 2020
GIMP 2.10 plugin: redimensiona camada selecionada para tamanho da primeira camada
View autoresize.py
#!/usr/bin/env python2
# coding: utf-8
from gimpfu import *
def autoresize(img, drw):
pdb.gimp_image_undo_group_start(img)
try:
new_width = base_width = img.layers[-1].width
new_height = base_height = img.layers[-1].height
@jsbueno
jsbueno / feliz_aniversario_ikke_2020.py
Last active Jun 2, 2020
One lines showing off what terminedia 0.3 can do
View feliz_aniversario_ikke_2020.py
(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", sc.data.sprites.add),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
jsbueno / autoassign.py
Created May 6, 2020
Auto assign decorator - eliminates attribute assignment boilerplate in __init__ functions
View autoassign.py
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)
@wraps(func)
def wrapper(*args, **kwargs):
@jsbueno
jsbueno / collaborative.py
Created Apr 15, 2020
Decorator to enable a @DataClass to call __init__ on superclasses
View collaborative.py
#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]
@wraps(cls.__init__)
def __init__(self, *args, **kw):
@jsbueno
jsbueno / example decorator above being used interactivelly
Last active Feb 11, 2020
A decorator to be applied on other decorators that make then automatically work for both sync and async functions (coroutine functions)
View example decorator above being used interactivelly
In [97]: @log_run
...: def ble(x):
...: time.sleep(0.5)
...: print(x)
...:
...:
In [98]: @log_run
...: async def bli(x):
...: await asyncio.sleep(1)