Skip to content

Instantly share code, notes, and snippets.

@vxgmichel
vxgmichel / compat.py
Created July 26, 2018 21:14
Asyncio/Curio/Trio compatibility module
import asyncio
try:
import curio
except ImportError:
curio = None
try:
import trio
except ImportError:
@vxgmichel
vxgmichel / parallelism.py
Created July 17, 2018 12:07
Test parallelism in python
"""Test parallelism in python.
$ \time -f "%e s - %P" python3 par.py 1 > /dev/null
6.74 s - 100%
$ \time -f "%e s - %P" python3 par.py 4 > /dev/null
1.87 s - 385%
$ bc -l <<< "6.74/1.87"
3.60...
"""
@vxgmichel
vxgmichel / long_sleep.py
Last active October 19, 2020 15:38
Asyncio long sleep (over 1 day)
import asyncio
async def long_sleep(arg):
hours = 60*60
async def bg():
while True:
await asyncio.sleep(12 * hours)
@vxgmichel
vxgmichel / pancake.hs
Created July 10, 2018 16:03
Solve the 'Infinite House of Pancakes' problem
-- Solve the 'Infinite House of Pancakes' problem.
-- https://code.google.com/codejam/contest/6224486/dashboard#s=p1
import Text.Printf
-- Generic solver code
main :: IO ()
main = interact
$ unlines . cases . map (format . solve) . parse . tail . lines
@vxgmichel
vxgmichel / benchmark.py
Created June 27, 2018 10:01
A benchmark comparing sympy and a pure python implementation of the Bareiss algorithm
import sys
import time
import hashlib
from fractions import Fraction
from contextlib import contextmanager
from sympy import Matrix
# https://gist.github.com/vxgmichel/080e9999a1020711f27cd60b5c2d14de
from bareiss import adjugate
@vxgmichel
vxgmichel / bareiss.py
Last active March 2, 2021 14:47
Pure python implementation of the Bareiss algorithm
def adjugate(a, m=None):
# Initialize
sign = 1
previous = pivot = 1
# Bareiss formula
def do_pivot(a, b, c, d, e):
x = a * d - b * c
if m is None:
q, r = divmod(x, e)
@vxgmichel
vxgmichel / MIT-license.md
Last active April 19, 2018 08:41
This license applies to all public gists https://gist.github.com/vxgmichel
@vxgmichel
vxgmichel / binary_search.py
Last active April 18, 2018 13:24
A binary search based on bisect module
import bisect
import itertools
def binary_search(f, lower=None, upper=None, precision=1):
# Switch lower and upper
if lower is None and upper is not None:
return precision - binary_search(
lambda x: not f(-x), -upper, None, precision)
@vxgmichel
vxgmichel / qgeventdispatcher.py
Created February 13, 2018 11:38
Qt-gevent dispatcher
import sys
import gevent.event
from collections import defaultdict, deque
from PyQt5.QtWidgets import QApplication, QPushButton
from PyQt5.QtCore import QAbstractEventDispatcher, QTimer, QTimerEvent
class QGeventDispatcher(QAbstractEventDispatcher):
@vxgmichel
vxgmichel / isolate.py
Created October 25, 2017 15:49
Isolate an asynchronous generator by running it in a background task
import asyncio
from itertools import count
from collections import AsyncIterable
async def clock(start=0, step=1, interval=1.):
for i in count(start, step):
yield i
await asyncio.sleep(interval)