code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def save(self):
"""Save/updates the user"""
import json
payload = {}
payload.update(self._store)
payload["user"] = payload["username"]
payload["passwd"] = payload["password"]
del(payload["username"])
del(payload["password"])
payload = json.dumps... | def function[save, parameter[self]]:
constant[Save/updates the user]
import module[json]
variable[payload] assign[=] dictionary[[], []]
call[name[payload].update, parameter[name[self]._store]]
call[name[payload]][constant[user]] assign[=] call[name[payload]][constant[username]]
... | keyword[def] identifier[save] ( identifier[self] ):
literal[string]
keyword[import] identifier[json]
identifier[payload] ={}
identifier[payload] . identifier[update] ( identifier[self] . identifier[_store] )
identifier[payload] [ literal[string] ]= identifier[payload]... | def save(self):
"""Save/updates the user"""
import json
payload = {}
payload.update(self._store)
payload['user'] = payload['username']
payload['passwd'] = payload['password']
del payload['username']
del payload['password']
payload = json.dumps(payload, default=str)
if not self.UR... |
def inc(self):
"""Get index for new entry."""
self.lock.acquire()
cur = self.counter
self.counter += 1
self.lock.release()
return cur | def function[inc, parameter[self]]:
constant[Get index for new entry.]
call[name[self].lock.acquire, parameter[]]
variable[cur] assign[=] name[self].counter
<ast.AugAssign object at 0x7da2054a5d50>
call[name[self].lock.release, parameter[]]
return[name[cur]] | keyword[def] identifier[inc] ( identifier[self] ):
literal[string]
identifier[self] . identifier[lock] . identifier[acquire] ()
identifier[cur] = identifier[self] . identifier[counter]
identifier[self] . identifier[counter] += literal[int]
identifier[self] . identifier[... | def inc(self):
"""Get index for new entry."""
self.lock.acquire()
cur = self.counter
self.counter += 1
self.lock.release()
return cur |
def insert(self, index: int, string: str) -> None:
"""Insert the given string before the specified index.
This method has the same effect as ``self[index:index] = string``;
it only avoids some condition checks as it rules out the possibility
of the key being an slice, or the need to shr... | def function[insert, parameter[self, index, string]]:
constant[Insert the given string before the specified index.
This method has the same effect as ``self[index:index] = string``;
it only avoids some condition checks as it rules out the possibility
of the key being an slice, or the ne... | keyword[def] identifier[insert] ( identifier[self] , identifier[index] : identifier[int] , identifier[string] : identifier[str] )-> keyword[None] :
literal[string]
identifier[ss] , identifier[se] = identifier[self] . identifier[_span]
identifier[lststr] = identifier[self] . identifier[_ls... | def insert(self, index: int, string: str) -> None:
"""Insert the given string before the specified index.
This method has the same effect as ``self[index:index] = string``;
it only avoids some condition checks as it rules out the possibility
of the key being an slice, or the need to shrink ... |
def start_group(self, scol, typ):
"""Start a new group"""
return Group(parent=self, level=scol, typ=typ) | def function[start_group, parameter[self, scol, typ]]:
constant[Start a new group]
return[call[name[Group], parameter[]]] | keyword[def] identifier[start_group] ( identifier[self] , identifier[scol] , identifier[typ] ):
literal[string]
keyword[return] identifier[Group] ( identifier[parent] = identifier[self] , identifier[level] = identifier[scol] , identifier[typ] = identifier[typ] ) | def start_group(self, scol, typ):
"""Start a new group"""
return Group(parent=self, level=scol, typ=typ) |
def ekacec(handle, segno, recno, column, nvals, cvals, isnull):
"""
Add data to a character column in a specified EK record.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ekacec_c.html
:param handle: EK file handle.
:type handle: int
:param segno: Index of segment containing record.
... | def function[ekacec, parameter[handle, segno, recno, column, nvals, cvals, isnull]]:
constant[
Add data to a character column in a specified EK record.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ekacec_c.html
:param handle: EK file handle.
:type handle: int
:param segno: Index... | keyword[def] identifier[ekacec] ( identifier[handle] , identifier[segno] , identifier[recno] , identifier[column] , identifier[nvals] , identifier[cvals] , identifier[isnull] ):
literal[string]
identifier[handle] = identifier[ctypes] . identifier[c_int] ( identifier[handle] )
identifier[segno] = ident... | def ekacec(handle, segno, recno, column, nvals, cvals, isnull):
"""
Add data to a character column in a specified EK record.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ekacec_c.html
:param handle: EK file handle.
:type handle: int
:param segno: Index of segment containing record.
... |
def upload_fail(message=None):
"""Return a upload failed response, for CKEditor >= 4.5.
For example::
from flask import send_from_directory
from flask_ckeditor import upload_success, upload_fail
app.config['CKEDITOR_FILE_UPLOADER'] = 'upload' # this value can be endpoint or ur... | def function[upload_fail, parameter[message]]:
constant[Return a upload failed response, for CKEditor >= 4.5.
For example::
from flask import send_from_directory
from flask_ckeditor import upload_success, upload_fail
app.config['CKEDITOR_FILE_UPLOADER'] = 'upload' # this v... | keyword[def] identifier[upload_fail] ( identifier[message] = keyword[None] ):
literal[string]
keyword[if] identifier[message] keyword[is] keyword[None] :
identifier[message] = identifier[current_app] . identifier[config] [ literal[string] ]
keyword[return] identifier[jsonify] ( identifier... | def upload_fail(message=None):
"""Return a upload failed response, for CKEditor >= 4.5.
For example::
from flask import send_from_directory
from flask_ckeditor import upload_success, upload_fail
app.config['CKEDITOR_FILE_UPLOADER'] = 'upload' # this value can be endpoint or ur... |
def remove(cls, id):
"""
Deletes an index with id
:param id string/document-handle
"""
api = Client.instance().api
api.index(id).delete() | def function[remove, parameter[cls, id]]:
constant[
Deletes an index with id
:param id string/document-handle
]
variable[api] assign[=] call[name[Client].instance, parameter[]].api
call[call[name[api].index, parameter[name[id]]].delete, parameter[]] | keyword[def] identifier[remove] ( identifier[cls] , identifier[id] ):
literal[string]
identifier[api] = identifier[Client] . identifier[instance] (). identifier[api]
identifier[api] . identifier[index] ( identifier[id] ). identifier[delete] () | def remove(cls, id):
"""
Deletes an index with id
:param id string/document-handle
"""
api = Client.instance().api
api.index(id).delete() |
def run(self, data_cb):
"""Run the event loop."""
if self._error:
err = self._error
if isinstance(self._error, KeyboardInterrupt):
# KeyboardInterrupt is not destructive(it may be used in
# the REPL).
# After throwing KeyboardInterr... | def function[run, parameter[self, data_cb]]:
constant[Run the event loop.]
if name[self]._error begin[:]
variable[err] assign[=] name[self]._error
if call[name[isinstance], parameter[name[self]._error, name[KeyboardInterrupt]]] begin[:]
name[self].... | keyword[def] identifier[run] ( identifier[self] , identifier[data_cb] ):
literal[string]
keyword[if] identifier[self] . identifier[_error] :
identifier[err] = identifier[self] . identifier[_error]
keyword[if] identifier[isinstance] ( identifier[self] . identifier[_error... | def run(self, data_cb):
"""Run the event loop."""
if self._error:
err = self._error
if isinstance(self._error, KeyboardInterrupt):
# KeyboardInterrupt is not destructive(it may be used in
# the REPL).
# After throwing KeyboardInterrupt, cleanup the _error fiel... |
def print_all(msg):
"""Print all objects.
Print a table of all active libvips objects. Handy for debugging.
"""
gc.collect()
logger.debug(msg)
vips_lib.vips_object_print_all()
logger.debug() | def function[print_all, parameter[msg]]:
constant[Print all objects.
Print a table of all active libvips objects. Handy for debugging.
]
call[name[gc].collect, parameter[]]
call[name[logger].debug, parameter[name[msg]]]
call[name[vips_lib].vips_object_print_all, paramet... | keyword[def] identifier[print_all] ( identifier[msg] ):
literal[string]
identifier[gc] . identifier[collect] ()
identifier[logger] . identifier[debug] ( identifier[msg] )
identifier[vips_lib] . identifier[vips_object_print_all] ()
identifier[logger] . identifier[debug] (... | def print_all(msg):
"""Print all objects.
Print a table of all active libvips objects. Handy for debugging.
"""
gc.collect()
logger.debug(msg)
vips_lib.vips_object_print_all()
logger.debug() |
def index(self, item):
"""
Return the 0-based position of `item` in this IpRange.
>>> r = IpRange('127.0.0.1', '127.255.255.255')
>>> r.index('127.0.0.1')
0
>>> r.index('127.255.255.255')
16777214
>>> r.index('10.0.0.1')
Traceback (most recent ca... | def function[index, parameter[self, item]]:
constant[
Return the 0-based position of `item` in this IpRange.
>>> r = IpRange('127.0.0.1', '127.255.255.255')
>>> r.index('127.0.0.1')
0
>>> r.index('127.255.255.255')
16777214
>>> r.index('10.0.0.1')
... | keyword[def] identifier[index] ( identifier[self] , identifier[item] ):
literal[string]
identifier[item] = identifier[self] . identifier[_cast] ( identifier[item] )
identifier[offset] = identifier[item] - identifier[self] . identifier[startIp]
keyword[if] identifier[offset] >= l... | def index(self, item):
"""
Return the 0-based position of `item` in this IpRange.
>>> r = IpRange('127.0.0.1', '127.255.255.255')
>>> r.index('127.0.0.1')
0
>>> r.index('127.255.255.255')
16777214
>>> r.index('10.0.0.1')
Traceback (most recent call l... |
def get_workflows():
"""Returns a mapping of id->workflow
"""
wftool = api.get_tool("portal_workflow")
wfs = {}
for wfid in wftool.objectIds():
wf = wftool.getWorkflowById(wfid)
if hasattr(aq_base(wf), "updateRoleMappingsFor"):
wfs[wfid] = wf
return wfs | def function[get_workflows, parameter[]]:
constant[Returns a mapping of id->workflow
]
variable[wftool] assign[=] call[name[api].get_tool, parameter[constant[portal_workflow]]]
variable[wfs] assign[=] dictionary[[], []]
for taget[name[wfid]] in starred[call[name[wftool].objectIds, pa... | keyword[def] identifier[get_workflows] ():
literal[string]
identifier[wftool] = identifier[api] . identifier[get_tool] ( literal[string] )
identifier[wfs] ={}
keyword[for] identifier[wfid] keyword[in] identifier[wftool] . identifier[objectIds] ():
identifier[wf] = identifier[wftool] .... | def get_workflows():
"""Returns a mapping of id->workflow
"""
wftool = api.get_tool('portal_workflow')
wfs = {}
for wfid in wftool.objectIds():
wf = wftool.getWorkflowById(wfid)
if hasattr(aq_base(wf), 'updateRoleMappingsFor'):
wfs[wfid] = wf # depends on [control=['if']... |
def matches(self, other):
"""Do a loose equivalency test suitable for comparing page names.
*other* can be any string-like object, including :class:`.Wikicode`, or
an iterable of these. This operation is symmetric; both sides are
adjusted. Specifically, whitespace and markup is stripped... | def function[matches, parameter[self, other]]:
constant[Do a loose equivalency test suitable for comparing page names.
*other* can be any string-like object, including :class:`.Wikicode`, or
an iterable of these. This operation is symmetric; both sides are
adjusted. Specifically, whites... | keyword[def] identifier[matches] ( identifier[self] , identifier[other] ):
literal[string]
identifier[cmp] = keyword[lambda] identifier[a] , identifier[b] :( identifier[a] [ literal[int] ]. identifier[upper] ()+ identifier[a] [ literal[int] :]== identifier[b] [ literal[int] ]. identifier[upper] ()... | def matches(self, other):
"""Do a loose equivalency test suitable for comparing page names.
*other* can be any string-like object, including :class:`.Wikicode`, or
an iterable of these. This operation is symmetric; both sides are
adjusted. Specifically, whitespace and markup is stripped and... |
def _save_payload(self, files, directories, links):
'''
Save payload (unmanaged files)
:param files:
:param directories:
:param links:
:return:
'''
idx = 0
for p_type, p_list in (('f', files), ('d', directories), ('l', links,),):
for ... | def function[_save_payload, parameter[self, files, directories, links]]:
constant[
Save payload (unmanaged files)
:param files:
:param directories:
:param links:
:return:
]
variable[idx] assign[=] constant[0]
for taget[tuple[[<ast.Name object at 0... | keyword[def] identifier[_save_payload] ( identifier[self] , identifier[files] , identifier[directories] , identifier[links] ):
literal[string]
identifier[idx] = literal[int]
keyword[for] identifier[p_type] , identifier[p_list] keyword[in] (( literal[string] , identifier[files] ),( lite... | def _save_payload(self, files, directories, links):
"""
Save payload (unmanaged files)
:param files:
:param directories:
:param links:
:return:
"""
idx = 0
for (p_type, p_list) in (('f', files), ('d', directories), ('l', links)):
for p_obj in p_list:
... |
def expand_filenames(self, filenames):
"""
Expand a list of filenames using environment variables,
followed by expansion of shell-style wildcards.
"""
results = []
for filename in filenames:
result = filename
if "$" in filename:
tem... | def function[expand_filenames, parameter[self, filenames]]:
constant[
Expand a list of filenames using environment variables,
followed by expansion of shell-style wildcards.
]
variable[results] assign[=] list[[]]
for taget[name[filename]] in starred[name[filenames]] begin... | keyword[def] identifier[expand_filenames] ( identifier[self] , identifier[filenames] ):
literal[string]
identifier[results] =[]
keyword[for] identifier[filename] keyword[in] identifier[filenames] :
identifier[result] = identifier[filename]
keyword[if] literal... | def expand_filenames(self, filenames):
"""
Expand a list of filenames using environment variables,
followed by expansion of shell-style wildcards.
"""
results = []
for filename in filenames:
result = filename
if '$' in filename:
template = Template(filenam... |
def require_prebuilt_dist(func):
"""Decorator for ToolchainCL methods. If present, the method will
automatically make sure a dist has been built before continuing
or, if no dists are present or can be obtained, will raise an
error.
"""
@wraps(func)
def wrapper_func(self, args):
ctx ... | def function[require_prebuilt_dist, parameter[func]]:
constant[Decorator for ToolchainCL methods. If present, the method will
automatically make sure a dist has been built before continuing
or, if no dists are present or can be obtained, will raise an
error.
]
def function[wrapper_func, ... | keyword[def] identifier[require_prebuilt_dist] ( identifier[func] ):
literal[string]
@ identifier[wraps] ( identifier[func] )
keyword[def] identifier[wrapper_func] ( identifier[self] , identifier[args] ):
identifier[ctx] = identifier[self] . identifier[ctx]
identifier[ctx] . identi... | def require_prebuilt_dist(func):
"""Decorator for ToolchainCL methods. If present, the method will
automatically make sure a dist has been built before continuing
or, if no dists are present or can be obtained, will raise an
error.
"""
@wraps(func)
def wrapper_func(self, args):
ctx ... |
def get_for_update(self, key):
"""
Locks the key and then gets and returns the value to which the specified key is mapped. Lock will be released at
the end of the transaction (either commit or rollback).
:param key: (object), the specified key.
:return: (object), the value for t... | def function[get_for_update, parameter[self, key]]:
constant[
Locks the key and then gets and returns the value to which the specified key is mapped. Lock will be released at
the end of the transaction (either commit or rollback).
:param key: (object), the specified key.
:return... | keyword[def] identifier[get_for_update] ( identifier[self] , identifier[key] ):
literal[string]
identifier[check_not_none] ( identifier[key] , literal[string] )
keyword[return] identifier[self] . identifier[_encode_invoke] ( identifier[transactional_map_get_for_update_codec] , identifier[... | def get_for_update(self, key):
"""
Locks the key and then gets and returns the value to which the specified key is mapped. Lock will be released at
the end of the transaction (either commit or rollback).
:param key: (object), the specified key.
:return: (object), the value for the s... |
def DeleteCronJob(self, cronjob_id):
"""Deletes a cronjob along with all its runs."""
if cronjob_id not in self.cronjobs:
raise db.UnknownCronJobError("Cron job %s not known." % cronjob_id)
del self.cronjobs[cronjob_id]
try:
del self.cronjob_leases[cronjob_id]
except KeyError:
pass... | def function[DeleteCronJob, parameter[self, cronjob_id]]:
constant[Deletes a cronjob along with all its runs.]
if compare[name[cronjob_id] <ast.NotIn object at 0x7da2590d7190> name[self].cronjobs] begin[:]
<ast.Raise object at 0x7da1b1d92770>
<ast.Delete object at 0x7da1b1d93f40>
<ast.Tr... | keyword[def] identifier[DeleteCronJob] ( identifier[self] , identifier[cronjob_id] ):
literal[string]
keyword[if] identifier[cronjob_id] keyword[not] keyword[in] identifier[self] . identifier[cronjobs] :
keyword[raise] identifier[db] . identifier[UnknownCronJobError] ( literal[string] % identif... | def DeleteCronJob(self, cronjob_id):
"""Deletes a cronjob along with all its runs."""
if cronjob_id not in self.cronjobs:
raise db.UnknownCronJobError('Cron job %s not known.' % cronjob_id) # depends on [control=['if'], data=['cronjob_id']]
del self.cronjobs[cronjob_id]
try:
del self.cr... |
def receive(self):
'''
Return the message received and the address.
'''
try:
msg = next(self.consumer)
except ValueError as error:
log.error('Received kafka error: %s', error, exc_info=True)
raise ListenerException(error)
log_source = m... | def function[receive, parameter[self]]:
constant[
Return the message received and the address.
]
<ast.Try object at 0x7da1b15f1600>
variable[log_source] assign[=] name[msg].key
<ast.Try object at 0x7da1b15f2620>
variable[log_message] assign[=] call[name[decoded].get, para... | keyword[def] identifier[receive] ( identifier[self] ):
literal[string]
keyword[try] :
identifier[msg] = identifier[next] ( identifier[self] . identifier[consumer] )
keyword[except] identifier[ValueError] keyword[as] identifier[error] :
identifier[log] . identif... | def receive(self):
"""
Return the message received and the address.
"""
try:
msg = next(self.consumer) # depends on [control=['try'], data=[]]
except ValueError as error:
log.error('Received kafka error: %s', error, exc_info=True)
raise ListenerException(error) # de... |
def inten(function):
"Decorator. Attempts to convert return value to int"
def wrapper(*args, **kwargs):
return coerce_to_int(function(*args, **kwargs))
return wrapper | def function[inten, parameter[function]]:
constant[Decorator. Attempts to convert return value to int]
def function[wrapper, parameter[]]:
return[call[name[coerce_to_int], parameter[call[name[function], parameter[<ast.Starred object at 0x7da18eb572b0>]]]]]
return[name[wrapper]] | keyword[def] identifier[inten] ( identifier[function] ):
literal[string]
keyword[def] identifier[wrapper] (* identifier[args] ,** identifier[kwargs] ):
keyword[return] identifier[coerce_to_int] ( identifier[function] (* identifier[args] ,** identifier[kwargs] ))
keyword[return] identifier[... | def inten(function):
"""Decorator. Attempts to convert return value to int"""
def wrapper(*args, **kwargs):
return coerce_to_int(function(*args, **kwargs))
return wrapper |
def lsof(name):
'''
Retrieve the lsof information of the given process name.
CLI Example:
.. code-block:: bash
salt '*' ps.lsof apache2
'''
sanitize_name = six.text_type(name)
lsof_infos = __salt__['cmd.run']("lsof -c " + sanitize_name)
ret = []
ret.extend([sanitize_name, ... | def function[lsof, parameter[name]]:
constant[
Retrieve the lsof information of the given process name.
CLI Example:
.. code-block:: bash
salt '*' ps.lsof apache2
]
variable[sanitize_name] assign[=] call[name[six].text_type, parameter[name[name]]]
variable[lsof_infos] ... | keyword[def] identifier[lsof] ( identifier[name] ):
literal[string]
identifier[sanitize_name] = identifier[six] . identifier[text_type] ( identifier[name] )
identifier[lsof_infos] = identifier[__salt__] [ literal[string] ]( literal[string] + identifier[sanitize_name] )
identifier[ret] =[]
id... | def lsof(name):
"""
Retrieve the lsof information of the given process name.
CLI Example:
.. code-block:: bash
salt '*' ps.lsof apache2
"""
sanitize_name = six.text_type(name)
lsof_infos = __salt__['cmd.run']('lsof -c ' + sanitize_name)
ret = []
ret.extend([sanitize_name, ... |
def subsets_of_fileinfo_from_txt(filename):
"""Returns a dictionary with subsets of FileInfo instances from a TXT file.
Each subset of files must be preceded by a line:
@ <number> <label>
where <number> indicates the number of files in that subset,
and <label> is a label for that subset. Any additi... | def function[subsets_of_fileinfo_from_txt, parameter[filename]]:
constant[Returns a dictionary with subsets of FileInfo instances from a TXT file.
Each subset of files must be preceded by a line:
@ <number> <label>
where <number> indicates the number of files in that subset,
and <label> is a la... | keyword[def] identifier[subsets_of_fileinfo_from_txt] ( identifier[filename] ):
literal[string]
keyword[if] keyword[not] identifier[os] . identifier[path] . identifier[isfile] ( identifier[filename] ):
keyword[raise] identifier[ValueError] ( literal[string] + identifier[filename] + litera... | def subsets_of_fileinfo_from_txt(filename):
"""Returns a dictionary with subsets of FileInfo instances from a TXT file.
Each subset of files must be preceded by a line:
@ <number> <label>
where <number> indicates the number of files in that subset,
and <label> is a label for that subset. Any additi... |
def mavlink_packet(self, m):
'''handle mavlink packets'''
if m.get_type() == 'GLOBAL_POSITION_INT':
if self.settings.target_system == 0 or self.settings.target_system == m.get_srcSystem():
self.packets_mytarget += 1
else:
self.packets_othertarget +... | def function[mavlink_packet, parameter[self, m]]:
constant[handle mavlink packets]
if compare[call[name[m].get_type, parameter[]] equal[==] constant[GLOBAL_POSITION_INT]] begin[:]
if <ast.BoolOp object at 0x7da2046238e0> begin[:]
<ast.AugAssign object at 0x7da204623010> | keyword[def] identifier[mavlink_packet] ( identifier[self] , identifier[m] ):
literal[string]
keyword[if] identifier[m] . identifier[get_type] ()== literal[string] :
keyword[if] identifier[self] . identifier[settings] . identifier[target_system] == literal[int] keyword[or] identifi... | def mavlink_packet(self, m):
"""handle mavlink packets"""
if m.get_type() == 'GLOBAL_POSITION_INT':
if self.settings.target_system == 0 or self.settings.target_system == m.get_srcSystem():
self.packets_mytarget += 1 # depends on [control=['if'], data=[]]
else:
self.packe... |
def switch(self, gen_mode:bool=None):
"Put the model in generator mode if `gen_mode`, in critic mode otherwise."
self.gen_mode = (not self.gen_mode) if gen_mode is None else gen_mode | def function[switch, parameter[self, gen_mode]]:
constant[Put the model in generator mode if `gen_mode`, in critic mode otherwise.]
name[self].gen_mode assign[=] <ast.IfExp object at 0x7da1b1e9b0a0> | keyword[def] identifier[switch] ( identifier[self] , identifier[gen_mode] : identifier[bool] = keyword[None] ):
literal[string]
identifier[self] . identifier[gen_mode] =( keyword[not] identifier[self] . identifier[gen_mode] ) keyword[if] identifier[gen_mode] keyword[is] keyword[None] keyword[e... | def switch(self, gen_mode: bool=None):
"""Put the model in generator mode if `gen_mode`, in critic mode otherwise."""
self.gen_mode = not self.gen_mode if gen_mode is None else gen_mode |
def normalize_parameters(params):
"""**Parameters Normalization**
Per `section 3.4.1.3.2`_ of the spec.
For example, the list of parameters from the previous section would
be normalized as follows:
Encoded::
+------------------------+------------------+
| Name | Va... | def function[normalize_parameters, parameter[params]]:
constant[**Parameters Normalization**
Per `section 3.4.1.3.2`_ of the spec.
For example, the list of parameters from the previous section would
be normalized as follows:
Encoded::
+------------------------+------------------+
| ... | keyword[def] identifier[normalize_parameters] ( identifier[params] ):
literal[string]
identifier[key_values] =[( identifier[utils] . identifier[escape] ( identifier[k] ), identifier[utils] . identifier[escape] ( identifier[v] )) keyword[for] identifier[k] , identi... | def normalize_parameters(params):
"""**Parameters Normalization**
Per `section 3.4.1.3.2`_ of the spec.
For example, the list of parameters from the previous section would
be normalized as follows:
Encoded::
+------------------------+------------------+
| Name | Va... |
def _create_container(context, path, l_mtime, size):
"""
Creates container for segments of file with `path`
"""
new_context = context.copy()
new_context.input_ = None
new_context.headers = None
new_context.query = None
container = path.split('/', 1)[0] + '_segments'
cli_put_container... | def function[_create_container, parameter[context, path, l_mtime, size]]:
constant[
Creates container for segments of file with `path`
]
variable[new_context] assign[=] call[name[context].copy, parameter[]]
name[new_context].input_ assign[=] constant[None]
name[new_context].heade... | keyword[def] identifier[_create_container] ( identifier[context] , identifier[path] , identifier[l_mtime] , identifier[size] ):
literal[string]
identifier[new_context] = identifier[context] . identifier[copy] ()
identifier[new_context] . identifier[input_] = keyword[None]
identifier[new_context]... | def _create_container(context, path, l_mtime, size):
"""
Creates container for segments of file with `path`
"""
new_context = context.copy()
new_context.input_ = None
new_context.headers = None
new_context.query = None
container = path.split('/', 1)[0] + '_segments'
cli_put_container... |
def backprop(self, **args):
"""
Computes error and wed for back propagation of error.
"""
retval = self.compute_error(**args)
if self.learning:
self.compute_wed()
return retval | def function[backprop, parameter[self]]:
constant[
Computes error and wed for back propagation of error.
]
variable[retval] assign[=] call[name[self].compute_error, parameter[]]
if name[self].learning begin[:]
call[name[self].compute_wed, parameter[]]
return[n... | keyword[def] identifier[backprop] ( identifier[self] ,** identifier[args] ):
literal[string]
identifier[retval] = identifier[self] . identifier[compute_error] (** identifier[args] )
keyword[if] identifier[self] . identifier[learning] :
identifier[self] . identifier[compute_we... | def backprop(self, **args):
"""
Computes error and wed for back propagation of error.
"""
retval = self.compute_error(**args)
if self.learning:
self.compute_wed() # depends on [control=['if'], data=[]]
return retval |
def mutate_file(backup, context):
"""
:type backup: bool
:type context: Context
"""
with open(context.filename) as f:
code = f.read()
context.source = code
if backup:
with open(context.filename + '.bak', 'w') as f:
f.write(code)
result, number_of_mutations_per... | def function[mutate_file, parameter[backup, context]]:
constant[
:type backup: bool
:type context: Context
]
with call[name[open], parameter[name[context].filename]] begin[:]
variable[code] assign[=] call[name[f].read, parameter[]]
name[context].source assign[=] name[... | keyword[def] identifier[mutate_file] ( identifier[backup] , identifier[context] ):
literal[string]
keyword[with] identifier[open] ( identifier[context] . identifier[filename] ) keyword[as] identifier[f] :
identifier[code] = identifier[f] . identifier[read] ()
identifier[context] . identifie... | def mutate_file(backup, context):
"""
:type backup: bool
:type context: Context
"""
with open(context.filename) as f:
code = f.read() # depends on [control=['with'], data=['f']]
context.source = code
if backup:
with open(context.filename + '.bak', 'w') as f:
f.wr... |
def makePlot(args):
"""
Make the plot with parallax horizons. The plot shows V-band magnitude vs distance for a number of
spectral types and over the range 5.7<G<20. In addition a set of crudely drawn contours show the points
where 0.1, 1, and 10 per cent relative parallax accracy are reached.
Parameters
-... | def function[makePlot, parameter[args]]:
constant[
Make the plot with parallax horizons. The plot shows V-band magnitude vs distance for a number of
spectral types and over the range 5.7<G<20. In addition a set of crudely drawn contours show the points
where 0.1, 1, and 10 per cent relative parallax accra... | keyword[def] identifier[makePlot] ( identifier[args] ):
literal[string]
identifier[distances] = literal[int] ** identifier[np] . identifier[linspace] ( literal[int] , literal[int] , literal[int] )
identifier[spts] =[ literal[string] , literal[string] , literal[string] , literal[string] , literal[string] , ... | def makePlot(args):
"""
Make the plot with parallax horizons. The plot shows V-band magnitude vs distance for a number of
spectral types and over the range 5.7<G<20. In addition a set of crudely drawn contours show the points
where 0.1, 1, and 10 per cent relative parallax accracy are reached.
Parameters
... |
def mv_voltage_deviation(network, voltage_levels='mv_lv'):
"""
Checks for voltage stability issues in MV grid.
Parameters
----------
network : :class:`~.grid.network.Network`
voltage_levels : :obj:`str`
Specifies which allowed voltage deviations to use. Possible options
are:
... | def function[mv_voltage_deviation, parameter[network, voltage_levels]]:
constant[
Checks for voltage stability issues in MV grid.
Parameters
----------
network : :class:`~.grid.network.Network`
voltage_levels : :obj:`str`
Specifies which allowed voltage deviations to use. Possible o... | keyword[def] identifier[mv_voltage_deviation] ( identifier[network] , identifier[voltage_levels] = literal[string] ):
literal[string]
identifier[crit_nodes] ={}
identifier[v_dev_allowed_per_case] ={}
identifier[v_dev_allowed_per_case] [ literal[string] ]= literal[int]
identifier[v_dev_all... | def mv_voltage_deviation(network, voltage_levels='mv_lv'):
"""
Checks for voltage stability issues in MV grid.
Parameters
----------
network : :class:`~.grid.network.Network`
voltage_levels : :obj:`str`
Specifies which allowed voltage deviations to use. Possible options
are:
... |
def data_orientation(self):
"""return a tuple of my permutated axes, non_indexable at the front"""
return tuple(itertools.chain([int(a[0]) for a in self.non_index_axes],
[int(a.axis) for a in self.index_axes])) | def function[data_orientation, parameter[self]]:
constant[return a tuple of my permutated axes, non_indexable at the front]
return[call[name[tuple], parameter[call[name[itertools].chain, parameter[<ast.ListComp object at 0x7da18bcca680>, <ast.ListComp object at 0x7da18bccbfa0>]]]]] | keyword[def] identifier[data_orientation] ( identifier[self] ):
literal[string]
keyword[return] identifier[tuple] ( identifier[itertools] . identifier[chain] ([ identifier[int] ( identifier[a] [ literal[int] ]) keyword[for] identifier[a] keyword[in] identifier[self] . identifier[non_index_axes]... | def data_orientation(self):
"""return a tuple of my permutated axes, non_indexable at the front"""
return tuple(itertools.chain([int(a[0]) for a in self.non_index_axes], [int(a.axis) for a in self.index_axes])) |
def get_subnets():
"""
:return: all knows subnets
"""
LOGGER.debug("SubnetService.get_subnets")
args = {'http_operation': 'GET', 'operation_path': ''}
response = SubnetService.requester.call(args)
ret = None
if response.rc == 0:
ret = []
... | def function[get_subnets, parameter[]]:
constant[
:return: all knows subnets
]
call[name[LOGGER].debug, parameter[constant[SubnetService.get_subnets]]]
variable[args] assign[=] dictionary[[<ast.Constant object at 0x7da1b1379600>, <ast.Constant object at 0x7da1b1379480>], [<ast.Co... | keyword[def] identifier[get_subnets] ():
literal[string]
identifier[LOGGER] . identifier[debug] ( literal[string] )
identifier[args] ={ literal[string] : literal[string] , literal[string] : literal[string] }
identifier[response] = identifier[SubnetService] . identifier[requester] ... | def get_subnets():
"""
:return: all knows subnets
"""
LOGGER.debug('SubnetService.get_subnets')
args = {'http_operation': 'GET', 'operation_path': ''}
response = SubnetService.requester.call(args)
ret = None
if response.rc == 0:
ret = []
for subnet in response.res... |
def create_engine(url, con=None, header=True, show_progress=5.0, clear_progress=True):
'''Create a handler for query engine based on a URL.
The following environment variables are used for default connection:
TD_API_KEY API key
TD_API_SERVER API server (default: api.treasuredata.com)
HT... | def function[create_engine, parameter[url, con, header, show_progress, clear_progress]]:
constant[Create a handler for query engine based on a URL.
The following environment variables are used for default connection:
TD_API_KEY API key
TD_API_SERVER API server (default: api.treasuredata.c... | keyword[def] identifier[create_engine] ( identifier[url] , identifier[con] = keyword[None] , identifier[header] = keyword[True] , identifier[show_progress] = literal[int] , identifier[clear_progress] = keyword[True] ):
literal[string]
identifier[url] = identifier[urlparse] ( identifier[url] )
identifi... | def create_engine(url, con=None, header=True, show_progress=5.0, clear_progress=True):
"""Create a handler for query engine based on a URL.
The following environment variables are used for default connection:
TD_API_KEY API key
TD_API_SERVER API server (default: api.treasuredata.com)
HT... |
def name(self, src=None):
"""Return string representing the name of this type."""
res = [_get_type_name(tt, src) for tt in self._types]
if len(res) == 2 and "None" in res:
res.remove("None")
return "?" + res[0]
else:
return " | ".join(res) | def function[name, parameter[self, src]]:
constant[Return string representing the name of this type.]
variable[res] assign[=] <ast.ListComp object at 0x7da1b03b9f30>
if <ast.BoolOp object at 0x7da1b03ba6e0> begin[:]
call[name[res].remove, parameter[constant[None]]]
return... | keyword[def] identifier[name] ( identifier[self] , identifier[src] = keyword[None] ):
literal[string]
identifier[res] =[ identifier[_get_type_name] ( identifier[tt] , identifier[src] ) keyword[for] identifier[tt] keyword[in] identifier[self] . identifier[_types] ]
keyword[if] identifie... | def name(self, src=None):
"""Return string representing the name of this type."""
res = [_get_type_name(tt, src) for tt in self._types]
if len(res) == 2 and 'None' in res:
res.remove('None')
return '?' + res[0] # depends on [control=['if'], data=[]]
else:
return ' | '.join(res) |
def track_event(self, name: str, properties: Dict[str, object] = None,
measurements: Dict[str, object] = None) -> None:
"""
Send information about a single event that has occurred in the context of the application.
:param name: the data to associate to this event.
:... | def function[track_event, parameter[self, name, properties, measurements]]:
constant[
Send information about a single event that has occurred in the context of the application.
:param name: the data to associate to this event.
:param properties: the set of custom properties the client w... | keyword[def] identifier[track_event] ( identifier[self] , identifier[name] : identifier[str] , identifier[properties] : identifier[Dict] [ identifier[str] , identifier[object] ]= keyword[None] ,
identifier[measurements] : identifier[Dict] [ identifier[str] , identifier[object] ]= keyword[None] )-> keyword[None] :
... | def track_event(self, name: str, properties: Dict[str, object]=None, measurements: Dict[str, object]=None) -> None:
"""
Send information about a single event that has occurred in the context of the application.
:param name: the data to associate to this event.
:param properties: the set of ... |
def add_proof(self, certificate_metadata, merkle_proof):
"""
:param certificate_metadata:
:param merkle_proof:
:return:
"""
certificate_json = self._get_certificate_to_issue(certificate_metadata)
certificate_json['signature'] = merkle_proof
with open(cert... | def function[add_proof, parameter[self, certificate_metadata, merkle_proof]]:
constant[
:param certificate_metadata:
:param merkle_proof:
:return:
]
variable[certificate_json] assign[=] call[name[self]._get_certificate_to_issue, parameter[name[certificate_metadata]]]
... | keyword[def] identifier[add_proof] ( identifier[self] , identifier[certificate_metadata] , identifier[merkle_proof] ):
literal[string]
identifier[certificate_json] = identifier[self] . identifier[_get_certificate_to_issue] ( identifier[certificate_metadata] )
identifier[certificate_json] [... | def add_proof(self, certificate_metadata, merkle_proof):
"""
:param certificate_metadata:
:param merkle_proof:
:return:
"""
certificate_json = self._get_certificate_to_issue(certificate_metadata)
certificate_json['signature'] = merkle_proof
with open(certificate_metadata.... |
def fetch(self, resource_class):
"""Construct a :class:`.Request` for the given resource type.
Provided an :class:`.Entry` subclass, the Content Type ID will be inferred and requested explicitly.
Examples::
client.fetch(Asset)
client.fetch(Entry)
client.fet... | def function[fetch, parameter[self, resource_class]]:
constant[Construct a :class:`.Request` for the given resource type.
Provided an :class:`.Entry` subclass, the Content Type ID will be inferred and requested explicitly.
Examples::
client.fetch(Asset)
client.fetch(En... | keyword[def] identifier[fetch] ( identifier[self] , identifier[resource_class] ):
literal[string]
keyword[if] identifier[issubclass] ( identifier[resource_class] , identifier[Entry] ):
identifier[params] = keyword[None]
identifier[content_type] = identifier[getattr] ( id... | def fetch(self, resource_class):
"""Construct a :class:`.Request` for the given resource type.
Provided an :class:`.Entry` subclass, the Content Type ID will be inferred and requested explicitly.
Examples::
client.fetch(Asset)
client.fetch(Entry)
client.fetch(C... |
def parse_byteranges(cls, environ):
"""
Outputs a list of tuples with ranges or the empty list
According to the rfc, start or end values can be omitted
"""
r = []
s = environ.get(cls.header_range, '').replace(' ','').lower()
if s:
l = s.split('=')
... | def function[parse_byteranges, parameter[cls, environ]]:
constant[
Outputs a list of tuples with ranges or the empty list
According to the rfc, start or end values can be omitted
]
variable[r] assign[=] list[[]]
variable[s] assign[=] call[call[call[name[environ].get, para... | keyword[def] identifier[parse_byteranges] ( identifier[cls] , identifier[environ] ):
literal[string]
identifier[r] =[]
identifier[s] = identifier[environ] . identifier[get] ( identifier[cls] . identifier[header_range] , literal[string] ). identifier[replace] ( literal[string] , literal[str... | def parse_byteranges(cls, environ):
"""
Outputs a list of tuples with ranges or the empty list
According to the rfc, start or end values can be omitted
"""
r = []
s = environ.get(cls.header_range, '').replace(' ', '').lower()
if s:
l = s.split('=')
if len(l) == 2:... |
def borrow_optimizer(self, shared_module):
"""Borrows optimizer from a shared module. Used in bucketing, where exactly the same
optimizer (esp. kvstore) is used.
Parameters
----------
shared_module : Module
"""
assert shared_module.optimizer_initialized
s... | def function[borrow_optimizer, parameter[self, shared_module]]:
constant[Borrows optimizer from a shared module. Used in bucketing, where exactly the same
optimizer (esp. kvstore) is used.
Parameters
----------
shared_module : Module
]
assert[name[shared_module].opti... | keyword[def] identifier[borrow_optimizer] ( identifier[self] , identifier[shared_module] ):
literal[string]
keyword[assert] identifier[shared_module] . identifier[optimizer_initialized]
identifier[self] . identifier[_optimizer] = identifier[shared_module] . identifier[_optimizer]
... | def borrow_optimizer(self, shared_module):
"""Borrows optimizer from a shared module. Used in bucketing, where exactly the same
optimizer (esp. kvstore) is used.
Parameters
----------
shared_module : Module
"""
assert shared_module.optimizer_initialized
self._optimiz... |
def _put_overlay(self, overlay_name, overlay):
"""Store overlay so that it is accessible by the given name.
:param overlay_name: name of the overlay
:param overlay: overlay must be a dictionary where the keys are
identifiers in the dataset
:raises: TypeError if t... | def function[_put_overlay, parameter[self, overlay_name, overlay]]:
constant[Store overlay so that it is accessible by the given name.
:param overlay_name: name of the overlay
:param overlay: overlay must be a dictionary where the keys are
identifiers in the dataset
... | keyword[def] identifier[_put_overlay] ( identifier[self] , identifier[overlay_name] , identifier[overlay] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[overlay] , identifier[dict] ):
keyword[raise] identifier[TypeError] ( literal[string] )
... | def _put_overlay(self, overlay_name, overlay):
"""Store overlay so that it is accessible by the given name.
:param overlay_name: name of the overlay
:param overlay: overlay must be a dictionary where the keys are
identifiers in the dataset
:raises: TypeError if the o... |
def bandwidth(self, subid, params=None):
''' /v1/server/bandwidth
GET - account
Get the bandwidth used by a virtual machine
Link: https://www.vultr.com/api/#server_bandwidth
'''
params = update_params(params, {'SUBID': subid})
return self.request('/v1/server/band... | def function[bandwidth, parameter[self, subid, params]]:
constant[ /v1/server/bandwidth
GET - account
Get the bandwidth used by a virtual machine
Link: https://www.vultr.com/api/#server_bandwidth
]
variable[params] assign[=] call[name[update_params], parameter[name[param... | keyword[def] identifier[bandwidth] ( identifier[self] , identifier[subid] , identifier[params] = keyword[None] ):
literal[string]
identifier[params] = identifier[update_params] ( identifier[params] ,{ literal[string] : identifier[subid] })
keyword[return] identifier[self] . identifier[req... | def bandwidth(self, subid, params=None):
""" /v1/server/bandwidth
GET - account
Get the bandwidth used by a virtual machine
Link: https://www.vultr.com/api/#server_bandwidth
"""
params = update_params(params, {'SUBID': subid})
return self.request('/v1/server/bandwidth', para... |
def _generate_main_scripts(self):
"""
Include the scripts used by solutions.
"""
head = self.parser.find('head').first_result()
if head is not None:
common_functions_script = self.parser.find(
'#'
+ AccessibleEventImplementation.ID_SCR... | def function[_generate_main_scripts, parameter[self]]:
constant[
Include the scripts used by solutions.
]
variable[head] assign[=] call[call[name[self].parser.find, parameter[constant[head]]].first_result, parameter[]]
if compare[name[head] is_not constant[None]] begin[:]
... | keyword[def] identifier[_generate_main_scripts] ( identifier[self] ):
literal[string]
identifier[head] = identifier[self] . identifier[parser] . identifier[find] ( literal[string] ). identifier[first_result] ()
keyword[if] identifier[head] keyword[is] keyword[not] keyword[None] :
... | def _generate_main_scripts(self):
"""
Include the scripts used by solutions.
"""
head = self.parser.find('head').first_result()
if head is not None:
common_functions_script = self.parser.find('#' + AccessibleEventImplementation.ID_SCRIPT_COMMON_FUNCTIONS).first_result()
if co... |
def visit_repr(self, node, parent):
"""visit a Backquote node by returning a fresh instance of it"""
newnode = nodes.Repr(node.lineno, node.col_offset, parent)
newnode.postinit(self.visit(node.value, newnode))
return newnode | def function[visit_repr, parameter[self, node, parent]]:
constant[visit a Backquote node by returning a fresh instance of it]
variable[newnode] assign[=] call[name[nodes].Repr, parameter[name[node].lineno, name[node].col_offset, name[parent]]]
call[name[newnode].postinit, parameter[call[name[sel... | keyword[def] identifier[visit_repr] ( identifier[self] , identifier[node] , identifier[parent] ):
literal[string]
identifier[newnode] = identifier[nodes] . identifier[Repr] ( identifier[node] . identifier[lineno] , identifier[node] . identifier[col_offset] , identifier[parent] )
identifier... | def visit_repr(self, node, parent):
"""visit a Backquote node by returning a fresh instance of it"""
newnode = nodes.Repr(node.lineno, node.col_offset, parent)
newnode.postinit(self.visit(node.value, newnode))
return newnode |
def zlib_compress(data):
"""
Compress things in a py2/3 safe fashion
>>> json_str = '{"test": 1}'
>>> blob = zlib_compress(json_str)
"""
if PY3K:
if isinstance(data, str):
return zlib.compress(bytes(data, 'utf-8'))
return zlib.compress(data)
return zlib.compress(d... | def function[zlib_compress, parameter[data]]:
constant[
Compress things in a py2/3 safe fashion
>>> json_str = '{"test": 1}'
>>> blob = zlib_compress(json_str)
]
if name[PY3K] begin[:]
if call[name[isinstance], parameter[name[data], name[str]]] begin[:]
return... | keyword[def] identifier[zlib_compress] ( identifier[data] ):
literal[string]
keyword[if] identifier[PY3K] :
keyword[if] identifier[isinstance] ( identifier[data] , identifier[str] ):
keyword[return] identifier[zlib] . identifier[compress] ( identifier[bytes] ( identifier[data] , li... | def zlib_compress(data):
"""
Compress things in a py2/3 safe fashion
>>> json_str = '{"test": 1}'
>>> blob = zlib_compress(json_str)
"""
if PY3K:
if isinstance(data, str):
return zlib.compress(bytes(data, 'utf-8')) # depends on [control=['if'], data=[]]
return zlib.c... |
def to_dict(obj, **kwargs):
"""
Convert an object into dictionary. Uses singledispatch to allow for
clean extensions for custom class types.
Reference: https://pypi.python.org/pypi/singledispatch
:param obj: object instance
:param kwargs: keyword arguments such as suppress_private_attr,
... | def function[to_dict, parameter[obj]]:
constant[
Convert an object into dictionary. Uses singledispatch to allow for
clean extensions for custom class types.
Reference: https://pypi.python.org/pypi/singledispatch
:param obj: object instance
:param kwargs: keyword arguments such as suppress... | keyword[def] identifier[to_dict] ( identifier[obj] ,** identifier[kwargs] ):
literal[string]
keyword[if] identifier[is_model] ( identifier[obj] . identifier[__class__] ):
keyword[return] identifier[related_obj_to_dict] ( identifier[obj] ,** identifier[kwargs] )
keyw... | def to_dict(obj, **kwargs):
"""
Convert an object into dictionary. Uses singledispatch to allow for
clean extensions for custom class types.
Reference: https://pypi.python.org/pypi/singledispatch
:param obj: object instance
:param kwargs: keyword arguments such as suppress_private_attr,
... |
def pre_save(self, model_instance, add):
"""Updates socket.gethostname() on each save."""
value = socket.gethostname()
setattr(model_instance, self.attname, value)
return value | def function[pre_save, parameter[self, model_instance, add]]:
constant[Updates socket.gethostname() on each save.]
variable[value] assign[=] call[name[socket].gethostname, parameter[]]
call[name[setattr], parameter[name[model_instance], name[self].attname, name[value]]]
return[name[value]] | keyword[def] identifier[pre_save] ( identifier[self] , identifier[model_instance] , identifier[add] ):
literal[string]
identifier[value] = identifier[socket] . identifier[gethostname] ()
identifier[setattr] ( identifier[model_instance] , identifier[self] . identifier[attname] , identifier[... | def pre_save(self, model_instance, add):
"""Updates socket.gethostname() on each save."""
value = socket.gethostname()
setattr(model_instance, self.attname, value)
return value |
def _contextkey(jail=None, chroot=None, root=None, prefix='pkg.list_pkgs'):
'''
As this module is designed to manipulate packages in jails and chroots, use
the passed jail/chroot to ensure that a key in the __context__ dict that is
unique to that jail/chroot is used.
'''
if jail:
return ... | def function[_contextkey, parameter[jail, chroot, root, prefix]]:
constant[
As this module is designed to manipulate packages in jails and chroots, use
the passed jail/chroot to ensure that a key in the __context__ dict that is
unique to that jail/chroot is used.
]
if name[jail] begin[:]... | keyword[def] identifier[_contextkey] ( identifier[jail] = keyword[None] , identifier[chroot] = keyword[None] , identifier[root] = keyword[None] , identifier[prefix] = literal[string] ):
literal[string]
keyword[if] identifier[jail] :
keyword[return] identifier[six] . identifier[text_type] ( ident... | def _contextkey(jail=None, chroot=None, root=None, prefix='pkg.list_pkgs'):
"""
As this module is designed to manipulate packages in jails and chroots, use
the passed jail/chroot to ensure that a key in the __context__ dict that is
unique to that jail/chroot is used.
"""
if jail:
return ... |
def add(self, registry):
""" Add works like replace, but only previously pushed metrics with the
same name (and the same job and instance) will be replaced.
(It uses HTTP method 'POST' to push to the Pushgateway.)
"""
# POST
payload = self.formatter.marshall(regis... | def function[add, parameter[self, registry]]:
constant[ Add works like replace, but only previously pushed metrics with the
same name (and the same job and instance) will be replaced.
(It uses HTTP method 'POST' to push to the Pushgateway.)
]
variable[payload] assign[=] c... | keyword[def] identifier[add] ( identifier[self] , identifier[registry] ):
literal[string]
identifier[payload] = identifier[self] . identifier[formatter] . identifier[marshall] ( identifier[registry] )
identifier[r] = identifier[requests] . identifier[post] ( identifier[self] . ide... | def add(self, registry):
""" Add works like replace, but only previously pushed metrics with the
same name (and the same job and instance) will be replaced.
(It uses HTTP method 'POST' to push to the Pushgateway.)
"""
# POST
payload = self.formatter.marshall(registry)
r =... |
def set_angle_limit(self, limit_for_id, **kwargs):
""" Sets the angle limit to the specified motors. """
convert = kwargs['convert'] if 'convert' in kwargs else self._convert
if 'wheel' in self.get_control_mode(limit_for_id.keys()):
raise ValueError('can not change the angle limit o... | def function[set_angle_limit, parameter[self, limit_for_id]]:
constant[ Sets the angle limit to the specified motors. ]
variable[convert] assign[=] <ast.IfExp object at 0x7da1b14c5cf0>
if compare[constant[wheel] in call[name[self].get_control_mode, parameter[call[name[limit_for_id].keys, paramet... | keyword[def] identifier[set_angle_limit] ( identifier[self] , identifier[limit_for_id] ,** identifier[kwargs] ):
literal[string]
identifier[convert] = identifier[kwargs] [ literal[string] ] keyword[if] literal[string] keyword[in] identifier[kwargs] keyword[else] identifier[self] . identifier[_... | def set_angle_limit(self, limit_for_id, **kwargs):
""" Sets the angle limit to the specified motors. """
convert = kwargs['convert'] if 'convert' in kwargs else self._convert
if 'wheel' in self.get_control_mode(limit_for_id.keys()):
raise ValueError('can not change the angle limit of a motor in whee... |
def get_applications(self, states=None, name=None, user=None, queue=None,
started_begin=None, started_end=None,
finished_begin=None, finished_end=None):
"""Get the status of current skein applications.
Parameters
----------
states : sequ... | def function[get_applications, parameter[self, states, name, user, queue, started_begin, started_end, finished_begin, finished_end]]:
constant[Get the status of current skein applications.
Parameters
----------
states : sequence of ApplicationState, optional
If provided, app... | keyword[def] identifier[get_applications] ( identifier[self] , identifier[states] = keyword[None] , identifier[name] = keyword[None] , identifier[user] = keyword[None] , identifier[queue] = keyword[None] ,
identifier[started_begin] = keyword[None] , identifier[started_end] = keyword[None] ,
identifier[finished_begi... | def get_applications(self, states=None, name=None, user=None, queue=None, started_begin=None, started_end=None, finished_begin=None, finished_end=None):
"""Get the status of current skein applications.
Parameters
----------
states : sequence of ApplicationState, optional
If prov... |
def extract_run_id(key):
"""Extract date part from run id
Arguments:
key - full key name, such as shredded-archive/run=2012-12-11-01-31-33/
(trailing slash is required)
>>> extract_run_id('shredded-archive/run=2012-12-11-01-11-33/')
'shredded-archive/run=2012-12-11-01-11-33/'
>>> ext... | def function[extract_run_id, parameter[key]]:
constant[Extract date part from run id
Arguments:
key - full key name, such as shredded-archive/run=2012-12-11-01-31-33/
(trailing slash is required)
>>> extract_run_id('shredded-archive/run=2012-12-11-01-11-33/')
'shredded-archive/run=20... | keyword[def] identifier[extract_run_id] ( identifier[key] ):
literal[string]
identifier[filename] = identifier[key] . identifier[split] ( literal[string] )[- literal[int] ]
identifier[run_id] = identifier[filename] . identifier[lstrip] ( literal[string] )
keyword[try] :
identifier[dateti... | def extract_run_id(key):
"""Extract date part from run id
Arguments:
key - full key name, such as shredded-archive/run=2012-12-11-01-31-33/
(trailing slash is required)
>>> extract_run_id('shredded-archive/run=2012-12-11-01-11-33/')
'shredded-archive/run=2012-12-11-01-11-33/'
>>> ext... |
def languages2marc(self, key, value):
"""Populate the ``041`` MARC field."""
return {'a': pycountry.languages.get(alpha_2=value).name.lower()} | def function[languages2marc, parameter[self, key, value]]:
constant[Populate the ``041`` MARC field.]
return[dictionary[[<ast.Constant object at 0x7da2041dbf40>], [<ast.Call object at 0x7da2041d8310>]]] | keyword[def] identifier[languages2marc] ( identifier[self] , identifier[key] , identifier[value] ):
literal[string]
keyword[return] { literal[string] : identifier[pycountry] . identifier[languages] . identifier[get] ( identifier[alpha_2] = identifier[value] ). identifier[name] . identifier[lower] ()} | def languages2marc(self, key, value):
"""Populate the ``041`` MARC field."""
return {'a': pycountry.languages.get(alpha_2=value).name.lower()} |
def _tree_store_sub_branch(self, traj_node, branch_name,
store_data=pypetconstants.STORE_DATA,
with_links=True,
recursive=False,
max_depth=None,
hdf5_group=None):
... | def function[_tree_store_sub_branch, parameter[self, traj_node, branch_name, store_data, with_links, recursive, max_depth, hdf5_group]]:
constant[Stores data starting from a node along a branch and starts recursively loading
all data at end of branch.
:param traj_node: The node where storing st... | keyword[def] identifier[_tree_store_sub_branch] ( identifier[self] , identifier[traj_node] , identifier[branch_name] ,
identifier[store_data] = identifier[pypetconstants] . identifier[STORE_DATA] ,
identifier[with_links] = keyword[True] ,
identifier[recursive] = keyword[False] ,
identifier[max_depth] = keyword[No... | def _tree_store_sub_branch(self, traj_node, branch_name, store_data=pypetconstants.STORE_DATA, with_links=True, recursive=False, max_depth=None, hdf5_group=None):
"""Stores data starting from a node along a branch and starts recursively loading
all data at end of branch.
:param traj_node: The node ... |
def make_confidence_report_bundled(filepath, train_start=TRAIN_START,
train_end=TRAIN_END, test_start=TEST_START,
test_end=TEST_END, which_set=WHICH_SET,
recipe=RECIPE, report_path=REPORT_PATH,
... | def function[make_confidence_report_bundled, parameter[filepath, train_start, train_end, test_start, test_end, which_set, recipe, report_path, nb_iter, base_eps, base_eps_iter, base_eps_iter_small, batch_size]]:
constant[
Load a saved model, gather its predictions, and save a confidence report.
:param filep... | keyword[def] identifier[make_confidence_report_bundled] ( identifier[filepath] , identifier[train_start] = identifier[TRAIN_START] ,
identifier[train_end] = identifier[TRAIN_END] , identifier[test_start] = identifier[TEST_START] ,
identifier[test_end] = identifier[TEST_END] , identifier[which_set] = identifier[WHIC... | def make_confidence_report_bundled(filepath, train_start=TRAIN_START, train_end=TRAIN_END, test_start=TEST_START, test_end=TEST_END, which_set=WHICH_SET, recipe=RECIPE, report_path=REPORT_PATH, nb_iter=NB_ITER, base_eps=None, base_eps_iter=None, base_eps_iter_small=None, batch_size=BATCH_SIZE):
"""
Load a saved m... |
def clean(self):
"""
Validate that an event with this name on this date does not exist.
"""
cleaned = super(EventForm, self).clean()
if Event.objects.filter(name=cleaned['name'], start_date=cleaned['start_date']).count():
raise forms.ValidationError(u'This event appea... | def function[clean, parameter[self]]:
constant[
Validate that an event with this name on this date does not exist.
]
variable[cleaned] assign[=] call[call[name[super], parameter[name[EventForm], name[self]]].clean, parameter[]]
if call[call[name[Event].objects.filter, parameter[]... | keyword[def] identifier[clean] ( identifier[self] ):
literal[string]
identifier[cleaned] = identifier[super] ( identifier[EventForm] , identifier[self] ). identifier[clean] ()
keyword[if] identifier[Event] . identifier[objects] . identifier[filter] ( identifier[name] = identifier[cleaned]... | def clean(self):
"""
Validate that an event with this name on this date does not exist.
"""
cleaned = super(EventForm, self).clean()
if Event.objects.filter(name=cleaned['name'], start_date=cleaned['start_date']).count():
raise forms.ValidationError(u'This event appears to be in the ... |
def xorsum(t):
"""
异或校验
:param t:
:type t:
:return:
:rtype:
"""
_b = t[0]
for i in t[1:]:
_b = _b ^ i
_b &= 0xff
return _b | def function[xorsum, parameter[t]]:
constant[
异或校验
:param t:
:type t:
:return:
:rtype:
]
variable[_b] assign[=] call[name[t]][constant[0]]
for taget[name[i]] in starred[call[name[t]][<ast.Slice object at 0x7da1b158a3b0>]] begin[:]
variable[_b] assign[=] bi... | keyword[def] identifier[xorsum] ( identifier[t] ):
literal[string]
identifier[_b] = identifier[t] [ literal[int] ]
keyword[for] identifier[i] keyword[in] identifier[t] [ literal[int] :]:
identifier[_b] = identifier[_b] ^ identifier[i]
identifier[_b] &= literal[int]
keyword[... | def xorsum(t):
"""
异或校验
:param t:
:type t:
:return:
:rtype:
"""
_b = t[0]
for i in t[1:]:
_b = _b ^ i
_b &= 255 # depends on [control=['for'], data=['i']]
return _b |
def any_user(password=None, permissions=[], groups=[], **kwargs):
"""
Shortcut for creating Users
Permissions could be a list of permission names
If not specified, creates active, non superuser
and non staff user
"""
is_active = kwargs.pop('is_active', True)
is_superuser = kwargs.pop... | def function[any_user, parameter[password, permissions, groups]]:
constant[
Shortcut for creating Users
Permissions could be a list of permission names
If not specified, creates active, non superuser
and non staff user
]
variable[is_active] assign[=] call[name[kwargs].pop, paramet... | keyword[def] identifier[any_user] ( identifier[password] = keyword[None] , identifier[permissions] =[], identifier[groups] =[],** identifier[kwargs] ):
literal[string]
identifier[is_active] = identifier[kwargs] . identifier[pop] ( literal[string] , keyword[True] )
identifier[is_superuser] = identifie... | def any_user(password=None, permissions=[], groups=[], **kwargs):
"""
Shortcut for creating Users
Permissions could be a list of permission names
If not specified, creates active, non superuser
and non staff user
"""
is_active = kwargs.pop('is_active', True)
is_superuser = kwargs.pop(... |
def spline_interpolate(x1, y1, x2):
"""
Given a function at a set of points (x1, y1), interpolate to
evaluate it at points x2.
"""
sp = Spline(x1, y1)
return sp(x2) | def function[spline_interpolate, parameter[x1, y1, x2]]:
constant[
Given a function at a set of points (x1, y1), interpolate to
evaluate it at points x2.
]
variable[sp] assign[=] call[name[Spline], parameter[name[x1], name[y1]]]
return[call[name[sp], parameter[name[x2]]]] | keyword[def] identifier[spline_interpolate] ( identifier[x1] , identifier[y1] , identifier[x2] ):
literal[string]
identifier[sp] = identifier[Spline] ( identifier[x1] , identifier[y1] )
keyword[return] identifier[sp] ( identifier[x2] ) | def spline_interpolate(x1, y1, x2):
"""
Given a function at a set of points (x1, y1), interpolate to
evaluate it at points x2.
"""
sp = Spline(x1, y1)
return sp(x2) |
def choose_path():
"""
Invoke a folder selection dialog here
:return:
"""
dirs = webview.create_file_dialog(webview.FOLDER_DIALOG)
if dirs and len(dirs) > 0:
directory = dirs[0]
if isinstance(directory, bytes):
directory = directory.decode("utf-8")
response =... | def function[choose_path, parameter[]]:
constant[
Invoke a folder selection dialog here
:return:
]
variable[dirs] assign[=] call[name[webview].create_file_dialog, parameter[name[webview].FOLDER_DIALOG]]
if <ast.BoolOp object at 0x7da18f723400> begin[:]
variable[direct... | keyword[def] identifier[choose_path] ():
literal[string]
identifier[dirs] = identifier[webview] . identifier[create_file_dialog] ( identifier[webview] . identifier[FOLDER_DIALOG] )
keyword[if] identifier[dirs] keyword[and] identifier[len] ( identifier[dirs] )> literal[int] :
identifier[dir... | def choose_path():
"""
Invoke a folder selection dialog here
:return:
"""
dirs = webview.create_file_dialog(webview.FOLDER_DIALOG)
if dirs and len(dirs) > 0:
directory = dirs[0]
if isinstance(directory, bytes):
directory = directory.decode('utf-8') # depends on [cont... |
def nodes_iter(self, t=None, data=False):
"""Return an iterator over the nodes with respect to a given temporal snapshot.
Parameters
----------
t : snapshot id (default=None).
If None the iterator returns all the nodes of the flattened graph.
data : boolean, optional... | def function[nodes_iter, parameter[self, t, data]]:
constant[Return an iterator over the nodes with respect to a given temporal snapshot.
Parameters
----------
t : snapshot id (default=None).
If None the iterator returns all the nodes of the flattened graph.
data : b... | keyword[def] identifier[nodes_iter] ( identifier[self] , identifier[t] = keyword[None] , identifier[data] = keyword[False] ):
literal[string]
keyword[if] identifier[t] keyword[is] keyword[not] keyword[None] :
keyword[return] identifier[iter] ([ identifier[n] keyword[for] identif... | def nodes_iter(self, t=None, data=False):
"""Return an iterator over the nodes with respect to a given temporal snapshot.
Parameters
----------
t : snapshot id (default=None).
If None the iterator returns all the nodes of the flattened graph.
data : boolean, optional (de... |
def resolve_one_step(self):
"""
Resolves model references.
"""
metamodel = self.parser.metamodel
current_crossrefs = self.parser._crossrefs
# print("DEBUG: Current crossrefs #: {}".
# format(len(current_crossrefs)))
new_crossrefs = []
self.de... | def function[resolve_one_step, parameter[self]]:
constant[
Resolves model references.
]
variable[metamodel] assign[=] name[self].parser.metamodel
variable[current_crossrefs] assign[=] name[self].parser._crossrefs
variable[new_crossrefs] assign[=] list[[]]
name[sel... | keyword[def] identifier[resolve_one_step] ( identifier[self] ):
literal[string]
identifier[metamodel] = identifier[self] . identifier[parser] . identifier[metamodel]
identifier[current_crossrefs] = identifier[self] . identifier[parser] . identifier[_crossrefs]
... | def resolve_one_step(self):
"""
Resolves model references.
"""
metamodel = self.parser.metamodel
current_crossrefs = self.parser._crossrefs
# print("DEBUG: Current crossrefs #: {}".
# format(len(current_crossrefs)))
new_crossrefs = []
self.delayed_crossrefs = []
reso... |
def render_to_response(self, context, **response_kwargs):
"""
Returns a response with a template depending if the request is ajax
or not and it renders with the given context.
"""
if self.request.is_ajax():
template = self.page_template
else:
temp... | def function[render_to_response, parameter[self, context]]:
constant[
Returns a response with a template depending if the request is ajax
or not and it renders with the given context.
]
if call[name[self].request.is_ajax, parameter[]] begin[:]
variable[template] ... | keyword[def] identifier[render_to_response] ( identifier[self] , identifier[context] ,** identifier[response_kwargs] ):
literal[string]
keyword[if] identifier[self] . identifier[request] . identifier[is_ajax] ():
identifier[template] = identifier[self] . identifier[page_template]
... | def render_to_response(self, context, **response_kwargs):
"""
Returns a response with a template depending if the request is ajax
or not and it renders with the given context.
"""
if self.request.is_ajax():
template = self.page_template # depends on [control=['if'], data=[]]
... |
def delete_track_at_index(self, href=None, index=None):
"""Delete a track, or all the tracks.
'href' the relative href to the track list. May not be None.
'index' the index of the track to delete. If none is given,
all tracks are deleted.
Returns nothing.
If the respon... | def function[delete_track_at_index, parameter[self, href, index]]:
constant[Delete a track, or all the tracks.
'href' the relative href to the track list. May not be None.
'index' the index of the track to delete. If none is given,
all tracks are deleted.
Returns nothing.
... | keyword[def] identifier[delete_track_at_index] ( identifier[self] , identifier[href] = keyword[None] , identifier[index] = keyword[None] ):
literal[string]
keyword[assert] identifier[href] keyword[is] keyword[not] keyword[None]
identifier[data] = keyword[None]
... | def delete_track_at_index(self, href=None, index=None):
"""Delete a track, or all the tracks.
'href' the relative href to the track list. May not be None.
'index' the index of the track to delete. If none is given,
all tracks are deleted.
Returns nothing.
If the response s... |
def process_custom(custom):
"""Process custom."""
custom_selectors = {}
if custom is not None:
for key, value in custom.items():
name = util.lower(key)
if RE_CUSTOM.match(name) is None:
raise SelectorSyntaxError("The name '{}' is not a valid custom pseudo-cla... | def function[process_custom, parameter[custom]]:
constant[Process custom.]
variable[custom_selectors] assign[=] dictionary[[], []]
if compare[name[custom] is_not constant[None]] begin[:]
for taget[tuple[[<ast.Name object at 0x7da207f992a0>, <ast.Name object at 0x7da207f9b3a0>]]] ... | keyword[def] identifier[process_custom] ( identifier[custom] ):
literal[string]
identifier[custom_selectors] ={}
keyword[if] identifier[custom] keyword[is] keyword[not] keyword[None] :
keyword[for] identifier[key] , identifier[value] keyword[in] identifier[custom] . identifier[items] ... | def process_custom(custom):
"""Process custom."""
custom_selectors = {}
if custom is not None:
for (key, value) in custom.items():
name = util.lower(key)
if RE_CUSTOM.match(name) is None:
raise SelectorSyntaxError("The name '{}' is not a valid custom pseudo-cl... |
def indent_files(arguments):
""" indent_files(fname : str)
1. Creates a backup of the source file(backup_source_file())
2. Reads the files contents(read_file())
3. Indents the code(indent_code())
4. Writes the file or print the indented code(_after_indentation())
"""
opts = parse_options(ar... | def function[indent_files, parameter[arguments]]:
constant[ indent_files(fname : str)
1. Creates a backup of the source file(backup_source_file())
2. Reads the files contents(read_file())
3. Indents the code(indent_code())
4. Writes the file or print the indented code(_after_indentation())
... | keyword[def] identifier[indent_files] ( identifier[arguments] ):
literal[string]
identifier[opts] = identifier[parse_options] ( identifier[arguments] )
keyword[if] keyword[not] identifier[opts] . identifier[files] :
identifier[code] = identifier[sys] . identifier[stdin] . identifier[re... | def indent_files(arguments):
""" indent_files(fname : str)
1. Creates a backup of the source file(backup_source_file())
2. Reads the files contents(read_file())
3. Indents the code(indent_code())
4. Writes the file or print the indented code(_after_indentation())
"""
opts = parse_options(ar... |
def sequences_add_end_id_after_pad(sequences, end_id=888, pad_id=0):
"""Add special end token(id) in the end of each sequence.
Parameters
-----------
sequences : list of list of int
All sequences where each row is a sequence.
end_id : int
The end ID.
pad_id : int
The pad... | def function[sequences_add_end_id_after_pad, parameter[sequences, end_id, pad_id]]:
constant[Add special end token(id) in the end of each sequence.
Parameters
-----------
sequences : list of list of int
All sequences where each row is a sequence.
end_id : int
The end ID.
pad... | keyword[def] identifier[sequences_add_end_id_after_pad] ( identifier[sequences] , identifier[end_id] = literal[int] , identifier[pad_id] = literal[int] ):
literal[string]
identifier[sequences_out] = identifier[copy] . identifier[deepcopy] ( identifier[sequences] )
... | def sequences_add_end_id_after_pad(sequences, end_id=888, pad_id=0):
"""Add special end token(id) in the end of each sequence.
Parameters
-----------
sequences : list of list of int
All sequences where each row is a sequence.
end_id : int
The end ID.
pad_id : int
The pad... |
def student_t(degrees_of_freedom, confidence=0.95):
"""Return Student-t statistic for given DOF and confidence interval."""
return scipy.stats.t.interval(alpha=confidence,
df=degrees_of_freedom)[-1] | def function[student_t, parameter[degrees_of_freedom, confidence]]:
constant[Return Student-t statistic for given DOF and confidence interval.]
return[call[call[name[scipy].stats.t.interval, parameter[]]][<ast.UnaryOp object at 0x7da20c76cdc0>]] | keyword[def] identifier[student_t] ( identifier[degrees_of_freedom] , identifier[confidence] = literal[int] ):
literal[string]
keyword[return] identifier[scipy] . identifier[stats] . identifier[t] . identifier[interval] ( identifier[alpha] = identifier[confidence] ,
identifier[df] = identifier[deg... | def student_t(degrees_of_freedom, confidence=0.95):
"""Return Student-t statistic for given DOF and confidence interval."""
return scipy.stats.t.interval(alpha=confidence, df=degrees_of_freedom)[-1] |
def atomic_write(filename):
"""
Open a NamedTemoraryFile handle in a context manager
"""
f = _tempfile(os.fsencode(filename))
try:
yield f
finally:
f.close()
# replace the original file with the new temp file (atomic on success)
os.replace(f.name, filename) | def function[atomic_write, parameter[filename]]:
constant[
Open a NamedTemoraryFile handle in a context manager
]
variable[f] assign[=] call[name[_tempfile], parameter[call[name[os].fsencode, parameter[name[filename]]]]]
<ast.Try object at 0x7da18bccab30> | keyword[def] identifier[atomic_write] ( identifier[filename] ):
literal[string]
identifier[f] = identifier[_tempfile] ( identifier[os] . identifier[fsencode] ( identifier[filename] ))
keyword[try] :
keyword[yield] identifier[f]
keyword[finally] :
identifier[f] . identifier[c... | def atomic_write(filename):
"""
Open a NamedTemoraryFile handle in a context manager
"""
f = _tempfile(os.fsencode(filename))
try:
yield f # depends on [control=['try'], data=[]]
finally:
f.close()
# replace the original file with the new temp file (atomic on success)
... |
def _denominator(self, weighted, include_transforms_for_dims, axis):
"""Calculate denominator for percentages.
Only include those H&S dimensions, across which we DON'T sum. These H&S
are needed because of the shape, when dividing. Those across dims
which are summed across MUST NOT be in... | def function[_denominator, parameter[self, weighted, include_transforms_for_dims, axis]]:
constant[Calculate denominator for percentages.
Only include those H&S dimensions, across which we DON'T sum. These H&S
are needed because of the shape, when dividing. Those across dims
which are s... | keyword[def] identifier[_denominator] ( identifier[self] , identifier[weighted] , identifier[include_transforms_for_dims] , identifier[axis] ):
literal[string]
identifier[table] = identifier[self] . identifier[_measure] ( identifier[weighted] ). identifier[raw_cube_array]
identifier[new_... | def _denominator(self, weighted, include_transforms_for_dims, axis):
"""Calculate denominator for percentages.
Only include those H&S dimensions, across which we DON'T sum. These H&S
are needed because of the shape, when dividing. Those across dims
which are summed across MUST NOT be includ... |
def paths(self):
'''
given a basedir, yield all test modules paths recursively found in
basedir that are test modules
return -- generator
'''
module_name = getattr(self, 'module_name', '')
module_prefix = getattr(self, 'prefix', '')
filepath = getattr(sel... | def function[paths, parameter[self]]:
constant[
given a basedir, yield all test modules paths recursively found in
basedir that are test modules
return -- generator
]
variable[module_name] assign[=] call[name[getattr], parameter[name[self], constant[module_name], constan... | keyword[def] identifier[paths] ( identifier[self] ):
literal[string]
identifier[module_name] = identifier[getattr] ( identifier[self] , literal[string] , literal[string] )
identifier[module_prefix] = identifier[getattr] ( identifier[self] , literal[string] , literal[string] )
iden... | def paths(self):
"""
given a basedir, yield all test modules paths recursively found in
basedir that are test modules
return -- generator
"""
module_name = getattr(self, 'module_name', '')
module_prefix = getattr(self, 'prefix', '')
filepath = getattr(self, 'filepath', '... |
def _mapColumn(self, index):
"""
Maps a column to its respective input index, keeping to the topology of
the region. It takes the index of the column as an argument and determines
what is the index of the flattened input vector that is to be the center of
the column's potential pool. It distributes ... | def function[_mapColumn, parameter[self, index]]:
constant[
Maps a column to its respective input index, keeping to the topology of
the region. It takes the index of the column as an argument and determines
what is the index of the flattened input vector that is to be the center of
the column's ... | keyword[def] identifier[_mapColumn] ( identifier[self] , identifier[index] ):
literal[string]
identifier[columnCoords] = identifier[numpy] . identifier[unravel_index] ( identifier[index] , identifier[self] . identifier[_columnDimensions] )
identifier[columnCoords] = identifier[numpy] . identifier[arra... | def _mapColumn(self, index):
"""
Maps a column to its respective input index, keeping to the topology of
the region. It takes the index of the column as an argument and determines
what is the index of the flattened input vector that is to be the center of
the column's potential pool. It distributes ... |
def GenerateNetworkedConfigFile(load_hook, normal_class_load_hook, normal_class_dump_hook, **kwargs) -> NetworkedConfigObject:
"""
Generates a NetworkedConfigObject using the specified hooks.
"""
def NetworkedConfigObjectGenerator(url, safe_load: bool=True):
cfg = NetworkedConfigObject(url=url, ... | def function[GenerateNetworkedConfigFile, parameter[load_hook, normal_class_load_hook, normal_class_dump_hook]]:
constant[
Generates a NetworkedConfigObject using the specified hooks.
]
def function[NetworkedConfigObjectGenerator, parameter[url, safe_load]]:
variable[cfg] assign[... | keyword[def] identifier[GenerateNetworkedConfigFile] ( identifier[load_hook] , identifier[normal_class_load_hook] , identifier[normal_class_dump_hook] ,** identifier[kwargs] )-> identifier[NetworkedConfigObject] :
literal[string]
keyword[def] identifier[NetworkedConfigObjectGenerator] ( identifier[url] , ... | def GenerateNetworkedConfigFile(load_hook, normal_class_load_hook, normal_class_dump_hook, **kwargs) -> NetworkedConfigObject:
"""
Generates a NetworkedConfigObject using the specified hooks.
"""
def NetworkedConfigObjectGenerator(url, safe_load: bool=True):
cfg = NetworkedConfigObject(url=url,... |
def get_returns_cached(filepath, update_func, latest_dt, **kwargs):
"""
Get returns from a cached file if the cache is recent enough,
otherwise, try to retrieve via a provided update function and
update the cache file.
Parameters
----------
filepath : str
Path to cached csv file
... | def function[get_returns_cached, parameter[filepath, update_func, latest_dt]]:
constant[
Get returns from a cached file if the cache is recent enough,
otherwise, try to retrieve via a provided update function and
update the cache file.
Parameters
----------
filepath : str
Path to... | keyword[def] identifier[get_returns_cached] ( identifier[filepath] , identifier[update_func] , identifier[latest_dt] ,** identifier[kwargs] ):
literal[string]
identifier[update_cache] = keyword[False]
keyword[try] :
identifier[mtime] = identifier[getmtime] ( identifier[filepath] )
key... | def get_returns_cached(filepath, update_func, latest_dt, **kwargs):
"""
Get returns from a cached file if the cache is recent enough,
otherwise, try to retrieve via a provided update function and
update the cache file.
Parameters
----------
filepath : str
Path to cached csv file
... |
async def populate(self, agent_cls, *args, **kwargs):
'''Populate all the slave grid environments with agents. Assumes that
no agents have been spawned yet to the slave environment grids. This
excludes the slave environment managers as they are not in the grids.)
'''
n = self.gs[... | <ast.AsyncFunctionDef object at 0x7da18f812410> | keyword[async] keyword[def] identifier[populate] ( identifier[self] , identifier[agent_cls] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
identifier[n] = identifier[self] . identifier[gs] [ literal[int] ]* identifier[self] . identifier[gs] [ literal[int] ]
identifier[tasks... | async def populate(self, agent_cls, *args, **kwargs):
"""Populate all the slave grid environments with agents. Assumes that
no agents have been spawned yet to the slave environment grids. This
excludes the slave environment managers as they are not in the grids.)
"""
n = self.gs[0] * sel... |
def get_token(code, token_service, client_id, client_secret, redirect_uri,
grant_type):
"""Fetches an OAuth 2 token."""
data = {
'code': code,
'client_id': client_id,
'client_secret': client_secret,
'redirect_uri': redirect_uri,
'grant_type': grant_type,
}
# Get the d... | def function[get_token, parameter[code, token_service, client_id, client_secret, redirect_uri, grant_type]]:
constant[Fetches an OAuth 2 token.]
variable[data] assign[=] dictionary[[<ast.Constant object at 0x7da207f99b10>, <ast.Constant object at 0x7da207f9ba60>, <ast.Constant object at 0x7da207f98c70>,... | keyword[def] identifier[get_token] ( identifier[code] , identifier[token_service] , identifier[client_id] , identifier[client_secret] , identifier[redirect_uri] ,
identifier[grant_type] ):
literal[string]
identifier[data] ={
literal[string] : identifier[code] ,
literal[string] : identifier[client_id] ,
... | def get_token(code, token_service, client_id, client_secret, redirect_uri, grant_type):
"""Fetches an OAuth 2 token."""
data = {'code': code, 'client_id': client_id, 'client_secret': client_secret, 'redirect_uri': redirect_uri, 'grant_type': grant_type}
# Get the default http client
resp = requests.post... |
def priority(cls, url):
"""
Returns LOW priority if the URL is not prefixed with hls:// but ends with
.m3u8 and return NORMAL priority if the URL is prefixed.
:param url: the URL to find the plugin priority for
:return: plugin priority for the given URL
"""
m = cl... | def function[priority, parameter[cls, url]]:
constant[
Returns LOW priority if the URL is not prefixed with hls:// but ends with
.m3u8 and return NORMAL priority if the URL is prefixed.
:param url: the URL to find the plugin priority for
:return: plugin priority for the given URL... | keyword[def] identifier[priority] ( identifier[cls] , identifier[url] ):
literal[string]
identifier[m] = identifier[cls] . identifier[_url_re] . identifier[match] ( identifier[url] )
keyword[if] identifier[m] :
identifier[prefix] , identifier[url] = identifier[cls] . identifi... | def priority(cls, url):
"""
Returns LOW priority if the URL is not prefixed with hls:// but ends with
.m3u8 and return NORMAL priority if the URL is prefixed.
:param url: the URL to find the plugin priority for
:return: plugin priority for the given URL
"""
m = cls._url_r... |
def mac_address_table_static_vlan(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
mac_address_table = ET.SubElement(config, "mac-address-table", xmlns="urn:brocade.com:mgmt:brocade-mac-address-table")
static = ET.SubElement(mac_address_table, "static")
... | def function[mac_address_table_static_vlan, parameter[self]]:
constant[Auto Generated Code
]
variable[config] assign[=] call[name[ET].Element, parameter[constant[config]]]
variable[mac_address_table] assign[=] call[name[ET].SubElement, parameter[name[config], constant[mac-address-table]]... | keyword[def] identifier[mac_address_table_static_vlan] ( identifier[self] ,** identifier[kwargs] ):
literal[string]
identifier[config] = identifier[ET] . identifier[Element] ( literal[string] )
identifier[mac_address_table] = identifier[ET] . identifier[SubElement] ( identifier[config] , l... | def mac_address_table_static_vlan(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element('config')
mac_address_table = ET.SubElement(config, 'mac-address-table', xmlns='urn:brocade.com:mgmt:brocade-mac-address-table')
static = ET.SubElement(mac_address_table, 'static')
mac_address_k... |
def cli_plugin_add_argument(*args, **kwargs):
"""
Decorator generator that adds an argument to the cli plugin based on the
decorated function
Args:
*args: Any args to be passed to
:func:`argparse.ArgumentParser.add_argument`
*kwargs: Any keyword args to be passed to
... | def function[cli_plugin_add_argument, parameter[]]:
constant[
Decorator generator that adds an argument to the cli plugin based on the
decorated function
Args:
*args: Any args to be passed to
:func:`argparse.ArgumentParser.add_argument`
*kwargs: Any keyword args to be pa... | keyword[def] identifier[cli_plugin_add_argument] (* identifier[args] ,** identifier[kwargs] ):
literal[string]
keyword[def] identifier[decorator] ( identifier[func] ):
keyword[if] keyword[not] identifier[isinstance] ( identifier[func] , identifier[CLIPluginFuncWrapper] ):
identifi... | def cli_plugin_add_argument(*args, **kwargs):
"""
Decorator generator that adds an argument to the cli plugin based on the
decorated function
Args:
*args: Any args to be passed to
:func:`argparse.ArgumentParser.add_argument`
*kwargs: Any keyword args to be passed to
... |
def get_operator_statistic(self, name):
"""|coro|
Gets the operator unique statistic from the operator definitions dict
Returns
-------
str
the name of the operator unique statistic"""
opdefs = yield from self.get_operator_definitions()
name = name.... | def function[get_operator_statistic, parameter[self, name]]:
constant[|coro|
Gets the operator unique statistic from the operator definitions dict
Returns
-------
str
the name of the operator unique statistic]
variable[opdefs] assign[=] <ast.YieldFrom object... | keyword[def] identifier[get_operator_statistic] ( identifier[self] , identifier[name] ):
literal[string]
identifier[opdefs] = keyword[yield] keyword[from] identifier[self] . identifier[get_operator_definitions] ()
identifier[name] = identifier[name] . identifier[lower] ()
keywo... | def get_operator_statistic(self, name):
"""|coro|
Gets the operator unique statistic from the operator definitions dict
Returns
-------
str
the name of the operator unique statistic"""
opdefs = (yield from self.get_operator_definitions())
name = name.lower()
... |
def device_log_list(self, **kwargs): # noqa: E501
"""DEPRECATED: List all device events. # noqa: E501
DEPRECATED: List all device events. Use `/v3/device-events/` instead. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, plea... | def function[device_log_list, parameter[self]]:
constant[DEPRECATED: List all device events. # noqa: E501
DEPRECATED: List all device events. Use `/v3/device-events/` instead. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, p... | keyword[def] identifier[device_log_list] ( identifier[self] ,** identifier[kwargs] ):
literal[string]
identifier[kwargs] [ literal[string] ]= keyword[True]
keyword[if] identifier[kwargs] . identifier[get] ( literal[string] ):
keyword[return] identifier[self] . identifier[de... | def device_log_list(self, **kwargs): # noqa: E501
'DEPRECATED: List all device events. # noqa: E501\n\n DEPRECATED: List all device events. Use `/v3/device-events/` instead. # noqa: E501\n This method makes a synchronous HTTP request by default. To make an\n asynchronous HTTP request, please... |
def bind_unix_socket(path):
""" Returns a unix file socket bound on (path). """
assert path
bindsocket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
try:
os.unlink(path)
except OSError:
if os.path.exists(path):
raise
try:
bindsocket.bind(path)
excep... | def function[bind_unix_socket, parameter[path]]:
constant[ Returns a unix file socket bound on (path). ]
assert[name[path]]
variable[bindsocket] assign[=] call[name[socket].socket, parameter[name[socket].AF_UNIX, name[socket].SOCK_STREAM]]
<ast.Try object at 0x7da204621f60>
<ast.Try object a... | keyword[def] identifier[bind_unix_socket] ( identifier[path] ):
literal[string]
keyword[assert] identifier[path]
identifier[bindsocket] = identifier[socket] . identifier[socket] ( identifier[socket] . identifier[AF_UNIX] , identifier[socket] . identifier[SOCK_STREAM] )
keyword[try] :
... | def bind_unix_socket(path):
""" Returns a unix file socket bound on (path). """
assert path
bindsocket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
try:
os.unlink(path) # depends on [control=['try'], data=[]]
except OSError:
if os.path.exists(path):
raise # depen... |
def json_decode(s: str) -> Any:
"""
Decodes an object from JSON using our custom decoder.
"""
try:
return json.JSONDecoder(object_hook=json_class_decoder_hook).decode(s)
except json.JSONDecodeError:
log.warning("Failed to decode JSON (returning None): {!r}", s)
return None | def function[json_decode, parameter[s]]:
constant[
Decodes an object from JSON using our custom decoder.
]
<ast.Try object at 0x7da1b185d300> | keyword[def] identifier[json_decode] ( identifier[s] : identifier[str] )-> identifier[Any] :
literal[string]
keyword[try] :
keyword[return] identifier[json] . identifier[JSONDecoder] ( identifier[object_hook] = identifier[json_class_decoder_hook] ). identifier[decode] ( identifier[s] )
keywo... | def json_decode(s: str) -> Any:
"""
Decodes an object from JSON using our custom decoder.
"""
try:
return json.JSONDecoder(object_hook=json_class_decoder_hook).decode(s) # depends on [control=['try'], data=[]]
except json.JSONDecodeError:
log.warning('Failed to decode JSON (returnin... |
def calculate_size(name, new_value):
""" Calculates the request payload size"""
data_size = 0
data_size += calculate_size_str(name)
data_size += BOOLEAN_SIZE_IN_BYTES
if new_value is not None:
data_size += calculate_size_data(new_value)
return data_size | def function[calculate_size, parameter[name, new_value]]:
constant[ Calculates the request payload size]
variable[data_size] assign[=] constant[0]
<ast.AugAssign object at 0x7da1b1722f20>
<ast.AugAssign object at 0x7da1b1722440>
if compare[name[new_value] is_not constant[None]] begin[:]
... | keyword[def] identifier[calculate_size] ( identifier[name] , identifier[new_value] ):
literal[string]
identifier[data_size] = literal[int]
identifier[data_size] += identifier[calculate_size_str] ( identifier[name] )
identifier[data_size] += identifier[BOOLEAN_SIZE_IN_BYTES]
keyword[if] id... | def calculate_size(name, new_value):
""" Calculates the request payload size"""
data_size = 0
data_size += calculate_size_str(name)
data_size += BOOLEAN_SIZE_IN_BYTES
if new_value is not None:
data_size += calculate_size_data(new_value) # depends on [control=['if'], data=['new_value']]
... |
def _extract_body(self):
""" Extract the body content from HTML. """
def is_descendant_node(parent, node):
node = node.getparent()
while node is not None:
if node == parent:
return True
node = node.getparent()
retur... | def function[_extract_body, parameter[self]]:
constant[ Extract the body content from HTML. ]
def function[is_descendant_node, parameter[parent, node]]:
variable[node] assign[=] call[name[node].getparent, parameter[]]
while compare[name[node] is_not constant[None]] begin[... | keyword[def] identifier[_extract_body] ( identifier[self] ):
literal[string]
keyword[def] identifier[is_descendant_node] ( identifier[parent] , identifier[node] ):
identifier[node] = identifier[node] . identifier[getparent] ()
keyword[while] identifier[node] keyword[is... | def _extract_body(self):
""" Extract the body content from HTML. """
def is_descendant_node(parent, node):
node = node.getparent()
while node is not None:
if node == parent:
return True # depends on [control=['if'], data=[]]
node = node.getparent() # de... |
def get_label(self):
"""
get label as ndarray from ImageFeature
"""
label = callBigDlFunc(self.bigdl_type, "imageFeatureToLabelTensor", self.value)
return label.to_ndarray() | def function[get_label, parameter[self]]:
constant[
get label as ndarray from ImageFeature
]
variable[label] assign[=] call[name[callBigDlFunc], parameter[name[self].bigdl_type, constant[imageFeatureToLabelTensor], name[self].value]]
return[call[name[label].to_ndarray, parameter[]]] | keyword[def] identifier[get_label] ( identifier[self] ):
literal[string]
identifier[label] = identifier[callBigDlFunc] ( identifier[self] . identifier[bigdl_type] , literal[string] , identifier[self] . identifier[value] )
keyword[return] identifier[label] . identifier[to_ndarray] () | def get_label(self):
"""
get label as ndarray from ImageFeature
"""
label = callBigDlFunc(self.bigdl_type, 'imageFeatureToLabelTensor', self.value)
return label.to_ndarray() |
def geoadd(self, name, *values):
"""
Add the specified geospatial items to the specified key identified
by the ``name`` argument. The Geospatial items are given as ordered
members of the ``values`` argument, each item or place is formed by
the triad longitude, latitude and name.
... | def function[geoadd, parameter[self, name]]:
constant[
Add the specified geospatial items to the specified key identified
by the ``name`` argument. The Geospatial items are given as ordered
members of the ``values`` argument, each item or place is formed by
the triad longitude, l... | keyword[def] identifier[geoadd] ( identifier[self] , identifier[name] ,* identifier[values] ):
literal[string]
keyword[if] identifier[len] ( identifier[values] )% literal[int] != literal[int] :
keyword[raise] identifier[DataError] ( literal[string]
literal[string] )
... | def geoadd(self, name, *values):
"""
Add the specified geospatial items to the specified key identified
by the ``name`` argument. The Geospatial items are given as ordered
members of the ``values`` argument, each item or place is formed by
the triad longitude, latitude and name.
... |
def breadcrumb(self):
"""List of ``(url, title)`` tuples defining the current breadcrumb
path.
"""
if self.path == '.':
return []
path = self.path
breadcrumb = [((self.url_ext or '.'), self.title)]
while True:
path = os.path.normpath(os.p... | def function[breadcrumb, parameter[self]]:
constant[List of ``(url, title)`` tuples defining the current breadcrumb
path.
]
if compare[name[self].path equal[==] constant[.]] begin[:]
return[list[[]]]
variable[path] assign[=] name[self].path
variable[breadcrumb] as... | keyword[def] identifier[breadcrumb] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[path] == literal[string] :
keyword[return] []
identifier[path] = identifier[self] . identifier[path]
identifier[breadcrumb] =[(( identifier[self] . i... | def breadcrumb(self):
"""List of ``(url, title)`` tuples defining the current breadcrumb
path.
"""
if self.path == '.':
return [] # depends on [control=['if'], data=[]]
path = self.path
breadcrumb = [(self.url_ext or '.', self.title)]
while True:
path = os.path.normp... |
def authenticate(self):
"""Authenticate the session"""
postdata = self.authentication_postdata
jar = requests.cookies.cookielib.CookieJar()
self.cookies = jar
resp = self.get(self.authentication_base_url)
authtok = _extract_authenticity_token(resp.content)
if post... | def function[authenticate, parameter[self]]:
constant[Authenticate the session]
variable[postdata] assign[=] name[self].authentication_postdata
variable[jar] assign[=] call[name[requests].cookies.cookielib.CookieJar, parameter[]]
name[self].cookies assign[=] name[jar]
variable[re... | keyword[def] identifier[authenticate] ( identifier[self] ):
literal[string]
identifier[postdata] = identifier[self] . identifier[authentication_postdata]
identifier[jar] = identifier[requests] . identifier[cookies] . identifier[cookielib] . identifier[CookieJar] ()
identifier[sel... | def authenticate(self):
"""Authenticate the session"""
postdata = self.authentication_postdata
jar = requests.cookies.cookielib.CookieJar()
self.cookies = jar
resp = self.get(self.authentication_base_url)
authtok = _extract_authenticity_token(resp.content)
if postdata is None:
# This... |
def P(self):
"""Diffusion operator (cached)
Return or calculate the diffusion operator
Returns
-------
P : array-like, shape=[n_samples, n_samples]
diffusion operator defined as a row-stochastic form
of the kernel matrix
"""
try:
... | def function[P, parameter[self]]:
constant[Diffusion operator (cached)
Return or calculate the diffusion operator
Returns
-------
P : array-like, shape=[n_samples, n_samples]
diffusion operator defined as a row-stochastic form
of the kernel matrix
... | keyword[def] identifier[P] ( identifier[self] ):
literal[string]
keyword[try] :
keyword[return] identifier[self] . identifier[_diff_op]
keyword[except] identifier[AttributeError] :
identifier[self] . identifier[_diff_op] = identifier[normalize] ( identifier[sel... | def P(self):
"""Diffusion operator (cached)
Return or calculate the diffusion operator
Returns
-------
P : array-like, shape=[n_samples, n_samples]
diffusion operator defined as a row-stochastic form
of the kernel matrix
"""
try:
return ... |
def annotate_segments(self, Z):
""" Report the copy number and start-end segment
"""
# We need a way to go from compressed idices to original indices
P = Z.copy()
P[~np.isfinite(P)] = -1
_, mapping = np.unique(np.cumsum(P >= 0), return_index=True)
dZ = Z.compress... | def function[annotate_segments, parameter[self, Z]]:
constant[ Report the copy number and start-end segment
]
variable[P] assign[=] call[name[Z].copy, parameter[]]
call[name[P]][<ast.UnaryOp object at 0x7da1b09bf730>] assign[=] <ast.UnaryOp object at 0x7da1b09bf4c0>
<ast.Tuple ob... | keyword[def] identifier[annotate_segments] ( identifier[self] , identifier[Z] ):
literal[string]
identifier[P] = identifier[Z] . identifier[copy] ()
identifier[P] [~ identifier[np] . identifier[isfinite] ( identifier[P] )]=- literal[int]
identifier[_] , identifier[mappin... | def annotate_segments(self, Z):
""" Report the copy number and start-end segment
"""
# We need a way to go from compressed idices to original indices
P = Z.copy()
P[~np.isfinite(P)] = -1
(_, mapping) = np.unique(np.cumsum(P >= 0), return_index=True)
dZ = Z.compressed()
(uniq, idx) = ... |
def parse_cgmlst_alleles(cgmlst_fasta):
"""Parse cgMLST alleles from fasta file
cgMLST FASTA file must have a header format of ">{marker name}|{allele name}"
Args:
cgmlst_fasta (str): cgMLST fasta file path
Returns:
dict of list: Marker name to list of allele sequences
"""
out ... | def function[parse_cgmlst_alleles, parameter[cgmlst_fasta]]:
constant[Parse cgMLST alleles from fasta file
cgMLST FASTA file must have a header format of ">{marker name}|{allele name}"
Args:
cgmlst_fasta (str): cgMLST fasta file path
Returns:
dict of list: Marker name to list of al... | keyword[def] identifier[parse_cgmlst_alleles] ( identifier[cgmlst_fasta] ):
literal[string]
identifier[out] = identifier[defaultdict] ( identifier[list] )
keyword[for] identifier[header] , identifier[seq] keyword[in] identifier[parse_fasta] ( identifier[cgmlst_fasta] ):
keyword[if] keywor... | def parse_cgmlst_alleles(cgmlst_fasta):
"""Parse cgMLST alleles from fasta file
cgMLST FASTA file must have a header format of ">{marker name}|{allele name}"
Args:
cgmlst_fasta (str): cgMLST fasta file path
Returns:
dict of list: Marker name to list of allele sequences
"""
out ... |
def as_posix(self):
"""Return the string representation of the path with forward (/)
slashes."""
f = self._flavour
return str(self).replace(f.sep, '/') | def function[as_posix, parameter[self]]:
constant[Return the string representation of the path with forward (/)
slashes.]
variable[f] assign[=] name[self]._flavour
return[call[call[name[str], parameter[name[self]]].replace, parameter[name[f].sep, constant[/]]]] | keyword[def] identifier[as_posix] ( identifier[self] ):
literal[string]
identifier[f] = identifier[self] . identifier[_flavour]
keyword[return] identifier[str] ( identifier[self] ). identifier[replace] ( identifier[f] . identifier[sep] , literal[string] ) | def as_posix(self):
"""Return the string representation of the path with forward (/)
slashes."""
f = self._flavour
return str(self).replace(f.sep, '/') |
def probabilistic_collocation(order, dist, subset=.1):
"""
Probabilistic collocation method.
Args:
order (int, numpy.ndarray) : Quadrature order along each axis.
dist (Dist) : Distribution to generate samples from.
subset (float) : Rate of which to removed samples.
"""
absci... | def function[probabilistic_collocation, parameter[order, dist, subset]]:
constant[
Probabilistic collocation method.
Args:
order (int, numpy.ndarray) : Quadrature order along each axis.
dist (Dist) : Distribution to generate samples from.
subset (float) : Rate of which to remove... | keyword[def] identifier[probabilistic_collocation] ( identifier[order] , identifier[dist] , identifier[subset] = literal[int] ):
literal[string]
identifier[abscissas] , identifier[weights] = identifier[chaospy] . identifier[quad] . identifier[collection] . identifier[golub_welsch] ( identifier[order] , ide... | def probabilistic_collocation(order, dist, subset=0.1):
"""
Probabilistic collocation method.
Args:
order (int, numpy.ndarray) : Quadrature order along each axis.
dist (Dist) : Distribution to generate samples from.
subset (float) : Rate of which to removed samples.
"""
(abs... |
def get_wrapping_class(node):
"""Get the class that wraps the given node.
We consider that a class wraps a node if the class
is a parent for the said node.
:returns: The class that wraps the given node
:rtype: ClassDef or None
"""
klass = node.frame()
while klass is not None and not i... | def function[get_wrapping_class, parameter[node]]:
constant[Get the class that wraps the given node.
We consider that a class wraps a node if the class
is a parent for the said node.
:returns: The class that wraps the given node
:rtype: ClassDef or None
]
variable[klass] assign[=] ... | keyword[def] identifier[get_wrapping_class] ( identifier[node] ):
literal[string]
identifier[klass] = identifier[node] . identifier[frame] ()
keyword[while] identifier[klass] keyword[is] keyword[not] keyword[None] keyword[and] keyword[not] identifier[isinstance] ( identifier[klass] , identifie... | def get_wrapping_class(node):
"""Get the class that wraps the given node.
We consider that a class wraps a node if the class
is a parent for the said node.
:returns: The class that wraps the given node
:rtype: ClassDef or None
"""
klass = node.frame()
while klass is not None and (not i... |
def FetchRequestsAndResponses(self, session_id, timestamp=None):
"""Fetches all outstanding requests and responses for this flow.
We first cache all requests and responses for this flow in memory to
prevent round trips.
Args:
session_id: The session_id to get the requests/responses for.
ti... | def function[FetchRequestsAndResponses, parameter[self, session_id, timestamp]]:
constant[Fetches all outstanding requests and responses for this flow.
We first cache all requests and responses for this flow in memory to
prevent round trips.
Args:
session_id: The session_id to get the reques... | keyword[def] identifier[FetchRequestsAndResponses] ( identifier[self] , identifier[session_id] , identifier[timestamp] = keyword[None] ):
literal[string]
keyword[if] identifier[timestamp] keyword[is] keyword[None] :
identifier[timestamp] =( literal[int] , identifier[self] . identifier[frozen_time... | def FetchRequestsAndResponses(self, session_id, timestamp=None):
"""Fetches all outstanding requests and responses for this flow.
We first cache all requests and responses for this flow in memory to
prevent round trips.
Args:
session_id: The session_id to get the requests/responses for.
ti... |
def new_completion_from_position(self, position):
"""
(Only for internal use!)
Get a new completion by splitting this one. Used by
`CommandLineInterface` when it needs to have a list of new completions
after inserting the common prefix.
"""
assert isinstance(posit... | def function[new_completion_from_position, parameter[self, position]]:
constant[
(Only for internal use!)
Get a new completion by splitting this one. Used by
`CommandLineInterface` when it needs to have a list of new completions
after inserting the common prefix.
]
as... | keyword[def] identifier[new_completion_from_position] ( identifier[self] , identifier[position] ):
literal[string]
keyword[assert] identifier[isinstance] ( identifier[position] , identifier[int] ) keyword[and] identifier[position] - identifier[self] . identifier[start_position] >= literal[int]
... | def new_completion_from_position(self, position):
"""
(Only for internal use!)
Get a new completion by splitting this one. Used by
`CommandLineInterface` when it needs to have a list of new completions
after inserting the common prefix.
"""
assert isinstance(position, int... |
def set_server_key(self, zmq_socket, server_secret_key_path):
'''must call before bind'''
load_and_set_key(zmq_socket, server_secret_key_path)
zmq_socket.curve_server = True | def function[set_server_key, parameter[self, zmq_socket, server_secret_key_path]]:
constant[must call before bind]
call[name[load_and_set_key], parameter[name[zmq_socket], name[server_secret_key_path]]]
name[zmq_socket].curve_server assign[=] constant[True] | keyword[def] identifier[set_server_key] ( identifier[self] , identifier[zmq_socket] , identifier[server_secret_key_path] ):
literal[string]
identifier[load_and_set_key] ( identifier[zmq_socket] , identifier[server_secret_key_path] )
identifier[zmq_socket] . identifier[curve_server] = keywo... | def set_server_key(self, zmq_socket, server_secret_key_path):
"""must call before bind"""
load_and_set_key(zmq_socket, server_secret_key_path)
zmq_socket.curve_server = True |
def auto_zoom(zoomx=True, zoomy=True, axes="gca", x_space=0.04, y_space=0.04, draw=True):
"""
Looks at the bounds of the plotted data and zooms accordingly, leaving some
space around the data.
"""
# Disable auto-updating by default.
_pylab.ioff()
if axes=="gca": axes = _pylab.gca()
# ... | def function[auto_zoom, parameter[zoomx, zoomy, axes, x_space, y_space, draw]]:
constant[
Looks at the bounds of the plotted data and zooms accordingly, leaving some
space around the data.
]
call[name[_pylab].ioff, parameter[]]
if compare[name[axes] equal[==] constant[gca]] begin[:]
... | keyword[def] identifier[auto_zoom] ( identifier[zoomx] = keyword[True] , identifier[zoomy] = keyword[True] , identifier[axes] = literal[string] , identifier[x_space] = literal[int] , identifier[y_space] = literal[int] , identifier[draw] = keyword[True] ):
literal[string]
identifier[_pylab] . identifi... | def auto_zoom(zoomx=True, zoomy=True, axes='gca', x_space=0.04, y_space=0.04, draw=True):
"""
Looks at the bounds of the plotted data and zooms accordingly, leaving some
space around the data.
"""
# Disable auto-updating by default.
_pylab.ioff()
if axes == 'gca':
axes = _pylab.gca()... |
def HA1(realm, username, password, algorithm):
"""Create HA1 hash by realm, username, password
HA1 = md5(A1) = MD5(username:realm:password)
"""
if not realm:
realm = u''
return H(b":".join([username.encode('utf-8'),
realm.encode('utf-8'),
... | def function[HA1, parameter[realm, username, password, algorithm]]:
constant[Create HA1 hash by realm, username, password
HA1 = md5(A1) = MD5(username:realm:password)
]
if <ast.UnaryOp object at 0x7da1b21bb070> begin[:]
variable[realm] assign[=] constant[]
return[call[name[H... | keyword[def] identifier[HA1] ( identifier[realm] , identifier[username] , identifier[password] , identifier[algorithm] ):
literal[string]
keyword[if] keyword[not] identifier[realm] :
identifier[realm] = literal[string]
keyword[return] identifier[H] ( literal[string] . identifier[join] ([ ... | def HA1(realm, username, password, algorithm):
"""Create HA1 hash by realm, username, password
HA1 = md5(A1) = MD5(username:realm:password)
"""
if not realm:
realm = u'' # depends on [control=['if'], data=[]]
return H(b':'.join([username.encode('utf-8'), realm.encode('utf-8'), password.enc... |
def cumulative_std(self):
"""
Return the cumulative standard deviation of the elements in the SArray.
Returns an SArray where each element in the output corresponds to the
standard deviation of all the elements preceding and including it. The
SArray is expected to be of numeric ... | def function[cumulative_std, parameter[self]]:
constant[
Return the cumulative standard deviation of the elements in the SArray.
Returns an SArray where each element in the output corresponds to the
standard deviation of all the elements preceding and including it. The
SArray is... | keyword[def] identifier[cumulative_std] ( identifier[self] ):
literal[string]
keyword[from] .. keyword[import] identifier[extensions]
identifier[agg_op] = literal[string]
keyword[return] identifier[SArray] ( identifier[_proxy] = identifier[self] . identifier[__proxy__] . ident... | def cumulative_std(self):
"""
Return the cumulative standard deviation of the elements in the SArray.
Returns an SArray where each element in the output corresponds to the
standard deviation of all the elements preceding and including it. The
SArray is expected to be of numeric type... |
def adjustPhase(self, adjustment):
"""
Adjust the accelerating phase of the cavity by the value of ``adjustment``.
The adjustment is additive, so a value of ``scalingFactor = 0.0`` will result
in no change of the phase.
"""
self.phase = self.phase._replace(val = self.phas... | def function[adjustPhase, parameter[self, adjustment]]:
constant[
Adjust the accelerating phase of the cavity by the value of ``adjustment``.
The adjustment is additive, so a value of ``scalingFactor = 0.0`` will result
in no change of the phase.
]
name[self].phase assign... | keyword[def] identifier[adjustPhase] ( identifier[self] , identifier[adjustment] ):
literal[string]
identifier[self] . identifier[phase] = identifier[self] . identifier[phase] . identifier[_replace] ( identifier[val] = identifier[self] . identifier[phase] . identifier[val] + identifier[adjustment] ... | def adjustPhase(self, adjustment):
"""
Adjust the accelerating phase of the cavity by the value of ``adjustment``.
The adjustment is additive, so a value of ``scalingFactor = 0.0`` will result
in no change of the phase.
"""
self.phase = self.phase._replace(val=self.phase.val + ad... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.