Skip to content

Instantly share code, notes, and snippets.

View Tadaboody's full-sized avatar
🐣
Breaking open

Tomer Tadaboody

🐣
Breaking open
View GitHub Profile
@Tadaboody
Tadaboody / input_char.py
Last active April 1, 2020 15:31
Input in a right to left language while correctly displaying the input
try:
import msvcrt
def input_char(): # Windows
"""Read a single character from user input"""
return msvcrt.getwch()
except ImportError:
import sys, tty, termios
def input_char():
"""Read a single character from user input"""
fd = sys.stdin.fileno()
@Tadaboody
Tadaboody / rasies.py
Created March 31, 2020 11:58
Check if a function raises an expected exception with given arguments
ExceptionMatch = typing.Union[
typing.Type[Exception], typing.Tuple[typing.Type[Exception], ...]
]
def raises(
expected_exception: ExceptionMatch,
function: typing.Callable,
*args,
**kwargs,
) -> bool:
@Tadaboody
Tadaboody / griddler.py
Created December 16, 2019 20:32
Calculate the hint for a line from a griddler image
import typing
def griddler_line_hint(line: typing.Sequence[int]) -> typing.Iterator[int]:
"""
Creates the hint for griddlers for the given line
>>> list(griddler_line_hint([1, 1, 1]))
[3]
>>> list(griddler_line_hint([1, 1, 0, 1, 1]))
[2, 2]
@Tadaboody
Tadaboody / find_in_sequence.py
Created April 21, 2019 11:01
Returns the element that satisfies the predicate, if exists
from typing import TypeVar, Sequence, Optional, Callable
T = TypeVar("T")
def find_in_sequence(
sequence: Sequence[T], predicate: Callable[[T], bool]
) -> Optional[T]:
"""Returns the element that satisfies the predicate, if exists"""
return next((element for element in sequence if predicate(element)), None)
@Tadaboody
Tadaboody / cd.py
Last active March 14, 2019 10:29
Cd as a context manager
import os
from contextlib import contextmanager
from typing import Union, ContextManager
PathType = Union[os.PathLike, str]
@contextmanager
def cd(path: PathType) -> ContextManager[None]:
old_path = Path.cwd()
@Tadaboody
Tadaboody / keyed_filter.py
Created January 17, 2019 14:47
Yields the iterable without key duplicates.
from typing import TypeVar, Hashable, Callable, Set, Iterable, Iterator
T = TypeVar("T")
K = TypeVar("K", bound=Hashable)
def keyed_filter(iterable: Iterable[T], key: Callable[[T], K]) -> Iterator[T]:
"""Yields the iterable without key duplicates.
>>> list(keyed_filter(["Alice","Adam","Bob","Ben"],key=lambda x:x[0]) )
@Tadaboody
Tadaboody / try_yield.py
Last active November 13, 2018 16:29
"""Returns an generator of all the items in `generator` that didn't throw"""
from typing import Iterator, TypeVar, Generator
T = TypeVar('T')
def try_yield(generator: Iterator[T])->Generator[T, None, None]:
"""Returns an generator of all the items in `generator` that didn't throw"""
while True:
try:
yield next(generator)
except StopIteration:
@Tadaboody
Tadaboody / cd.py
Created October 29, 2018 12:59
Context manager to cd into a dir for a while
import os
from contextlib import contextmanager
@contextmanager
def cd(path: os.PathLike):
"""Context manager that sets the cwd to be `path`"""
old_path = os.getcwd()
os.chdir(path)
yield
@Tadaboody
Tadaboody / dfs.py
Last active January 9, 2019 14:29
Generic and pythonic implementation of the Depth First Search traversal algorithm
"""Generic and pythonic implementation of the Depth First Search traversal algorithm"""
from typing import Callable, List, Iterable,TypeVar,Hashable, MutableSequence
from pathlib import Path
from collections import deque
T = TypeVar('T', bound=Hashable)
S = TypeVar('S')
def iter_top(stack: MutableSequence[S]) -> Iterator[S]:
"""Iterate a stack as long as it is full, yielding the top every time"""
@Tadaboody
Tadaboody / JsonWebview.kt
Created October 9, 2018 11:09
Wrapper for a webview that handles JSONs, invoking a callback when encountering them
class JsonWebView(private val webView: WebView) {
private val BASEURL: String = BackendRemote.SERVER_ADDRESS
val TAG = JsonWebView::class.java.name
@SuppressLint("SetJavaScriptEnabled")
fun loadURL(url:URL,cb: (JSONObject) -> Unit) {
webView.settings.apply {
javaScriptEnabled = true
domStorageEnabled = true
webView.loadUrl(url.toString())