code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
r
time_df['weekday'] = time_df.index.weekday + 1
time_df['date'] = time_df.index.date
# Set weekday to Holiday (0) for all holidays
if holidays is not None:
if isinstance(holidays, dict):
holidays = list(holidays.keys())
time_df['weekday'].mask(pd.to_datetime(time_df['da... | def add_weekdays2df(time_df, holidays=None, holiday_is_sunday=False) | r"""Giving back a DataFrame containing weekdays and optionally holidays for
the given year.
Parameters
----------
time_df : pandas DataFrame
DataFrame to which the weekdays should be added
Optional Parameters
-------------------
holidays : array with information for every hour of ... | 2.568616 | 2.909089 | 0.882962 |
# Day(am to pm), night (pm to am), week day (week),
# weekend day (weekend)
am = kwargs.get('am', settime(7, 00, 0))
pm = kwargs.get('pm', settime(23, 30, 0))
week = kwargs.get('week', [1, 2, 3, 4, 5])
weekend = kwargs.get('weekend', [0, 6, 7])
default... | def simple_profile(self, annual_demand, **kwargs) | Create industrial load profile
Parameters
----------
annual_demand : float
Total demand.
Other Parameters
----------------
am : datetime.time
beginning of workday
pm : datetime.time
end of workday
week : list
... | 2.757271 | 2.423438 | 1.137752 |
# The script object is cached, since constructing it may involve
# a number of string-manipulation operations.
if getattr(self, '_script', None) is None:
self._script = self._script__getter()
return self._script | def script(self) | Returns a Script object representing a contract script portion of a
payment to the destination. | 8.628548 | 8.837322 | 0.976376 |
if not n: return 0
e = 0
while (n % 10) == 0 and e < 9:
n = n // 10
e = e + 1
if e < 9:
n, d = divmod(n, 10);
return 1 + (n*9 + d - 1)*10 + e
else:
return 1 + (n - 1)*10 + 9 | def compress_amount(n) | \
Compress 64-bit integer values, preferring a smaller size for whole
numbers (base-10), so as to achieve run-length encoding gains on real-
world data. The basic algorithm:
* If the amount is 0, return 0
* Divide the amount (in base units) evenly by the largest power of 10
possibl... | 2.963858 | 2.410746 | 1.229436 |
if not x: return 0;
x = x - 1;
# x = 10*(9*n + d - 1) + e
x, e = divmod(x, 10);
n = 0;
if e < 9:
# x = 9*n + d - 1
x, d = divmod(x, 9)
d = d + 1
# x = n
n = x*10 + d
else:
n = x + 1
return n * 10**e | def decompress_amount(x) | \
Undo the value compression performed by x=compress_amount(n). The input
x matches one of the following patterns:
x = n = 0
x = 1+10*(9*n + d - 1) + e
x = 1+10*(n - 1) + 9 | 3.789509 | 2.980025 | 1.271637 |
bn = _BigInteger(target).serialize()
size = len(bn)
if size <= 3:
word = target << 8 * (3 - size)
else:
word = target >> 8 * (size - 3)
if word & 0x00800000:
word >>= 8
size += 1
word |= size << 24
if target < 0:
word |= 0x00800000
return word | def compact_from_target(target) | \
The “compact” format is a representation of a whole number N using an
unsigned 32bit number similar to a floating point format. Conversion
necessarily involves truncation if the target is greater than 2^23-1.
The most significant 8 bits are the unsigned exponent of base 256.
This exponent can be ... | 3.173566 | 3.472606 | 0.913886 |
size = bits >> 24
word = bits & 0x007fffff
if size < 3:
word >>= 8 * (3 - size)
else:
word <<= 8 * (size - 3)
if bits & 0x00800000:
word = -word
return word | def target_from_compact(bits) | \
Extract a full target from its compact representation, undoing the
transformation x=compact_from_target(t). See compact_from_target() for
more information on this 32-bit floating point format. | 2.738395 | 2.843055 | 0.963188 |
"Like cmp(), but for any iterator."
for xa in a:
try:
xb = next(b)
d = cmp(xa, xb)
if d: return d
except StopIteration:
return 1
try:
next(b)
return -1
except StopIteration:
return 0 | def icmp(a, b) | Like cmp(), but for any iterator. | 4.433366 | 2.890474 | 1.533785 |
"Return a clone of this hash object."
other = _ChainedHashAlgorithm(self._algorithms)
other._hobj = deepcopy(self._hobj)
other._fobj = deepcopy(self._fobj)
return other | def copy(self) | Return a clone of this hash object. | 9.741955 | 7.95726 | 1.224285 |
"Computes _fobj, the completed hash."
hobj = self._hobj
for hashname in self._algorithms[1:]:
fobj = hashlib.new(hashname)
fobj.update(hobj.digest())
hobj = fobj
self._fobj = hobj | def _finalize(self) | Computes _fobj, the completed hash. | 7.415941 | 4.094755 | 1.811083 |
"Appends any passed in byte arrays to the digest object."
for string in args:
self._hobj.update(string)
self._fobj = None | def update(self, *args) | Appends any passed in byte arrays to the digest object. | 21.052042 | 7.217041 | 2.916991 |
"Returns the size (in bytes) of the resulting digest."
if getattr(self, '_fobj', None) is not None:
return self._fobj.digest_size
else:
return hashlib.new(self._algorithms[-1]).digest_size | def digest_size(self) | Returns the size (in bytes) of the resulting digest. | 4.252522 | 4.045326 | 1.051218 |
if len(self):
hobj = _ChainedHashAlgorithm(self, *args, **kwargs)
else:
hobj = _NopHashAlgorithm(*args, **kwargs)
if string is not None:
hobj.update(string)
return hobj | def new(self, string=None, *args, **kwargs) | Returns a `_ChainedHashAlgorithm` if the underlying tuple
(specifying the list of algorithms) is not empty, otherwise a
`_NopHashAlgorithm` instance is returned. | 4.567355 | 2.299293 | 1.986417 |
"The number of items, pruned or otherwise, contained by this branch."
if getattr(self, '_count', None) is None:
self._count = getattr(self.node, 'count', 0)
return self._count | def count(self) | The number of items, pruned or otherwise, contained by this branch. | 5.988257 | 2.779814 | 2.154193 |
"The canonical serialized size of this branch."
if getattr(self, '_size', None) is None:
self._size = getattr(self.node, 'size', 0)
return self._size | def size(self) | The canonical serialized size of this branch. | 5.931031 | 3.350096 | 1.770406 |
"Returns a forward iterator over the trie"
path = [(self, 0, Bits())]
while path:
node, idx, prefix = path.pop()
if idx==0 and node.value is not None and not node.prune_value:
yield (self._unpickle_key(prefix), self._unpickle_value(node.value))
... | def _forward_iterator(self) | Returns a forward iterator over the trie | 3.944232 | 3.763999 | 1.047883 |
prefix, subkey, node = Bits(), key, self
while prefix != key:
for idx,link in enumerate(node.children):
if subkey.startswith(link.prefix):
if link.pruned:
return (prefix, node)
subkey = subkey[len(link.p... | def _get_node_by_key(self, key, path=None) | Returns the 2-tuple (prefix, node) where node either contains the value
corresponding to the key, or is the most specific prefix on the path which
would contain the key if it were there. The key was found if prefix==key
and the node.value is not None. | 4.125361 | 3.747731 | 1.100762 |
"x.get(k[,d]) -> x[k] if k in x, else d. d defaults to None."
_key = self._prepare_key(key)
prefix, node = self._get_node_by_key(_key)
if prefix==_key and node.value is not None:
return self._unpickle_value(node.value)
else:
return value | def get(self, key, value=None) | x.get(k[,d]) -> x[k] if k in x, else d. d defaults to None. | 3.986301 | 3.286456 | 1.212948 |
if other is None:
other = ()
if hasattr(other, 'keys'):
for key in other:
self._update(key, other[key])
else:
for key,value in other:
self._update(key, value)
for key,value in six.iteritems(kwargs):
... | def update(self, other=None, **kwargs) | x.update(E, **F) -> None. update x from trie/dict/iterable E or F.
If E has a .keys() method, does: for k in E: x[k] = E[k]
If E lacks .keys() method, does: for (k, v) in E: x[k] = v
In either case, this is followed by: for k in F: x[k] = F[k] | 2.498051 | 2.385939 | 1.046989 |
"Prunes any keys beginning with the specified the specified prefixes."
_prefixes, prefixes = set(map(lambda k:self._prepare_key(k), prefixes)), list()
for t in lookahead(sorted(_prefixes)):
if t[1] is not None:
if t[0] == commonprefix(t):
continue
... | def trim(self, prefixes) | Prunes any keys beginning with the specified the specified prefixes. | 7.607866 | 5.863083 | 1.297588 |
"Write a compressed representation of script to the Pickler's file object."
if file is None:
file = self._file
self._dump(script, file, self._protocol, self._version) | def dump(self, script, file=None) | Write a compressed representation of script to the Pickler's file object. | 8.049105 | 3.608171 | 2.230799 |
"Return a compressed representation of script as a binary string."
string = BytesIO()
self._dump(script, string, self._protocol, self._version)
return string.getvalue() | def dumps(self, script) | Return a compressed representation of script as a binary string. | 7.851707 | 5.567878 | 1.410179 |
"Read and decompress a compact script from the Pickler's file object."
if file is None:
file = self._file
script_class = self.get_script_class()
script = self._load(file, self._protocol, self._version)
return script_class(script) | def load(self, file=None) | Read and decompress a compact script from the Pickler's file object. | 7.925038 | 3.511551 | 2.256848 |
"Decompress the passed-in compact script and return the result."
script_class = self.get_script_class()
script = self._load(BytesIO(string), self._protocol, self._version)
return script_class(script) | def loads(self, string) | Decompress the passed-in compact script and return the result. | 9.756131 | 5.297771 | 1.841554 |
# Return zero-hash is no arguments are provided (the hash of an empty
# Merkle tree is defined to be zero).
if not args:
return 0
# This helper function extracts and returns the hash value of a parameter.
# Note that if the parameter is itself a Merkle tree or iterable, this
# resul... | def _merkle_hash256(*args) | The default transform provided to merkle(), which calculates the hash
of its parameters, serializes and joins them together, then performs a
has256 of the resulting string. There are two special cases: no arguments,
which results in 0, and a single argument, whose hash value is returned
unmodified. | 5.941043 | 5.400482 | 1.100095 |
# We use append to duplicate the final item in the iterable of hashes, so
# we need hashes to be a list-like object, regardless of what we were
# passed.
hashes = list(iter(hashes))
# If the passed-in iterable is empty, allow the constructor to choose our
# return value:
if not hashes:
... | def merkle(hashes, func=_merkle_hash256) | Convert an iterable of hashes or hashable objects into a binary tree,
construct the interior values using a passed-in constructor or compression
function, and return the root value of the tree. The default compressor is
the hash256 function, resulting in root-hash for the entire tree. | 9.007926 | 8.582733 | 1.04954 |
"x.iteritems() -> an iterator over the (key, value) items of x in sorted order"
left_is_hash = isinstance(self.left, numbers.Integral)
right_is_hash = isinstance(self.right, numbers.Integral)
if all([left_is_hash, right_is_hash]) or self.right is None:
if all((self.size>=1, s... | def iteritems(self) | x.iteritems() -> an iterator over the (key, value) items of x in sorted order | 3.244873 | 3.005944 | 1.079485 |
left_size = 2 ** ((self.size-1).bit_length() - 1)
if index < 0 or self.size <= index:
return (None, self, index)
if index < left_size:
if self.prune is self.LEFT_NODE:
return (None, self, index)
if isinstance(self.left, numbers.Integra... | def _get_by_index(self, index, path=None) | Returns the 2-tuple (node, idx) where node is either a terminal leaf
node containing the value of that index in either it's left or right slot,
or is the most specific node on the path which would contain the index if
it were not pruned. | 2.294231 | 2.129097 | 1.077561 |
"Encode bytes to a base58-encoded string."
len_ = len(b)
# Convert big-endian bytes to integer
n = BigInteger.deserialize(BytesIO(b), len_)
# Divide that integer into base58
res = []
while n > 0:
n, r = divmod (n, 58)
res.append(b58digits[r])
res = ''.join(res[::-1])
... | def b58encode(b, errors='strict') | Encode bytes to a base58-encoded string. | 3.202893 | 3.133028 | 1.0223 |
"Decode a base58-encoding string, returning bytes."
if not s:
return (b'', 0)
# Convert the string to an integer
n = 0
for c in s:
n *= 58
if c not in b58digits:
raise InvalidBase58Error(u"character %r is not a valid base58 "
u"character" % c)
... | def b58decode(s, errors='strict') | Decode a base58-encoding string, returning bytes. | 2.804597 | 2.596736 | 1.080047 |
my_torrent = Torrent.from_file(torrent_path)
size = my_torrent.total_size
click.secho('Name: %s' % my_torrent.name, fg='blue')
click.secho('Files:')
for file_tuple in my_torrent.files:
click.secho(file_tuple.name)
click.secho('Hash: %s' % my_torrent.info_hash, fg='blue')
cli... | def info(torrent_path) | Print out information from .torrent file. | 2.339151 | 2.359846 | 0.99123 |
source_title = path.basename(source).replace('.', '_').replace(' ', '_')
dest = '%s.torrent' % path.join(dest, source_title)
click.secho('Creating torrent from %s ...' % source)
my_torrent = Torrent.create_from(source)
if comment:
my_torrent.comment = comment
urls = []
if ... | def create(source, dest, tracker, open_trackers, comment, cache) | Create torrent file from a single file or a directory. | 3.141083 | 3.05849 | 1.027005 |
files = []
info = self._struct.get('info')
if not info:
return files
if 'files' in info:
base = info['name']
for f in info['files']:
files.append(TorrentFile(join(base, *f['path']), f['length']))
else:
f... | def files(self) | Files in torrent.
List of namedtuples (filepath, size).
:rtype: list[TorrentFile] | 4.19521 | 3.687915 | 1.137556 |
info = self._struct.get('info')
if not info:
return None
return sha1(Bencode.encode(info)).hexdigest() | def info_hash(self) | Hash of torrent file info section. Also known as torrent hash. | 7.40059 | 6.373945 | 1.161069 |
urls = self._struct.get('announce-list')
if not urls:
urls = self._struct.get('announce')
if not urls:
return []
urls = [[urls]]
return urls | def announce_urls(self) | List of lists of announce (tracker) URLs.
First inner list is considered as primary announcers list,
the following lists as back-ups.
http://bittorrent.org/beps/bep_0012.html | 5.76697 | 4.826462 | 1.194865 |
result = 'magnet:?xt=urn:btih:' + self.info_hash
def add_tr():
urls = self.announce_urls
if not urls:
return
trackers = []
urls = urls[0] # Only primary announcers are enough.
for url in urls:
tracke... | def get_magnet(self, detailed=True) | Returns torrent magnet link, consisting of BTIH (BitTorrent Info Hash) URN
anr optional other information.
:param bool|list|tuple|set detailed:
For boolean - whether additional info (such as trackers) should be included.
For iterable - expected allowed parameter names:
... | 3.485996 | 3.045536 | 1.144625 |
if filepath is None and self._filepath is None:
raise TorrentError('Unable to save torrent to file: no filepath supplied.')
if filepath is not None:
self._filepath = filepath
with open(self._filepath, mode='wb') as f:
f.write(self.to_string()) | def to_file(self, filepath=None) | Writes Torrent object into file, either
:param filepath: | 3.288323 | 3.235674 | 1.016272 |
is_dir = isdir(src_path)
target_files, size_data = cls._get_target_files_info(src_path)
SIZE_MIN = 32768 # 32 KiB
SIZE_DEFAULT = 262144 # 256 KiB
SIZE_MAX = 1048576 # 1 MiB
CHUNKS_MIN = 1000 # todo use those limits as advised
CHUNKS_MAX = 2200
... | def create_from(cls, src_path) | Returns Torrent object created from a file or a directory.
:param str src_path:
:rtype: Torrent | 2.866766 | 2.762331 | 1.037807 |
torrent = cls(Bencode.read_file(filepath))
torrent._filepath = filepath
return torrent | def from_file(cls, filepath) | Alternative constructor to get Torrent object from file.
:param str filepath:
:rtype: Torrent | 9.475768 | 13.422702 | 0.705951 |
if not bytes_size:
return '0 B'
names = ('B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB')
name_idx = int(math.floor(math.log(bytes_size, 1024)))
size = round(bytes_size / math.pow(1024, name_idx), 2)
return '%s %s' % (size, names[name_idx]) | def humanize_filesize(bytes_size) | Returns human readable filesize.
:param int bytes_size:
:rtype: str | 1.757755 | 1.849009 | 0.950647 |
url_base = 'http://torrage.info'
url_upload = '%s/autoupload.php' % url_base
url_download = '%s/torrent.php?h=' % url_base
file_field = 'torrent'
try:
import requests
response = requests.post(url_upload, files={file_field: open(fpath, 'rb')}, timeout=REMOTE_TIMEOUT)
re... | def upload_to_cache_server(fpath) | Uploads .torrent file to a cache server.
Returns upload file URL.
:rtype: str | 5.125887 | 5.063345 | 1.012352 |
url_base = 'https://raw.githubusercontent.com/idlesign/torrentool/master/torrentool/repo'
url = '%s/%s' % (url_base, OPEN_TRACKERS_FILENAME)
try:
import requests
response = requests.get(url, timeout=REMOTE_TIMEOUT)
response.raise_for_status()
open_trackers = response... | def get_open_trackers_from_remote() | Returns open trackers announce URLs list from remote repo. | 4.704155 | 4.29133 | 1.0962 |
with open(path.join(path.dirname(__file__), 'repo', OPEN_TRACKERS_FILENAME)) as f:
open_trackers = map(str.strip, f.readlines())
return list(open_trackers) | def get_open_trackers_from_local() | Returns open trackers announce URLs list from local backup. | 3.805411 | 3.442887 | 1.105297 |
val_encoding = 'utf-8'
def encode_str(v):
try:
v_enc = encode(v, val_encoding)
except UnicodeDecodeError:
if PY3:
raise
else:
# Suppose bytestring
v_enc = v
... | def encode(cls, value) | Encodes a value into bencoded bytes.
:param value: Python object to be encoded (str, int, list, dict).
:param str val_encoding: Encoding used by strings in a given object.
:rtype: bytes | 2.786011 | 2.697805 | 1.032696 |
def create_dict(items):
# Let's guarantee that dictionaries are sorted.
k_v_pair = zip(*[iter(items)] * 2)
return OrderedDict(sorted(k_v_pair, key=itemgetter(0)))
def create_list(items):
return list(items)
stack_items = []
stack_... | def decode(cls, encoded) | Decodes bencoded data introduced as bytes.
Returns decoded structure(s).
:param bytes encoded: | 2.788288 | 2.73885 | 1.018051 |
if PY3 and not isinstance(string, byte_types):
string = string.encode()
return cls.decode(string) | def read_string(cls, string) | Decodes a given bencoded string or bytestring.
Returns decoded structure(s).
:param str string:
:rtype: list | 6.29171 | 8.195823 | 0.767673 |
with open(filepath, mode='rb') as f:
contents = f.read()
return cls.decode(contents) | def read_file(cls, filepath) | Decodes bencoded data of a given file.
Returns decoded structure(s).
:param str filepath:
:rtype: list | 3.308915 | 4.781215 | 0.692066 |
policy = ['%s %s' % (k, v) for k, v in cspDict.items() if v != '']
return '; '.join(policy) | def create_csp_header(cspDict) | create csp header string | 3.051676 | 2.891192 | 1.055508 |
_csp = csp_default().read()
_csp.update(csp)
_header = ''
if 'report-only' in _csp and _csp['report-only'] is True:
_header = 'Content-Security-Policy-Report-Only'
else:
_header = 'Content-Security-Policy'
if 'report-only' in _csp:
del _csp['report-only']
_headers = ... | def csp_header(csp={}) | Decorator to include csp header on app.route wrapper | 2.393865 | 2.312221 | 1.03531 |
with open(self.default_file) as json_file:
try:
return json.load(json_file)
except Exception as e:
raise 'empty file' | def read(self) | read default csp settings from json file | 3.895967 | 3.422451 | 1.138356 |
try:
csp = self.read()
except:
csp = {'default-src':"'self'"}
self.write(csp)
csp.update(updates)
self.write(csp) | def update(self,updates={}) | update csp_default.json with dict
if file empty add default-src and create dict | 4.079385 | 2.791834 | 1.461185 |
image_set_pk = self.kwargs.get("pk", None)
if image_set_pk is None:
return self.request.user.image_sets.create()
return get_object_or_404(self.get_queryset(), pk=image_set_pk) | def get_image_set(self) | Obtain existing ImageSet if `pk` is specified, otherwise
create a new ImageSet for the user. | 2.611085 | 2.042763 | 1.278212 |
__init__(*args, **kwargs)
tracing = app.settings.get('opentracing_tracing')
tracer_callable = app.settings.get('opentracing_tracer_callable')
tracer_parameters = app.settings.get('opentracing_tracer_parameters', {})
if tracer_callable is not None:
if not callable(tracer_callable):
... | def tracer_config(__init__, app, args, kwargs) | Wraps the Tornado web application initialization so that the
TornadoTracing instance is created around an OpenTracing-compatible tracer. | 2.549642 | 2.49847 | 1.020481 |
@wrapt.decorator
def wrapper(wrapped, instance, args, kwargs):
if self._trace_all:
return wrapped(*args, **kwargs)
handler = instance
with tracer_stack_context():
try:
self._apply_tracing(handler, list(at... | def trace(self, *attributes) | Function decorator that traces functions
NOTE: Must be placed before the Tornado decorators
@param attributes any number of request attributes
(strings) to be set as tags on the created span | 3.665049 | 3.66011 | 1.001349 |
operation_name = self._get_operation_name(handler)
headers = handler.request.headers
request = handler.request
# start new span from trace info
try:
span_ctx = self._tracer.extract(opentracing.Format.HTTP_HEADERS,
... | def _apply_tracing(self, handler, attributes) | Helper function to avoid rewriting for middleware and decorator.
Returns a new span from the request with logged attributes and
correct operation name from the func. | 2.439034 | 2.319634 | 1.051474 |
tracing = handler.settings.get('opentracing_tracing')
with tracer_stack_context():
if tracing._trace_all:
attrs = handler.settings.get('opentracing_traced_attributes', [])
tracing._apply_tracing(handler, attrs)
return func(*args, **kwargs) | def execute(func, handler, args, kwargs) | Wrap the handler ``_execute`` method to trace incoming requests,
extracting the context from the headers, if available. | 6.703278 | 6.586038 | 1.017801 |
tracing = handler.settings.get('opentracing_tracing')
tracing._finish_tracing(handler)
return func(*args, **kwargs) | def on_finish(func, handler, args, kwargs) | Wrap the handler ``on_finish`` method to finish the Span for the
given request, if available. | 9.031872 | 9.590321 | 0.94177 |
# safe-guard: expected arguments -> log_exception(self, typ, value, tb)
value = args[1] if len(args) == 3 else None
if value is None:
return func(*args, **kwargs)
tracing = handler.settings.get('opentracing_tracing')
if not isinstance(value, HTTPError) or 500 <= value.status_code <= 59... | def log_exception(func, handler, args, kwargs) | Wrap the handler ``log_exception`` method to finish the Span for the
given request, if available. This method is called when an Exception
is not handled in the user code. | 5.278081 | 4.926744 | 1.071312 |
sn = self
while sn.parent:
sn = sn.parent
return sn | def schema_root(self) -> "SchemaTreeNode" | Return the root node of the receiver's schema. | 4.772093 | 4.601815 | 1.037002 |
return self._ctype if self._ctype else self.parent.content_type() | def content_type(self) -> ContentType | Return receiver's content type. | 11.243013 | 7.545131 | 1.490102 |
parent = self.parent
while parent:
if isinstance(parent, DataNode):
return parent
parent = parent.parent | def data_parent(self) -> Optional["InternalNode"] | Return the closest ancestor data node. | 3.091223 | 2.460372 | 1.256405 |
dp = self.data_parent()
return (self.name if dp and self.ns == dp.ns
else self.ns + ":" + self.name) | def iname(self) -> InstanceName | Return the instance name corresponding to the receiver. | 8.914231 | 8.236156 | 1.082329 |
dp = self.data_parent()
return (dp.data_path() if dp else "") + "/" + self.iname() | def data_path(self) -> DataPath | Return the receiver's data path. | 11.329659 | 8.877457 | 1.276228 |
res = {"kind": self._yang_class()}
if self.mandatory:
res["mandatory"] = True
if self.description:
res["description"] = self.description
return res | def _node_digest(self) -> Dict[str, Any] | Return dictionary of receiver's properties suitable for clients. | 6.222745 | 5.98404 | 1.03989 |
p, s, loc = iname.partition(":")
return (loc, p) if s else (p, self.ns) | def _iname2qname(self, iname: InstanceName) -> QualName | Translate instance name to qualified name in the receiver's context. | 13.100628 | 11.198163 | 1.169891 |
for s in stmt.substatements:
if s.prefix:
key = (
sctx.schema_data.modules[sctx.text_mid].prefix_map[s.prefix][0]
+ ":" + s.keyword)
else:
key = s.keyword
mname = SchemaNode._stmt_callback.get(ke... | def _handle_substatements(self, stmt: Statement, sctx: SchemaContext) -> None | Dispatch actions for substatements of `stmt`. | 7.993303 | 7.168668 | 1.115033 |
if isinstance(xpath, LocationPath):
lft = self._follow_leafref(xpath.left, init)
if lft is None:
return None
return lft._follow_leafref(xpath.right, init)
elif isinstance(xpath, Step):
if xpath.axis == Axis.parent:
... | def _follow_leafref(
self, xpath: "Expr", init: "TerminalNode") -> Optional["DataNode"] | Return the data node referred to by a leafref path.
Args:
xpath: XPath expression compiled from a leafref path.
init: initial context node | 3.443711 | 3.7747 | 0.912314 |
return self._tree_line_prefix() + " " + self.iname() | def _tree_line(self, no_type: bool = False) -> str | Return the receiver's contribution to tree diagram. | 26.241812 | 14.651423 | 1.791076 |
if not hasattr(self, 'default_deny'):
return
if stmt.keyword == "default-deny-all":
self.default_deny = DefaultDeny.all
elif stmt.keyword == "default-deny-write":
self.default_deny = DefaultDeny.write | def _nacm_default_deny_stmt(self, stmt: Statement, sctx: SchemaContext) -> None | Set NACM default access. | 3.844001 | 3.218574 | 1.194318 |
ns = ns if ns else self.ns
todo = []
for child in self.children:
if child.name is None:
todo.append(child)
elif child.name == name and child.ns == ns:
return child
for c in todo:
grandchild = c.get_child(name, n... | def get_child(self, name: YangIdentifier,
ns: YangIdentifier = None) -> Optional[SchemaNode] | Return receiver's schema child.
Args:
name: Child's name.
ns: Child's namespace (= `self.ns` if absent). | 2.604447 | 2.859109 | 0.91093 |
node = self
for p in route:
node = node.get_child(*p)
if node is None:
return None
return node | def get_schema_descendant(
self, route: SchemaRoute) -> Optional[SchemaNode] | Return descendant schema node or ``None`` if not found.
Args:
route: Schema route to the descendant node
(relative to the receiver). | 4.57607 | 6.00716 | 0.761769 |
ns = ns if ns else self.ns
todo = []
for child in self.children:
if child.name == name and child.ns == ns:
if isinstance(child, DataNode):
return child
todo.insert(0, child)
elif not isinstance(child, DataNode):... | def get_data_child(self, name: YangIdentifier,
ns: YangIdentifier = None) -> Optional["DataNode"] | Return data node directly under the receiver. | 2.429151 | 2.312439 | 1.050471 |
if ctype is None:
ctype = self.content_type()
return [c for c in self.children if
not isinstance(c, (RpcActionNode, NotificationNode)) and
c.content_type().value & ctype.value != 0] | def filter_children(self, ctype: ContentType = None) -> List[SchemaNode] | Return receiver's children based on content type.
Args:
ctype: Content type. | 4.778502 | 4.978832 | 0.959764 |
res = []
for child in self.children:
if isinstance(child, DataNode):
res.append(child)
elif not isinstance(child, SchemaTreeNode):
res.extend(child.data_children())
return res | def data_children(self) -> List["DataNode"] | Return the set of all data nodes directly under the receiver. | 2.696875 | 2.445325 | 1.10287 |
if not isinstance(rval, dict):
raise RawTypeError(jptr, "object")
res = ObjectValue()
for qn in rval:
if qn.startswith("@"):
if qn != "@":
tgt = qn[1:]
if tgt not in rval:
raise Missi... | def from_raw(self, rval: RawObject, jptr: JSONPointer = "") -> ObjectValue | Override the superclass method. | 4.671892 | 4.653909 | 1.003864 |
if scope.value & ValidationScope.syntax.value: # schema
self._check_schema_pattern(inst, ctype)
for m in inst:
inst._member(m).validate(scope, ctype)
super()._validate(inst, scope, ctype) | def _validate(self, inst: "InstanceNode", scope: ValidationScope,
ctype: ContentType) -> None | Extend the superclass method. | 8.385111 | 7.515181 | 1.115756 |
return frozenset([c.iname() for c in self.data_children()]) | def _child_inst_names(self) -> Set[InstanceName] | Return the set of instance names under the receiver. | 21.22146 | 14.81778 | 1.432162 |
self.schema_pattern = self._schema_pattern()
for dc in self.data_children():
if isinstance(dc, InternalNode):
dc._make_schema_patterns() | def _make_schema_patterns(self) -> None | Build schema pattern for the receiver and its data descendants. | 7.207479 | 4.144819 | 1.738913 |
if not sctx.schema_data.if_features(stmt, sctx.text_mid):
return
node.name = stmt.argument
node.ns = sctx.default_ns
node._get_description(stmt)
self._add_child(node)
node._handle_substatements(stmt, sctx) | def _handle_child(
self, node: SchemaNode, stmt: Statement, sctx: SchemaContext) -> None | Add child node to the receiver and handle substatements. | 10.869545 | 8.489371 | 1.280371 |
if not sctx.schema_data.if_features(stmt, sctx.text_mid):
return
path = sctx.schema_data.sni2route(stmt.argument, sctx)
target = self.get_schema_descendant(path)
if stmt.find1("when"):
gr = GroupNode()
target._add_child(gr)
target ... | def _augment_stmt(self, stmt: Statement, sctx: SchemaContext) -> None | Handle **augment** statement. | 14.138094 | 12.763111 | 1.107731 |
target = self.get_schema_descendant(
sctx.schema_data.sni2route(stmt.argument, sctx))
if not sctx.schema_data.if_features(stmt, sctx.text_mid):
target.parent.children.remove(target)
else:
target._handle_substatements(stmt, sctx) | def _refine_stmt(self, stmt: Statement, sctx: SchemaContext) -> None | Handle **refine** statement. | 14.865911 | 13.094733 | 1.135259 |
if not sctx.schema_data.if_features(stmt, sctx.text_mid):
return
grp, gid = sctx.schema_data.get_definition(stmt, sctx)
if stmt.find1("when"):
sn = GroupNode()
self._add_child(sn)
else:
sn = self
sn._handle_substatements(gr... | def _uses_stmt(self, stmt: Statement, sctx: SchemaContext) -> None | Handle uses statement. | 7.305411 | 6.976067 | 1.047211 |
self._handle_child(ContainerNode(), stmt, sctx) | def _container_stmt(self, stmt: Statement, sctx: SchemaContext) -> None | Handle container statement. | 27.60372 | 11.605047 | 2.378596 |
if not sctx.schema_data.if_features(stmt, sctx.text_mid):
return
id = (stmt.argument, sctx.schema_data.namespace(sctx.text_mid))
adj = sctx.schema_data.identity_adjs.setdefault(id, IdentityAdjacency())
for bst in stmt.find_all("base"):
bid = sctx.schema_d... | def _identity_stmt(self, stmt: Statement, sctx: SchemaContext) -> None | Handle identity statement. | 5.679565 | 5.4894 | 1.034642 |
self._handle_child(ListNode(), stmt, sctx) | def _list_stmt(self, stmt: Statement, sctx: SchemaContext) -> None | Handle list statement. | 41.479137 | 17.155787 | 2.417793 |
self._handle_child(ChoiceNode(), stmt, sctx) | def _choice_stmt(self, stmt: Statement, sctx: SchemaContext) -> None | Handle choice statement. | 28.324074 | 11.361831 | 2.492915 |
self._handle_child(CaseNode(), stmt, sctx) | def _case_stmt(self, stmt: Statement, sctx: SchemaContext) -> None | Handle case statement. | 30.200605 | 14.35114 | 2.104405 |
node = LeafNode()
node.type = DataType._resolve_type(
stmt.find1("type", required=True), sctx)
self._handle_child(node, stmt, sctx) | def _leaf_stmt(self, stmt: Statement, sctx: SchemaContext) -> None | Handle leaf statement. | 10.248846 | 8.383245 | 1.222539 |
node = LeafListNode()
node.type = DataType._resolve_type(
stmt.find1("type", required=True), sctx)
self._handle_child(node, stmt, sctx) | def _leaf_list_stmt(self, stmt: Statement, sctx: SchemaContext) -> None | Handle leaf-list statement. | 10.732512 | 9.065203 | 1.183924 |
self._handle_child(RpcActionNode(), stmt, sctx) | def _rpc_action_stmt(self, stmt: Statement, sctx: SchemaContext) -> None | Handle rpc or action statement. | 36.141254 | 16.150551 | 2.237772 |
self._handle_child(NotificationNode(), stmt, sctx) | def _notification_stmt(self, stmt: Statement, sctx: SchemaContext) -> None | Handle notification statement. | 40.874016 | 16.097599 | 2.539137 |
self._handle_child(AnydataNode(), stmt, sctx) | def _anydata_stmt(self, stmt: Statement, sctx: SchemaContext) -> None | Handle anydata statement. | 23.169144 | 11.180108 | 2.072354 |
def suffix(sn):
return f" {{{sn.val_count}}}\n" if val_count else "\n"
if not self.children:
return ""
cs = []
for c in self.children:
cs.extend(c._flatten())
cs.sort(key=lambda x: x.qual_name)
res = ""
for c in cs[:-1]... | def _ascii_tree(self, indent: str, no_types: bool, val_count: bool) -> str | Return the receiver's subtree as ASCII art. | 3.178423 | 3.111113 | 1.021635 |
if not sctx.schema_data.if_features(stmt, sctx.text_mid):
return
dst = stmt.find1("description")
self.annotations[(stmt.argument, sctx.default_ns)] = Annotation(
DataType._resolve_type(stmt.find1("type", required=True), sctx),
dst.argument if dst else... | def _annotation_stmt(self, stmt: Statement, sctx: SchemaContext) -> None | Handle annotation statement. | 14.840725 | 13.628758 | 1.088927 |
val = self.from_raw(rval)
return ObjectMember(self.iname(), {}, val, None, self, datetime.now()) | def orphan_instance(self, rval: RawValue) -> "ObjectMember" | Return an isolated instance of the receiver.
Args:
rval: Raw value to be used for the returned instance. | 12.2367 | 14.871894 | 0.822807 |
sroute = []
sn = self
while sn:
sroute.append(sn.iname())
sn = sn.data_parent()
i = 0
while True:
if not sroute:
break
inst = sroute.pop()
if inst != route[i].iname():
return None... | def split_instance_route(self, route: "InstanceRoute") -> Optional[Tuple[
"InstanceRoute", "InstanceRoute"]] | Split `route` into the part up to receiver and the rest.
Args:
route: Absolute instance route (the receiver should correspond to an
instance node on this route).
Returns:
A tuple consisting of
- the part of `route` from the root up to and includi... | 4.892495 | 5.537213 | 0.883566 |
if scope.value & ValidationScope.semantics.value:
self._check_must(inst) # must expressions
super()._validate(inst, scope, ctype) | def _validate(self, inst: "InstanceNode", scope: ValidationScope,
ctype: ContentType) -> None | Extend the superclass method. | 12.999116 | 10.107333 | 1.286107 |
if self._ctype:
return self._ctype
return (ContentType.config if self.parent.config else
ContentType.nonconfig) | def content_type(self) -> ContentType | Override superclass method. | 11.028622 | 8.317903 | 1.32589 |
res = self.type.from_raw(rval)
if res is None:
raise RawTypeError(jptr, self.type.yang_type() + " value")
return res | def from_raw(self, rval: RawScalar, jptr: JSONPointer = "") -> ScalarValue | Override the superclass method. | 6.813627 | 6.085337 | 1.119679 |
if (scope.value & ValidationScope.syntax.value and
inst.value not in self.type):
raise YangTypeError(inst.json_pointer(), self.type.error_tag,
self.type.error_message)
if (isinstance(self.type, LinkType) and # referential integr... | def _validate(self, inst: "InstanceNode", scope: ValidationScope,
ctype: ContentType) -> None | Extend the superclass method. | 7.124776 | 6.721708 | 1.059965 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.