-
Notifications
You must be signed in to change notification settings - Fork 1
/
shorthand.py
38 lines (32 loc) · 1.16 KB
/
shorthand.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
from contextlib import contextmanager
try:
from types import SimpleNamespace
except ImportError:
class SimpleNamespace(object):
"""Generic object with attributes provided as keyword arguments"""
def __init__(self, **kw):
self.__dict__.update(kw)
def __repr__(self):
return "{0}({1})".format(type(self).__name__,
", ".join("{0}={1!r}".format(name, value)
for (name, value) in self.__dict__.items()))
def strip(s, start="", end=""):
if start and not s.startswith(start):
raise ValueError("Expected {0!r} starting string".format(start))
if end and not s.endswith(end):
raise ValueError("Expected {0!r} ending string".format(end))
if len(s) < len(start) + len(end):
raise ValueError(
"String not enclosed by {0!r} and {1!r}".format(start, end))
return s[len(start):len(s) - len(end)]
def bitmask(size):
return ~(~0 << size)
def floordiv(a, b):
return int(a // b)
def ceildiv(a, b):
return -floordiv(-a, b)
def read_exactly(stream, n):
result = stream.read(n)
if len(result) != n:
raise EOFError()
return result