Skip to content

Instantly share code, notes, and snippets.

View kolypto's full-sized avatar

Mark kolypto

View GitHub Profile
@kolypto
kolypto / GitHub-TOC.js
Last active July 21, 2020 16:51
GitHub: generate TOC table of contents for README.md
// Execute me in Console on the repository page
Array.prototype.map.call(document.querySelectorAll('a[class=anchor]'), el => {
var href = el.href,
title = el.parentElement.textContent.replace(/^\s+|\s+$/g, ''),
level = parseInt(el.parentElement.tagName.substr(1)),
indent = (new Array(level)).join(' ');
return indent + '* <a href="'+href.replace(/^user-content-/, '')+'">'+title+'</a>';
}).join("\n ");
@kolypto
kolypto / threadpool-runner-benchmark.py
Last active January 18, 2021 13:03
Benchmark: test the overhead of running functions in threadpool
import time
import asyncio
import functools
def runs_in_threadpool(function):
""" Decorate a sync function to become an async one run in a threadpool """
@functools.wraps(function)
async def wrapper(*args, **kwargs):
loop = asyncio.get_event_loop()
@kolypto
kolypto / socklock.py
Created March 12, 2021 13:36
A global named lock. An easy way to prevent multiple copies of a process from running concurrently
import sys
import socket
class SocketLock:
""" A global named lock. Better than pidfiles.
This uses a bind() on AF_UNIX sockets as a means to acquire a lock that is non-blocking.
Socket files are not created in the real filesystem, but in an "abstract namespace":
a Linux-only feature of hidden socket files.
@kolypto
kolypto / generators.py
Created July 27, 2021 15:21
Advanced examples for Python generators: next(), send(), throw(), yield
# https://docs.python.org/3/library/typing.html#typing.Generator
# 💥💥💥 Simple generator: yield values one by one
# This function pauses to return a value to the outer scope, then proceeds
DICTIONARY = {
'a': 'apple',
'b': 'banana',
'c': 'cat',
@kolypto
kolypto / gibdd_codes.py
Created September 18, 2021 20:45
ГИБДД коды
# Source: common sense
PERSON_TYPES = {
'Natural': 'Физическое лицо',
'Legal': 'Юридическое лицо',
}
# Source: https://documenter.getpostman.com/view/3912450/TWDdkZcK
OPERATION_TYPES = {
@kolypto
kolypto / gist:8e43e7453614b378e258f09c4aba4a35
Created November 12, 2021 11:26
Цитатник 1227
ШКОЛЬНЫЙ ЦИТАТНИК
(из личной коллекции)
Вартанян Марк, 17 сентября 2002 год
Математика.
Ирина Александровна:
- Это материал какого класса? Шестого! Вы поняли меня?
- Маша [Лысанчук], эти кнопки похожи на точки. Возьми, и прикнопь их в уравнение.
- Что вы делаете карандашом?! Ручки на место положите!
@kolypto
kolypto / gist:3cc9035b339bca9528e861e108bf6205
Last active December 22, 2021 21:50
Доклад Святейшего Патриарха Кирилла, 22 декабря 2021
Доклад Святейшего Патриарха Кирилла, 22 декабря 2021
https://www.youtube.com/watch?v=IVrzLXCKkLE
00:36 Профилактические меры могут быть неприятны, как например, длительное ношение масок. Призыва всех потерпеть — в первую очередь, ради сохранения возможности участия в божественной евхаристии
02:55 Благодарность тому духовеству, которое самоотверженно трудится в красной зоне, не опасаясь ни инфекции, ни последствий.
03:50 Кто-то считает вакцинацию нужной, кто-то неприемлемой
@kolypto
kolypto / manual.md
Created January 9, 2022 13:37
Raspberry Pi + 4G Huawei E8382 + Wireguard

Raspberry Pi + 4G Huawei E8382 + Wireguard

Install RaspberryOS

  1. Install Raspberry Pi Imager

    $ sudo snap install rpi-imager
@kolypto
kolypto / README.md
Created September 26, 2023 14:37
Starline API: работа с сигнализацией Starline из Go

Starline API

Чтобы получить доступ, нужно войти под своей учетной записью на my.starline.ru и перейти на страницу https://my.starline.ru/developer. После заполнения формы, заявку на предоставление доступа к API для аккаунта рассмотрят сотрудники StarLine.

Получение кода приложения для дальнейшего получения токена. Срок годности кода приложения – 1 час.

$ http GET https://id.starline.ru/apiV3/application/getCode appId==123456 secret==(echo -n "<secret>" | md5sum | cut -d' ' -f1)
@kolypto
kolypto / pre-commit
Created November 10, 2023 12:45
Git pre-commit hook: ban "nocommit" lines, do not allow to commit
#!/bin/bash
# .git/hooks/pre-commit
# Find "//nocommit" lines in the diff, do not allow them
# This line will output all "nocommit" lines, if any: you'll see this as git error.
git diff --no-ext-diff --cached | grep -iE '//\s*nocommit'
# If the retcode=0, then "nocommit" lines were found. Fail on them.
if [[ $? -eq 0 ]]; then