index
int64
0
731k
package
stringlengths
2
98
name
stringlengths
1
76
docstring
stringlengths
0
281k
code
stringlengths
4
1.07M
signature
stringlengths
2
42.8k
6,797
bottle
abort
Aborts execution and causes a HTTP error.
def abort(code=500, text='Unknown Error.'): """ Aborts execution and causes a HTTP error. """ raise HTTPError(code, text)
(code=500, text='Unknown Error.')
6,798
bottle
auth_basic
Callback decorator to require HTTP auth (basic). TODO: Add route(check_auth=...) parameter.
def auth_basic(check, realm="private", text="Access denied"): ''' Callback decorator to require HTTP auth (basic). TODO: Add route(check_auth=...) parameter. ''' def decorator(func): @functools.wraps(func) def wrapper(*a, **ka): user, password = request.auth or (None, None) ...
(check, realm='private', text='Access denied')
6,801
bottle
cached_property
A property that is only computed once per instance and then replaces itself with an ordinary attribute. Deleting the attribute resets the property.
class cached_property(object): ''' A property that is only computed once per instance and then replaces itself with an ordinary attribute. Deleting the attribute resets the property. ''' def __init__(self, func): self.__doc__ = getattr(func, '__doc__') self.func = func def ...
(func)
6,802
bottle
__get__
null
def __get__(self, obj, cls): if obj is None: return self value = obj.__dict__[self.func.__name__] = self.func(obj) return value
(self, obj, cls)
6,803
bottle
__init__
null
def __init__(self, func): self.__doc__ = getattr(func, '__doc__') self.func = func
(self, func)
6,804
bottle
<lambda>
null
callable = lambda x: hasattr(x, '__call__')
(x)
6,806
bottle
cookie_decode
Verify and decode an encoded string. Return an object or None.
def cookie_decode(data, key): ''' Verify and decode an encoded string. Return an object or None.''' data = tob(data) if cookie_is_encoded(data): sig, msg = data.split(tob('?'), 1) if _lscmp(sig[1:], base64.b64encode(hmac.new(tob(key), msg, digestmod=hashlib.md5).digest())): retur...
(data, key)
6,807
bottle
cookie_encode
Encode and sign a pickle-able object. Return a (byte) string
def cookie_encode(data, key): ''' Encode and sign a pickle-able object. Return a (byte) string ''' msg = base64.b64encode(pickle.dumps(data, -1)) sig = base64.b64encode(hmac.new(tob(key), msg, digestmod=hashlib.md5).digest()) return tob('!') + sig + tob('?') + msg
(data, key)
6,808
bottle
cookie_is_encoded
Return True if the argument looks like a encoded cookie.
def cookie_is_encoded(data): ''' Return True if the argument looks like a encoded cookie.''' return bool(data.startswith(tob('!')) and tob('?') in data)
(data)
6,809
datetime
date
date(year, month, day) --> date object
class date: """Concrete date type. Constructors: __new__() fromtimestamp() today() fromordinal() Operators: __repr__, __str__ __eq__, __le__, __lt__, __ge__, __gt__, __hash__ __add__, __radd__, __sub__ (add/radd only with timedelta arg) Methods: timetuple() toor...
null
6,812
bottle
delete
Equals :meth:`route` with a ``DELETE`` method parameter.
def make_default_app_wrapper(name): ''' Return a callable that relays calls to the current default app. ''' @functools.wraps(getattr(Bottle, name)) def wrapper(*a, **ka): return getattr(app(), name)(*a, **ka) return wrapper
(self, path=None, method='DELETE', **options)
6,813
bottle
depr
null
def depr(message, hard=False): warnings.warn(message, DeprecationWarning, stacklevel=3)
(message, hard=False)
6,815
bottle
error
Decorator: Register an output handler for a HTTP error code
def make_default_app_wrapper(name): ''' Return a callable that relays calls to the current default app. ''' @functools.wraps(getattr(Bottle, name)) def wrapper(*a, **ka): return getattr(app(), name)(*a, **ka) return wrapper
(self, code=500)
6,817
traceback
format_exc
Like print_exc() but return a string.
def format_exc(limit=None, chain=True): """Like print_exc() but return a string.""" return "".join(format_exception(*sys.exc_info(), limit=limit, chain=chain))
(limit=None, chain=True)
6,819
bottle
get
Equals :meth:`route`.
def make_default_app_wrapper(name): ''' Return a callable that relays calls to the current default app. ''' @functools.wraps(getattr(Bottle, name)) def wrapper(*a, **ka): return getattr(app(), name)(*a, **ka) return wrapper
(self, path=None, method='GET', **options)
6,820
bottle
getargspec
null
def getargspec(func): spec = getfullargspec(func) kwargs = makelist(spec[0]) + makelist(spec.kwonlyargs) return kwargs, spec[1], spec[2], spec[3]
(func)
6,821
inspect
getfullargspec
Get the names and default values of a callable object's parameters. A tuple of seven things is returned: (args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, annotations). 'args' is a list of the parameter names. 'varargs' and 'varkw' are the names of the * and ** parameters or None. 'defau...
def getfullargspec(func): """Get the names and default values of a callable object's parameters. A tuple of seven things is returned: (args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, annotations). 'args' is a list of the parameter names. 'varargs' and 'varkw' are the names of the * and ...
(func)
6,824
bottle
hook
Return a decorator that attaches a callback to a hook. See :meth:`add_hook` for details.
def make_default_app_wrapper(name): ''' Return a callable that relays calls to the current default app. ''' @functools.wraps(getattr(Bottle, name)) def wrapper(*a, **ka): return getattr(app(), name)(*a, **ka) return wrapper
(self, name)
6,825
bottle
html_escape
Escape HTML special characters ``&<>`` and quotes ``'"``.
def html_escape(string): ''' Escape HTML special characters ``&<>`` and quotes ``'"``. ''' return string.replace('&','&amp;').replace('<','&lt;').replace('>','&gt;')\ .replace('"','&quot;').replace("'",'&#039;')
(string)
6,826
bottle
html_quote
Escape and quote a string to be used as an HTTP attribute.
def html_quote(string): ''' Escape and quote a string to be used as an HTTP attribute.''' return '"%s"' % html_escape(string).replace('\n','&#10;')\ .replace('\r','&#13;').replace('\t','&#9;')
(string)
6,827
bottle
http_date
null
def http_date(value): if isinstance(value, (datedate, datetime)): value = value.utctimetuple() elif isinstance(value, (int, float)): value = time.gmtime(value) if not isinstance(value, basestring): value = time.strftime("%a, %d %b %Y %H:%M:%S GMT", value) return value
(value)
6,829
builtins
map
map(func, *iterables) --> map object Make an iterator that computes the function using arguments from each of the iterables. Stops when the shortest iterable is exhausted.
from builtins import map
null
6,830
bottle
install
Add a plugin to the list of plugins and prepare it for being applied to all routes of this application. A plugin may be a simple decorator or an object that implements the :class:`Plugin` API.
def make_default_app_wrapper(name): ''' Return a callable that relays calls to the current default app. ''' @functools.wraps(getattr(Bottle, name)) def wrapper(*a, **ka): return getattr(app(), name)(*a, **ka) return wrapper
(self, plugin)
6,832
json
dumps
Serialize ``obj`` to a JSON formatted ``str``. If ``skipkeys`` is true then ``dict`` keys that are not basic types (``str``, ``int``, ``float``, ``bool``, ``None``) will be skipped instead of raising a ``TypeError``. If ``ensure_ascii`` is false, then the return value can contain non-ASCII charact...
def dumps(obj, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw): """Serialize ``obj`` to a JSON formatted ``str``. If ``skipkeys`` is true then ``dict`` keys that are not basic types (``st...
(obj, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw)
6,834
bottle
<lambda>
null
json_loads = lambda s: json_lds(touni(s))
(s)
6,835
bottle
lazy_attribute
A property that caches itself to the class object.
class lazy_attribute(object): ''' A property that caches itself to the class object. ''' def __init__(self, func): functools.update_wrapper(self, func, updated=[]) self.getter = func def __get__(self, obj, cls): value = self.getter(cls) setattr(cls, self.__name__, value) ...
(func)
6,836
bottle
__get__
null
def __get__(self, obj, cls): value = self.getter(cls) setattr(cls, self.__name__, value) return value
(self, obj, cls)
6,837
bottle
__init__
null
def __init__(self, func): functools.update_wrapper(self, func, updated=[]) self.getter = func
(self, func)
6,838
bottle
load
Import a module or fetch an object from a module. * ``package.module`` returns `module` as a module object. * ``pack.mod:name`` returns the module variable `name` from `pack.mod`. * ``pack.mod:func()`` calls `pack.mod.func()` and returns the result. The last form accepts not only func...
def load(target, **namespace): """ Import a module or fetch an object from a module. * ``package.module`` returns `module` as a module object. * ``pack.mod:name`` returns the module variable `name` from `pack.mod`. * ``pack.mod:func()`` calls `pack.mod.func()` and returns the result. ...
(target, **namespace)
6,839
bottle
load_app
Load a bottle application from a module and make sure that the import does not affect the current default application, but returns a separate application object. See :func:`load` for the target parameter.
def load_app(target): """ Load a bottle application from a module and make sure that the import does not affect the current default application, but returns a separate application object. See :func:`load` for the target parameter. """ global NORUN; NORUN, nr_old = True, NORUN try: tm...
(target)
6,840
bottle
local_property
null
def local_property(name=None): if name: depr('local_property() is deprecated and will be removed.') #0.12 ls = threading.local() def fget(self): try: return ls.var except AttributeError: raise RuntimeError("Request context not initialized.") def fset(self, value): ls.var = va...
(name=None)
6,841
bottle
make_default_app_wrapper
Return a callable that relays calls to the current default app.
def make_default_app_wrapper(name): ''' Return a callable that relays calls to the current default app. ''' @functools.wraps(getattr(Bottle, name)) def wrapper(*a, **ka): return getattr(app(), name)(*a, **ka) return wrapper
(name)
6,842
bottle
makelist
null
def makelist(data): # This is just to handy if isinstance(data, (tuple, list, set, dict)): return list(data) elif data: return [data] else: return []
(data)
6,844
bottle
mount
Mount an application (:class:`Bottle` or plain WSGI) to a specific URL prefix. Example:: root_app.mount('/admin/', admin_app) :param prefix: path prefix or `mount-point`. If it ends in a slash, that slash is mandatory. :param app: an instance of :cl...
def make_default_app_wrapper(name): ''' Return a callable that relays calls to the current default app. ''' @functools.wraps(getattr(Bottle, name)) def wrapper(*a, **ka): return getattr(app(), name)(*a, **ka) return wrapper
(self, prefix, app, **options)
6,845
builtins
module
Create a module object. The name must be a string; the optional doc argument can have any type.
from builtins import module
(name, doc=None)
6,847
bottle
parse_auth
Parse rfc2617 HTTP authentication header string (basic) and return (user,pass) tuple or None
def parse_auth(header): """ Parse rfc2617 HTTP authentication header string (basic) and return (user,pass) tuple or None""" try: method, data = header.split(None, 1) if method.lower() == 'basic': user, pwd = touni(base64.b64decode(tob(data))).split(':',1) return user, pwd...
(header)
6,848
bottle
parse_date
Parse rfc1123, rfc850 and asctime timestamps and return UTC epoch.
def parse_date(ims): """ Parse rfc1123, rfc850 and asctime timestamps and return UTC epoch. """ try: ts = email.utils.parsedate_tz(ims) return time.mktime(ts[:8] + (0,)) - (ts[9] or 0) - time.timezone except (TypeError, ValueError, IndexError, OverflowError): return None
(ims)
6,849
bottle
parse_range_header
Yield (start, end) ranges parsed from a HTTP Range header. Skip unsatisfiable ranges. The end index is non-inclusive.
def parse_range_header(header, maxlen=0): ''' Yield (start, end) ranges parsed from a HTTP Range header. Skip unsatisfiable ranges. The end index is non-inclusive.''' if not header or header[:6] != 'bytes=': return ranges = [r.split('-', 1) for r in header[6:].split(',') if '-' in r] for start, ...
(header, maxlen=0)
6,850
bottle
path_shift
Shift path fragments from PATH_INFO to SCRIPT_NAME and vice versa. :return: The modified paths. :param script_name: The SCRIPT_NAME path. :param script_name: The PATH_INFO path. :param shift: The number of path fragments to shift. May be negative to change the shift direction...
def path_shift(script_name, path_info, shift=1): ''' Shift path fragments from PATH_INFO to SCRIPT_NAME and vice versa. :return: The modified paths. :param script_name: The SCRIPT_NAME path. :param script_name: The PATH_INFO path. :param shift: The number of path fragments to shift....
(script_name, path_info, shift=1)
6,852
bottle
post
Equals :meth:`route` with a ``POST`` method parameter.
def make_default_app_wrapper(name): ''' Return a callable that relays calls to the current default app. ''' @functools.wraps(getattr(Bottle, name)) def wrapper(*a, **ka): return getattr(app(), name)(*a, **ka) return wrapper
(self, path=None, method='POST', **options)
6,853
traceback
print_exc
Shorthand for 'print_exception(*sys.exc_info(), limit, file)'.
def print_exc(limit=None, file=None, chain=True): """Shorthand for 'print_exception(*sys.exc_info(), limit, file)'.""" print_exception(*sys.exc_info(), limit=limit, file=file, chain=chain)
(limit=None, file=None, chain=True)
6,854
bottle
put
Equals :meth:`route` with a ``PUT`` method parameter.
def make_default_app_wrapper(name): ''' Return a callable that relays calls to the current default app. ''' @functools.wraps(getattr(Bottle, name)) def wrapper(*a, **ka): return getattr(app(), name)(*a, **ka) return wrapper
(self, path=None, method='PUT', **options)
6,856
bottle
redirect
Aborts execution and causes a 303 or 302 redirect, depending on the HTTP protocol version.
def redirect(url, code=None): """ Aborts execution and causes a 303 or 302 redirect, depending on the HTTP protocol version. """ if not code: code = 303 if request.get('SERVER_PROTOCOL') == "HTTP/1.1" else 302 res = response.copy(cls=HTTPResponse) res.status = code res.body = "" ...
(url, code=None)
6,857
bottle
route
A decorator to bind a function to a request URL. Example:: @app.route('/hello/:name') def hello(name): return 'Hello %s' % name The ``:name`` part is a wildcard. See :class:`Router` for syntax details. :param path: Request path ...
def make_default_app_wrapper(name): ''' Return a callable that relays calls to the current default app. ''' @functools.wraps(getattr(Bottle, name)) def wrapper(*a, **ka): return getattr(app(), name)(*a, **ka) return wrapper
(self, path=None, method='GET', callback=None, name=None, apply=None, skip=None, **config)
6,858
bottle
run
Start a server instance. This method blocks until the server terminates. :param app: WSGI application or target string supported by :func:`load_app`. (default: :func:`default_app`) :param server: Server adapter to use. See :data:`server_names` keys for valid names or pass...
def run(app=None, server='wsgiref', host='127.0.0.1', port=8080, interval=1, reloader=False, quiet=False, plugins=None, debug=None, **kargs): """ Start a server instance. This method blocks until the server terminates. :param app: WSGI application or target string supported by ...
(app=None, server='wsgiref', host='127.0.0.1', port=8080, interval=1, reloader=False, quiet=False, plugins=None, debug=None, **kargs)
6,859
bottle
static_file
Open a file in a safe way and return :exc:`HTTPResponse` with status code 200, 305, 403 or 404. The ``Content-Type``, ``Content-Encoding``, ``Content-Length`` and ``Last-Modified`` headers are set if possible. Special support for ``If-Modified-Since``, ``Range`` and ``HEAD`` requests. ...
def static_file(filename, root, mimetype='auto', download=False, charset='UTF-8'): """ Open a file in a safe way and return :exc:`HTTPResponse` with status code 200, 305, 403 or 404. The ``Content-Type``, ``Content-Encoding``, ``Content-Length`` and ``Last-Modified`` headers are set if possible. ...
(filename, root, mimetype='auto', download=False, charset='UTF-8')
6,863
bottle
template
Get a rendered template as a string iterator. You can use a name, a filename or a template string as first parameter. Template rendering arguments can be passed as dictionaries or directly (as keyword arguments).
def template(*args, **kwargs): ''' Get a rendered template as a string iterator. You can use a name, a filename or a template string as first parameter. Template rendering arguments can be passed as dictionaries or directly (as keyword arguments). ''' tpl = args[0] if args else None adap...
(*args, **kwargs)
6,868
bottle
tob
null
def tob(s, enc='utf8'): return s.encode(enc) if isinstance(s, unicode) else bytes(s)
(s, enc='utf8')
6,869
bottle
touni
null
def touni(s, enc='utf8', err='strict'): return s.decode(enc, err) if isinstance(s, bytes) else unicode(s)
(s, enc='utf8', err='strict')
6,872
bottle
uninstall
Uninstall plugins. Pass an instance to remove a specific plugin, a type object to remove all plugins that match that type, a string to remove all plugins with a matching ``name`` attribute or ``True`` to remove all plugins. Return the list of removed plugins.
def make_default_app_wrapper(name): ''' Return a callable that relays calls to the current default app. ''' @functools.wraps(getattr(Bottle, name)) def wrapper(*a, **ka): return getattr(app(), name)(*a, **ka) return wrapper
(self, plugin)
6,873
bottle
update_wrapper
null
def update_wrapper(wrapper, wrapped, *a, **ka): try: functools.update_wrapper(wrapper, wrapped, *a, **ka) except AttributeError: pass
(wrapper, wrapped, *a, **ka)
6,874
bottle
get_url
Return a string that matches a named route
def make_default_app_wrapper(name): ''' Return a callable that relays calls to the current default app. ''' @functools.wraps(getattr(Bottle, name)) def wrapper(*a, **ka): return getattr(app(), name)(*a, **ka) return wrapper
(self, routename, **kargs)
6,875
urllib.parse
urlencode
Encode a dict or sequence of two-element tuples into a URL query string. If any values in the query arg are sequences and doseq is true, each sequence element is converted to a separate parameter. If the query arg is a sequence of two-element tuples, the order of the parameters in the output will matc...
def urlencode(query, doseq=False, safe='', encoding=None, errors=None, quote_via=quote_plus): """Encode a dict or sequence of two-element tuples into a URL query string. If any values in the query arg are sequences and doseq is true, each sequence element is converted to a separate parameter....
(query, doseq=False, safe='', encoding=None, errors=None, quote_via=<function quote_plus at 0x7f45e6cf81f0>)
6,876
urllib.parse
urljoin
Join a base URL and a possibly relative URL to form an absolute interpretation of the latter.
def urljoin(base, url, allow_fragments=True): """Join a base URL and a possibly relative URL to form an absolute interpretation of the latter.""" if not base: return url if not url: return base base, url, _coerce_result = _coerce_args(base, url) bscheme, bnetloc, bpath, bparams,...
(base, url, allow_fragments=True)
6,877
urllib.parse
quote
quote('abc def') -> 'abc%20def' Each part of a URL, e.g. the path info, the query, etc., has a different set of reserved characters that must be quoted. The quote function offers a cautious (not minimal) way to quote a string for most of these parts. RFC 3986 Uniform Resource Identifier (URI): Gen...
def quote(string, safe='/', encoding=None, errors=None): """quote('abc def') -> 'abc%20def' Each part of a URL, e.g. the path info, the query, etc., has a different set of reserved characters that must be quoted. The quote function offers a cautious (not minimal) way to quote a string for most of t...
(string, safe='/', encoding=None, errors=None)
6,878
bottle
view
Decorator: renders a template for a handler. The handler can control its behavior like that: - return a dict of template vars to fill out the template - return something other than a dict and the view decorator will not process the template, but return the handler result as is....
def view(tpl_name, **defaults): ''' Decorator: renders a template for a handler. The handler can control its behavior like that: - return a dict of template vars to fill out the template - return something other than a dict and the view decorator will not process the templat...
(tpl_name, **defaults)
6,880
bottle
yieldroutes
Return a generator for routes that match the signature (name, args) of the func parameter. This may yield more than one route if the function takes optional keyword arguments. The output is best described by example:: a() -> '/a' b(x, y) -> '/b/<x>/<y>' c(x, y=5) -> '/c/<...
def yieldroutes(func): """ Return a generator for routes that match the signature (name, args) of the func parameter. This may yield more than one route if the function takes optional keyword arguments. The output is best described by example:: a() -> '/a' b(x, y) -> '/b/<x>/<y>...
(func)
6,881
colorhash.colorhash
ColorHash
Generate a color value and provide it in several format. Args: obj: the value. lightness: a range of values, one of which will be picked for the lightness component of the result. Can also be a single number. saturation: a range of values, one of w...
class ColorHash: """ Generate a color value and provide it in several format. Args: obj: the value. lightness: a range of values, one of which will be picked for the lightness component of the result. Can also be a single number. saturation: a r...
(obj: Any, lightness: Sequence[float] = (0.35, 0.5, 0.65), saturation: Sequence[float] = (0.35, 0.5, 0.65), min_h: Optional[int] = None, max_h: Optional[int] = None)
6,882
colorhash.colorhash
__init__
null
def __init__( self, obj: Any, lightness: Sequence[float] = (0.35, 0.5, 0.65), saturation: Sequence[float] = (0.35, 0.5, 0.65), min_h: Optional[int] = None, max_h: Optional[int] = None, ): self.hsl: Tuple[float, float, float] = color_hash( obj=obj, lightness=lightness, ...
(self, obj: Any, lightness: Sequence[float] = (0.35, 0.5, 0.65), saturation: Sequence[float] = (0.35, 0.5, 0.65), min_h: Optional[int] = None, max_h: Optional[int] = None)
6,884
colorhash
get_version
Fast (dev time) way to get version.
def get_version(_): """ Fast (dev time) way to get version. """ with open("pyproject.toml") as f: for line in f.readlines(): if line.startswith("version = "): ver = line.split("=")[1].strip().strip('"') return ver
(_)
6,885
importlib.metadata
version
Get the version string for the named package. :param distribution_name: The name of the distribution package to query. :return: The version string for the package as defined in the package's "Version" metadata key.
def version(distribution_name): """Get the version string for the named package. :param distribution_name: The name of the distribution package to query. :return: The version string for the package as defined in the package's "Version" metadata key. """ return distribution(distribution_name...
(distribution_name)
6,886
roa_checker.roa
ROA
null
class ROA(CIDRNode): def __init__(self, *args, **kwargs): """Initializes the ROA node""" super(ROA, self).__init__(*args, **kwargs) # Origin max length pairs self.origin_max_lengths: set[tuple[int, int]] = set() # Mypy doesn't understand *args in super class def add_data( ...
(*args, **kwargs)
6,887
roa_checker.roa
__init__
Initializes the ROA node
def __init__(self, *args, **kwargs): """Initializes the ROA node""" super(ROA, self).__init__(*args, **kwargs) # Origin max length pairs self.origin_max_lengths: set[tuple[int, int]] = set()
(self, *args, **kwargs)
6,888
roa_checker.roa
add_data
Adds data to the node
def add_data( # type: ignore self, prefix: IPv4Network | IPv6Network, origin: int, max_length: Optional[int] = None, ): """Adds data to the node""" if max_length is None: max_length = prefix.prefixlen self.prefix = prefix self.origin_max_lengths.add((origin, max_length))
(self, prefix: ipaddress.IPv4Network | ipaddress.IPv6Network, origin: int, max_length: Optional[int] = None)
6,889
roa_checker.roa
get_validity
Gets the ROA validity of a prefix origin pair This gets pretty complicated because we need to calculate both validiate and routed, and there can be multiple ROAs for the same announcement. In other words, we need to calculate the best ROA for a given announcement, and then use ...
def get_validity( self, prefix: IPv4Network | IPv6Network, origin: int ) -> tuple[ROAValidity, ROARouted]: """Gets the ROA validity of a prefix origin pair This gets pretty complicated because we need to calculate both validiate and routed, and there can be multiple ROAs for the same announcement. ...
(self, prefix: ipaddress.IPv4Network | ipaddress.IPv6Network, origin: int) -> tuple[roa_checker.enums.ROAValidity, roa_checker.enums.ROARouted]
6,890
roa_checker.roa_checker
ROAChecker
Gets validity of prefix origin pairs against ROAs
class ROAChecker: """Gets validity of prefix origin pairs against ROAs""" def __init__(self): """Initializes both ROA tries""" self.ipv4_trie = IPv4ROATrie() self.ipv6_trie = IPv6ROATrie() def insert( self, prefix: IPv4Network | IPv6Network, origin: int, max_length: Option...
()
6,891
roa_checker.roa_checker
__init__
Initializes both ROA tries
def __init__(self): """Initializes both ROA tries""" self.ipv4_trie = IPv4ROATrie() self.ipv6_trie = IPv6ROATrie()
(self)
6,892
roa_checker.roa_checker
get_roa
Gets the ROA covering prefix-origin pair
def get_roa(self, prefix: IPv4Network | IPv6Network, *args) -> Optional[ROA]: """Gets the ROA covering prefix-origin pair""" trie = self.ipv4_trie if prefix.version == 4 else self.ipv6_trie assert isinstance(trie, CIDRTrie) roa = trie.get_most_specific_trie_supernet(prefix) assert roa is None or isi...
(self, prefix: ipaddress.IPv4Network | ipaddress.IPv6Network, *args) -> Optional[roa_checker.roa.ROA]
6,893
roa_checker.roa_checker
get_validity
Gets the validity of a prefix origin pair
def get_validity( self, prefix: IPv4Network | IPv6Network, origin: int ) -> tuple[ROAValidity, ROARouted]: """Gets the validity of a prefix origin pair""" trie = self.ipv4_trie if prefix.version == 4 else self.ipv6_trie assert isinstance(trie, ROATrie), "for mypy" return trie.get_validity(prefix, or...
(self, prefix: ipaddress.IPv4Network | ipaddress.IPv6Network, origin: int) -> tuple[roa_checker.enums.ROAValidity, roa_checker.enums.ROARouted]
6,894
roa_checker.roa_checker
insert
Inserts a prefix into the tries
def insert( self, prefix: IPv4Network | IPv6Network, origin: int, max_length: Optional[int] ) -> None: """Inserts a prefix into the tries""" trie = self.ipv4_trie if prefix.version == 4 else self.ipv6_trie # mypy struggling with this return trie.insert(prefix, origin, max_length) # type: ignore
(self, prefix: ipaddress.IPv4Network | ipaddress.IPv6Network, origin: int, max_length: Optional[int]) -> NoneType
6,895
roa_checker.enums
ROARouted
An enumeration.
class ROARouted(Enum): ROUTED = 0 UNKNOWN = 1 # A ROA is Non Routed if it is for an origin of ASN 0 # This means that the prefix for this ROA should never be announced NON_ROUTED = 2
(value, names=None, *, module=None, qualname=None, type=None, start=1)
6,896
roa_checker.enums
ROAValidity
An enumeration.
class ROAValidity(Enum): # NOTE: These values double as "scores" for validity, # so do NOT change the order # (used in the ROA class) VALID = 0 UNKNOWN = 1 # Note that we cannot differentiate between invalid by length # or invalid by origin or invalid by both # That is because for the sa...
(value, names=None, *, module=None, qualname=None, type=None, start=1)
6,906
getschema.impl
fix_type
Convert the fields into the proper object types. e.g. {"number": "1.0"} -> {"number": 1.0} - on_invalid_property: ["raise", "null", "force"] What to do when the value cannot be converted. - raise: Raise exception - null: Impute with null - force: Keep it as is (string)
def fix_type( obj, schema, dict_path=[], on_invalid_property="raise", lower=False, replace_special=False, snake_case=False, date_to_datetime=False, ): """Convert the fields into the proper object types. e.g. {"number": "1.0"} -> {"number": 1.0}...
(obj, schema, dict_path=[], on_invalid_property='raise', lower=False, replace_special=False, snake_case=False, date_to_datetime=False)
6,908
getschema.impl
infer_from_csv_file
null
def infer_from_csv_file(filename, skip=0, lower=False, replace_special=False, snake_case=False): with open(filename) as f: count = 0 while count < skip: count = count + 1 f.readline() reader = csv.DictReader(f) data = [dict(row) for row...
(filename, skip=0, lower=False, replace_special=False, snake_case=False)
6,909
getschema.impl
infer_from_file
null
def infer_from_file(filename, fmt="json", skip=0, lower=False, replace_special=False, snake_case=False): if fmt == "json": schema = infer_from_json_file( filename, skip, lower, replace_special, snake_case) elif fmt == "yaml": schema = infer_from_yaml_file( ...
(filename, fmt='json', skip=0, lower=False, replace_special=False, snake_case=False)
6,910
getschema.impl
infer_from_json_file
null
def infer_from_json_file(filename, skip=0, lower=False, replace_special=False, snake_case=False): with open(filename, "r") as f: content = f.read() data = json.loads(content) if type(data) is list: data = data[skip:] schema = infer_schema(data, lower=lower, repla...
(filename, skip=0, lower=False, replace_special=False, snake_case=False)
6,911
getschema.impl
infer_from_yaml_file
null
def infer_from_yaml_file(filename, skip=0, lower=False, replace_special=False, snake_case=False): with open(filename, "r") as f: content = f.read() data = yaml.load(content, Loader=yaml.FullLoader) if type(data) is list: data = data[skip:] schema = infer_schema(d...
(filename, skip=0, lower=False, replace_special=False, snake_case=False)
6,912
getschema.impl
infer_schema
Infer schema from a given object or a list of objects - record_level: - lower: Convert the key to all lower case - replace_special: Replace letters to _ if not 0-9, A-Z, a-z, _ and -, or " " - snake_case: Replace space to _
def infer_schema(obj, record_level=None, lower=False, replace_special=False, snake_case=False): """Infer schema from a given object or a list of objects - record_level: - lower: Convert the key to all lower case - replace_special: Replace letters to _ if not 0-9, A-Z, a-z, _ and -, or "...
(obj, record_level=None, lower=False, replace_special=False, snake_case=False)
6,916
getschema
main
Entry point
def main(): """ Entry point """ parser = argparse.ArgumentParser(COMMAND) parser.add_argument("data", type=str, help="json record file") parser.add_argument("--indent", "-i", default=2, type=int, help="Number of spaces for indentation") parser.add_argument("--type", "...
()
6,920
dateutil.tz.tz
tzoffset
A simple class for representing a fixed offset from UTC. :param name: The timezone name, to be returned when ``tzname()`` is called. :param offset: The time zone offset in seconds, or (since version 2.6.0, represented as a :py:class:`datetime.timedelta` object).
class tzoffset(datetime.tzinfo): """ A simple class for representing a fixed offset from UTC. :param name: The timezone name, to be returned when ``tzname()`` is called. :param offset: The time zone offset in seconds, or (since version 2.6.0, represented as a :py:class:`datetime...
(name, offset)
6,921
dateutil.tz.tz
__eq__
null
def __eq__(self, other): if not isinstance(other, tzoffset): return NotImplemented return self._offset == other._offset
(self, other)
6,922
dateutil.tz.tz
__init__
null
def __init__(self, name, offset): self._name = name try: # Allow a timedelta offset = offset.total_seconds() except (TypeError, AttributeError): pass self._offset = datetime.timedelta(seconds=_get_supported_offset(offset))
(self, name, offset)
6,923
dateutil.tz.tz
__ne__
null
def __ne__(self, other): return not (self == other)
(self, other)
6,924
dateutil.tz.tz
__repr__
null
def __repr__(self): return "%s(%s, %s)" % (self.__class__.__name__, repr(self._name), int(self._offset.total_seconds()))
(self)
6,925
dateutil.tz.tz
dst
null
def dst(self, dt): return ZERO
(self, dt)
6,926
dateutil.tz.tz
fromutc
null
@six.add_metaclass(_TzOffsetFactory) class tzoffset(datetime.tzinfo): """ A simple class for representing a fixed offset from UTC. :param name: The timezone name, to be returned when ``tzname()`` is called. :param offset: The time zone offset in seconds, or (since version 2.6.0, represe...
(self, dt)
6,927
dateutil.tz.tz
is_ambiguous
Whether or not the "wall time" of a given datetime is ambiguous in this zone. :param dt: A :py:class:`datetime.datetime`, naive or time zone aware. :return: Returns ``True`` if ambiguous, ``False`` otherwise. .. versionadded:: 2.6.0
def is_ambiguous(self, dt): """ Whether or not the "wall time" of a given datetime is ambiguous in this zone. :param dt: A :py:class:`datetime.datetime`, naive or time zone aware. :return: Returns ``True`` if ambiguous, ``False`` otherwise. .. versionadded:: 2.6.0 """ ret...
(self, dt)
6,928
dateutil.tz.tz
tzname
null
@tzname_in_python2 def tzname(self, dt): return self._name
(self, dt)
6,929
dateutil.tz.tz
utcoffset
null
def utcoffset(self, dt): return self._offset
(self, dt)
6,931
abc
ABC
Helper class that provides a standard way to create an ABC using inheritance.
class ABC(metaclass=ABCMeta): """Helper class that provides a standard way to create an ABC using inheritance. """ __slots__ = ()
()
6,932
growthbook
AbstractFeatureCache
null
class AbstractFeatureCache(ABC): @abstractmethod def get(self, key: str) -> Optional[Dict]: pass @abstractmethod def set(self, key: str, value: Dict, ttl: int) -> None: pass def clear(self) -> None: pass
()
6,933
growthbook
clear
null
def clear(self) -> None: pass
(self) -> NoneType
6,934
growthbook
get
null
@abstractmethod def get(self, key: str) -> Optional[Dict]: pass
(self, key: str) -> Optional[Dict]
6,935
growthbook
set
null
@abstractmethod def set(self, key: str, value: Dict, ttl: int) -> None: pass
(self, key: str, value: Dict, ttl: int) -> NoneType
6,936
growthbook
AbstractStickyBucketService
null
class AbstractStickyBucketService(ABC): @abstractmethod def get_assignments(self, attributeName: str, attributeValue: str) -> Optional[Dict]: pass @abstractmethod def save_assignments(self, doc: Dict) -> None: pass def get_key(self, attributeName: str, attributeValue: str) -> str: ...
()
6,937
growthbook
get_all_assignments
null
def get_all_assignments(self, attributes: Dict[str, str]) -> Dict[str, Dict]: docs = {} for attributeName, attributeValue in attributes.items(): doc = self.get_assignments(attributeName, attributeValue) if doc: docs[self.get_key(attributeName, attributeValue)] = doc return docs
(self, attributes: Dict[str, str]) -> Dict[str, Dict]
6,938
growthbook
get_assignments
null
@abstractmethod def get_assignments(self, attributeName: str, attributeValue: str) -> Optional[Dict]: pass
(self, attributeName: str, attributeValue: str) -> Optional[Dict]
6,939
growthbook
get_key
null
def get_key(self, attributeName: str, attributeValue: str) -> str: return f"{attributeName}||{attributeValue}"
(self, attributeName: str, attributeValue: str) -> str
6,940
growthbook
save_assignments
null
@abstractmethod def save_assignments(self, doc: Dict) -> None: pass
(self, doc: Dict) -> NoneType
6,941
growthbook
CacheEntry
null
class CacheEntry(object): def __init__(self, value: Dict, ttl: int) -> None: self.value = value self.ttl = ttl self.expires = time() + ttl def update(self, value: Dict): self.value = value self.expires = time() + self.ttl
(value: Dict, ttl: int) -> None