code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
return Time(kwargs.get("hour", self.__hour),
kwargs.get("minute", self.__minute),
kwargs.get("second", self.__second),
kwargs.get("tzinfo", self.__tzinfo)) | def replace(self, **kwargs) | Return a :class:`.Time` with one or more components replaced
with new values. | 3.023258 | 2.516198 | 1.201519 |
h, m, s = self.hour_minute_second
s, ns = nano_divmod(s, 1)
ms = int(nano_mul(ns, 1000000))
return time(h, m, s, ms) | def to_native(self) | Convert to a native Python `datetime.time` value. | 4.860383 | 4.246674 | 1.144515 |
if value:
if value.isdigit():
user = User.query.get(str(value))
else:
user = User.query.filter(User.email == value).one_or_none()
return user | def process_user(ctx, param, value) | Return a user if exists. | 2.951267 | 2.514217 | 1.173832 |
token = Token.create_personal(
name, user.id, scopes=scopes, is_internal=internal)
db.session.commit()
click.secho(token.access_token, fg='blue') | def tokens_create(name, user, scopes, internal) | Create a personal OAuth token. | 4.382349 | 3.959283 | 1.106854 |
if not (name or user) and not read_access_token:
click.get_current_context().fail(
'You have to pass either a "name" and "user" or the "token"')
if name and user:
client = Client.query.filter(
Client.user_id == user.id,
Client.name == name,
Cl... | def tokens_delete(name=None, user=None, read_access_token=None, force=False) | Delete a personal OAuth token. | 2.329006 | 2.292809 | 1.015787 |
residuals = self.evaluate_residual(points)
solutions = self.evaluate_solution(points)
return [resid / soln for resid, soln in zip(residuals, solutions)] | def normalize_residuals(self, points) | Normalize residuals by the level of the variable. | 3.939658 | 4.16396 | 0.946132 |
try:
value = uuid.UUID(value)
return query.filter(self.column == value)
except ValueError:
return query | def apply(self, query, value, alias) | Convert UUID.
:param query: SQLAlchemy query object.
:param value: UUID value.
:param alias: Alias of the column.
:returns: Filtered query matching the UUID value. | 3.622644 | 3.356432 | 1.079314 |
return [f(column, name, **kwargs) for f in self.uuid_filters] | def conv_uuid(self, column, name, **kwargs) | Convert UUID filter. | 5.408134 | 4.744939 | 1.139769 |
return self.convert(str(column.type), column, name, **kwargs) | def conv_variant(self, column, name, **kwargs) | Convert variants. | 9.263035 | 7.686282 | 1.205139 |
ca_bundle_path = self._get_ca_bundle_path()
otp = OTP(otp, self.translate_otp)
rand_str = b(os.urandom(30))
nonce = base64.b64encode(rand_str, b('xz'))[:25].decode('utf-8')
query_string = self.generate_query_string(otp.otp, nonce, timestamp,
... | def verify(self, otp, timestamp=False, sl=None, timeout=None,
return_response=False) | Verify a provided OTP.
:param otp: OTP to verify.
:type otp: ``str``
:param timestamp: True to include request timestamp and session counter
in the response. Defaults to False.
:type timestamp: ``bool``
:param sl: A value indicating percentage of sync... | 3.603441 | 3.956413 | 0.910785 |
# Create the OTP objects
otps = []
for otp in otp_list:
otps.append(OTP(otp, self.translate_otp))
if len(otp_list) < 2:
raise ValueError('otp_list needs to contain at least two OTPs')
device_ids = set()
for otp in otps:
devi... | def verify_multi(self, otp_list, max_time_window=DEFAULT_MAX_TIME_WINDOW,
sl=None, timeout=None) | Verify a provided list of OTPs.
:param max_time_window: Maximum number of seconds which can pass
between the first and last OTP generation for
the OTP to still be considered valid.
:type max_time_window: ``int`` | 4.289128 | 4.184928 | 1.024899 |
try:
status = re.search(r'status=([A-Z0-9_]+)', response) \
.groups()
if len(status) > 1:
message = 'More than one status= returned. Possible attack!'
raise InvalidValidationResponse(message, response)
status =... | def verify_response(self, response, otp, nonce, return_response=False) | Returns True if the OTP is valid (status=OK) and return_response=False,
otherwise (return_response = True) it returns the server response as a
dictionary.
Throws an exception if the OTP is replayed, the server response message
verification failed or the client id is invalid, returns Fal... | 3.680212 | 3.540016 | 1.039603 |
data = [('id', self.client_id),
('otp', otp),
('nonce', nonce)]
if timestamp:
data.append(('timestamp', '1'))
if sl is not None:
if sl not in range(0, 101) and sl not in ['fast', 'secure']:
raise Exception('sl par... | def generate_query_string(self, otp, nonce, timestamp=False, sl=None,
timeout=None) | Returns a query string which is sent to the validation servers. | 2.906733 | 2.923765 | 0.994175 |
# split for sorting
pairs = query_string.split('&')
pairs = [pair.split('=', 1) for pair in pairs]
pairs_sorted = sorted(pairs)
pairs_string = '&' . join(['=' . join(pair) for pair in pairs_sorted])
digest = hmac.new(self.key, b(pairs_string), hashlib.sha1).dige... | def generate_message_signature(self, query_string) | Returns a HMAC-SHA-1 signature for the given query string.
http://goo.gl/R4O0E | 2.543115 | 2.494801 | 1.019366 |
lines = response.splitlines()
pairs = [line.strip().split('=', 1) for line in lines if '=' in line]
pairs = sorted(pairs)
signature = ([unquote(v) for k, v in pairs if k == 'h'] or [None])[0]
# already quoted
query_string = '&' . join([k + '=' + v for k, v in pai... | def parse_parameters_from_response(self, response) | Returns a response signature and query string generated from the
server response. 'h' aka signature argument is stripped from the
returned query string. | 4.12636 | 3.221377 | 1.28093 |
pairs = (x.split('=', 1) for x in query_string.split('&'))
return dict((k, unquote(v)) for k, v in pairs) | def get_parameters_as_dictionary(self, query_string) | Returns query string parameters as a dictionary. | 2.749169 | 2.71849 | 1.011285 |
if not isinstance(api_urls, (str, list, tuple)):
raise TypeError('api_urls needs to be string or iterable!')
if isinstance(api_urls, str):
api_urls = (api_urls,)
api_urls = list(api_urls)
for url in api_urls:
if not url.startswith('http://'... | def _init_request_urls(self, api_urls) | Returns a list of the API URLs. | 2.980565 | 2.751627 | 1.083201 |
if self.ca_certs_bundle_path:
# User provided a custom path
return self.ca_certs_bundle_path
# Return first bundle which is available
for file_path in COMMON_CA_LOCATIONS:
if self._is_valid_ca_bundle_file(file_path=file_path):
return ... | def _get_ca_bundle_path(self) | Return a path to the CA bundle which is used for verifying the hosts
SSL certificate. | 4.6619 | 4.499361 | 1.036125 |
'''execute
High-level api: The fact that most connection classes implement
execute method lead us to add this method here as well.
Supported operations are get, get_config, get_schema, dispatch,
edit_config, copy_config, validate, commit, discard_changes,
delete_config, ... | def execute(self, operation, *args, **kwargs) | execute
High-level api: The fact that most connection classes implement
execute method lead us to add this method here as well.
Supported operations are get, get_config, get_schema, dispatch,
edit_config, copy_config, validate, commit, discard_changes,
delete_config, lock, unloc... | 6.805657 | 2.150223 | 3.165094 |
'''_request
Override method _request in class ncclient.operations.RPC, so it can
handle raw rpc requests in string format without validating your rpc
request syntax. When your rpc-reply is received, in most cases, it
simply returns rpc-reply again in string format, except one sc... | def _request(self, msg) | _request
Override method _request in class ncclient.operations.RPC, so it can
handle raw rpc requests in string format without validating your rpc
request syntax. When your rpc-reply is received, in most cases, it
simply returns rpc-reply again in string format, except one scenario:
... | 6.050556 | 2.617424 | 2.311645 |
if not isinstance(string_length, int) or not 1 <= string_length <= 32:
msg = "string_length must be type int where 1 <= string_length <= 32"
raise ValueError(msg)
random = str(uuid.uuid4()).upper().replace('-', '')
return random[0:string_length] | def random_str_uuid(string_length) | Returns a random string of length string_length | 2.64852 | 2.605924 | 1.016346 |
'''Take a filepath, add randome characters to its basename,
and return the new filepath
:param filename: either a filename or filepath
:param length_random: length of random string to be generated
'''
path_full_pre_extension, extension = os.path.splitext(path_full)
random_str = random_str_u... | def random_name_filepath(path_full, length_random=5) | Take a filepath, add randome characters to its basename,
and return the new filepath
:param filename: either a filename or filepath
:param length_random: length of random string to be generated | 4.483369 | 2.380931 | 1.883032 |
'''List all filepathes in a directory that begin with predicate
:param path_dir: the directory whose top-level contents you wish to list
:param predicate: the predicate you want to test the directory's
found files against
'''
if not os.path.isdir(path_dir):
raise ValueError("{} is n... | def list_filepathes_with_predicate(path_dir, predicate) | List all filepathes in a directory that begin with predicate
:param path_dir: the directory whose top-level contents you wish to list
:param predicate: the predicate you want to test the directory's
found files against | 3.316921 | 1.968617 | 1.684899 |
'''Recursively apply a function to all levels of nested iterables
:param inval: the object to run the function on
:param func: the function that will be run on the inval
'''
if isinstance(inval, dict):
return {k: recursive_apply(v, func) for k, v in inval.items()}
elif isinstance(inval,... | def recursive_apply(inval, func) | Recursively apply a function to all levels of nested iterables
:param inval: the object to run the function on
:param func: the function that will be run on the inval | 2.152218 | 1.609346 | 1.337325 |
self.check_files()
n = 0
for manifest in self.partition_dumps():
dumpbase = "%s%05d" % (basename, n)
dumpfile = "%s.%s" % (dumpbase, self.format)
if (write_separate_manifests):
manifest.write(basename=dumpbase + '.xml')
if ... | def write(self, basename=None, write_separate_manifests=True) | Write one or more dump files to complete this dump.
Returns the number of dump/archive files written. | 3.328799 | 3.124517 | 1.06538 |
compression = (ZIP_DEFLATED if self.compress else ZIP_STORED)
zf = ZipFile(
dumpfile,
mode="w",
compression=compression,
allowZip64=True)
# Write resources first
rdm = ResourceDumpManifest(resources=resources)
real_path = {... | def write_zip(self, resources=None, dumpfile=None) | Write a ZIP format dump file.
Writes a ZIP file containing the resources in the iterable resources along with
a manifest file manifest.xml (written first). No checks on the size of files
or total size are performed, this is expected to have been done beforehand. | 2.997861 | 2.924535 | 1.025073 |
# Load library late as we want to be able to run rest of code
# without this installed
try:
from warc import WARCFile, WARCHeader, WARCRecord
except:
raise DumpError("Failed to load WARC library")
wf = WARCFile(dumpfile, mode="w", compress=self.co... | def write_warc(self, resources=None, dumpfile=None) | Write a WARC dump file.
WARC support is not part of ResourceSync v1.0 (Z39.99 2014) but is left
in this library for experimentation. | 4.7583 | 4.797888 | 0.991749 |
total_size = 0 # total size of all files in bytes
path_prefix = None
for resource in self.resources:
if (resource.path is None):
# explicit test because exception raised by getsize otherwise
# confusing
raise DumpError(
... | def check_files(self, set_length=True, check_length=True) | Check all files in self.resources, find longest common prefix.
Go though and check all files in self.resources, add up size, and find
longest common path that can be used when writing the dump file. Saved in
self.path_prefix.
Parameters set_length and check_length control control wheth... | 2.827387 | 2.578338 | 1.096593 |
manifest = self.manifest_class()
manifest_size = 0
manifest_files = 0
for resource in self.resources:
manifest.add(resource)
manifest_size += resource.length
manifest_files += 1
if (manifest_size >= self.max_size or
... | def partition_dumps(self) | Yeild a set of manifest object that parition the dumps.
Simply adds resources/files to a manifest until their are either the
the correct number of files or the size limit is exceeded, then yields
that manifest. | 2.755959 | 2.213997 | 1.244789 |
if (not self.path_prefix):
return(real_path)
else:
return(os.path.relpath(real_path, self.path_prefix)) | def archive_path(self, real_path) | Return the archive path for file with real_path.
Mapping is based on removal of self.path_prefix which is determined
by self.check_files(). | 3.1709 | 2.749829 | 1.153126 |
self.scene = cocos.scene.Scene()
self.z = 0
palette = config.settings['view']['palette']
#Player.palette = palette
r, g, b = palette['bg']
self.scene.add(cocos.layer.ColorLayer(r, g, b, 255), z=self.z)
self.z += 1
message_layer = MessageLayer()
... | def reset(self) | Attach a new engine to director | 4.529157 | 4.420971 | 1.024471 |
# FIXME: Hack to change in return type
action = int(action)
assert isinstance(action, int)
assert action < self.actions_num, "%r (%s) invalid"%(action, type(action))
# Reset buttons
for k in self.world_layer.buttons:
self.world_layer.buttons[k] = 0
... | def act(self, action) | Take one action for one step | 4.035844 | 4.020134 | 1.003908 |
self.director.window.switch_to()
self.director.window.dispatch_events()
self.director.window.dispatch_event('on_draw')
self.director.window.flip()
# Ticking before events caused glitches.
pyglet.clock.tick() | def step(self) | Step the engine one tick | 4.988452 | 4.674788 | 1.067097 |
'''Main runner for latex build
Should compile the object's Latex template using a list of latex
shell commands, along with an output file location. Runs the latex
shell command until the process's .aux file remains unchanged.
:return: STR template text that is ultimately render... | def run_latex(self, cmd_wo_infile, path_outfile) | Main runner for latex build
Should compile the object's Latex template using a list of latex
shell commands, along with an output file location. Runs the latex
shell command until the process's .aux file remains unchanged.
:return: STR template text that is ultimately rendered
... | 4.234103 | 2.713193 | 1.560561 |
return v.x * config.scale_x, v.y * config.scale_y | def world_to_view(v) | world coords to view coords; v an eu.Vector2, returns (float, float) | 5.645066 | 5.160337 | 1.093934 |
assert isinstance(cshape_center, eu.Vector2)
self.position = world_to_view(cshape_center)
self.cshape.center = cshape_center | def update_center(self, cshape_center) | cshape_center must be eu.Vector2 | 5.46125 | 3.598474 | 1.517657 |
deps = {}
for i in dir(cls):
if i.startswith('__') and i.endswith('__'):
continue
val = getattr(cls, i, None)
if isinstance(val, Dependency):
deps[i] = val
if val.name is None:
val.name = i
cls.__injections__ = deps
return ... | def has(cls) | Class decorator that declares dependencies | 2.819211 | 2.628181 | 1.072685 |
if renames:
di = self.clone(**renames)
else:
di = self
pro = di._provides
inst.__injections_source__ = di
deps = getattr(inst, '__injections__', None)
if deps:
for attr, dep in deps.items():
val = pro.get(dep.na... | def inject(self, inst, **renames) | Injects dependencies and propagates dependency injector | 3.981637 | 3.720628 | 1.070152 |
for dep in topologically_sorted(self._provides):
if hasattr(dep, '__injections__') and not hasattr(dep, '__injections_source__'):
self.inject(dep) | def interconnect_all(self) | Propagate dependencies for provided instances | 9.858388 | 7.526395 | 1.309842 |
valid_kind = cls._validate(kind)
basis_polynomial = getattr(np.polynomial, valid_kind)
return basis_polynomial | def _basis_polynomial_factory(cls, kind) | Return a polynomial given some coefficients. | 5.804844 | 5.549634 | 1.045987 |
if kind not in cls._valid_kinds:
mesg = "'kind' must be one of {}, {}, {}, or {}."
raise ValueError(mesg.format(*cls._valid_kinds))
else:
return kind | def _validate(cls, kind) | Validate the kind argument. | 3.559071 | 3.107789 | 1.14521 |
basis_polynomial = cls._basis_polynomial_factory(kind)
return basis_polynomial(coef, domain).deriv() | def derivatives_factory(cls, coef, domain, kind, **kwargs) | Given some coefficients, return a the derivative of a certain kind of
orthogonal polynomial defined over a specific domain. | 6.996521 | 5.778075 | 1.210874 |
basis_polynomial = cls._basis_polynomial_factory(kind)
return basis_polynomial(coef, domain) | def functions_factory(cls, coef, domain, kind, **kwargs) | Given some coefficients, return a certain kind of orthogonal polynomial
defined over a specific domain. | 5.770326 | 4.630349 | 1.246197 |
basis_coefs = cls._basis_monomial_coefs(degree)
basis_poly = cls.functions_factory(basis_coefs, domain, kind)
return basis_poly.roots() | def roots(cls, degree, domain, kind) | Return optimal collocation nodes for some orthogonal polynomial. | 6.957064 | 5.936587 | 1.171896 |
if (hasattr(capability_list, 'uri')):
r = Resource(uri=capability_list.uri,
capability=capability_list.capability_name)
if (capability_list.describedby is not None):
r.link_set(rel='describedby', href=capability_list.describedby)
... | def add_capability_list(self, capability_list=None) | Add a capability list.
Adds either a CapabiltyList object specified in capability_list
or else creates a Resource with the URI given in capability_list
and adds that to the Source Description | 4.253473 | 3.782326 | 1.124566 |
for func in oauth2._before_request_funcs:
func()
if not hasattr(request, 'oauth') or not request.oauth:
scopes = []
try:
valid, req = oauth2.verify_request(scopes)
except ValueError:
abort(400, 'Error trying to decode a non urlencoded string.')
... | def verify_oauth_token_and_set_current_user() | Verify OAuth token and set current user on request stack.
This function should be used **only** on REST application.
.. code-block:: python
app.before_request(verify_oauth_token_and_set_current_user) | 4.99284 | 6.232675 | 0.801075 |
return [
(k, scope) for k, scope in sorted(self.scopes.items())
if not exclude_internal or not scope.is_internal
] | def scope_choices(self, exclude_internal=True) | Return list of scope choices.
:param exclude_internal: Exclude internal scopes or not.
(Default: ``True``)
:returns: A list of tuples (id, scope). | 3.807566 | 4.759479 | 0.799996 |
if not isinstance(scope, Scope):
raise TypeError("Invalid scope type.")
assert scope.id not in self.scopes
self.scopes[scope.id] = scope | def register_scope(self, scope) | Register a scope.
:param scope: A :class:`invenio_oauth2server.models.Scope` instance. | 3.237198 | 4.469909 | 0.72422 |
for ep in pkg_resources.iter_entry_points(group=entry_point_group):
self.register_scope(ep.load()) | def load_entry_point_group(self, entry_point_group) | Load actions from an entry point group.
:param entry_point_group: The entrypoint group name to load plugins. | 4.180257 | 4.543346 | 0.920083 |
imp = self.app.config.get(value)
if isinstance(imp, six.string_types):
return import_string(imp)
elif imp:
return imp | def load_obj_or_import_string(self, value) | Import string or return object.
:params value: Import path or class object to instantiate.
:params default: Default object to return if the import fails.
:returns: The imported object. | 4.39842 | 5.859077 | 0.750702 |
self.init_config(app)
state = _OAuth2ServerState(app, entry_point_group=entry_point_group)
app.extensions['invenio-oauth2server'] = state
return state | def init_app(self, app, entry_point_group='invenio_oauth2server.scopes',
**kwargs) | Flask application initialization.
:param app: An instance of :class:`flask.Flask`.
:param entry_point_group: The entrypoint group name to load plugins.
(Default: ``'invenio_oauth2server.scopes'``) | 3.490161 | 4.438283 | 0.786376 |
self.init_config(app)
allowed_urlencode_chars = app.config.get(
'OAUTH2SERVER_ALLOWED_URLENCODE_CHARACTERS')
if allowed_urlencode_chars:
InvenioOAuth2ServerREST.monkeypatch_oauthlib_urlencode_chars(
allowed_urlencode_chars)
app.before_req... | def init_app(self, app, **kwargs) | Flask application initialization.
:param app: An instance of :class:`flask.Flask`. | 5.198623 | 5.920778 | 0.87803 |
modified_chars = set(chars)
always_safe = set(oauthlib_commmon.always_safe)
original_special_chars = oauthlib_commmon.urlencoded - always_safe
if modified_chars != original_special_chars:
warnings.warn(
'You are overriding the default OAuthlib "URL en... | def monkeypatch_oauthlib_urlencode_chars(chars) | Monkeypatch OAuthlib set of "URL encoded"-safe characters.
.. note::
OAuthlib keeps a set of characters that it considers as valid
inside an URL-encoded query-string during parsing of requests. The
issue is that this set of characters wasn't designed to be
confi... | 7.078098 | 6.418472 | 1.10277 |
assert isinstance(point, eu.Vector2)
assert isinstance(direction, int) or isinstance(direction, float)
assert isinstance(length, int) or isinstance(length, float)
# Recursive dead-reckoning to next tile
# Given `point`, look for where intersects with next boundary (`y %... | def distance_to_tile(self, point, direction, length = 50) | Find nearest wall on a given bearing.
Used for agent wall sensors. | 3.54033 | 3.50044 | 1.011396 |
# Calculate the log probability
length = len(next(iter(frequency_map)))
# TODO: 0.01 is a magic number. Needs to be better than that.
floor = math.log10(0.01 / sum(frequency_map.values()))
ngrams = frequency.frequency_to_probability(frequency_map, decorator=math.log10)
def inner(text):
... | def NgramScorer(frequency_map) | Compute the score of a text by using the frequencies of ngrams.
Example:
>>> fitness = NgramScorer(english.unigrams)
>>> fitness("ABC")
-4.3622319742618245
Args:
frequency_map (dict): ngram to frequency mapping | 6.719561 | 7.216758 | 0.931105 |
if (capability is not None):
name = capability.capability_name
if (capability.uri is not None):
uri = capability.uri
self.add(Resource(uri=uri, capability=name)) | def add_capability(self, capability=None, uri=None, name=None) | Specific add function for capabilities.
Takes either:
- a capability object (derived from ListBase) as the first argument
from which the capability name is extracted, and the URI if given
- or a plain name string
and
- the URI of the capability | 4.230692 | 4.751702 | 0.890353 |
for r in self.resources:
if (r.capability == name):
return(r)
return(None) | def capability_info(self, name=None) | Return information about the requested capability from this list.
Will return None if there is no information about the requested capability. | 5.351346 | 5.447628 | 0.982326 |
'''emit_children
High-level api: Emit a string presentation of the model.
Parameters
----------
type : `str`
Type of model content required. Its value can be 'other', 'rpc', or
'notification'.
Returns
-------
str
A ... | def emit_children(self, type='other') | emit_children
High-level api: Emit a string presentation of the model.
Parameters
----------
type : `str`
Type of model content required. Its value can be 'other', 'rpc', or
'notification'.
Returns
-------
str
A string pres... | 4.102855 | 2.586176 | 1.586456 |
'''get_width
High-level api: Calculate how much indent is needed for a node.
Parameters
----------
element : `Element`
A node in model tree.
Returns
-------
int
Start position from the left margin.
'''
parent =... | def get_width(self, element) | get_width
High-level api: Calculate how much indent is needed for a node.
Parameters
----------
element : `Element`
A node in model tree.
Returns
-------
int
Start position from the left margin. | 4.932309 | 2.339856 | 2.107954 |
'''get_depth_str
High-level api: Produce a string that represents tree hierarchy.
Parameters
----------
element : `Element`
A node in model tree.
type : `str`
Type of model content required. Its value can be 'other', 'rpc', or
'noti... | def get_depth_str(element, type='other') | get_depth_str
High-level api: Produce a string that represents tree hierarchy.
Parameters
----------
element : `Element`
A node in model tree.
type : `str`
Type of model content required. Its value can be 'other', 'rpc', or
'notification'.
... | 3.507606 | 2.091956 | 1.676711 |
'''get_flags_str
High-level api: Produce a string that represents the type of a node.
Parameters
----------
element : `Element`
A node in model tree.
Returns
-------
str
A string that represents the type of a node.
'''
... | def get_flags_str(element) | get_flags_str
High-level api: Produce a string that represents the type of a node.
Parameters
----------
element : `Element`
A node in model tree.
Returns
-------
str
A string that represents the type of a node. | 3.588417 | 2.23284 | 1.607109 |
'''get_name_str
High-level api: Produce a string that represents the name of a node.
Parameters
----------
element : `Element`
A node in model tree.
Returns
-------
str
A string that represents the name of a node.
'''
... | def get_name_str(self, element) | get_name_str
High-level api: Produce a string that represents the name of a node.
Parameters
----------
element : `Element`
A node in model tree.
Returns
-------
str
A string that represents the name of a node. | 2.557088 | 2.050325 | 1.247162 |
'''get_datatype_str
High-level api: Produce a string that indicates the data type of a node.
Parameters
----------
element : `Element`
A node in model tree.
length : `int`
String length that has been consumed.
Returns
-------
... | def get_datatype_str(self, element, length) | get_datatype_str
High-level api: Produce a string that indicates the data type of a node.
Parameters
----------
element : `Element`
A node in model tree.
length : `int`
String length that has been consumed.
Returns
-------
str... | 4.376001 | 2.592838 | 1.687726 |
'''prefix_to_url
High-level api: Convert an identifier from `prefix:tagname` notation to
`{namespace}tagname` notation. If the identifier does not have a
prefix, it is assumed that the whole identifier is a tag name.
Parameters
----------
id : `str`
... | def prefix_to_url(self, id) | prefix_to_url
High-level api: Convert an identifier from `prefix:tagname` notation to
`{namespace}tagname` notation. If the identifier does not have a
prefix, it is assumed that the whole identifier is a tag name.
Parameters
----------
id : `str`
Identifier... | 3.790558 | 1.777597 | 2.132406 |
'''url_to_prefix
High-level api: Convert an identifier from `{namespace}tagname` notation
to `prefix:tagname` notation. If the identifier does not have a
namespace, it is assumed that the whole identifier is a tag name.
Parameters
----------
id : `str`
... | def url_to_prefix(self, id) | url_to_prefix
High-level api: Convert an identifier from `{namespace}tagname` notation
to `prefix:tagname` notation. If the identifier does not have a
namespace, it is assumed that the whole identifier is a tag name.
Parameters
----------
id : `str`
Identif... | 4.377707 | 1.870981 | 2.339792 |
'''remove_model_prefix
High-level api: If prefix is the model prefix, return tagname without
prefix. If prefix is not the model prefix, simply return the identifier
without modification.
Parameters
----------
id : `str`
Identifier in `prefix:tagname... | def remove_model_prefix(self, id) | remove_model_prefix
High-level api: If prefix is the model prefix, return tagname without
prefix. If prefix is not the model prefix, simply return the identifier
without modification.
Parameters
----------
id : `str`
Identifier in `prefix:tagname` notation.... | 4.147488 | 1.650154 | 2.513394 |
'''convert_tree
High-level api: Convert cxml tree to an internal schema tree. This
method is recursive.
Parameters
----------
element1 : `Element`
The node to be converted.
element2 : `Element`
A new node being constructed.
Ret... | def convert_tree(self, element1, element2=None) | convert_tree
High-level api: Convert cxml tree to an internal schema tree. This
method is recursive.
Parameters
----------
element1 : `Element`
The node to be converted.
element2 : `Element`
A new node being constructed.
Returns
... | 3.910822 | 2.078735 | 1.881347 |
'''download_all
High-level api: Convert cxml tree to an internal schema tree. This
method is recursive.
Parameters
----------
check_before_download : `bool`
True if checking capabilities.txt file is required.
Returns
-------
None
... | def download_all(self, check_before_download=True) | download_all
High-level api: Convert cxml tree to an internal schema tree. This
method is recursive.
Parameters
----------
check_before_download : `bool`
True if checking capabilities.txt file is required.
Returns
-------
None
... | 5.171726 | 3.144269 | 1.644811 |
'''download
High-level api: Download a module schema.
Parameters
----------
module : `str`
Module name that will be downloaded.
Returns
-------
None
Nothing returns.
'''
import_r = '^[ |\t]+import[ |\t]+([a-zA-... | def download(self, module) | download
High-level api: Download a module schema.
Parameters
----------
module : `str`
Module name that will be downloaded.
Returns
-------
None
Nothing returns. | 3.398954 | 2.930235 | 1.15996 |
'''build_dependencies
High-level api: Briefly compile all yang files and find out dependency
infomation of all modules.
Returns
-------
None
Nothing returns.
'''
cmd_list = ['pyang', '--plugindir', self.pyang_plugins]
cmd_list += ['... | def build_dependencies(self) | build_dependencies
High-level api: Briefly compile all yang files and find out dependency
infomation of all modules.
Returns
-------
None
Nothing returns. | 4.057485 | 2.51819 | 1.61127 |
'''get_dependencies
High-level api: Get dependency infomationa of a module.
Parameters
----------
module : `str`
Module name that is inquired about.
Returns
-------
tuple
A tuple with two elements: a set of imports and a set of... | def get_dependencies(self, module) | get_dependencies
High-level api: Get dependency infomationa of a module.
Parameters
----------
module : `str`
Module name that is inquired about.
Returns
-------
tuple
A tuple with two elements: a set of imports and a set of depends. | 3.495592 | 2.086566 | 1.675285 |
'''compile
High-level api: Compile a module.
Parameters
----------
module : `str`
Module name that is inquired about.
Returns
-------
Model
A Model object.
'''
imports, depends = self.get_dependencies(module)
... | def compile(self, module) | compile
High-level api: Compile a module.
Parameters
----------
module : `str`
Module name that is inquired about.
Returns
-------
Model
A Model object. | 3.420449 | 2.621481 | 1.304777 |
'''get_name_str
High-level api: Produce a string that represents the name of a node.
Parameters
----------
element : `Element`
A node in model tree.
Returns
-------
str
A string that represents the name of a node.
'''
... | def get_name_str(self, element) | get_name_str
High-level api: Produce a string that represents the name of a node.
Parameters
----------
element : `Element`
A node in model tree.
Returns
-------
str
A string that represents the name of a node. | 5.03125 | 2.38852 | 2.106429 |
'''get_diff_str
High-level api: Produce a string that indicates the difference between
two models.
Parameters
----------
element : `Element`
A node in model tree.
length : `int`
String length that has been consumed.
Returns
... | def get_diff_str(self, element, length) | get_diff_str
High-level api: Produce a string that indicates the difference between
two models.
Parameters
----------
element : `Element`
A node in model tree.
length : `int`
String length that has been consumed.
Returns
------... | 6.360452 | 2.279898 | 2.789797 |
'''compare_nodes
High-level api: Compare node1 and node2 and put the result in ret.
Parameters
----------
node1 : `Element`
A node in a model tree.
node2 : `Element`
A node in another model tree.
ret : `Element`
A node in s... | def compare_nodes(node1, node2, ret) | compare_nodes
High-level api: Compare node1 and node2 and put the result in ret.
Parameters
----------
node1 : `Element`
A node in a model tree.
node2 : `Element`
A node in another model tree.
ret : `Element`
A node in self.tree.
... | 3.157089 | 2.174953 | 1.451566 |
'''copy_subtree
High-level api: Copy element as a subtree and put it as a child of ret.
Parameters
----------
element : `Element`
A node in a model tree.
msg : `str`
Message to be added.
ret : `Element`
A node in self.tree.... | def copy_subtree(ret, element, msg) | copy_subtree
High-level api: Copy element as a subtree and put it as a child of ret.
Parameters
----------
element : `Element`
A node in a model tree.
msg : `str`
Message to be added.
ret : `Element`
A node in self.tree.
R... | 7.552517 | 2.429904 | 3.108154 |
'''copy_node
High-level api: Copy element as a node without its children and put it
as a child of ret.
Parameters
----------
element : `Element`
A node in a model tree.
msg : `str`
Message to be added.
ret : `Element`
... | def copy_node(ret, element, msg) | copy_node
High-level api: Copy element as a node without its children and put it
as a child of ret.
Parameters
----------
element : `Element`
A node in a model tree.
msg : `str`
Message to be added.
ret : `Element`
A node i... | 7.749325 | 2.434025 | 3.183749 |
'''process_attrib
High-level api: Delete four attributes from an ElementTree node if they
exist: operation, insert, value and key. Then a new attribute 'diff' is
added.
Parameters
----------
element : `Element`
A node needs to be looked at.
... | def process_attrib(element, msg) | process_attrib
High-level api: Delete four attributes from an ElementTree node if they
exist: operation, insert, value and key. Then a new attribute 'diff' is
added.
Parameters
----------
element : `Element`
A node needs to be looked at.
msg : `str... | 7.663346 | 2.001535 | 3.828734 |
'''get_peer
High-level api: Find all children under the node with the tag.
Parameters
----------
tag : `str`
A tag in `{namespace}tagname` notaion.
node : `Element`
A node to be looked at.
Returns
-------
Element or No... | def get_peer(tag, node) | get_peer
High-level api: Find all children under the node with the tag.
Parameters
----------
tag : `str`
A tag in `{namespace}tagname` notaion.
node : `Element`
A node to be looked at.
Returns
-------
Element or None
... | 5.731097 | 1.896963 | 3.021196 |
'''node_equal
High-level api: Evaluate whether two nodes are equal.
Parameters
----------
node1 : `Element`
A node in a model tree.
node2 : `Element`
A node in another model tree.
Returns
-------
bool
True ... | def node_equal(node1, node2) | node_equal
High-level api: Evaluate whether two nodes are equal.
Parameters
----------
node1 : `Element`
A node in a model tree.
node2 : `Element`
A node in another model tree.
Returns
-------
bool
True if node1 an... | 4.020465 | 2.233792 | 1.799839 |
'''node_less
Low-level api: Return True if all descendants of node1 exist in node2.
Otherwise False. This is a recursive method.
Parameters
----------
node1 : `Element`
A node in a model tree.
node2 : `Element`
A node in another model t... | def node_less(node1, node2) | node_less
Low-level api: Return True if all descendants of node1 exist in node2.
Otherwise False. This is a recursive method.
Parameters
----------
node1 : `Element`
A node in a model tree.
node2 : `Element`
A node in another model tree.
... | 3.046481 | 2.014933 | 1.511951 |
cmd_funct = {"quit": False,
"run": node_cmd,
"stop": node_cmd,
"connect": node_cmd,
"details": node_cmd,
"update": True}
ui_print("\033[?25l") # cursor off
print("{}\n".format(fmt_table))
sys.stdout.flush()
# ... | def ui_main(fmt_table, node_dict) | Create the base UI in command mode. | 4.464124 | 4.361698 | 1.023483 |
key_lu = {"q": ["quit", True], "r": ["run", True],
"s": ["stop", True], "u": ["update", True],
"c": ["connect", True], "d": ["details", True]}
ui_cmd_bar()
cmd_valid = False
input_flush()
with term.cbreak():
while not cmd_valid:
val = input_by_key... | def get_user_cmd(node_dict) | Get main command selection. | 5.353694 | 5.106649 | 1.048377 |
sc = {"run": cmd_startstop, "stop": cmd_startstop,
"connect": cmd_connect, "details": cmd_details}
node_num = node_selection(cmd_name, len(node_dict))
refresh_main = None
if node_num != 0:
(node_valid, node_info) = node_validate(node_dict, node_num, cmd_name)
if node_valid... | def node_cmd(cmd_name, node_dict) | Process commands that target specific nodes. | 5.869603 | 5.723026 | 1.025612 |
cmd_disp = cmd_name.upper()
cmd_title = ("\r{1}{0} NODE{2} - Enter {3}#{2}"
" ({4}0 = Exit Command{2}): ".
format(cmd_disp, C_TI, C_NORM, C_WARN, C_HEAD2))
ui_cmd_title(cmd_title)
selection_valid = False
input_flush()
with term.cbreak():
while not s... | def node_selection(cmd_name, node_qty) | Determine Node via alternate input method. | 5.976661 | 5.96997 | 1.001121 |
# cmd: [required-state, action-to-displayed, error-statement]
req_lu = {"run": ["stopped", "Already Running"],
"stop": ["running", "Already Stopped"],
"connect": ["running", "Can't Connect, Node Not Running"],
"details": [node_dict[node_num].state, ""]}
tm = {T... | def node_validate(node_dict, node_num, cmd_name) | Validate that command can be performed on target node. | 6.741531 | 6.78923 | 0.992974 |
cmd_lu = {"run": ["ex_start_node", "wait_until_running", "RUNNING"],
"stop": ["ex_stop_node", "", "STOPPING"]}
# specific delay & message {provider: {command: [delay, message]}}
cld_lu = {"azure": {"stop": [6, "Initiated"]},
"aws": {"stop": [6, "Initiated"]}}
conf_mess =... | def cmd_startstop(node, cmd_name, node_info) | Confirm command and execute it. | 5.237311 | 5.104794 | 1.025959 |
# FUTURE: call function to check for custom connection-info
conn_info = "Defaults"
conf_mess = ("\r{0}{1} TO{2} {3} using {5}{4}{2} - Confirm [y/N]: ".
format(C_STAT[cmd_name.upper()], cmd_name.upper(), C_NORM,
node_info, conn_info, C_HEAD2))
cmd_result = No... | def cmd_connect(node, cmd_name, node_info) | Connect to node. | 4.321622 | 4.313086 | 1.001979 |
ssh_key = ""
if node.cloud == "aws":
raw_key = node.extra['key_name']
ssh_key = "-i {0}{1}.pem ".format(CONFIG_DIR, raw_key)
ssh_user = ssh_calc_aws(node)
elif node.cloud == "azure":
ssh_user = node.extra['properties']['osProfile']['adminUsername']
elif node.cloud ==... | def ssh_get_info(node) | Determine ssh-user and ssh-key for node. | 4.37398 | 4.039167 | 1.082892 |
userlu = {"ubunt": "ubuntu", "debia": "admin", "fedor": "root",
"cento": "centos", "openb": "root"}
image_name = node.driver.get_image(node.extra['image_id']).name
if not image_name:
image_name = node.name
usertemp = ['name'] + [value for key, value in list(userlu.items())
... | def ssh_calc_aws(node) | Calculate default ssh-user based on image-if of AWS instance. | 6.057187 | 5.187026 | 1.167757 |
cmd_bar = ("\rSELECT COMMAND - {2}(R){1}un {0}(C){1}onnect "
"{3}(S){1}top {0}(U){1}pdate"
" {0}(Q){1}uit: ".
format(C_TI, C_NORM, C_GOOD, C_ERR))
# FUTURE - TO BE USED WHEN DETAILS IMPLEMENTED
# cmd_bar = ("\rSELECT COMMAND - {2}(R){1}un {0}(C){... | def ui_cmd_bar() | Display Command Bar. | 5.275924 | 5.072443 | 1.040115 |
try:
import sys, termios # noqa
termios.tcflush(sys.stdin, termios.TCIFLUSH)
except ImportError:
import msvcrt
while msvcrt.kbhit():
msvcrt.getch() | def input_flush() | Flush the input buffer on posix and windows. | 2.755448 | 2.820508 | 0.976933 |
usr_inp = ''
input_valid = True
input_flush()
with term.cbreak():
while input_valid:
ui_print("\033[?25h") # cursor on
key_raw = term.inkey()
if key_raw.name == "KEY_ENTER":
input_valid = False
ui_print("\033[?25l") # cur... | def input_by_key() | Get user input using term.inkey to prevent /n printing at end. | 3.367707 | 3.146822 | 1.070193 |
ui_erase_ln()
ui_print(conf_mess)
with term.cbreak():
input_flush()
val = input_by_key()
return bool(val.lower() == 'y') | def input_yn(conf_mess) | Print Confirmation Message and Get Y/N response from user. | 10.074544 | 10.727551 | 0.939128 |
user = datastore.find_user(email=email)
if user and user.active and verify_password(password, user.password):
return user | def get_user(email, password, *args, **kwargs) | Get user for grant type password.
Needed for grant type 'password'. Note, grant type password is by default
disabled.
:param email: User email.
:param password: Password.
:returns: The user instance or ``None``. | 3.945944 | 5.448021 | 0.724289 |
if access_token:
t = Token.query.filter_by(access_token=access_token).first()
if t and t.is_personal and t.user.active:
t.expires = datetime.utcnow() + timedelta(
seconds=int(current_app.config.get(
'OAUTH2_PROVIDER_TOKEN_EXPIRES_IN'
... | def get_token(access_token=None, refresh_token=None) | Load an access token.
Add support for personal access tokens compared to flask-oauthlib.
If the access token is ``None``, it looks for the refresh token.
:param access_token: The access token. (Default: ``None``)
:param refresh_token: The refresh token. (Default: ``None``)
:returns: The token inst... | 2.69016 | 2.687909 | 1.000838 |
client = Client.query.get(client_id)
if client and client.user.active:
return client | def get_client(client_id) | Load the client.
Needed for grant_type client_credentials.
Add support for OAuth client_credentials access type, with user
inactivation support.
:param client_id: The client ID.
:returns: The client instance or ``None``. | 4.240094 | 5.717007 | 0.741663 |
# Exclude the personal access tokens which doesn't expire.
user = request.user if request.user else current_user
# Add user information in token endpoint response.
# Currently, this is the only way to have the access to the user of the
# token as well as the token response.
token.update(us... | def save_token(token, request, *args, **kwargs) | Token persistence.
:param token: A dictionary with the token data.
:param request: The request instance.
:returns: A :class:`invenio_oauth2server.models.Token` instance. | 3.439395 | 3.384315 | 1.016275 |
if valid:
oauth.user.login_via_oauth2 = True
_request_ctx_stack.top.user = oauth.user
identity_changed.send(current_app._get_current_object(),
identity=Identity(oauth.user.id))
return valid, oauth | def login_oauth2_user(valid, oauth) | Log in a user after having been verified. | 3.526741 | 3.455696 | 1.020559 |
body = dict(
status=self.code,
message=self.description,
)
errors = self.get_errors()
if self.errors:
body['errors'] = errors
return json.dumps(body) | def get_body(self, environ=None) | Get the request body. | 3.914986 | 3.772991 | 1.037635 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.