code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def __render(self, context, **kwargs):
"""
Render template.
:param context: A dict or dict-like object to instantiate given
template file
:param kwargs: Keyword arguments passed to the template engine to
render templates with specific features enabled.
:... | def function[__render, parameter[self, context]]:
constant[
Render template.
:param context: A dict or dict-like object to instantiate given
template file
:param kwargs: Keyword arguments passed to the template engine to
render templates with specific features en... | keyword[def] identifier[__render] ( identifier[self] , identifier[context] ,** identifier[kwargs] ):
literal[string]
identifier[kwargs] [ literal[string] ]=[ identifier[context] ,]+ identifier[kwargs] . identifier[get] ( literal[string] ,[])+ identifier[kwargs] . identifier[get] ( literal[... | def __render(self, context, **kwargs):
"""
Render template.
:param context: A dict or dict-like object to instantiate given
template file
:param kwargs: Keyword arguments passed to the template engine to
render templates with specific features enabled.
:retu... |
def set_project_avatar(self, avatar_blob, project_id):
"""SetProjectAvatar.
[Preview API] Sets the avatar for the project.
:param :class:`<ProjectAvatar> <azure.devops.v5_1.core.models.ProjectAvatar>` avatar_blob: The avatar blob data object to upload.
:param str project_id: The ID or na... | def function[set_project_avatar, parameter[self, avatar_blob, project_id]]:
constant[SetProjectAvatar.
[Preview API] Sets the avatar for the project.
:param :class:`<ProjectAvatar> <azure.devops.v5_1.core.models.ProjectAvatar>` avatar_blob: The avatar blob data object to upload.
:param s... | keyword[def] identifier[set_project_avatar] ( identifier[self] , identifier[avatar_blob] , identifier[project_id] ):
literal[string]
identifier[route_values] ={}
keyword[if] identifier[project_id] keyword[is] keyword[not] keyword[None] :
identifier[route_values] [ literal[... | def set_project_avatar(self, avatar_blob, project_id):
"""SetProjectAvatar.
[Preview API] Sets the avatar for the project.
:param :class:`<ProjectAvatar> <azure.devops.v5_1.core.models.ProjectAvatar>` avatar_blob: The avatar blob data object to upload.
:param str project_id: The ID or name o... |
def start_runtime(self):
'''
Start the system!
'''
while True:
try:
self.call_runtime()
except Exception:
log.error('Exception in Thorium: ', exc_info=True)
time.sleep(self.opts['thorium_interval']) | def function[start_runtime, parameter[self]]:
constant[
Start the system!
]
while constant[True] begin[:]
<ast.Try object at 0x7da2054a4f40> | keyword[def] identifier[start_runtime] ( identifier[self] ):
literal[string]
keyword[while] keyword[True] :
keyword[try] :
identifier[self] . identifier[call_runtime] ()
keyword[except] identifier[Exception] :
identifier[log] . identifie... | def start_runtime(self):
"""
Start the system!
"""
while True:
try:
self.call_runtime() # depends on [control=['try'], data=[]]
except Exception:
log.error('Exception in Thorium: ', exc_info=True)
time.sleep(self.opts['thorium_interval']) # d... |
def process(self): # pragma: no cover
"""
Process the logic and structuration of the mining database.
"""
if PyFunceble.CONFIGURATION["mining"]:
# The mining is activated.
# We load the mining logic.
mined = self.mine()
if mined:
... | def function[process, parameter[self]]:
constant[
Process the logic and structuration of the mining database.
]
if call[name[PyFunceble].CONFIGURATION][constant[mining]] begin[:]
variable[mined] assign[=] call[name[self].mine, parameter[]]
if name[mined] b... | keyword[def] identifier[process] ( identifier[self] ):
literal[string]
keyword[if] identifier[PyFunceble] . identifier[CONFIGURATION] [ literal[string] ]:
identifier[mined] = identifier[self] . identifier[mine] ()
keyword[if] identifier[mined] :
... | def process(self): # pragma: no cover
'\n Process the logic and structuration of the mining database.\n '
if PyFunceble.CONFIGURATION['mining']:
# The mining is activated.
# We load the mining logic.
mined = self.mine()
if mined:
# The mined data is not... |
def run_one(self, name, migrator, fake=True, downgrade=False, force=False):
"""Run/emulate a migration with given name."""
try:
migrate, rollback = self.read(name)
if fake:
with mock.patch('peewee.Model.select'):
with mock.patch('peewee.Query._... | def function[run_one, parameter[self, name, migrator, fake, downgrade, force]]:
constant[Run/emulate a migration with given name.]
<ast.Try object at 0x7da1b20a8640> | keyword[def] identifier[run_one] ( identifier[self] , identifier[name] , identifier[migrator] , identifier[fake] = keyword[True] , identifier[downgrade] = keyword[False] , identifier[force] = keyword[False] ):
literal[string]
keyword[try] :
identifier[migrate] , identifier[rollback] = ... | def run_one(self, name, migrator, fake=True, downgrade=False, force=False):
"""Run/emulate a migration with given name."""
try:
(migrate, rollback) = self.read(name)
if fake:
with mock.patch('peewee.Model.select'):
with mock.patch('peewee.Query._execute'):
... |
def abfGroups(abfFolder):
"""
Given a folder path or list of files, return groups (dict) by cell.
Rules which define parents (cells):
* assume each cell has one or several ABFs
* that cell can be labeled by its "ID" or "parent" ABF (first abf)
* the ID is just the filename of the fi... | def function[abfGroups, parameter[abfFolder]]:
constant[
Given a folder path or list of files, return groups (dict) by cell.
Rules which define parents (cells):
* assume each cell has one or several ABFs
* that cell can be labeled by its "ID" or "parent" ABF (first abf)
* the ID... | keyword[def] identifier[abfGroups] ( identifier[abfFolder] ):
literal[string]
identifier[files] = keyword[False]
keyword[if] identifier[type] ( identifier[abfFolder] ) keyword[is] identifier[str] keyword[and] identifier[os] . identifier[path] . identifier[isdir] ( identifier[abfFolder] ):
... | def abfGroups(abfFolder):
"""
Given a folder path or list of files, return groups (dict) by cell.
Rules which define parents (cells):
* assume each cell has one or several ABFs
* that cell can be labeled by its "ID" or "parent" ABF (first abf)
* the ID is just the filename of the fi... |
def handle_exec(args):
"""usage: cosmic-ray exec <session-file>
Perform the remaining work to be done in the specified session.
This requires that the rest of your mutation testing
infrastructure (e.g. worker processes) are already running.
"""
session_file = get_db_name(args.get('<session-file... | def function[handle_exec, parameter[args]]:
constant[usage: cosmic-ray exec <session-file>
Perform the remaining work to be done in the specified session.
This requires that the rest of your mutation testing
infrastructure (e.g. worker processes) are already running.
]
variable[session_... | keyword[def] identifier[handle_exec] ( identifier[args] ):
literal[string]
identifier[session_file] = identifier[get_db_name] ( identifier[args] . identifier[get] ( literal[string] ))
identifier[cosmic_ray] . identifier[commands] . identifier[execute] ( identifier[session_file] )
keyword[return]... | def handle_exec(args):
"""usage: cosmic-ray exec <session-file>
Perform the remaining work to be done in the specified session.
This requires that the rest of your mutation testing
infrastructure (e.g. worker processes) are already running.
"""
session_file = get_db_name(args.get('<session-file... |
def process_added_port(self, device_details):
"""Process the new ports.
Wraps _process_added_port, and treats the sucessful and exception
cases.
"""
device = device_details['device']
port_id = device_details['port_id']
reprocess = True
try:
se... | def function[process_added_port, parameter[self, device_details]]:
constant[Process the new ports.
Wraps _process_added_port, and treats the sucessful and exception
cases.
]
variable[device] assign[=] call[name[device_details]][constant[device]]
variable[port_id] assign[... | keyword[def] identifier[process_added_port] ( identifier[self] , identifier[device_details] ):
literal[string]
identifier[device] = identifier[device_details] [ literal[string] ]
identifier[port_id] = identifier[device_details] [ literal[string] ]
identifier[reprocess] = keyword[T... | def process_added_port(self, device_details):
"""Process the new ports.
Wraps _process_added_port, and treats the sucessful and exception
cases.
"""
device = device_details['device']
port_id = device_details['port_id']
reprocess = True
try:
self._process_added_port(d... |
def pre_release(self):
""" Return true if version is a pre-release. """
label = self.version_info.get('label', None)
pre = self.version_info.get('pre', None)
return True if (label is not None and pre is not None) else False | def function[pre_release, parameter[self]]:
constant[ Return true if version is a pre-release. ]
variable[label] assign[=] call[name[self].version_info.get, parameter[constant[label], constant[None]]]
variable[pre] assign[=] call[name[self].version_info.get, parameter[constant[pre], constant[Non... | keyword[def] identifier[pre_release] ( identifier[self] ):
literal[string]
identifier[label] = identifier[self] . identifier[version_info] . identifier[get] ( literal[string] , keyword[None] )
identifier[pre] = identifier[self] . identifier[version_info] . identifier[get] ( literal[string]... | def pre_release(self):
""" Return true if version is a pre-release. """
label = self.version_info.get('label', None)
pre = self.version_info.get('pre', None)
return True if label is not None and pre is not None else False |
def split_input(cls, job_config):
"""Inherit docs."""
params = job_config.input_reader_params
shard_count = job_config.shard_count
query_spec = cls._get_query_spec(params)
if not property_range.should_shard_by_property_range(query_spec.filters):
return super(ModelDatastoreInputReader, cls).sp... | def function[split_input, parameter[cls, job_config]]:
constant[Inherit docs.]
variable[params] assign[=] name[job_config].input_reader_params
variable[shard_count] assign[=] name[job_config].shard_count
variable[query_spec] assign[=] call[name[cls]._get_query_spec, parameter[name[params... | keyword[def] identifier[split_input] ( identifier[cls] , identifier[job_config] ):
literal[string]
identifier[params] = identifier[job_config] . identifier[input_reader_params]
identifier[shard_count] = identifier[job_config] . identifier[shard_count]
identifier[query_spec] = identifier[cls] . ... | def split_input(cls, job_config):
"""Inherit docs."""
params = job_config.input_reader_params
shard_count = job_config.shard_count
query_spec = cls._get_query_spec(params)
if not property_range.should_shard_by_property_range(query_spec.filters):
return super(ModelDatastoreInputReader, cls).s... |
def add_partitioning_indexes(portal):
"""Adds the indexes for partitioning
"""
logger.info("Adding partitioning indexes")
add_index(portal, catalog_id=CATALOG_ANALYSIS_LISTING,
index_name="getAncestorsUIDs",
index_attribute="getAncestorsUIDs",
index_metatype="K... | def function[add_partitioning_indexes, parameter[portal]]:
constant[Adds the indexes for partitioning
]
call[name[logger].info, parameter[constant[Adding partitioning indexes]]]
call[name[add_index], parameter[name[portal]]]
call[name[add_index], parameter[name[portal]]] | keyword[def] identifier[add_partitioning_indexes] ( identifier[portal] ):
literal[string]
identifier[logger] . identifier[info] ( literal[string] )
identifier[add_index] ( identifier[portal] , identifier[catalog_id] = identifier[CATALOG_ANALYSIS_LISTING] ,
identifier[index_name] = literal[string... | def add_partitioning_indexes(portal):
"""Adds the indexes for partitioning
"""
logger.info('Adding partitioning indexes')
add_index(portal, catalog_id=CATALOG_ANALYSIS_LISTING, index_name='getAncestorsUIDs', index_attribute='getAncestorsUIDs', index_metatype='KeywordIndex')
add_index(portal, catalog... |
def copy_no_data(self):
"""
Returns a copy of the object without any data.
"""
return type(self)(
[],
order=list(self.header_modes),
types=self.header_types.copy(),
modes=self.header_modes.copy()) | def function[copy_no_data, parameter[self]]:
constant[
Returns a copy of the object without any data.
]
return[call[call[name[type], parameter[name[self]]], parameter[list[[]]]]] | keyword[def] identifier[copy_no_data] ( identifier[self] ):
literal[string]
keyword[return] identifier[type] ( identifier[self] )(
[],
identifier[order] = identifier[list] ( identifier[self] . identifier[header_modes] ),
identifier[types] = identifier[self] . identifier[h... | def copy_no_data(self):
"""
Returns a copy of the object without any data.
"""
return type(self)([], order=list(self.header_modes), types=self.header_types.copy(), modes=self.header_modes.copy()) |
def run(url, cmd, log_path, log_level, log_session, force_discovery, print_info):
"""Run the main function."""
log_level = log_levels[log_level]
conn = condoor.Connection("host", list(url), log_session=log_session, log_level=log_level, log_dir=log_path)
try:
conn.connect(force_discovery=force_di... | def function[run, parameter[url, cmd, log_path, log_level, log_session, force_discovery, print_info]]:
constant[Run the main function.]
variable[log_level] assign[=] call[name[log_levels]][name[log_level]]
variable[conn] assign[=] call[name[condoor].Connection, parameter[constant[host], call[nam... | keyword[def] identifier[run] ( identifier[url] , identifier[cmd] , identifier[log_path] , identifier[log_level] , identifier[log_session] , identifier[force_discovery] , identifier[print_info] ):
literal[string]
identifier[log_level] = identifier[log_levels] [ identifier[log_level] ]
identifier[conn] ... | def run(url, cmd, log_path, log_level, log_session, force_discovery, print_info):
"""Run the main function."""
log_level = log_levels[log_level]
conn = condoor.Connection('host', list(url), log_session=log_session, log_level=log_level, log_dir=log_path)
try:
conn.connect(force_discovery=force_di... |
def scale_to_zero_one(x):
"""Take some 1d data and scale it so that min matches 0 and max 1.
"""
xscaled = x - np.min(x)
xscaled /= np.max(xscaled)
return xscaled | def function[scale_to_zero_one, parameter[x]]:
constant[Take some 1d data and scale it so that min matches 0 and max 1.
]
variable[xscaled] assign[=] binary_operation[name[x] - call[name[np].min, parameter[name[x]]]]
<ast.AugAssign object at 0x7da204620df0>
return[name[xscaled]] | keyword[def] identifier[scale_to_zero_one] ( identifier[x] ):
literal[string]
identifier[xscaled] = identifier[x] - identifier[np] . identifier[min] ( identifier[x] )
identifier[xscaled] /= identifier[np] . identifier[max] ( identifier[xscaled] )
keyword[return] identifier[xscaled] | def scale_to_zero_one(x):
"""Take some 1d data and scale it so that min matches 0 and max 1.
"""
xscaled = x - np.min(x)
xscaled /= np.max(xscaled)
return xscaled |
def special_key_assignment(self):
"""
Determines the keycodes for common special keys on the keyboard. These
are integer values and can be passed to the other key methods.
Generally speaking, these are non-printable codes.
"""
#This set of keys compiled using the X11 keys... | def function[special_key_assignment, parameter[self]]:
constant[
Determines the keycodes for common special keys on the keyboard. These
are integer values and can be passed to the other key methods.
Generally speaking, these are non-printable codes.
]
name[self].backspace... | keyword[def] identifier[special_key_assignment] ( identifier[self] ):
literal[string]
identifier[self] . identifier[backspace_key] = identifier[self] . identifier[lookup_character_keycode] ( literal[string] )
identifier[self] . identifier[tab_ke... | def special_key_assignment(self):
"""
Determines the keycodes for common special keys on the keyboard. These
are integer values and can be passed to the other key methods.
Generally speaking, these are non-printable codes.
"""
#This set of keys compiled using the X11 keysymdef.h ... |
def generate_file_rst(fname, target_dir, src_dir, gallery_conf):
"""Generate the rst file for a given example.
Parameters
----------
fname : str
Filename of python script
target_dir : str
Absolute path to directory in documentation where examples are saved
src_dir : str
... | def function[generate_file_rst, parameter[fname, target_dir, src_dir, gallery_conf]]:
constant[Generate the rst file for a given example.
Parameters
----------
fname : str
Filename of python script
target_dir : str
Absolute path to directory in documentation where examples are s... | keyword[def] identifier[generate_file_rst] ( identifier[fname] , identifier[target_dir] , identifier[src_dir] , identifier[gallery_conf] ):
literal[string]
identifier[src_file] = identifier[os] . identifier[path] . identifier[normpath] ( identifier[os] . identifier[path] . identifier[join] ( identifier[src... | def generate_file_rst(fname, target_dir, src_dir, gallery_conf):
"""Generate the rst file for a given example.
Parameters
----------
fname : str
Filename of python script
target_dir : str
Absolute path to directory in documentation where examples are saved
src_dir : str
... |
def generate(self):
"""Generate a new string and return it."""
key = self._propose_new_key()
while self.key_exists(key):
_logger.warning('Previous candidate was used.'
' Regenerating another...')
key = self._propose_new_key()
return key | def function[generate, parameter[self]]:
constant[Generate a new string and return it.]
variable[key] assign[=] call[name[self]._propose_new_key, parameter[]]
while call[name[self].key_exists, parameter[name[key]]] begin[:]
call[name[_logger].warning, parameter[constant[Previous ... | keyword[def] identifier[generate] ( identifier[self] ):
literal[string]
identifier[key] = identifier[self] . identifier[_propose_new_key] ()
keyword[while] identifier[self] . identifier[key_exists] ( identifier[key] ):
identifier[_logger] . identifier[warning] ( literal[strin... | def generate(self):
"""Generate a new string and return it."""
key = self._propose_new_key()
while self.key_exists(key):
_logger.warning('Previous candidate was used. Regenerating another...')
key = self._propose_new_key() # depends on [control=['while'], data=[]]
return key |
def process(self, expression):
""" Process color expression
args:
expression (tuple): color expression
returns:
str
"""
a, o, b = expression
c1 = self._hextorgb(a)
c2 = self._hextorgb(b)
r = ['#']
for i in range(3):
... | def function[process, parameter[self, expression]]:
constant[ Process color expression
args:
expression (tuple): color expression
returns:
str
]
<ast.Tuple object at 0x7da1b00d9270> assign[=] name[expression]
variable[c1] assign[=] call[name[self].... | keyword[def] identifier[process] ( identifier[self] , identifier[expression] ):
literal[string]
identifier[a] , identifier[o] , identifier[b] = identifier[expression]
identifier[c1] = identifier[self] . identifier[_hextorgb] ( identifier[a] )
identifier[c2] = identifier[self] . i... | def process(self, expression):
""" Process color expression
args:
expression (tuple): color expression
returns:
str
"""
(a, o, b) = expression
c1 = self._hextorgb(a)
c2 = self._hextorgb(b)
r = ['#']
for i in range(3):
v = self.operate(c1[i]... |
def Rules(**rules):
"""Create a dictionary mapping symbols to alternative sequences.
>>> Rules(A = "B C | D E")
{'A': [['B', 'C'], ['D', 'E']]}
"""
for (lhs, rhs) in rules.items():
rules[lhs] = [alt.strip().split() for alt in rhs.split('|')]
return rules | def function[Rules, parameter[]]:
constant[Create a dictionary mapping symbols to alternative sequences.
>>> Rules(A = "B C | D E")
{'A': [['B', 'C'], ['D', 'E']]}
]
for taget[tuple[[<ast.Name object at 0x7da204564f70>, <ast.Name object at 0x7da204564520>]]] in starred[call[name[rules].items... | keyword[def] identifier[Rules] (** identifier[rules] ):
literal[string]
keyword[for] ( identifier[lhs] , identifier[rhs] ) keyword[in] identifier[rules] . identifier[items] ():
identifier[rules] [ identifier[lhs] ]=[ identifier[alt] . identifier[strip] (). identifier[split] () keyword[for] ident... | def Rules(**rules):
"""Create a dictionary mapping symbols to alternative sequences.
>>> Rules(A = "B C | D E")
{'A': [['B', 'C'], ['D', 'E']]}
"""
for (lhs, rhs) in rules.items():
rules[lhs] = [alt.strip().split() for alt in rhs.split('|')] # depends on [control=['for'], data=[]]
retur... |
def build(self, builder):
"""
Build this element
:param builder:
:return:
"""
builder.start(self.__class__.__name__)
builder.data(self.country_code)
builder.end(self.__class__.__name__) | def function[build, parameter[self, builder]]:
constant[
Build this element
:param builder:
:return:
]
call[name[builder].start, parameter[name[self].__class__.__name__]]
call[name[builder].data, parameter[name[self].country_code]]
call[name[builder].end... | keyword[def] identifier[build] ( identifier[self] , identifier[builder] ):
literal[string]
identifier[builder] . identifier[start] ( identifier[self] . identifier[__class__] . identifier[__name__] )
identifier[builder] . identifier[data] ( identifier[self] . identifier[country_code] )
... | def build(self, builder):
"""
Build this element
:param builder:
:return:
"""
builder.start(self.__class__.__name__)
builder.data(self.country_code)
builder.end(self.__class__.__name__) |
def _get_service_bindings(self, service_name):
"""
Return the service bindings for the service instance.
"""
instance = self.get_instance(service_name)
return self.api.get(instance['service_bindings_url']) | def function[_get_service_bindings, parameter[self, service_name]]:
constant[
Return the service bindings for the service instance.
]
variable[instance] assign[=] call[name[self].get_instance, parameter[name[service_name]]]
return[call[name[self].api.get, parameter[call[name[instance... | keyword[def] identifier[_get_service_bindings] ( identifier[self] , identifier[service_name] ):
literal[string]
identifier[instance] = identifier[self] . identifier[get_instance] ( identifier[service_name] )
keyword[return] identifier[self] . identifier[api] . identifier[get] ( identifier... | def _get_service_bindings(self, service_name):
"""
Return the service bindings for the service instance.
"""
instance = self.get_instance(service_name)
return self.api.get(instance['service_bindings_url']) |
def replace(self, key, initial_value, new_value):
"""Atomically replace the value of a key with a new value.
This compares the current value of a key, then replaces it with a new
value if it is equal to a specified value. This operation takes place
in a transaction.
:param key:... | def function[replace, parameter[self, key, initial_value, new_value]]:
constant[Atomically replace the value of a key with a new value.
This compares the current value of a key, then replaces it with a new
value if it is equal to a specified value. This operation takes place
in a transa... | keyword[def] identifier[replace] ( identifier[self] , identifier[key] , identifier[initial_value] , identifier[new_value] ):
literal[string]
identifier[base64_key] = identifier[_encode] ( identifier[key] )
identifier[base64_initial_value] = identifier[_encode] ( identifier[initial_value] )... | def replace(self, key, initial_value, new_value):
"""Atomically replace the value of a key with a new value.
This compares the current value of a key, then replaces it with a new
value if it is equal to a specified value. This operation takes place
in a transaction.
:param key: key... |
def do_indent(s, width=4, indentfirst=False):
"""Return a copy of the passed string, each line indented by
4 spaces. The first line is not indented. If you want to
change the number of spaces or indent the first line too
you can pass additional parameters to the filter:
.. sourcecode:: jinja
... | def function[do_indent, parameter[s, width, indentfirst]]:
constant[Return a copy of the passed string, each line indented by
4 spaces. The first line is not indented. If you want to
change the number of spaces or indent the first line too
you can pass additional parameters to the filter:
.. so... | keyword[def] identifier[do_indent] ( identifier[s] , identifier[width] = literal[int] , identifier[indentfirst] = keyword[False] ):
literal[string]
identifier[indention] = literal[string] * identifier[width]
identifier[rv] =( literal[string] + identifier[indention] ). identifier[join] ( identifier[s]... | def do_indent(s, width=4, indentfirst=False):
"""Return a copy of the passed string, each line indented by
4 spaces. The first line is not indented. If you want to
change the number of spaces or indent the first line too
you can pass additional parameters to the filter:
.. sourcecode:: jinja
... |
def run(self):
"""
Runs all jobs.
Returns:
All errors encountered as a list of list.
[[error_dicts for job 1], [error_dicts for job 2], ....]
Raises:
ValidationError: if a job fails validation
ReturnCodeError: if the process has a return ... | def function[run, parameter[self]]:
constant[
Runs all jobs.
Returns:
All errors encountered as a list of list.
[[error_dicts for job 1], [error_dicts for job 2], ....]
Raises:
ValidationError: if a job fails validation
ReturnCodeError: i... | keyword[def] identifier[run] ( identifier[self] ):
literal[string]
identifier[cwd] = identifier[os] . identifier[getcwd] ()
keyword[with] identifier[ScratchDir] ( identifier[self] . identifier[scratch_dir] , identifier[create_symbolic_link] = keyword[True] ,
identifier[copy_to_c... | def run(self):
"""
Runs all jobs.
Returns:
All errors encountered as a list of list.
[[error_dicts for job 1], [error_dicts for job 2], ....]
Raises:
ValidationError: if a job fails validation
ReturnCodeError: if the process has a return code... |
def parse(readDataInstance, arrayType, arrayLength):
"""
Returns a new L{Array} object.
@type readDataInstance: L{ReadData}
@param readDataInstance: The L{ReadData} object containing the array data.
@type arrayType: int
@param arrayType: The type of L{... | def function[parse, parameter[readDataInstance, arrayType, arrayLength]]:
constant[
Returns a new L{Array} object.
@type readDataInstance: L{ReadData}
@param readDataInstance: The L{ReadData} object containing the array data.
@type arrayType: int
@param ... | keyword[def] identifier[parse] ( identifier[readDataInstance] , identifier[arrayType] , identifier[arrayLength] ):
literal[string]
identifier[newArray] = identifier[Array] ( identifier[arrayType] )
identifier[dataLength] = identifier[len] ( identifier[readDataInstance] )
keyword... | def parse(readDataInstance, arrayType, arrayLength):
"""
Returns a new L{Array} object.
@type readDataInstance: L{ReadData}
@param readDataInstance: The L{ReadData} object containing the array data.
@type arrayType: int
@param arrayType: The type of L{Array}... |
def get_embedded_items(result_collection):
"""
Given a result_collection (returned by a previous API call that
returns a collection, like get_bundle_list() or search()), return a
list of embedded items with each item in the returned list
considered a result object.
'result_collection' a JSON ob... | def function[get_embedded_items, parameter[result_collection]]:
constant[
Given a result_collection (returned by a previous API call that
returns a collection, like get_bundle_list() or search()), return a
list of embedded items with each item in the returned list
considered a result object.
... | keyword[def] identifier[get_embedded_items] ( identifier[result_collection] ):
literal[string]
keyword[assert] identifier[result_collection] keyword[is] keyword[not] keyword[None]
identifier[result] =[]
identifier[embedded_objects] = identifier[result_collection] . identifier[get] ( ... | def get_embedded_items(result_collection):
"""
Given a result_collection (returned by a previous API call that
returns a collection, like get_bundle_list() or search()), return a
list of embedded items with each item in the returned list
considered a result object.
'result_collection' a JSON ob... |
def hex_to_name(hexx):
"""
Convert hex to a color name, using matplotlib's colour names.
Args:
hexx (str): A hexadecimal colour, starting with '#'.
Returns:
str: The name of the colour, or None if not found.
"""
for n, h in defaults.COLOURS.items():
if (len(n) > 1) and ... | def function[hex_to_name, parameter[hexx]]:
constant[
Convert hex to a color name, using matplotlib's colour names.
Args:
hexx (str): A hexadecimal colour, starting with '#'.
Returns:
str: The name of the colour, or None if not found.
]
for taget[tuple[[<ast.Name object... | keyword[def] identifier[hex_to_name] ( identifier[hexx] ):
literal[string]
keyword[for] identifier[n] , identifier[h] keyword[in] identifier[defaults] . identifier[COLOURS] . identifier[items] ():
keyword[if] ( identifier[len] ( identifier[n] )> literal[int] ) keyword[and] ( identifier[h] == id... | def hex_to_name(hexx):
"""
Convert hex to a color name, using matplotlib's colour names.
Args:
hexx (str): A hexadecimal colour, starting with '#'.
Returns:
str: The name of the colour, or None if not found.
"""
for (n, h) in defaults.COLOURS.items():
if len(n) > 1 and ... |
def alert_type(self, alert_type):
"""Sets the alert_type of this Alert.
Alert type. # noqa: E501
:param alert_type: The alert_type of this Alert. # noqa: E501
:type: str
"""
allowed_values = ["CLASSIC", "THRESHOLD"] # noqa: E501
if alert_type not in allowed_v... | def function[alert_type, parameter[self, alert_type]]:
constant[Sets the alert_type of this Alert.
Alert type. # noqa: E501
:param alert_type: The alert_type of this Alert. # noqa: E501
:type: str
]
variable[allowed_values] assign[=] list[[<ast.Constant object at 0x7d... | keyword[def] identifier[alert_type] ( identifier[self] , identifier[alert_type] ):
literal[string]
identifier[allowed_values] =[ literal[string] , literal[string] ]
keyword[if] identifier[alert_type] keyword[not] keyword[in] identifier[allowed_values] :
keyword[raise] ide... | def alert_type(self, alert_type):
"""Sets the alert_type of this Alert.
Alert type. # noqa: E501
:param alert_type: The alert_type of this Alert. # noqa: E501
:type: str
"""
allowed_values = ['CLASSIC', 'THRESHOLD'] # noqa: E501
if alert_type not in allowed_values: # no... |
def get_dotstr(self):
"""Return a string containing DAG graph in Grpahviz's dot language."""
dotobj = self.gosubdagplot.get_pydot_graph() # pydot.Dot
dotstr = dotobj.create_dot()
return dotstr | def function[get_dotstr, parameter[self]]:
constant[Return a string containing DAG graph in Grpahviz's dot language.]
variable[dotobj] assign[=] call[name[self].gosubdagplot.get_pydot_graph, parameter[]]
variable[dotstr] assign[=] call[name[dotobj].create_dot, parameter[]]
return[name[dotstr... | keyword[def] identifier[get_dotstr] ( identifier[self] ):
literal[string]
identifier[dotobj] = identifier[self] . identifier[gosubdagplot] . identifier[get_pydot_graph] ()
identifier[dotstr] = identifier[dotobj] . identifier[create_dot] ()
keyword[return] identifier[dotstr] | def get_dotstr(self):
"""Return a string containing DAG graph in Grpahviz's dot language."""
dotobj = self.gosubdagplot.get_pydot_graph() # pydot.Dot
dotstr = dotobj.create_dot()
return dotstr |
def apply_strain(self, strain):
"""
Apply a strain to the lattice.
Args:
strain (float or list): Amount of strain to apply. Can be a float,
or a sequence of 3 numbers. E.g., 0.01 means all lattice
vectors are increased by 1%. This is equivalent to cal... | def function[apply_strain, parameter[self, strain]]:
constant[
Apply a strain to the lattice.
Args:
strain (float or list): Amount of strain to apply. Can be a float,
or a sequence of 3 numbers. E.g., 0.01 means all lattice
vectors are increased by 1%... | keyword[def] identifier[apply_strain] ( identifier[self] , identifier[strain] ):
literal[string]
identifier[s] =( literal[int] + identifier[np] . identifier[array] ( identifier[strain] ))* identifier[np] . identifier[eye] ( literal[int] )
identifier[self] . identifier[lattice] = identifier... | def apply_strain(self, strain):
"""
Apply a strain to the lattice.
Args:
strain (float or list): Amount of strain to apply. Can be a float,
or a sequence of 3 numbers. E.g., 0.01 means all lattice
vectors are increased by 1%. This is equivalent to calling... |
def progress(self, msg, onerror=None, sep='...', end='DONE', abrt='FAIL',
prog='.', excs=(Exception,), reraise=True):
""" Context manager for handling interactive prog indication
This context manager streamlines presenting banners and prog
indicators. To start the prog, pass ``... | def function[progress, parameter[self, msg, onerror, sep, end, abrt, prog, excs, reraise]]:
constant[ Context manager for handling interactive prog indication
This context manager streamlines presenting banners and prog
indicators. To start the prog, pass ``msg`` argument as a start
mes... | keyword[def] identifier[progress] ( identifier[self] , identifier[msg] , identifier[onerror] = keyword[None] , identifier[sep] = literal[string] , identifier[end] = literal[string] , identifier[abrt] = literal[string] ,
identifier[prog] = literal[string] , identifier[excs] =( identifier[Exception] ,), identifier[rer... | def progress(self, msg, onerror=None, sep='...', end='DONE', abrt='FAIL', prog='.', excs=(Exception,), reraise=True):
""" Context manager for handling interactive prog indication
This context manager streamlines presenting banners and prog
indicators. To start the prog, pass ``msg`` argument as a s... |
def Boolean(value, true=(u'yes', u'1', u'true'), false=(u'no', u'0', u'false'),
encoding=None):
"""
Parse a value as a boolean.
:type value: `unicode` or `bytes`
:param value: Text value to parse.
:type true: `tuple` of `unicode`
:param true: Values to compare, ignoring case, for... | def function[Boolean, parameter[value, true, false, encoding]]:
constant[
Parse a value as a boolean.
:type value: `unicode` or `bytes`
:param value: Text value to parse.
:type true: `tuple` of `unicode`
:param true: Values to compare, ignoring case, for ``True`` values.
:type fals... | keyword[def] identifier[Boolean] ( identifier[value] , identifier[true] =( literal[string] , literal[string] , literal[string] ), identifier[false] =( literal[string] , literal[string] , literal[string] ),
identifier[encoding] = keyword[None] ):
literal[string]
identifier[value] = identifier[Text] ( ident... | def Boolean(value, true=(u'yes', u'1', u'true'), false=(u'no', u'0', u'false'), encoding=None):
"""
Parse a value as a boolean.
:type value: `unicode` or `bytes`
:param value: Text value to parse.
:type true: `tuple` of `unicode`
:param true: Values to compare, ignoring case, for ``True`` va... |
def get_warning_choice(self, message, short_message,
style=wx.YES_NO | wx.NO_DEFAULT | wx.ICON_WARNING):
"""Launches proceeding dialog and returns True if ok to proceed"""
dlg = GMD.GenericMessageDialog(self.main_window, message,
short_m... | def function[get_warning_choice, parameter[self, message, short_message, style]]:
constant[Launches proceeding dialog and returns True if ok to proceed]
variable[dlg] assign[=] call[name[GMD].GenericMessageDialog, parameter[name[self].main_window, name[message], name[short_message], name[style]]]
... | keyword[def] identifier[get_warning_choice] ( identifier[self] , identifier[message] , identifier[short_message] ,
identifier[style] = identifier[wx] . identifier[YES_NO] | identifier[wx] . identifier[NO_DEFAULT] | identifier[wx] . identifier[ICON_WARNING] ):
literal[string]
identifier[dlg] = ide... | def get_warning_choice(self, message, short_message, style=wx.YES_NO | wx.NO_DEFAULT | wx.ICON_WARNING):
"""Launches proceeding dialog and returns True if ok to proceed"""
dlg = GMD.GenericMessageDialog(self.main_window, message, short_message, style)
choice = dlg.ShowModal()
dlg.Destroy()
return ch... |
def clearConnections( self, cls ):
"""
Clears all the connections for this node.
:param cls | <subclass of XNodeConnection> || None
:return <int> | number of connections removed
"""
count = 0
for connection in self.connections(cls):
... | def function[clearConnections, parameter[self, cls]]:
constant[
Clears all the connections for this node.
:param cls | <subclass of XNodeConnection> || None
:return <int> | number of connections removed
]
variable[count] assign[=] constant[0]
... | keyword[def] identifier[clearConnections] ( identifier[self] , identifier[cls] ):
literal[string]
identifier[count] = literal[int]
keyword[for] identifier[connection] keyword[in] identifier[self] . identifier[connections] ( identifier[cls] ):
identifier[connection] . ident... | def clearConnections(self, cls):
"""
Clears all the connections for this node.
:param cls | <subclass of XNodeConnection> || None
:return <int> | number of connections removed
"""
count = 0
for connection in self.connections(cls):
connection... |
def build_where_clause(mappings, operator='AND'):
"""Constructs the where clause based on a dictionary of values
>>> build_where_clause({'id': 456, 'name': 'myrecord'}, operator='OR')
>>> 'WHERE id = 456 OR name = "myrecord" '
"""
where_clause_mappings = {}
where_clause... | def function[build_where_clause, parameter[mappings, operator]]:
constant[Constructs the where clause based on a dictionary of values
>>> build_where_clause({'id': 456, 'name': 'myrecord'}, operator='OR')
>>> 'WHERE id = 456 OR name = "myrecord" '
]
variable[where_clause_mappin... | keyword[def] identifier[build_where_clause] ( identifier[mappings] , identifier[operator] = literal[string] ):
literal[string]
identifier[where_clause_mappings] ={}
identifier[where_clause_mappings] . identifier[update] ( identifier[mappings] )
identifier[where_clause] = literal[... | def build_where_clause(mappings, operator='AND'):
"""Constructs the where clause based on a dictionary of values
>>> build_where_clause({'id': 456, 'name': 'myrecord'}, operator='OR')
>>> 'WHERE id = 456 OR name = "myrecord" '
"""
where_clause_mappings = {}
where_clause_mappings.up... |
def create(cls, source, *, transform_args=None):
"""Create an instance of the class from the source. By default cls.transform_args is used, but
can be overridden by passing in transform_args.
"""
if transform_args is None:
transform_args = cls.transform_args
return cls(get_obj(source, *transf... | def function[create, parameter[cls, source]]:
constant[Create an instance of the class from the source. By default cls.transform_args is used, but
can be overridden by passing in transform_args.
]
if compare[name[transform_args] is constant[None]] begin[:]
variable[transform_args... | keyword[def] identifier[create] ( identifier[cls] , identifier[source] ,*, identifier[transform_args] = keyword[None] ):
literal[string]
keyword[if] identifier[transform_args] keyword[is] keyword[None] :
identifier[transform_args] = identifier[cls] . identifier[transform_args]
keyword[retu... | def create(cls, source, *, transform_args=None):
"""Create an instance of the class from the source. By default cls.transform_args is used, but
can be overridden by passing in transform_args.
"""
if transform_args is None:
transform_args = cls.transform_args # depends on [control=['if'], data=[... |
def model_getattr():
"""
Creates a getter that will drop the current value
and retrieve the model's attribute with the context key as name.
"""
def model_getattr(_value, context, **_params):
value = getattr(context["model"], context["key"])
return _attr(value)
return model_geta... | def function[model_getattr, parameter[]]:
constant[
Creates a getter that will drop the current value
and retrieve the model's attribute with the context key as name.
]
def function[model_getattr, parameter[_value, context]]:
variable[value] assign[=] call[name[getattr], para... | keyword[def] identifier[model_getattr] ():
literal[string]
keyword[def] identifier[model_getattr] ( identifier[_value] , identifier[context] ,** identifier[_params] ):
identifier[value] = identifier[getattr] ( identifier[context] [ literal[string] ], identifier[context] [ literal[string] ])
... | def model_getattr():
"""
Creates a getter that will drop the current value
and retrieve the model's attribute with the context key as name.
"""
def model_getattr(_value, context, **_params):
value = getattr(context['model'], context['key'])
return _attr(value)
return model_getat... |
def update(self):
"""
Update this provider. Should be invoked when the server gets updated.
This method will notify all clients that wait for
`self.next_revision_available`.
"""
with self.lock:
# Increment revision and commit it.
self.revision +=... | def function[update, parameter[self]]:
constant[
Update this provider. Should be invoked when the server gets updated.
This method will notify all clients that wait for
`self.next_revision_available`.
]
with name[self].lock begin[:]
<ast.AugAssign object at 0x7da... | keyword[def] identifier[update] ( identifier[self] ):
literal[string]
keyword[with] identifier[self] . identifier[lock] :
identifier[self] . identifier[revision] += literal[int]
identifier[self] . identifier[server] . identifier[commit] ( identifier[self] . ide... | def update(self):
"""
Update this provider. Should be invoked when the server gets updated.
This method will notify all clients that wait for
`self.next_revision_available`.
"""
with self.lock:
# Increment revision and commit it.
self.revision += 1
self.s... |
def get_grid_data(xall, yall, zall, nbins=100, method='nearest'):
"""Interpolate unstructured two-dimensional data.
Parameters
----------
xall : ndarray(T)
Sample x-coordinates.
yall : ndarray(T)
Sample y-coordinates.
zall : ndarray(T)
Sample z-coordinates.
nbins : i... | def function[get_grid_data, parameter[xall, yall, zall, nbins, method]]:
constant[Interpolate unstructured two-dimensional data.
Parameters
----------
xall : ndarray(T)
Sample x-coordinates.
yall : ndarray(T)
Sample y-coordinates.
zall : ndarray(T)
Sample z-coordinat... | keyword[def] identifier[get_grid_data] ( identifier[xall] , identifier[yall] , identifier[zall] , identifier[nbins] = literal[int] , identifier[method] = literal[string] ):
literal[string]
keyword[from] identifier[scipy] . identifier[interpolate] keyword[import] identifier[griddata]
identifier[x] ... | def get_grid_data(xall, yall, zall, nbins=100, method='nearest'):
"""Interpolate unstructured two-dimensional data.
Parameters
----------
xall : ndarray(T)
Sample x-coordinates.
yall : ndarray(T)
Sample y-coordinates.
zall : ndarray(T)
Sample z-coordinates.
nbins : i... |
def get_neighbor_names(self, node_name: str, order: int = 1) -> list:
"""Get the names of all neighbors of a node, and the node itself.
:param node_name: Node whose neighbor names are requested.
:return: A list of names of all neighbors of a node, and the node itself.
"""
logger... | def function[get_neighbor_names, parameter[self, node_name, order]]:
constant[Get the names of all neighbors of a node, and the node itself.
:param node_name: Node whose neighbor names are requested.
:return: A list of names of all neighbors of a node, and the node itself.
]
cal... | keyword[def] identifier[get_neighbor_names] ( identifier[self] , identifier[node_name] : identifier[str] , identifier[order] : identifier[int] = literal[int] )-> identifier[list] :
literal[string]
identifier[logger] . identifier[info] ( literal[string] )
identifier[node] = identifier[self]... | def get_neighbor_names(self, node_name: str, order: int=1) -> list:
"""Get the names of all neighbors of a node, and the node itself.
:param node_name: Node whose neighbor names are requested.
:return: A list of names of all neighbors of a node, and the node itself.
"""
logger.info('In ... |
def plot4_nolog(self, num):
"""
Plots the abundances of H-1, He-4, C-12 and O-16.
"""
self.plot_prof_2(num,'H-1',0.,5.)
self.plot_prof_2(num,'He-4',0.,5.)
self.plot_prof_2(num,'C-12',0.,5.)
self.plot_prof_2(num,'O-16',0.,5.)
pyl.legend(loc=3) | def function[plot4_nolog, parameter[self, num]]:
constant[
Plots the abundances of H-1, He-4, C-12 and O-16.
]
call[name[self].plot_prof_2, parameter[name[num], constant[H-1], constant[0.0], constant[5.0]]]
call[name[self].plot_prof_2, parameter[name[num], constant[He-4], cons... | keyword[def] identifier[plot4_nolog] ( identifier[self] , identifier[num] ):
literal[string]
identifier[self] . identifier[plot_prof_2] ( identifier[num] , literal[string] , literal[int] , literal[int] )
identifier[self] . identifier[plot_prof_2] ( identifier[num] , literal[string] , liter... | def plot4_nolog(self, num):
"""
Plots the abundances of H-1, He-4, C-12 and O-16.
"""
self.plot_prof_2(num, 'H-1', 0.0, 5.0)
self.plot_prof_2(num, 'He-4', 0.0, 5.0)
self.plot_prof_2(num, 'C-12', 0.0, 5.0)
self.plot_prof_2(num, 'O-16', 0.0, 5.0)
pyl.legend(loc=3) |
def from_epw_file(cls, epwfile, timestep=1):
"""Create a wea object using the solar irradiance values in an epw file.
Args:
epwfile: Full path to epw weather file.
timestep: An optional integer to set the number of time steps per hour.
Default is 1 for one value ... | def function[from_epw_file, parameter[cls, epwfile, timestep]]:
constant[Create a wea object using the solar irradiance values in an epw file.
Args:
epwfile: Full path to epw weather file.
timestep: An optional integer to set the number of time steps per hour.
De... | keyword[def] identifier[from_epw_file] ( identifier[cls] , identifier[epwfile] , identifier[timestep] = literal[int] ):
literal[string]
identifier[is_leap_year] = keyword[False]
identifier[epw] = identifier[EPW] ( identifier[epwfile] )
identifier[direct_normal] , identifier[diff... | def from_epw_file(cls, epwfile, timestep=1):
"""Create a wea object using the solar irradiance values in an epw file.
Args:
epwfile: Full path to epw weather file.
timestep: An optional integer to set the number of time steps per hour.
Default is 1 for one value per ... |
def p_use_declaration(p):
'''use_declaration : namespace_name
| NS_SEPARATOR namespace_name
| namespace_name AS STRING
| NS_SEPARATOR namespace_name AS STRING'''
if len(p) == 2:
p[0] = ast.UseDeclaration(p[1], None, lineno=p.lineno(1))... | def function[p_use_declaration, parameter[p]]:
constant[use_declaration : namespace_name
| NS_SEPARATOR namespace_name
| namespace_name AS STRING
| NS_SEPARATOR namespace_name AS STRING]
if compare[call[name[len], parameter[name[p]]] e... | keyword[def] identifier[p_use_declaration] ( identifier[p] ):
literal[string]
keyword[if] identifier[len] ( identifier[p] )== literal[int] :
identifier[p] [ literal[int] ]= identifier[ast] . identifier[UseDeclaration] ( identifier[p] [ literal[int] ], keyword[None] , identifier[lineno] = identifi... | def p_use_declaration(p):
"""use_declaration : namespace_name
| NS_SEPARATOR namespace_name
| namespace_name AS STRING
| NS_SEPARATOR namespace_name AS STRING"""
if len(p) == 2:
p[0] = ast.UseDeclaration(p[1], None, lineno=p.lineno(1))... |
def MOVHPD(cpu, dest, src):
"""
Moves high packed double-precision floating-point value.
Moves a double-precision floating-point value from the source operand (second operand) and the
destination operand (first operand). The source and destination operands can be an XMM register
... | def function[MOVHPD, parameter[cpu, dest, src]]:
constant[
Moves high packed double-precision floating-point value.
Moves a double-precision floating-point value from the source operand (second operand) and the
destination operand (first operand). The source and destination operands can... | keyword[def] identifier[MOVHPD] ( identifier[cpu] , identifier[dest] , identifier[src] ):
literal[string]
keyword[if] identifier[src] . identifier[size] == literal[int] :
keyword[assert] identifier[dest] . identifier[size] == literal[int]
identifier[dest] . identifier[w... | def MOVHPD(cpu, dest, src):
"""
Moves high packed double-precision floating-point value.
Moves a double-precision floating-point value from the source operand (second operand) and the
destination operand (first operand). The source and destination operands can be an XMM register
or ... |
def getdatastrs(self):
"""Retrieve the dataset standard string attributes.
Args::
no argument
Returns::
4-element tuple holding:
- dataset label string (attribute 'long_name')
- dataset unit (attribute 'units')
- dataset output format (attri... | def function[getdatastrs, parameter[self]]:
constant[Retrieve the dataset standard string attributes.
Args::
no argument
Returns::
4-element tuple holding:
- dataset label string (attribute 'long_name')
- dataset unit (attribute 'units')
- d... | keyword[def] identifier[getdatastrs] ( identifier[self] ):
literal[string]
identifier[status] , identifier[label] , identifier[unit] , identifier[format] , identifier[coord_system] = identifier[_C] . identifier[SDgetdatastrs] ( identifier[self] . identifier[_id] , literal[int] )
identifie... | def getdatastrs(self):
"""Retrieve the dataset standard string attributes.
Args::
no argument
Returns::
4-element tuple holding:
- dataset label string (attribute 'long_name')
- dataset unit (attribute 'units')
- dataset output format (attribute... |
def fileupdate(self, data):
"""Method to update extra metadata fields with dict obtained
through `fileinfo`"""
self.name = data["name"]
add = self.__additional
add["filetype"] = "other"
for filetype in ("book", "image", "video", "audio", "archive"):
if filety... | def function[fileupdate, parameter[self, data]]:
constant[Method to update extra metadata fields with dict obtained
through `fileinfo`]
name[self].name assign[=] call[name[data]][constant[name]]
variable[add] assign[=] name[self].__additional
call[name[add]][constant[filetype]] a... | keyword[def] identifier[fileupdate] ( identifier[self] , identifier[data] ):
literal[string]
identifier[self] . identifier[name] = identifier[data] [ literal[string] ]
identifier[add] = identifier[self] . identifier[__additional]
identifier[add] [ literal[string] ]= literal[stri... | def fileupdate(self, data):
"""Method to update extra metadata fields with dict obtained
through `fileinfo`"""
self.name = data['name']
add = self.__additional
add['filetype'] = 'other'
for filetype in ('book', 'image', 'video', 'audio', 'archive'):
if filetype in data:
a... |
def qos_queue_scheduler_strict_priority_priority_number(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
qos = ET.SubElement(config, "qos", xmlns="urn:brocade.com:mgmt:brocade-qos")
queue = ET.SubElement(qos, "queue")
scheduler = ET.SubElement(que... | def function[qos_queue_scheduler_strict_priority_priority_number, parameter[self]]:
constant[Auto Generated Code
]
variable[config] assign[=] call[name[ET].Element, parameter[constant[config]]]
variable[qos] assign[=] call[name[ET].SubElement, parameter[name[config], constant[qos]]]
... | keyword[def] identifier[qos_queue_scheduler_strict_priority_priority_number] ( identifier[self] ,** identifier[kwargs] ):
literal[string]
identifier[config] = identifier[ET] . identifier[Element] ( literal[string] )
identifier[qos] = identifier[ET] . identifier[SubElement] ( identifier[con... | def qos_queue_scheduler_strict_priority_priority_number(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element('config')
qos = ET.SubElement(config, 'qos', xmlns='urn:brocade.com:mgmt:brocade-qos')
queue = ET.SubElement(qos, 'queue')
scheduler = ET.SubElement(queue, 'scheduler')
... |
def query_segdb(cls, flags, *args, **kwargs):
"""Query the inital LIGO segment database for a list of flags.
Parameters
----------
flags : `iterable`
A list of flag names for which to query.
*args
Either, two `float`-like numbers indicating the
... | def function[query_segdb, parameter[cls, flags]]:
constant[Query the inital LIGO segment database for a list of flags.
Parameters
----------
flags : `iterable`
A list of flag names for which to query.
*args
Either, two `float`-like numbers indicating the
... | keyword[def] identifier[query_segdb] ( identifier[cls] , identifier[flags] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
identifier[warnings] . identifier[warn] ( literal[string]
literal[string] , identifier[DeprecationWarning] )
identifier[qsegs] = iden... | def query_segdb(cls, flags, *args, **kwargs):
"""Query the inital LIGO segment database for a list of flags.
Parameters
----------
flags : `iterable`
A list of flag names for which to query.
*args
Either, two `float`-like numbers indicating the
GP... |
def _find_players(self, year):
"""
Find all player IDs for the requested team.
For the requested team and year (if applicable), pull the roster table
and parse the player ID for all players on the roster and create an
instance of the Player class for the player. All player insta... | def function[_find_players, parameter[self, year]]:
constant[
Find all player IDs for the requested team.
For the requested team and year (if applicable), pull the roster table
and parse the player ID for all players on the roster and create an
instance of the Player class for t... | keyword[def] identifier[_find_players] ( identifier[self] , identifier[year] ):
literal[string]
keyword[if] keyword[not] identifier[year] :
identifier[year] = identifier[utils] . identifier[_find_year_for_season] ( literal[string] )
identifier[url] = identifier[self] . ident... | def _find_players(self, year):
"""
Find all player IDs for the requested team.
For the requested team and year (if applicable), pull the roster table
and parse the player ID for all players on the roster and create an
instance of the Player class for the player. All player instances... |
def _add_prj_file(original_gis_file, new_gis_file):
"""
Adds projection file
"""
out_prj_file = "{0}.prj".format(os.path.splitext(new_gis_file)[0])
if original_gis_file.endswith(".shp"):
dataset = ogr.Open(original_gis_file)
layer = dataset.GetLayer()
... | def function[_add_prj_file, parameter[original_gis_file, new_gis_file]]:
constant[
Adds projection file
]
variable[out_prj_file] assign[=] call[constant[{0}.prj].format, parameter[call[call[name[os].path.splitext, parameter[name[new_gis_file]]]][constant[0]]]]
if call[name[origin... | keyword[def] identifier[_add_prj_file] ( identifier[original_gis_file] , identifier[new_gis_file] ):
literal[string]
identifier[out_prj_file] = literal[string] . identifier[format] ( identifier[os] . identifier[path] . identifier[splitext] ( identifier[new_gis_file] )[ literal[int] ])
keyw... | def _add_prj_file(original_gis_file, new_gis_file):
"""
Adds projection file
"""
out_prj_file = '{0}.prj'.format(os.path.splitext(new_gis_file)[0])
if original_gis_file.endswith('.shp'):
dataset = ogr.Open(original_gis_file)
layer = dataset.GetLayer()
spatial_ref = la... |
def add_extra_datas(self, extra_datas):
"""
Add extra datas to the last row
headers : [col1, col2, col3, col4, col5]
row : {col1: a1, col2: a2, col3: a3}
extra_datas : [a4, a5]
row becomes : {col1: a1, col2: a2, col3: a3, col4: a4, col5: a5}
in case of longer ex... | def function[add_extra_datas, parameter[self, extra_datas]]:
constant[
Add extra datas to the last row
headers : [col1, col2, col3, col4, col5]
row : {col1: a1, col2: a2, col3: a3}
extra_datas : [a4, a5]
row becomes : {col1: a1, col2: a2, col3: a3, col4: a4, col5: a5}
... | keyword[def] identifier[add_extra_datas] ( identifier[self] , identifier[extra_datas] ):
literal[string]
keyword[for] identifier[index] , identifier[data] keyword[in] identifier[enumerate] ( identifier[extra_datas] ):
identifier[header] = identifier[self] . identifier[extra... | def add_extra_datas(self, extra_datas):
"""
Add extra datas to the last row
headers : [col1, col2, col3, col4, col5]
row : {col1: a1, col2: a2, col3: a3}
extra_datas : [a4, a5]
row becomes : {col1: a1, col2: a2, col3: a3, col4: a4, col5: a5}
in case of longer extra_... |
def get_edge_color(self, increment=1):
"""
Returns the current face, then increments the face by what's specified
"""
i = self.edge_colors_index
self.edge_colors_index += increment
if self.edge_colors_index >= len(self.edge_colors):
self.edge_colors_index = ... | def function[get_edge_color, parameter[self, increment]]:
constant[
Returns the current face, then increments the face by what's specified
]
variable[i] assign[=] name[self].edge_colors_index
<ast.AugAssign object at 0x7da18bc70700>
if compare[name[self].edge_colors_index gre... | keyword[def] identifier[get_edge_color] ( identifier[self] , identifier[increment] = literal[int] ):
literal[string]
identifier[i] = identifier[self] . identifier[edge_colors_index]
identifier[self] . identifier[edge_colors_index] += identifier[increment]
keyword[if] identifi... | def get_edge_color(self, increment=1):
"""
Returns the current face, then increments the face by what's specified
"""
i = self.edge_colors_index
self.edge_colors_index += increment
if self.edge_colors_index >= len(self.edge_colors):
self.edge_colors_index = self.edge_colors_index... |
def _save_documentation(version, base_url="https://spark.apache.org/docs"):
"""
Write the spark property documentation to a file
"""
target_dir = join(dirname(__file__), 'spylon', 'spark')
with open(join(target_dir, "spark_properties_{}.json".format(version)), 'w') as fp:
all_props = _fetch_... | def function[_save_documentation, parameter[version, base_url]]:
constant[
Write the spark property documentation to a file
]
variable[target_dir] assign[=] call[name[join], parameter[call[name[dirname], parameter[name[__file__]]], constant[spylon], constant[spark]]]
with call[name[open]... | keyword[def] identifier[_save_documentation] ( identifier[version] , identifier[base_url] = literal[string] ):
literal[string]
identifier[target_dir] = identifier[join] ( identifier[dirname] ( identifier[__file__] ), literal[string] , literal[string] )
keyword[with] identifier[open] ( identifier[join... | def _save_documentation(version, base_url='https://spark.apache.org/docs'):
"""
Write the spark property documentation to a file
"""
target_dir = join(dirname(__file__), 'spylon', 'spark')
with open(join(target_dir, 'spark_properties_{}.json'.format(version)), 'w') as fp:
all_props = _fetch_... |
def external_system_identifiers(endpoint):
"""Populate the ``external_system_identifiers`` key.
Also populates the ``new_record`` key through side effects.
"""
@utils.flatten
@utils.for_each_value
def _external_system_identifiers(self, key, value):
new_recid = maybe_int(value.get('d'))
... | def function[external_system_identifiers, parameter[endpoint]]:
constant[Populate the ``external_system_identifiers`` key.
Also populates the ``new_record`` key through side effects.
]
def function[_external_system_identifiers, parameter[self, key, value]]:
variable[new_recid] a... | keyword[def] identifier[external_system_identifiers] ( identifier[endpoint] ):
literal[string]
@ identifier[utils] . identifier[flatten]
@ identifier[utils] . identifier[for_each_value]
keyword[def] identifier[_external_system_identifiers] ( identifier[self] , identifier[key] , identifier[value]... | def external_system_identifiers(endpoint):
"""Populate the ``external_system_identifiers`` key.
Also populates the ``new_record`` key through side effects.
"""
@utils.flatten
@utils.for_each_value
def _external_system_identifiers(self, key, value):
new_recid = maybe_int(value.get('d'))... |
def fill_cache(self):
"""Fill the cache with new data from the sensor."""
_LOGGER.debug('Filling cache with new sensor data.')
try:
self.firmware_version()
except BluetoothBackendException:
# If a sensor doesn't work, wait 5 minutes before retrying
sel... | def function[fill_cache, parameter[self]]:
constant[Fill the cache with new data from the sensor.]
call[name[_LOGGER].debug, parameter[constant[Filling cache with new sensor data.]]]
<ast.Try object at 0x7da1b0cffbe0>
with call[name[self]._bt_interface.connect, parameter[name[self]._mac]] be... | keyword[def] identifier[fill_cache] ( identifier[self] ):
literal[string]
identifier[_LOGGER] . identifier[debug] ( literal[string] )
keyword[try] :
identifier[self] . identifier[firmware_version] ()
keyword[except] identifier[BluetoothBackendException] :
... | def fill_cache(self):
"""Fill the cache with new data from the sensor."""
_LOGGER.debug('Filling cache with new sensor data.')
try:
self.firmware_version() # depends on [control=['try'], data=[]]
except BluetoothBackendException:
# If a sensor doesn't work, wait 5 minutes before retryin... |
def find_all(self, sub, ignore_case=False):
"""
Find all occurances of the substring. Return a list of absolute
positions in the document.
"""
flags = re.IGNORECASE if ignore_case else 0
return [a.start() for a in re.finditer(re.escape(sub), self.text, flags)] | def function[find_all, parameter[self, sub, ignore_case]]:
constant[
Find all occurances of the substring. Return a list of absolute
positions in the document.
]
variable[flags] assign[=] <ast.IfExp object at 0x7da18f58c6d0>
return[<ast.ListComp object at 0x7da18f58c1f0>] | keyword[def] identifier[find_all] ( identifier[self] , identifier[sub] , identifier[ignore_case] = keyword[False] ):
literal[string]
identifier[flags] = identifier[re] . identifier[IGNORECASE] keyword[if] identifier[ignore_case] keyword[else] literal[int]
keyword[return] [ identifier[... | def find_all(self, sub, ignore_case=False):
"""
Find all occurances of the substring. Return a list of absolute
positions in the document.
"""
flags = re.IGNORECASE if ignore_case else 0
return [a.start() for a in re.finditer(re.escape(sub), self.text, flags)] |
def _register_function(name: str, func, universe: bool, in_place: bool):
"""Register a transformation function under the given name.
:param name: Name to register the function under
:param func: A function
:param universe:
:param in_place:
:return: The same function, with additional properties ... | def function[_register_function, parameter[name, func, universe, in_place]]:
constant[Register a transformation function under the given name.
:param name: Name to register the function under
:param func: A function
:param universe:
:param in_place:
:return: The same function, with addition... | keyword[def] identifier[_register_function] ( identifier[name] : identifier[str] , identifier[func] , identifier[universe] : identifier[bool] , identifier[in_place] : identifier[bool] ):
literal[string]
keyword[if] identifier[name] keyword[in] identifier[mapped] :
identifier[mapped_func] = iden... | def _register_function(name: str, func, universe: bool, in_place: bool):
"""Register a transformation function under the given name.
:param name: Name to register the function under
:param func: A function
:param universe:
:param in_place:
:return: The same function, with additional properties ... |
def fight(nick, rest):
"Pit two sworn enemies against each other (separate with 'vs.')"
if rest:
vtype = random.choice(phrases.fight_victories)
fdesc = random.choice(phrases.fight_descriptions)
# valid separators are vs., v., and vs
pattern = re.compile('(.*) (?:vs[.]?|v[.]) (.*)')
matcher = pattern.match(r... | def function[fight, parameter[nick, rest]]:
constant[Pit two sworn enemies against each other (separate with 'vs.')]
if name[rest] begin[:]
variable[vtype] assign[=] call[name[random].choice, parameter[name[phrases].fight_victories]]
variable[fdesc] assign[=] call[name[ra... | keyword[def] identifier[fight] ( identifier[nick] , identifier[rest] ):
literal[string]
keyword[if] identifier[rest] :
identifier[vtype] = identifier[random] . identifier[choice] ( identifier[phrases] . identifier[fight_victories] )
identifier[fdesc] = identifier[random] . identifier[choice] ( identifier[... | def fight(nick, rest):
"""Pit two sworn enemies against each other (separate with 'vs.')"""
if rest:
vtype = random.choice(phrases.fight_victories)
fdesc = random.choice(phrases.fight_descriptions) # valid separators are vs., v., and vs
pattern = re.compile('(.*) (?:vs[.]?|v[.]) (.*)')
... |
def write_file(writer, filename):
"""Write all of lines from file using the writer."""
for line in txt_line_iterator(filename):
writer.write(line)
writer.write("\n") | def function[write_file, parameter[writer, filename]]:
constant[Write all of lines from file using the writer.]
for taget[name[line]] in starred[call[name[txt_line_iterator], parameter[name[filename]]]] begin[:]
call[name[writer].write, parameter[name[line]]]
call[name[wr... | keyword[def] identifier[write_file] ( identifier[writer] , identifier[filename] ):
literal[string]
keyword[for] identifier[line] keyword[in] identifier[txt_line_iterator] ( identifier[filename] ):
identifier[writer] . identifier[write] ( identifier[line] )
identifier[writer] . identifier[write] ( ... | def write_file(writer, filename):
"""Write all of lines from file using the writer."""
for line in txt_line_iterator(filename):
writer.write(line)
writer.write('\n') # depends on [control=['for'], data=['line']] |
def is_running(self):
"""
Checks if the child process is running (or is starting).
"""
return self._process.state() in [self._process.Running, self._process.Starting] | def function[is_running, parameter[self]]:
constant[
Checks if the child process is running (or is starting).
]
return[compare[call[name[self]._process.state, parameter[]] in list[[<ast.Attribute object at 0x7da18c4cee60>, <ast.Attribute object at 0x7da18c4ce1d0>]]]] | keyword[def] identifier[is_running] ( identifier[self] ):
literal[string]
keyword[return] identifier[self] . identifier[_process] . identifier[state] () keyword[in] [ identifier[self] . identifier[_process] . identifier[Running] , identifier[self] . identifier[_process] . identifier[Starting] ] | def is_running(self):
"""
Checks if the child process is running (or is starting).
"""
return self._process.state() in [self._process.Running, self._process.Starting] |
def push_header(self, filename):
"""
Push the header to a given filename
:param filename: the file path to push into.
"""
# open file and read it all
with open(filename, "r") as infile:
content = infile.read()
# push header
content = self.__he... | def function[push_header, parameter[self, filename]]:
constant[
Push the header to a given filename
:param filename: the file path to push into.
]
with call[name[open], parameter[name[filename], constant[r]]] begin[:]
variable[content] assign[=] call[name[infile].... | keyword[def] identifier[push_header] ( identifier[self] , identifier[filename] ):
literal[string]
keyword[with] identifier[open] ( identifier[filename] , literal[string] ) keyword[as] identifier[infile] :
identifier[content] = identifier[infile] . identifier[read] ()
... | def push_header(self, filename):
"""
Push the header to a given filename
:param filename: the file path to push into.
"""
# open file and read it all
with open(filename, 'r') as infile:
content = infile.read() # depends on [control=['with'], data=['infile']]
# push heade... |
def max_consecutive_days(self) -> Optional[Tuple[int, Interval]]:
"""
The length of the longest sequence of days in which all days include
an interval.
Returns:
tuple:
``(longest_length, longest_interval)`` where
``longest_interval`` is a :cl... | def function[max_consecutive_days, parameter[self]]:
constant[
The length of the longest sequence of days in which all days include
an interval.
Returns:
tuple:
``(longest_length, longest_interval)`` where
``longest_interval`` is a :class:`In... | keyword[def] identifier[max_consecutive_days] ( identifier[self] )-> identifier[Optional] [ identifier[Tuple] [ identifier[int] , identifier[Interval] ]]:
literal[string]
keyword[if] identifier[len] ( identifier[self] . identifier[intervals] )== literal[int] :
keyword[return] keyword... | def max_consecutive_days(self) -> Optional[Tuple[int, Interval]]:
"""
The length of the longest sequence of days in which all days include
an interval.
Returns:
tuple:
``(longest_length, longest_interval)`` where
``longest_interval`` is a :class:... |
def create_project(name, include_examples=True):
'''
creates the initial project skeleton and files
:param name: the project name
:return:
'''
# from the start directory, create a project directory with the project name
path = "{}/{}".format(os.getcwd(), name)
... | def function[create_project, parameter[name, include_examples]]:
constant[
creates the initial project skeleton and files
:param name: the project name
:return:
]
variable[path] assign[=] call[constant[{}/{}].format, parameter[call[name[os].getcwd, parameter[]], name[name... | keyword[def] identifier[create_project] ( identifier[name] , identifier[include_examples] = keyword[True] ):
literal[string]
identifier[path] = literal[string] . identifier[format] ( identifier[os] . identifier[getcwd] (), identifier[name] )
keyword[if] identifier[os] . identifi... | def create_project(name, include_examples=True):
"""
creates the initial project skeleton and files
:param name: the project name
:return:
"""
# from the start directory, create a project directory with the project name
path = '{}/{}'.format(os.getcwd(), name)
if os.path.... |
def wafer_form_helper(context, helper_name):
'''
Find the specified Crispy FormHelper and instantiate it.
Handy when you are crispyifying other apps' forms.
'''
request = context.request
module, class_name = helper_name.rsplit('.', 1)
if module not in sys.modules:
__import__(module)
... | def function[wafer_form_helper, parameter[context, helper_name]]:
constant[
Find the specified Crispy FormHelper and instantiate it.
Handy when you are crispyifying other apps' forms.
]
variable[request] assign[=] name[context].request
<ast.Tuple object at 0x7da18f00f340> assign[=] c... | keyword[def] identifier[wafer_form_helper] ( identifier[context] , identifier[helper_name] ):
literal[string]
identifier[request] = identifier[context] . identifier[request]
identifier[module] , identifier[class_name] = identifier[helper_name] . identifier[rsplit] ( literal[string] , literal[int] )
... | def wafer_form_helper(context, helper_name):
"""
Find the specified Crispy FormHelper and instantiate it.
Handy when you are crispyifying other apps' forms.
"""
request = context.request
(module, class_name) = helper_name.rsplit('.', 1)
if module not in sys.modules:
__import__(module... |
def build_list_params(self, params, items, label):
"""
Items is a list of dictionaries or strings::
[
{
'Protocol' : 'HTTP',
'LoadBalancerPort' : '80',
'InstancePort' : '80'
},
..
... | def function[build_list_params, parameter[self, params, items, label]]:
constant[
Items is a list of dictionaries or strings::
[
{
'Protocol' : 'HTTP',
'LoadBalancerPort' : '80',
'InstancePort' : '80'
... | keyword[def] identifier[build_list_params] ( identifier[self] , identifier[params] , identifier[items] , identifier[label] ):
literal[string]
keyword[for] identifier[i] keyword[in] identifier[xrange] ( literal[int] , identifier[len] ( identifier[items] )+ literal[int] ):
ke... | def build_list_params(self, params, items, label):
"""
Items is a list of dictionaries or strings::
[
{
'Protocol' : 'HTTP',
'LoadBalancerPort' : '80',
'InstancePort' : '80'
},
..
... |
def get_arguments(self):
""" Gets the arguments from the command line. """
parser = argparse.ArgumentParser(
description='Downloads images from given URL')
parser.add_argument('url2scrape', nargs=1, help="URL to scrape")
parser.add_argument('-m', '--max-images', type=int, de... | def function[get_arguments, parameter[self]]:
constant[ Gets the arguments from the command line. ]
variable[parser] assign[=] call[name[argparse].ArgumentParser, parameter[]]
call[name[parser].add_argument, parameter[constant[url2scrape]]]
call[name[parser].add_argument, parameter[const... | keyword[def] identifier[get_arguments] ( identifier[self] ):
literal[string]
identifier[parser] = identifier[argparse] . identifier[ArgumentParser] (
identifier[description] = literal[string] )
identifier[parser] . identifier[add_argument] ( literal[string] , identifier[nargs] = ... | def get_arguments(self):
""" Gets the arguments from the command line. """
parser = argparse.ArgumentParser(description='Downloads images from given URL')
parser.add_argument('url2scrape', nargs=1, help='URL to scrape')
parser.add_argument('-m', '--max-images', type=int, default=None, help='Limit on num... |
def _clear(self):
"""
Clear the current image.
"""
self._plain_image = [" " * self._width for _ in range(self._height)]
self._colour_map = [[(None, 0, 0) for _ in range(self._width)]
for _ in range(self._height)] | def function[_clear, parameter[self]]:
constant[
Clear the current image.
]
name[self]._plain_image assign[=] <ast.ListComp object at 0x7da1b1d35b40>
name[self]._colour_map assign[=] <ast.ListComp object at 0x7da1b1d37f70> | keyword[def] identifier[_clear] ( identifier[self] ):
literal[string]
identifier[self] . identifier[_plain_image] =[ literal[string] * identifier[self] . identifier[_width] keyword[for] identifier[_] keyword[in] identifier[range] ( identifier[self] . identifier[_height] )]
identifier[s... | def _clear(self):
"""
Clear the current image.
"""
self._plain_image = [' ' * self._width for _ in range(self._height)]
self._colour_map = [[(None, 0, 0) for _ in range(self._width)] for _ in range(self._height)] |
def transform_32_33(inst, new_inst, i, n, offset,
instructions, new_asm):
"""MAKEFUNCTION adds another const. probably MAKECLASS as well
"""
add_size = xdis.op_size(new_inst.opcode, opcode_33)
if inst.opname in ('MAKE_FUNCTION','MAKE_CLOSURE'):
# Previous instruction should b... | def function[transform_32_33, parameter[inst, new_inst, i, n, offset, instructions, new_asm]]:
constant[MAKEFUNCTION adds another const. probably MAKECLASS as well
]
variable[add_size] assign[=] call[name[xdis].op_size, parameter[name[new_inst].opcode, name[opcode_33]]]
if compare[name[inst]... | keyword[def] identifier[transform_32_33] ( identifier[inst] , identifier[new_inst] , identifier[i] , identifier[n] , identifier[offset] ,
identifier[instructions] , identifier[new_asm] ):
literal[string]
identifier[add_size] = identifier[xdis] . identifier[op_size] ( identifier[new_inst] . identifier[opco... | def transform_32_33(inst, new_inst, i, n, offset, instructions, new_asm):
"""MAKEFUNCTION adds another const. probably MAKECLASS as well
"""
add_size = xdis.op_size(new_inst.opcode, opcode_33)
if inst.opname in ('MAKE_FUNCTION', 'MAKE_CLOSURE'):
# Previous instruction should be a load const whic... |
def validate_params(valid_options, params):
"""
Helps us validate the parameters for the request
:param valid_options: a list of strings of valid options for the
api request
:param params: a dict, the key-value store which we really only care about
the key w... | def function[validate_params, parameter[valid_options, params]]:
constant[
Helps us validate the parameters for the request
:param valid_options: a list of strings of valid options for the
api request
:param params: a dict, the key-value store which we really only care abo... | keyword[def] identifier[validate_params] ( identifier[valid_options] , identifier[params] ):
literal[string]
keyword[if] keyword[not] identifier[params] :
keyword[return]
identifier[data_filter] =[ literal[string] , literal[string] , literal[string] , literal[string] ]
... | def validate_params(valid_options, params):
"""
Helps us validate the parameters for the request
:param valid_options: a list of strings of valid options for the
api request
:param params: a dict, the key-value store which we really only care about
the key w... |
def parameters(self, namespaced=False):
"""returns the exception varlink error parameters"""
if namespaced:
return json.loads(json.dumps(self.args[0]['parameters']), object_hook=lambda d: SimpleNamespace(**d))
else:
return self.args[0].get('parameters') | def function[parameters, parameter[self, namespaced]]:
constant[returns the exception varlink error parameters]
if name[namespaced] begin[:]
return[call[name[json].loads, parameter[call[name[json].dumps, parameter[call[call[name[self].args][constant[0]]][constant[parameters]]]]]]] | keyword[def] identifier[parameters] ( identifier[self] , identifier[namespaced] = keyword[False] ):
literal[string]
keyword[if] identifier[namespaced] :
keyword[return] identifier[json] . identifier[loads] ( identifier[json] . identifier[dumps] ( identifier[self] . identifier[args] [... | def parameters(self, namespaced=False):
"""returns the exception varlink error parameters"""
if namespaced:
return json.loads(json.dumps(self.args[0]['parameters']), object_hook=lambda d: SimpleNamespace(**d)) # depends on [control=['if'], data=[]]
else:
return self.args[0].get('parameters'... |
def insert_entry(self, entry, taxids):
"""Insert UniProt entry"
:param entry: XML node entry
:param taxids: Optional[iter[int]] taxids: NCBI taxonomy IDs
"""
entry_dict = entry.attrib
entry_dict['created'] = datetime.strptime(entry_dict['created'], '%Y-%m-%d')
en... | def function[insert_entry, parameter[self, entry, taxids]]:
constant[Insert UniProt entry"
:param entry: XML node entry
:param taxids: Optional[iter[int]] taxids: NCBI taxonomy IDs
]
variable[entry_dict] assign[=] name[entry].attrib
call[name[entry_dict]][constant[create... | keyword[def] identifier[insert_entry] ( identifier[self] , identifier[entry] , identifier[taxids] ):
literal[string]
identifier[entry_dict] = identifier[entry] . identifier[attrib]
identifier[entry_dict] [ literal[string] ]= identifier[datetime] . identifier[strptime] ( identifier[entry_d... | def insert_entry(self, entry, taxids):
"""Insert UniProt entry"
:param entry: XML node entry
:param taxids: Optional[iter[int]] taxids: NCBI taxonomy IDs
"""
entry_dict = entry.attrib
entry_dict['created'] = datetime.strptime(entry_dict['created'], '%Y-%m-%d')
entry_dict['modifi... |
def _lookup_by_mapping():
"""Return a the init system based on a constant mapping of
distribution+version to init system..
See constants.py for the mapping.
A failover of the version is proposed for when no version is supplied.
For instance, Arch Linux's version will most probab... | def function[_lookup_by_mapping, parameter[]]:
constant[Return a the init system based on a constant mapping of
distribution+version to init system..
See constants.py for the mapping.
A failover of the version is proposed for when no version is supplied.
For instance, Arch Linux... | keyword[def] identifier[_lookup_by_mapping] ():
literal[string]
identifier[like] = identifier[distro] . identifier[like] (). identifier[lower] ()
identifier[distribution_id] = identifier[distro] . identifier[id] (). identifier[lower] ()
identifier[version] = identifier[distro] . i... | def _lookup_by_mapping():
"""Return a the init system based on a constant mapping of
distribution+version to init system..
See constants.py for the mapping.
A failover of the version is proposed for when no version is supplied.
For instance, Arch Linux's version will most probably b... |
def info(self, **kwargs):
"""
Get the system wide configuration info.
Returns:
A dict respresentation of the JSON returned from the API.
"""
path = self._get_path('info')
response = self._GET(path, kwargs)
self._set_attrs_to_values(response)
... | def function[info, parameter[self]]:
constant[
Get the system wide configuration info.
Returns:
A dict respresentation of the JSON returned from the API.
]
variable[path] assign[=] call[name[self]._get_path, parameter[constant[info]]]
variable[response] assig... | keyword[def] identifier[info] ( identifier[self] ,** identifier[kwargs] ):
literal[string]
identifier[path] = identifier[self] . identifier[_get_path] ( literal[string] )
identifier[response] = identifier[self] . identifier[_GET] ( identifier[path] , identifier[kwargs] )
identifi... | def info(self, **kwargs):
"""
Get the system wide configuration info.
Returns:
A dict respresentation of the JSON returned from the API.
"""
path = self._get_path('info')
response = self._GET(path, kwargs)
self._set_attrs_to_values(response)
return response |
def update_count(self, name, incr_by=1, key=None):
"""Update the value of CountMetric or MultiCountMetric
:type name: str
:param name: name of the registered metric to be updated.
:type incr_by: int
:param incr_by: specifies how much to increment. Default is 1.
:type key: str or None
:param... | def function[update_count, parameter[self, name, incr_by, key]]:
constant[Update the value of CountMetric or MultiCountMetric
:type name: str
:param name: name of the registered metric to be updated.
:type incr_by: int
:param incr_by: specifies how much to increment. Default is 1.
:type key... | keyword[def] identifier[update_count] ( identifier[self] , identifier[name] , identifier[incr_by] = literal[int] , identifier[key] = keyword[None] ):
literal[string]
keyword[if] identifier[name] keyword[not] keyword[in] identifier[self] . identifier[metrics] :
identifier[Log] . identifier[error]... | def update_count(self, name, incr_by=1, key=None):
"""Update the value of CountMetric or MultiCountMetric
:type name: str
:param name: name of the registered metric to be updated.
:type incr_by: int
:param incr_by: specifies how much to increment. Default is 1.
:type key: str or None
:param... |
def geometry_linestring(lat, lon, elev):
"""
GeoJSON Linestring. Latitude and Longitude have 2 values each.
:param list lat: Latitude values
:param list lon: Longitude values
:return dict:
"""
logger_excel.info("enter geometry_linestring")
d = OrderedDict()
coordinates = []
temp... | def function[geometry_linestring, parameter[lat, lon, elev]]:
constant[
GeoJSON Linestring. Latitude and Longitude have 2 values each.
:param list lat: Latitude values
:param list lon: Longitude values
:return dict:
]
call[name[logger_excel].info, parameter[constant[enter geometry_l... | keyword[def] identifier[geometry_linestring] ( identifier[lat] , identifier[lon] , identifier[elev] ):
literal[string]
identifier[logger_excel] . identifier[info] ( literal[string] )
identifier[d] = identifier[OrderedDict] ()
identifier[coordinates] =[]
identifier[temp] =[ literal[string] , ... | def geometry_linestring(lat, lon, elev):
"""
GeoJSON Linestring. Latitude and Longitude have 2 values each.
:param list lat: Latitude values
:param list lon: Longitude values
:return dict:
"""
logger_excel.info('enter geometry_linestring')
d = OrderedDict()
coordinates = []
temp... |
def triangulize(image, tile_size):
"""Processes the given image by breaking it down into tiles of the given
size and applying a triangular effect to each tile. Returns the processed
image as a PIL Image object.
The image can be given as anything suitable for passing to `Image.open`
(ie, the path to... | def function[triangulize, parameter[image, tile_size]]:
constant[Processes the given image by breaking it down into tiles of the given
size and applying a triangular effect to each tile. Returns the processed
image as a PIL Image object.
The image can be given as anything suitable for passing to `I... | keyword[def] identifier[triangulize] ( identifier[image] , identifier[tile_size] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[image] , identifier[basestring] ) keyword[or] identifier[hasattr] ( identifier[image] , literal[string] ):
identifier[image] = identifier[Image] . i... | def triangulize(image, tile_size):
"""Processes the given image by breaking it down into tiles of the given
size and applying a triangular effect to each tile. Returns the processed
image as a PIL Image object.
The image can be given as anything suitable for passing to `Image.open`
(ie, the path to... |
def ttl(self):
"""LeaseTimeToLive retrieves lease information.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
:return:
"""
result = sel... | def function[ttl, parameter[self]]:
constant[LeaseTimeToLive retrieves lease information.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
:return:
... | keyword[def] identifier[ttl] ( identifier[self] ):
literal[string]
identifier[result] = identifier[self] . identifier[client] . identifier[post] ( identifier[self] . identifier[client] . identifier[get_url] ( literal[string] ),
identifier[json] ={ literal[string] : identifier[self] . ident... | def ttl(self):
"""LeaseTimeToLive retrieves lease information.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
:return:
"""
result = self.client... |
def chunks_of(max_chunk_size, list_to_chunk):
"""
Yields the list with a max size of max_chunk_size
"""
for i in range(0, len(list_to_chunk), max_chunk_size):
yield list_to_chunk[i:i + max_chunk_size] | def function[chunks_of, parameter[max_chunk_size, list_to_chunk]]:
constant[
Yields the list with a max size of max_chunk_size
]
for taget[name[i]] in starred[call[name[range], parameter[constant[0], call[name[len], parameter[name[list_to_chunk]]], name[max_chunk_size]]]] begin[:]
... | keyword[def] identifier[chunks_of] ( identifier[max_chunk_size] , identifier[list_to_chunk] ):
literal[string]
keyword[for] identifier[i] keyword[in] identifier[range] ( literal[int] , identifier[len] ( identifier[list_to_chunk] ), identifier[max_chunk_size] ):
keyword[yield] identifier[list_t... | def chunks_of(max_chunk_size, list_to_chunk):
"""
Yields the list with a max size of max_chunk_size
"""
for i in range(0, len(list_to_chunk), max_chunk_size):
yield list_to_chunk[i:i + max_chunk_size] # depends on [control=['for'], data=['i']] |
def stop_pipeline(url, pipeline_id, auth, verify_ssl):
"""Stop a running pipeline. The API waits for the pipeline to be 'STOPPED' before returning.
Args:
url (str): the host url in the form 'http://host:port/'.
pipeline_id (str): the ID of of the exported pipeline.
auth (tu... | def function[stop_pipeline, parameter[url, pipeline_id, auth, verify_ssl]]:
constant[Stop a running pipeline. The API waits for the pipeline to be 'STOPPED' before returning.
Args:
url (str): the host url in the form 'http://host:port/'.
pipeline_id (str): the ID of of the exported ... | keyword[def] identifier[stop_pipeline] ( identifier[url] , identifier[pipeline_id] , identifier[auth] , identifier[verify_ssl] ):
literal[string]
identifier[stop_result] = identifier[requests] . identifier[post] ( identifier[url] + literal[string] + identifier[pipeline_id] + literal[string] , identifier[h... | def stop_pipeline(url, pipeline_id, auth, verify_ssl):
"""Stop a running pipeline. The API waits for the pipeline to be 'STOPPED' before returning.
Args:
url (str): the host url in the form 'http://host:port/'.
pipeline_id (str): the ID of of the exported pipeline.
auth (tu... |
def add_asset_hashes(self, path='dist/assets'):
"""
Scan through a directory and add hashes for each file found.
"""
for fullpath in _listfiles(os.path.join(self.root_path, path)):
relpath = fullpath.replace(self.root_path + '/' + path + '/', '')
md5sum = hashlib.md5(open(fullpath, 'rb').read()).hexdigest... | def function[add_asset_hashes, parameter[self, path]]:
constant[
Scan through a directory and add hashes for each file found.
]
for taget[name[fullpath]] in starred[call[name[_listfiles], parameter[call[name[os].path.join, parameter[name[self].root_path, name[path]]]]]] begin[:]
vari... | keyword[def] identifier[add_asset_hashes] ( identifier[self] , identifier[path] = literal[string] ):
literal[string]
keyword[for] identifier[fullpath] keyword[in] identifier[_listfiles] ( identifier[os] . identifier[path] . identifier[join] ( identifier[self] . identifier[root_path] , identifier[path] )):
... | def add_asset_hashes(self, path='dist/assets'):
"""
Scan through a directory and add hashes for each file found.
"""
for fullpath in _listfiles(os.path.join(self.root_path, path)):
relpath = fullpath.replace(self.root_path + '/' + path + '/', '')
md5sum = hashlib.md5(open(fullpath, 'rb').rea... |
def check(self, spec, data):
'''Given a mongo-style spec and some data or python object,
check whether the object complies with the spec. Fails eagerly.
'''
path_eval = self.path_eval
for keypath, specvalue in spec.items():
if keypath.startswith('$'):
... | def function[check, parameter[self, spec, data]]:
constant[Given a mongo-style spec and some data or python object,
check whether the object complies with the spec. Fails eagerly.
]
variable[path_eval] assign[=] name[self].path_eval
for taget[tuple[[<ast.Name object at 0x7da20c7c... | keyword[def] identifier[check] ( identifier[self] , identifier[spec] , identifier[data] ):
literal[string]
identifier[path_eval] = identifier[self] . identifier[path_eval]
keyword[for] identifier[keypath] , identifier[specvalue] keyword[in] identifier[spec] . identifier[items] ():
... | def check(self, spec, data):
"""Given a mongo-style spec and some data or python object,
check whether the object complies with the spec. Fails eagerly.
"""
path_eval = self.path_eval
for (keypath, specvalue) in spec.items():
if keypath.startswith('$'):
optext = keypath
... |
def make_action_list(self, item_list, **kwargs):
''' Generates a list of actions for sending to Elasticsearch '''
action_list = []
es_index = get2(kwargs, "es_index", self.es_index)
action_type = kwargs.get("action_type","index")
action_settings = {'_op_type': action_type,... | def function[make_action_list, parameter[self, item_list]]:
constant[ Generates a list of actions for sending to Elasticsearch ]
variable[action_list] assign[=] list[[]]
variable[es_index] assign[=] call[name[get2], parameter[name[kwargs], constant[es_index], name[self].es_index]]
variab... | keyword[def] identifier[make_action_list] ( identifier[self] , identifier[item_list] ,** identifier[kwargs] ):
literal[string]
identifier[action_list] =[]
identifier[es_index] = identifier[get2] ( identifier[kwargs] , literal[string] , identifier[self] . identifier[es_index] )
... | def make_action_list(self, item_list, **kwargs):
""" Generates a list of actions for sending to Elasticsearch """
action_list = []
es_index = get2(kwargs, 'es_index', self.es_index)
action_type = kwargs.get('action_type', 'index')
action_settings = {'_op_type': action_type, '_index': es_index}
d... |
def _write(self, lines, fname):
"""
Writes a intermediate temporary sorted file
:param lines: The lines to write.
:param fname: The name of the temporary file.
:return:
"""
with open(fname, 'wb') as out_fhndl:
for line in sorted(lines, key=self.key):
... | def function[_write, parameter[self, lines, fname]]:
constant[
Writes a intermediate temporary sorted file
:param lines: The lines to write.
:param fname: The name of the temporary file.
:return:
]
with call[name[open], parameter[name[fname], constant[wb]]] begin... | keyword[def] identifier[_write] ( identifier[self] , identifier[lines] , identifier[fname] ):
literal[string]
keyword[with] identifier[open] ( identifier[fname] , literal[string] ) keyword[as] identifier[out_fhndl] :
keyword[for] identifier[line] keyword[in] identifier[sorted] ( i... | def _write(self, lines, fname):
"""
Writes a intermediate temporary sorted file
:param lines: The lines to write.
:param fname: The name of the temporary file.
:return:
"""
with open(fname, 'wb') as out_fhndl:
for line in sorted(lines, key=self.key):
... |
def reload(self):
"""Reload the configuration from disk returning True if the
configuration has changed from the previous values.
"""
config = self._default_configuration()
if self._file_path:
config.update(self._load_config_file())
if config != self._values:... | def function[reload, parameter[self]]:
constant[Reload the configuration from disk returning True if the
configuration has changed from the previous values.
]
variable[config] assign[=] call[name[self]._default_configuration, parameter[]]
if name[self]._file_path begin[:]
... | keyword[def] identifier[reload] ( identifier[self] ):
literal[string]
identifier[config] = identifier[self] . identifier[_default_configuration] ()
keyword[if] identifier[self] . identifier[_file_path] :
identifier[config] . identifier[update] ( identifier[self] . identifier[... | def reload(self):
"""Reload the configuration from disk returning True if the
configuration has changed from the previous values.
"""
config = self._default_configuration()
if self._file_path:
config.update(self._load_config_file()) # depends on [control=['if'], data=[]]
if con... |
def config_flag(self, which, new=None):
"""
Get or set a config flag.
'which' can be either a string ('PACING_20MS' etc.), or an integer.
You should ALWAYS use a string, unless you really know what you are doing.
"""
flag = _get_flag(which, ConfigFlags)
if flag:
... | def function[config_flag, parameter[self, which, new]]:
constant[
Get or set a config flag.
'which' can be either a string ('PACING_20MS' etc.), or an integer.
You should ALWAYS use a string, unless you really know what you are doing.
]
variable[flag] assign[=] call[name... | keyword[def] identifier[config_flag] ( identifier[self] , identifier[which] , identifier[new] = keyword[None] ):
literal[string]
identifier[flag] = identifier[_get_flag] ( identifier[which] , identifier[ConfigFlags] )
keyword[if] identifier[flag] :
keyword[if] keyword[not] ... | def config_flag(self, which, new=None):
"""
Get or set a config flag.
'which' can be either a string ('PACING_20MS' etc.), or an integer.
You should ALWAYS use a string, unless you really know what you are doing.
"""
flag = _get_flag(which, ConfigFlags)
if flag:
if n... |
def interval_host(host, time, f, *args, **kwargs):
'''
Creates an Event attached to the *host* for management that will
execute the *f* function every *time* seconds.
See example in :ref:`sample_inter`
:param Proxy host: proxy of the host. Can be obtained from inside a
class with ``self.ho... | def function[interval_host, parameter[host, time, f]]:
constant[
Creates an Event attached to the *host* for management that will
execute the *f* function every *time* seconds.
See example in :ref:`sample_inter`
:param Proxy host: proxy of the host. Can be obtained from inside a
class ... | keyword[def] identifier[interval_host] ( identifier[host] , identifier[time] , identifier[f] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
keyword[def] identifier[wrap] (* identifier[args] ,** identifier[kwargs] ):
identifier[thread] = identifier[getcurrent] ()
identifier... | def interval_host(host, time, f, *args, **kwargs):
"""
Creates an Event attached to the *host* for management that will
execute the *f* function every *time* seconds.
See example in :ref:`sample_inter`
:param Proxy host: proxy of the host. Can be obtained from inside a
class with ``self.ho... |
def get_dict_leaves(data):
"""
Given a nested dictionary, this returns all its leave elements in a list.
:param adict:
:return: list
"""
result = []
if isinstance(data, dict):
for item in data.values():
result.extend(get_dict_leaves(item))
elif isinstance(data, list... | def function[get_dict_leaves, parameter[data]]:
constant[
Given a nested dictionary, this returns all its leave elements in a list.
:param adict:
:return: list
]
variable[result] assign[=] list[[]]
if call[name[isinstance], parameter[name[data], name[dict]]] begin[:]
... | keyword[def] identifier[get_dict_leaves] ( identifier[data] ):
literal[string]
identifier[result] =[]
keyword[if] identifier[isinstance] ( identifier[data] , identifier[dict] ):
keyword[for] identifier[item] keyword[in] identifier[data] . identifier[values] ():
identifier[res... | def get_dict_leaves(data):
"""
Given a nested dictionary, this returns all its leave elements in a list.
:param adict:
:return: list
"""
result = []
if isinstance(data, dict):
for item in data.values():
result.extend(get_dict_leaves(item)) # depends on [control=['for']... |
def _q_to_dcm(self, q):
"""
Create DCM from q
:param q: array q which represents a quaternion [w, x, y, z]
:returns: 3x3 dcm array
"""
assert(len(q) == 4)
assert(np.allclose(QuaternionBase.norm_array(q), 1))
dcm = np.zeros([3, 3])
a = q[0]
... | def function[_q_to_dcm, parameter[self, q]]:
constant[
Create DCM from q
:param q: array q which represents a quaternion [w, x, y, z]
:returns: 3x3 dcm array
]
assert[compare[call[name[len], parameter[name[q]]] equal[==] constant[4]]]
assert[call[name[np].allclose, parame... | keyword[def] identifier[_q_to_dcm] ( identifier[self] , identifier[q] ):
literal[string]
keyword[assert] ( identifier[len] ( identifier[q] )== literal[int] )
keyword[assert] ( identifier[np] . identifier[allclose] ( identifier[QuaternionBase] . identifier[norm_array] ( identifier[q] ), lit... | def _q_to_dcm(self, q):
"""
Create DCM from q
:param q: array q which represents a quaternion [w, x, y, z]
:returns: 3x3 dcm array
"""
assert len(q) == 4
assert np.allclose(QuaternionBase.norm_array(q), 1)
dcm = np.zeros([3, 3])
a = q[0]
b = q[1]
c = q[2]
... |
def _find_function(name,
region=None, key=None, keyid=None, profile=None):
'''
Given function name, find and return matching Lambda information.
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
for funcs in __utils__['boto3.paged_call'](conn.list_functio... | def function[_find_function, parameter[name, region, key, keyid, profile]]:
constant[
Given function name, find and return matching Lambda information.
]
variable[conn] assign[=] call[name[_get_conn], parameter[]]
for taget[name[funcs]] in starred[call[call[name[__utils__]][constant[boto... | keyword[def] identifier[_find_function] ( identifier[name] ,
identifier[region] = keyword[None] , identifier[key] = keyword[None] , identifier[keyid] = keyword[None] , identifier[profile] = keyword[None] ):
literal[string]
identifier[conn] = identifier[_get_conn] ( identifier[region] = identifier[region] ... | def _find_function(name, region=None, key=None, keyid=None, profile=None):
"""
Given function name, find and return matching Lambda information.
"""
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
for funcs in __utils__['boto3.paged_call'](conn.list_functions):
for fun... |
def remove(self, index=None, hash=None, keepSorted=True):
"""
Removes a particle from the simulation.
Parameters
----------
index : int, optional
Specify particle to remove by index.
hash : c_uint32 or string, optional
Specifiy particle to remove... | def function[remove, parameter[self, index, hash, keepSorted]]:
constant[
Removes a particle from the simulation.
Parameters
----------
index : int, optional
Specify particle to remove by index.
hash : c_uint32 or string, optional
Specifiy partic... | keyword[def] identifier[remove] ( identifier[self] , identifier[index] = keyword[None] , identifier[hash] = keyword[None] , identifier[keepSorted] = keyword[True] ):
literal[string]
keyword[if] identifier[index] keyword[is] keyword[not] keyword[None] :
identifier[clibrebound] . ide... | def remove(self, index=None, hash=None, keepSorted=True):
"""
Removes a particle from the simulation.
Parameters
----------
index : int, optional
Specify particle to remove by index.
hash : c_uint32 or string, optional
Specifiy particle to remove by ... |
def p_goto(p):
""" statement : goto NUMBER
| goto ID
"""
entry = check_and_make_label(p[2], p.lineno(2))
if entry is not None:
p[0] = make_sentence(p[1].upper(), entry)
else:
p[0] = None | def function[p_goto, parameter[p]]:
constant[ statement : goto NUMBER
| goto ID
]
variable[entry] assign[=] call[name[check_and_make_label], parameter[call[name[p]][constant[2]], call[name[p].lineno, parameter[constant[2]]]]]
if compare[name[entry] is_not constant[None]] be... | keyword[def] identifier[p_goto] ( identifier[p] ):
literal[string]
identifier[entry] = identifier[check_and_make_label] ( identifier[p] [ literal[int] ], identifier[p] . identifier[lineno] ( literal[int] ))
keyword[if] identifier[entry] keyword[is] keyword[not] keyword[None] :
identifier[... | def p_goto(p):
""" statement : goto NUMBER
| goto ID
"""
entry = check_and_make_label(p[2], p.lineno(2))
if entry is not None:
p[0] = make_sentence(p[1].upper(), entry) # depends on [control=['if'], data=['entry']]
else:
p[0] = None |
def respond(self, text, sessionID = "general"):
"""
Generate a response to the user input.
:type text: str
:param text: The string to be mapped
:rtype: str
"""
text = self.__normalize(text)
previousText = self.__normalize(self.conversation[sessionID][-2]... | def function[respond, parameter[self, text, sessionID]]:
constant[
Generate a response to the user input.
:type text: str
:param text: The string to be mapped
:rtype: str
]
variable[text] assign[=] call[name[self].__normalize, parameter[name[text]]]
varia... | keyword[def] identifier[respond] ( identifier[self] , identifier[text] , identifier[sessionID] = literal[string] ):
literal[string]
identifier[text] = identifier[self] . identifier[__normalize] ( identifier[text] )
identifier[previousText] = identifier[self] . identifier[__normalize] ( ide... | def respond(self, text, sessionID='general'):
"""
Generate a response to the user input.
:type text: str
:param text: The string to be mapped
:rtype: str
"""
text = self.__normalize(text)
previousText = self.__normalize(self.conversation[sessionID][-2])
text_corr... |
def validate_ENUM(in_value, restriction):
"""
Test to ensure that the given value is contained in the provided list.
the value parameter must be either a single value or a 1-dimensional list.
All the values in this list must satisfy the ENUM
"""
value = _get_val(in_value)
if type... | def function[validate_ENUM, parameter[in_value, restriction]]:
constant[
Test to ensure that the given value is contained in the provided list.
the value parameter must be either a single value or a 1-dimensional list.
All the values in this list must satisfy the ENUM
]
varia... | keyword[def] identifier[validate_ENUM] ( identifier[in_value] , identifier[restriction] ):
literal[string]
identifier[value] = identifier[_get_val] ( identifier[in_value] )
keyword[if] identifier[type] ( identifier[value] ) keyword[is] identifier[list] :
keyword[for] identifier[subval] ke... | def validate_ENUM(in_value, restriction):
"""
Test to ensure that the given value is contained in the provided list.
the value parameter must be either a single value or a 1-dimensional list.
All the values in this list must satisfy the ENUM
"""
value = _get_val(in_value)
if type... |
async def fromURL(
cls, url, *, credentials=None, insecure=False):
"""Return a `SessionAPI` for a given MAAS instance."""
try:
description = await helpers.fetch_api_description(
url, insecure=insecure)
except helpers.RemoteError as error:
# For... | <ast.AsyncFunctionDef object at 0x7da20c76f1f0> | keyword[async] keyword[def] identifier[fromURL] (
identifier[cls] , identifier[url] ,*, identifier[credentials] = keyword[None] , identifier[insecure] = keyword[False] ):
literal[string]
keyword[try] :
identifier[description] = keyword[await] identifier[helpers] . identifier[fetch_a... | async def fromURL(cls, url, *, credentials=None, insecure=False):
"""Return a `SessionAPI` for a given MAAS instance."""
try:
description = await helpers.fetch_api_description(url, insecure=insecure) # depends on [control=['try'], data=[]]
except helpers.RemoteError as error:
# For now just... |
def annual_event_counts(kind='all'):
"""
Returns a QuerySet of dicts, each one with these keys:
* year - a date object representing the year
* total - the number of events of `kind` that year
kind - The Event `kind`, or 'all' for all kinds (default).
"""
qs = Event.objects
if ... | def function[annual_event_counts, parameter[kind]]:
constant[
Returns a QuerySet of dicts, each one with these keys:
* year - a date object representing the year
* total - the number of events of `kind` that year
kind - The Event `kind`, or 'all' for all kinds (default).
]
... | keyword[def] identifier[annual_event_counts] ( identifier[kind] = literal[string] ):
literal[string]
identifier[qs] = identifier[Event] . identifier[objects]
keyword[if] identifier[kind] != literal[string] :
identifier[qs] = identifier[qs] . identifier[filter] ( identifier[kind] = identifi... | def annual_event_counts(kind='all'):
"""
Returns a QuerySet of dicts, each one with these keys:
* year - a date object representing the year
* total - the number of events of `kind` that year
kind - The Event `kind`, or 'all' for all kinds (default).
"""
qs = Event.objects
if k... |
def _to_dict(self):
"""Return a json dictionary representing this model."""
_dict = {}
if hasattr(self, 'position') and self.position is not None:
_dict['position'] = self.position
if hasattr(self, 'document_id') and self.document_id is not None:
_dict['document_i... | def function[_to_dict, parameter[self]]:
constant[Return a json dictionary representing this model.]
variable[_dict] assign[=] dictionary[[], []]
if <ast.BoolOp object at 0x7da18fe907f0> begin[:]
call[name[_dict]][constant[position]] assign[=] name[self].position
if <ast.... | keyword[def] identifier[_to_dict] ( identifier[self] ):
literal[string]
identifier[_dict] ={}
keyword[if] identifier[hasattr] ( identifier[self] , literal[string] ) keyword[and] identifier[self] . identifier[position] keyword[is] keyword[not] keyword[None] :
identifier[_d... | def _to_dict(self):
"""Return a json dictionary representing this model."""
_dict = {}
if hasattr(self, 'position') and self.position is not None:
_dict['position'] = self.position # depends on [control=['if'], data=[]]
if hasattr(self, 'document_id') and self.document_id is not None:
_... |
def namedb_op_sanity_check( opcode, op_data, record ):
"""
Sanity checks over operation and state graph data:
* opcode and op_data must be consistent
* record must have an opcode
* the given opcode must be reachable from it.
"""
assert 'address' in record, "BUG: current record has no 'addre... | def function[namedb_op_sanity_check, parameter[opcode, op_data, record]]:
constant[
Sanity checks over operation and state graph data:
* opcode and op_data must be consistent
* record must have an opcode
* the given opcode must be reachable from it.
]
assert[compare[constant[address] in ... | keyword[def] identifier[namedb_op_sanity_check] ( identifier[opcode] , identifier[op_data] , identifier[record] ):
literal[string]
keyword[assert] literal[string] keyword[in] identifier[record] , literal[string]
keyword[assert] identifier[op_data] . identifier[has_key] ( literal[string] ), lite... | def namedb_op_sanity_check(opcode, op_data, record):
"""
Sanity checks over operation and state graph data:
* opcode and op_data must be consistent
* record must have an opcode
* the given opcode must be reachable from it.
"""
assert 'address' in record, "BUG: current record has no 'address'... |
def find(self, *args, **kwargs):
"""Find and return the files collection documents that match ``filter``.
Returns a cursor that iterates across files matching
arbitrary queries on the files collection. Can be combined
with other modifiers for additional control.
For example::
... | def function[find, parameter[self]]:
constant[Find and return the files collection documents that match ``filter``.
Returns a cursor that iterates across files matching
arbitrary queries on the files collection. Can be combined
with other modifiers for additional control.
For e... | keyword[def] identifier[find] ( identifier[self] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
identifier[cursor] = identifier[self] . identifier[delegate] . identifier[find] (* identifier[args] ,** identifier[kwargs] )
identifier[grid_out_cursor] = identifier[create_class_... | def find(self, *args, **kwargs):
"""Find and return the files collection documents that match ``filter``.
Returns a cursor that iterates across files matching
arbitrary queries on the files collection. Can be combined
with other modifiers for additional control.
For example::
... |
def rmdir(self, paths):
''' Delete a directory
:param paths: Paths to delete
:type paths: list
:returns: a generator that yields dictionaries
.. note: directories have to be empty.
'''
if not isinstance(paths, list):
raise InvalidInputException("Path... | def function[rmdir, parameter[self, paths]]:
constant[ Delete a directory
:param paths: Paths to delete
:type paths: list
:returns: a generator that yields dictionaries
.. note: directories have to be empty.
]
if <ast.UnaryOp object at 0x7da1b08f9810> begin[:]
... | keyword[def] identifier[rmdir] ( identifier[self] , identifier[paths] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[paths] , identifier[list] ):
keyword[raise] identifier[InvalidInputException] ( literal[string] )
keyword[if] keyword[not] ... | def rmdir(self, paths):
""" Delete a directory
:param paths: Paths to delete
:type paths: list
:returns: a generator that yields dictionaries
.. note: directories have to be empty.
"""
if not isinstance(paths, list):
raise InvalidInputException('Paths should be ... |
def provision_system_vessel(items, database_name, overwrite=False, clear=False, skip_user_check=False):
"""Provisions the default system vessel"""
from hfos.provisions.base import provisionList
from hfos.database import objectmodels
vessel = objectmodels['vessel'].find_one({'name': 'Default System Ves... | def function[provision_system_vessel, parameter[items, database_name, overwrite, clear, skip_user_check]]:
constant[Provisions the default system vessel]
from relative_module[hfos.provisions.base] import module[provisionList]
from relative_module[hfos.database] import module[objectmodels]
variab... | keyword[def] identifier[provision_system_vessel] ( identifier[items] , identifier[database_name] , identifier[overwrite] = keyword[False] , identifier[clear] = keyword[False] , identifier[skip_user_check] = keyword[False] ):
literal[string]
keyword[from] identifier[hfos] . identifier[provisions] . identi... | def provision_system_vessel(items, database_name, overwrite=False, clear=False, skip_user_check=False):
"""Provisions the default system vessel"""
from hfos.provisions.base import provisionList
from hfos.database import objectmodels
vessel = objectmodels['vessel'].find_one({'name': 'Default System Vesse... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.