code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def safe_put_bulk(self, url, bulk_json):
""" Bulk PUT controlling unicode issues """
headers = {"Content-Type": "application/x-ndjson"}
try:
res = self.requests.put(url + '?refresh=true', data=bulk_json, headers=headers)
res.raise_for_status()
except UnicodeEnco... | def function[safe_put_bulk, parameter[self, url, bulk_json]]:
constant[ Bulk PUT controlling unicode issues ]
variable[headers] assign[=] dictionary[[<ast.Constant object at 0x7da1b0fefeb0>], [<ast.Constant object at 0x7da1b0fef520>]]
<ast.Try object at 0x7da1b0fef580>
variable[result] assig... | keyword[def] identifier[safe_put_bulk] ( identifier[self] , identifier[url] , identifier[bulk_json] ):
literal[string]
identifier[headers] ={ literal[string] : literal[string] }
keyword[try] :
identifier[res] = identifier[self] . identifier[requests] . identifier[put] ( iden... | def safe_put_bulk(self, url, bulk_json):
""" Bulk PUT controlling unicode issues """
headers = {'Content-Type': 'application/x-ndjson'}
try:
res = self.requests.put(url + '?refresh=true', data=bulk_json, headers=headers)
res.raise_for_status() # depends on [control=['try'], data=[]]
exc... |
def generate_data_for_env_problem(problem_name):
"""Generate data for `EnvProblem`s."""
assert FLAGS.env_problem_max_env_steps > 0, ("--env_problem_max_env_steps "
"should be greater than zero")
assert FLAGS.env_problem_batch_size > 0, ("--env_problem_batch_size shou... | def function[generate_data_for_env_problem, parameter[problem_name]]:
constant[Generate data for `EnvProblem`s.]
assert[compare[name[FLAGS].env_problem_max_env_steps greater[>] constant[0]]]
assert[compare[name[FLAGS].env_problem_batch_size greater[>] constant[0]]]
variable[problem] assign[=] ca... | keyword[def] identifier[generate_data_for_env_problem] ( identifier[problem_name] ):
literal[string]
keyword[assert] identifier[FLAGS] . identifier[env_problem_max_env_steps] > literal[int] ,( literal[string]
literal[string] )
keyword[assert] identifier[FLAGS] . identifier[env_problem_batch_size] > li... | def generate_data_for_env_problem(problem_name):
"""Generate data for `EnvProblem`s."""
assert FLAGS.env_problem_max_env_steps > 0, '--env_problem_max_env_steps should be greater than zero'
assert FLAGS.env_problem_batch_size > 0, '--env_problem_batch_size should be greather than zero'
problem = registr... |
def _load_cell(args, cell_body):
"""Implements the BigQuery load magic used to load data from GCS to a table.
The supported syntax is:
%bq load <optional args>
Args:
args: the arguments following '%bq load'.
cell_body: optional contents of the cell interpreted as YAML or JSON.
Returns:
A ... | def function[_load_cell, parameter[args, cell_body]]:
constant[Implements the BigQuery load magic used to load data from GCS to a table.
The supported syntax is:
%bq load <optional args>
Args:
args: the arguments following '%bq load'.
cell_body: optional contents of the cell interpreted a... | keyword[def] identifier[_load_cell] ( identifier[args] , identifier[cell_body] ):
literal[string]
identifier[env] = identifier[google] . identifier[datalab] . identifier[utils] . identifier[commands] . identifier[notebook_environment] ()
identifier[config] = identifier[google] . identifier[datalab] . identi... | def _load_cell(args, cell_body):
"""Implements the BigQuery load magic used to load data from GCS to a table.
The supported syntax is:
%bq load <optional args>
Args:
args: the arguments following '%bq load'.
cell_body: optional contents of the cell interpreted as YAML or JSON.
Returns:
... |
def expand_with_style(template, style, data, body_subtree='body'):
"""Expand a data dictionary with a template AND a style.
DEPRECATED -- Remove this entire function in favor of expand(d, style=style)
A style is a Template instance that factors out the common strings in several
"body" templates.
Args:
... | def function[expand_with_style, parameter[template, style, data, body_subtree]]:
constant[Expand a data dictionary with a template AND a style.
DEPRECATED -- Remove this entire function in favor of expand(d, style=style)
A style is a Template instance that factors out the common strings in several
"body... | keyword[def] identifier[expand_with_style] ( identifier[template] , identifier[style] , identifier[data] , identifier[body_subtree] = literal[string] ):
literal[string]
keyword[if] identifier[template] . identifier[has_defines] :
keyword[return] identifier[template] . identifier[expand] ( identi... | def expand_with_style(template, style, data, body_subtree='body'):
"""Expand a data dictionary with a template AND a style.
DEPRECATED -- Remove this entire function in favor of expand(d, style=style)
A style is a Template instance that factors out the common strings in several
"body" templates.
Args:
... |
def dfa(data, nvals=None, overlap=True, order=1, fit_trend="poly",
fit_exp="RANSAC", debug_plot=False, debug_data=False, plot_file=None):
"""
Performs a detrended fluctuation analysis (DFA) on the given data
Recommendations for parameter settings by Hardstone et al.:
* nvals should be equally spaced ... | def function[dfa, parameter[data, nvals, overlap, order, fit_trend, fit_exp, debug_plot, debug_data, plot_file]]:
constant[
Performs a detrended fluctuation analysis (DFA) on the given data
Recommendations for parameter settings by Hardstone et al.:
* nvals should be equally spaced on a logarithmic sca... | keyword[def] identifier[dfa] ( identifier[data] , identifier[nvals] = keyword[None] , identifier[overlap] = keyword[True] , identifier[order] = literal[int] , identifier[fit_trend] = literal[string] ,
identifier[fit_exp] = literal[string] , identifier[debug_plot] = keyword[False] , identifier[debug_data] = keyword[F... | def dfa(data, nvals=None, overlap=True, order=1, fit_trend='poly', fit_exp='RANSAC', debug_plot=False, debug_data=False, plot_file=None):
"""
Performs a detrended fluctuation analysis (DFA) on the given data
Recommendations for parameter settings by Hardstone et al.:
* nvals should be equally spaced on a l... |
def deprecated(*optional_message):
"""This is a decorator which can be used to mark functions
as deprecated. It will result in a warning being emitted
when the function is used.
Parameters
----------
*optional_message : str
an optional user level hint which should indicate which feature... | def function[deprecated, parameter[]]:
constant[This is a decorator which can be used to mark functions
as deprecated. It will result in a warning being emitted
when the function is used.
Parameters
----------
*optional_message : str
an optional user level hint which should indicate... | keyword[def] identifier[deprecated] (* identifier[optional_message] ):
literal[string]
keyword[def] identifier[_deprecated] ( identifier[func] ,* identifier[args] ,** identifier[kw] ):
identifier[caller_stack] = identifier[stack] ()[ literal[int] :]
keyword[while] identifier[len] ( iden... | def deprecated(*optional_message):
"""This is a decorator which can be used to mark functions
as deprecated. It will result in a warning being emitted
when the function is used.
Parameters
----------
*optional_message : str
an optional user level hint which should indicate which feature... |
def colRegex(self, colName):
"""
Selects column based on the column name specified as a regex and returns it
as :class:`Column`.
:param colName: string, column name specified as a regex.
>>> df = spark.createDataFrame([("a", 1), ("b", 2), ("c", 3)], ["Col1", "Col2"])
>... | def function[colRegex, parameter[self, colName]]:
constant[
Selects column based on the column name specified as a regex and returns it
as :class:`Column`.
:param colName: string, column name specified as a regex.
>>> df = spark.createDataFrame([("a", 1), ("b", 2), ("c", 3)], ... | keyword[def] identifier[colRegex] ( identifier[self] , identifier[colName] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[colName] , identifier[basestring] ):
keyword[raise] identifier[ValueError] ( literal[string] )
identifier[jc] = identif... | def colRegex(self, colName):
"""
Selects column based on the column name specified as a regex and returns it
as :class:`Column`.
:param colName: string, column name specified as a regex.
>>> df = spark.createDataFrame([("a", 1), ("b", 2), ("c", 3)], ["Col1", "Col2"])
>>> d... |
def lookup_document_pointer(ident_hash, cursor):
"""Lookup a document by id and version."""
id, version = split_ident_hash(ident_hash, split_version=True)
stmt = "SELECT name FROM modules WHERE uuid = %s"
args = [id]
if version and version[0] is not None:
operator = version[1] is None and 'i... | def function[lookup_document_pointer, parameter[ident_hash, cursor]]:
constant[Lookup a document by id and version.]
<ast.Tuple object at 0x7da1b003c580> assign[=] call[name[split_ident_hash], parameter[name[ident_hash]]]
variable[stmt] assign[=] constant[SELECT name FROM modules WHERE uuid = %s... | keyword[def] identifier[lookup_document_pointer] ( identifier[ident_hash] , identifier[cursor] ):
literal[string]
identifier[id] , identifier[version] = identifier[split_ident_hash] ( identifier[ident_hash] , identifier[split_version] = keyword[True] )
identifier[stmt] = literal[string]
identifi... | def lookup_document_pointer(ident_hash, cursor):
"""Lookup a document by id and version."""
(id, version) = split_ident_hash(ident_hash, split_version=True)
stmt = 'SELECT name FROM modules WHERE uuid = %s'
args = [id]
if version and version[0] is not None:
operator = version[1] is None and ... |
def _make_command_method(cls, command_name):
"""
Return a function which call _call_command for the given name.
Used to bind redis commands to our own calls
"""
def func(self, *args, **kwargs):
return self._call_command(command_name, *args, **kwargs)
return fu... | def function[_make_command_method, parameter[cls, command_name]]:
constant[
Return a function which call _call_command for the given name.
Used to bind redis commands to our own calls
]
def function[func, parameter[self]]:
return[call[name[self]._call_command, parameter[n... | keyword[def] identifier[_make_command_method] ( identifier[cls] , identifier[command_name] ):
literal[string]
keyword[def] identifier[func] ( identifier[self] ,* identifier[args] ,** identifier[kwargs] ):
keyword[return] identifier[self] . identifier[_call_command] ( identifier[comma... | def _make_command_method(cls, command_name):
"""
Return a function which call _call_command for the given name.
Used to bind redis commands to our own calls
"""
def func(self, *args, **kwargs):
return self._call_command(command_name, *args, **kwargs)
return func |
def get_child_values(parent, names):
""" return a list of values for the specified child fields. If field not in Element then replace with nan. """
vals = []
for name in names:
if parent.HasElement(name):
vals.append(XmlHelper.as_value(parent.GetElement(name)))
... | def function[get_child_values, parameter[parent, names]]:
constant[ return a list of values for the specified child fields. If field not in Element then replace with nan. ]
variable[vals] assign[=] list[[]]
for taget[name[name]] in starred[name[names]] begin[:]
if call[name[paren... | keyword[def] identifier[get_child_values] ( identifier[parent] , identifier[names] ):
literal[string]
identifier[vals] =[]
keyword[for] identifier[name] keyword[in] identifier[names] :
keyword[if] identifier[parent] . identifier[HasElement] ( identifier[name] ):
... | def get_child_values(parent, names):
""" return a list of values for the specified child fields. If field not in Element then replace with nan. """
vals = []
for name in names:
if parent.HasElement(name):
vals.append(XmlHelper.as_value(parent.GetElement(name))) # depends on [control=['i... |
def device_path(cls, project, location, registry, device):
"""Return a fully-qualified device string."""
return google.api_core.path_template.expand(
"projects/{project}/locations/{location}/registries/{registry}/devices/{device}",
project=project,
location=location,
... | def function[device_path, parameter[cls, project, location, registry, device]]:
constant[Return a fully-qualified device string.]
return[call[name[google].api_core.path_template.expand, parameter[constant[projects/{project}/locations/{location}/registries/{registry}/devices/{device}]]]] | keyword[def] identifier[device_path] ( identifier[cls] , identifier[project] , identifier[location] , identifier[registry] , identifier[device] ):
literal[string]
keyword[return] identifier[google] . identifier[api_core] . identifier[path_template] . identifier[expand] (
literal[string] ,... | def device_path(cls, project, location, registry, device):
"""Return a fully-qualified device string."""
return google.api_core.path_template.expand('projects/{project}/locations/{location}/registries/{registry}/devices/{device}', project=project, location=location, registry=registry, device=device) |
def create_key_to_messages_dict(messages):
"""Return dict mapping the key to list of messages."""
dictionary = collections.defaultdict(lambda: [])
for message in messages:
dictionary[message.message_args[0]].append(message)
return dictionary | def function[create_key_to_messages_dict, parameter[messages]]:
constant[Return dict mapping the key to list of messages.]
variable[dictionary] assign[=] call[name[collections].defaultdict, parameter[<ast.Lambda object at 0x7da1b0297760>]]
for taget[name[message]] in starred[name[messages]] begi... | keyword[def] identifier[create_key_to_messages_dict] ( identifier[messages] ):
literal[string]
identifier[dictionary] = identifier[collections] . identifier[defaultdict] ( keyword[lambda] :[])
keyword[for] identifier[message] keyword[in] identifier[messages] :
identifier[dictionary] [ iden... | def create_key_to_messages_dict(messages):
"""Return dict mapping the key to list of messages."""
dictionary = collections.defaultdict(lambda : [])
for message in messages:
dictionary[message.message_args[0]].append(message) # depends on [control=['for'], data=['message']]
return dictionary |
def _get_exceptions_db(self):
"""Return a list of dictionaries suitable to be used with ptrie module."""
template = "{extype} ({exmsg}){raised}"
if not self._full_cname:
# When full callable name is not used the calling path is
# irrelevant and there is no function associ... | def function[_get_exceptions_db, parameter[self]]:
constant[Return a list of dictionaries suitable to be used with ptrie module.]
variable[template] assign[=] constant[{extype} ({exmsg}){raised}]
if <ast.UnaryOp object at 0x7da1b2587130> begin[:]
variable[ret] assign[=] list[[]]
... | keyword[def] identifier[_get_exceptions_db] ( identifier[self] ):
literal[string]
identifier[template] = literal[string]
keyword[if] keyword[not] identifier[self] . identifier[_full_cname] :
identifier[ret] =[]
keyword[for] identifie... | def _get_exceptions_db(self):
"""Return a list of dictionaries suitable to be used with ptrie module."""
template = '{extype} ({exmsg}){raised}'
if not self._full_cname:
# When full callable name is not used the calling path is
# irrelevant and there is no function associated with an
... |
def _progress_print(self, sent, total):
"""Progress print show the progress of the current upload with a neat progress bar
Credits: http://redino.net/blog/2013/07/display-a-progress-bar-in-console-using-python/
"""
percent = min(int(sent*100.0/total), 100)
sys.stdout.write('\r... | def function[_progress_print, parameter[self, sent, total]]:
constant[Progress print show the progress of the current upload with a neat progress bar
Credits: http://redino.net/blog/2013/07/display-a-progress-bar-in-console-using-python/
]
variable[percent] assign[=] call[name[min], p... | keyword[def] identifier[_progress_print] ( identifier[self] , identifier[sent] , identifier[total] ):
literal[string]
identifier[percent] = identifier[min] ( identifier[int] ( identifier[sent] * literal[int] / identifier[total] ), literal[int] )
identifier[sys] . identifier[stdout] . ident... | def _progress_print(self, sent, total):
"""Progress print show the progress of the current upload with a neat progress bar
Credits: http://redino.net/blog/2013/07/display-a-progress-bar-in-console-using-python/
"""
percent = min(int(sent * 100.0 / total), 100)
sys.stdout.write('\r{0}[{1}{... |
def add_cxnSp(self, id_, name, type_member, x, y, cx, cy, flipH, flipV):
"""
Append a new ``<p:cxnSp>`` shape to the group/shapetree having the
properties specified in call.
"""
prst = MSO_CONNECTOR_TYPE.to_xml(type_member)
cxnSp = CT_Connector.new_cxnSp(
id_,... | def function[add_cxnSp, parameter[self, id_, name, type_member, x, y, cx, cy, flipH, flipV]]:
constant[
Append a new ``<p:cxnSp>`` shape to the group/shapetree having the
properties specified in call.
]
variable[prst] assign[=] call[name[MSO_CONNECTOR_TYPE].to_xml, parameter[name... | keyword[def] identifier[add_cxnSp] ( identifier[self] , identifier[id_] , identifier[name] , identifier[type_member] , identifier[x] , identifier[y] , identifier[cx] , identifier[cy] , identifier[flipH] , identifier[flipV] ):
literal[string]
identifier[prst] = identifier[MSO_CONNECTOR_TYPE] . ident... | def add_cxnSp(self, id_, name, type_member, x, y, cx, cy, flipH, flipV):
"""
Append a new ``<p:cxnSp>`` shape to the group/shapetree having the
properties specified in call.
"""
prst = MSO_CONNECTOR_TYPE.to_xml(type_member)
cxnSp = CT_Connector.new_cxnSp(id_, name, prst, x, y, cx, cy... |
def _change_source_state(name, state):
'''
Instructs Chocolatey to change the state of a source.
name
Name of the repository to affect.
state
State in which you want the chocolatey repository.
'''
choc_path = _find_chocolatey(__context__, __salt__)
cmd = [choc_path, 'sourc... | def function[_change_source_state, parameter[name, state]]:
constant[
Instructs Chocolatey to change the state of a source.
name
Name of the repository to affect.
state
State in which you want the chocolatey repository.
]
variable[choc_path] assign[=] call[name[_find_c... | keyword[def] identifier[_change_source_state] ( identifier[name] , identifier[state] ):
literal[string]
identifier[choc_path] = identifier[_find_chocolatey] ( identifier[__context__] , identifier[__salt__] )
identifier[cmd] =[ identifier[choc_path] , literal[string] , identifier[state] , literal[strin... | def _change_source_state(name, state):
"""
Instructs Chocolatey to change the state of a source.
name
Name of the repository to affect.
state
State in which you want the chocolatey repository.
"""
choc_path = _find_chocolatey(__context__, __salt__)
cmd = [choc_path, 'sourc... |
def set_computer_sleep(minutes):
'''
Set the amount of idle time until the computer sleeps. Pass "Never" of "Off"
to never sleep.
:param minutes: Can be an integer between 1 and 180 or "Never" or "Off"
:ptype: int, str
:return: True if successful, False if not
:rtype: bool
CLI Example... | def function[set_computer_sleep, parameter[minutes]]:
constant[
Set the amount of idle time until the computer sleeps. Pass "Never" of "Off"
to never sleep.
:param minutes: Can be an integer between 1 and 180 or "Never" or "Off"
:ptype: int, str
:return: True if successful, False if not
... | keyword[def] identifier[set_computer_sleep] ( identifier[minutes] ):
literal[string]
identifier[value] = identifier[_validate_sleep] ( identifier[minutes] )
identifier[cmd] = literal[string] . identifier[format] ( identifier[value] )
identifier[salt] . identifier[utils] . identifier[mac_utils] . ... | def set_computer_sleep(minutes):
"""
Set the amount of idle time until the computer sleeps. Pass "Never" of "Off"
to never sleep.
:param minutes: Can be an integer between 1 and 180 or "Never" or "Off"
:ptype: int, str
:return: True if successful, False if not
:rtype: bool
CLI Example... |
def find_next_comma(self, node, sub):
"""Find comma after sub andd add NodeWithPosition in node"""
position = (sub.last_line, sub.last_col)
first, last = find_next_comma(self.lcode, position)
if first: # comma exists
node.op_pos.append(NodeWithPosition(last, first)) | def function[find_next_comma, parameter[self, node, sub]]:
constant[Find comma after sub andd add NodeWithPosition in node]
variable[position] assign[=] tuple[[<ast.Attribute object at 0x7da1b170f1c0>, <ast.Attribute object at 0x7da1b170c070>]]
<ast.Tuple object at 0x7da1b170f940> assign[=] call... | keyword[def] identifier[find_next_comma] ( identifier[self] , identifier[node] , identifier[sub] ):
literal[string]
identifier[position] =( identifier[sub] . identifier[last_line] , identifier[sub] . identifier[last_col] )
identifier[first] , identifier[last] = identifier[find_next_comma] ... | def find_next_comma(self, node, sub):
"""Find comma after sub andd add NodeWithPosition in node"""
position = (sub.last_line, sub.last_col)
(first, last) = find_next_comma(self.lcode, position)
if first: # comma exists
node.op_pos.append(NodeWithPosition(last, first)) # depends on [control=['i... |
def quantile_curve(quantile, curves, weights=None):
"""
Compute the weighted quantile aggregate of a set of curves.
:param quantile:
Quantile value to calculate. Should be in the range [0.0, 1.0].
:param curves:
Array of R PoEs (possibly arrays)
:param weights:
Array-like of... | def function[quantile_curve, parameter[quantile, curves, weights]]:
constant[
Compute the weighted quantile aggregate of a set of curves.
:param quantile:
Quantile value to calculate. Should be in the range [0.0, 1.0].
:param curves:
Array of R PoEs (possibly arrays)
:param weig... | keyword[def] identifier[quantile_curve] ( identifier[quantile] , identifier[curves] , identifier[weights] = keyword[None] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[curves] , identifier[numpy] . identifier[ndarray] ):
identifier[curves] = identifier[numpy] . ... | def quantile_curve(quantile, curves, weights=None):
"""
Compute the weighted quantile aggregate of a set of curves.
:param quantile:
Quantile value to calculate. Should be in the range [0.0, 1.0].
:param curves:
Array of R PoEs (possibly arrays)
:param weights:
Array-like of... |
def noise2(self, x, y):
"""2D Perlin simplex noise.
Return a floating point value from -1 to 1 for the given x, y coordinate.
The same value is always returned for a given x, y pair unless the
permutation table changes (see randomize above).
"""
# Skew input space to determine which simplex (triangle)... | def function[noise2, parameter[self, x, y]]:
constant[2D Perlin simplex noise.
Return a floating point value from -1 to 1 for the given x, y coordinate.
The same value is always returned for a given x, y pair unless the
permutation table changes (see randomize above).
]
variable[s] assign[... | keyword[def] identifier[noise2] ( identifier[self] , identifier[x] , identifier[y] ):
literal[string]
identifier[s] =( identifier[x] + identifier[y] )* identifier[_F2]
identifier[i] = identifier[floor] ( identifier[x] + identifier[s] )
identifier[j] = identifier[floor] ( identifier[y] + identifier[s]... | def noise2(self, x, y):
"""2D Perlin simplex noise.
Return a floating point value from -1 to 1 for the given x, y coordinate.
The same value is always returned for a given x, y pair unless the
permutation table changes (see randomize above).
""" # Skew input space to determine which simplex (triangle... |
def get_params(self):
"""Get parameters from this object
"""
params = Data.get_params(self)
params.update(BaseGraph.get_params(self))
return params | def function[get_params, parameter[self]]:
constant[Get parameters from this object
]
variable[params] assign[=] call[name[Data].get_params, parameter[name[self]]]
call[name[params].update, parameter[call[name[BaseGraph].get_params, parameter[name[self]]]]]
return[name[params]] | keyword[def] identifier[get_params] ( identifier[self] ):
literal[string]
identifier[params] = identifier[Data] . identifier[get_params] ( identifier[self] )
identifier[params] . identifier[update] ( identifier[BaseGraph] . identifier[get_params] ( identifier[self] ))
keyword[retu... | def get_params(self):
"""Get parameters from this object
"""
params = Data.get_params(self)
params.update(BaseGraph.get_params(self))
return params |
def xpathNextDescendant(self, ctxt):
"""Traversal function for the "descendant" direction the
descendant axis contains the descendants of the context
node in document order; a descendant is a child or a child
of a child and so on. """
if ctxt is None: ctxt__o = None
... | def function[xpathNextDescendant, parameter[self, ctxt]]:
constant[Traversal function for the "descendant" direction the
descendant axis contains the descendants of the context
node in document order; a descendant is a child or a child
of a child and so on. ]
if compare[na... | keyword[def] identifier[xpathNextDescendant] ( identifier[self] , identifier[ctxt] ):
literal[string]
keyword[if] identifier[ctxt] keyword[is] keyword[None] : identifier[ctxt__o] = keyword[None]
keyword[else] : identifier[ctxt__o] = identifier[ctxt] . identifier[_o]
identifie... | def xpathNextDescendant(self, ctxt):
"""Traversal function for the "descendant" direction the
descendant axis contains the descendants of the context
node in document order; a descendant is a child or a child
of a child and so on. """
if ctxt is None:
ctxt__o = None # dep... |
def write_to_fp(self, fp):
"""Do the TTS API request and write bytes to a file-like object.
Args:
fp (file object): Any file-like object to write the ``mp3`` to.
Raises:
:class:`gTTSError`: When there's an error with the API request.
TypeError: When ``fp`` i... | def function[write_to_fp, parameter[self, fp]]:
constant[Do the TTS API request and write bytes to a file-like object.
Args:
fp (file object): Any file-like object to write the ``mp3`` to.
Raises:
:class:`gTTSError`: When there's an error with the API request.
... | keyword[def] identifier[write_to_fp] ( identifier[self] , identifier[fp] ):
literal[string]
identifier[urllib3] . identifier[disable_warnings] ( identifier[urllib3] . identifier[exceptions] . identifier[InsecureRequestWarning] )
identifier[text_parts] = identifier[self] ... | def write_to_fp(self, fp):
"""Do the TTS API request and write bytes to a file-like object.
Args:
fp (file object): Any file-like object to write the ``mp3`` to.
Raises:
:class:`gTTSError`: When there's an error with the API request.
TypeError: When ``fp`` is no... |
def by_phone(self, phone, cc=None):
"""
Perform a Yelp Phone API Search based on phone number given.
Args:
phone - Phone number to search by
cc - ISO 3166-1 alpha-2 country code. (Optional)
"""
header, content = self._http_request(self.BASE_URL, ph... | def function[by_phone, parameter[self, phone, cc]]:
constant[
Perform a Yelp Phone API Search based on phone number given.
Args:
phone - Phone number to search by
cc - ISO 3166-1 alpha-2 country code. (Optional)
]
<ast.Tuple object at 0x7da1b224afb0... | keyword[def] identifier[by_phone] ( identifier[self] , identifier[phone] , identifier[cc] = keyword[None] ):
literal[string]
identifier[header] , identifier[content] = identifier[self] . identifier[_http_request] ( identifier[self] . identifier[BASE_URL] , identifier[phone] = identifier[phone] , i... | def by_phone(self, phone, cc=None):
"""
Perform a Yelp Phone API Search based on phone number given.
Args:
phone - Phone number to search by
cc - ISO 3166-1 alpha-2 country code. (Optional)
"""
(header, content) = self._http_request(self.BASE_URL, phone=pho... |
def offset2line(offset, linestarts):
"""linestarts is expected to be a *list) of (offset, line number)
where both offset and line number are in increasing order.
Return the closes line number at or below the offset.
If offset is less than the first line number given in linestarts,
return line number... | def function[offset2line, parameter[offset, linestarts]]:
constant[linestarts is expected to be a *list) of (offset, line number)
where both offset and line number are in increasing order.
Return the closes line number at or below the offset.
If offset is less than the first line number given in lin... | keyword[def] identifier[offset2line] ( identifier[offset] , identifier[linestarts] ):
literal[string]
keyword[if] identifier[len] ( identifier[linestarts] )== literal[int] keyword[or] identifier[offset] < identifier[linestarts] [ literal[int] ][ literal[int] ]:
keyword[return] literal[int]
... | def offset2line(offset, linestarts):
"""linestarts is expected to be a *list) of (offset, line number)
where both offset and line number are in increasing order.
Return the closes line number at or below the offset.
If offset is less than the first line number given in linestarts,
return line number... |
def get_asset_admin_session_for_repository(self, repository_id, proxy):
"""Gets an asset administration session for the given repository.
arg: repository_id (osid.id.Id): the ``Id`` of the repository
arg: proxy (osid.proxy.Proxy): a proxy
return: (osid.repository.AssetAdminSession... | def function[get_asset_admin_session_for_repository, parameter[self, repository_id, proxy]]:
constant[Gets an asset administration session for the given repository.
arg: repository_id (osid.id.Id): the ``Id`` of the repository
arg: proxy (osid.proxy.Proxy): a proxy
return: (osid.r... | keyword[def] identifier[get_asset_admin_session_for_repository] ( identifier[self] , identifier[repository_id] , identifier[proxy] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[supports_asset_admin] ():
keyword[raise] identifier[errors] . identifier[Unimp... | def get_asset_admin_session_for_repository(self, repository_id, proxy):
"""Gets an asset administration session for the given repository.
arg: repository_id (osid.id.Id): the ``Id`` of the repository
arg: proxy (osid.proxy.Proxy): a proxy
return: (osid.repository.AssetAdminSession) - ... |
def write(self, byte):
"""
Writes a byte buffer to the underlying output file.
Raise exception when file is already closed.
"""
if self.is_closed_flag:
raise Exception("Unable to write - already closed!")
self.written += len(byte)
self.file.write(byte) | def function[write, parameter[self, byte]]:
constant[
Writes a byte buffer to the underlying output file.
Raise exception when file is already closed.
]
if name[self].is_closed_flag begin[:]
<ast.Raise object at 0x7da18fe907c0>
<ast.AugAssign object at 0x7da18fe91fc0>... | keyword[def] identifier[write] ( identifier[self] , identifier[byte] ):
literal[string]
keyword[if] identifier[self] . identifier[is_closed_flag] :
keyword[raise] identifier[Exception] ( literal[string] )
identifier[self] . identifier[written] += identifier[len] ( identifier... | def write(self, byte):
"""
Writes a byte buffer to the underlying output file.
Raise exception when file is already closed.
"""
if self.is_closed_flag:
raise Exception('Unable to write - already closed!') # depends on [control=['if'], data=[]]
self.written += len(byte)
s... |
def pcmd(host, seq, progressive, lr, fb, vv, va):
"""
Makes the drone move (translate/rotate).
Parameters:
seq -- sequence number
progressive -- True: enable progressive commands, False: disable (i.e.
enable hovering mode)
lr -- left-right tilt: float [-1..1] negative: left, positive: r... | def function[pcmd, parameter[host, seq, progressive, lr, fb, vv, va]]:
constant[
Makes the drone move (translate/rotate).
Parameters:
seq -- sequence number
progressive -- True: enable progressive commands, False: disable (i.e.
enable hovering mode)
lr -- left-right tilt: float [-1.... | keyword[def] identifier[pcmd] ( identifier[host] , identifier[seq] , identifier[progressive] , identifier[lr] , identifier[fb] , identifier[vv] , identifier[va] ):
literal[string]
identifier[p] = literal[int] keyword[if] identifier[progressive] keyword[else] literal[int]
identifier[at] ( identifi... | def pcmd(host, seq, progressive, lr, fb, vv, va):
"""
Makes the drone move (translate/rotate).
Parameters:
seq -- sequence number
progressive -- True: enable progressive commands, False: disable (i.e.
enable hovering mode)
lr -- left-right tilt: float [-1..1] negative: left, positive: r... |
def i_logp(self, index):
"""
Evaluates the log-probability of the Markov blanket of
a stochastic owning a particular index.
"""
all_relevant_stochastics = set()
p, i = self.stochastic_indices[index]
try:
return p.logp + logp_of_set(p.extended_children)... | def function[i_logp, parameter[self, index]]:
constant[
Evaluates the log-probability of the Markov blanket of
a stochastic owning a particular index.
]
variable[all_relevant_stochastics] assign[=] call[name[set], parameter[]]
<ast.Tuple object at 0x7da1b184a800> assign[=... | keyword[def] identifier[i_logp] ( identifier[self] , identifier[index] ):
literal[string]
identifier[all_relevant_stochastics] = identifier[set] ()
identifier[p] , identifier[i] = identifier[self] . identifier[stochastic_indices] [ identifier[index] ]
keyword[try] :
k... | def i_logp(self, index):
"""
Evaluates the log-probability of the Markov blanket of
a stochastic owning a particular index.
"""
all_relevant_stochastics = set()
(p, i) = self.stochastic_indices[index]
try:
return p.logp + logp_of_set(p.extended_children) # depends on [co... |
def check_compressed_file_type(filepath):
"""Check if filename is a compressed file supported by the tool.
This function uses magic numbers (first four bytes) to determine
the type of the file. Supported types are 'gz' and 'bz2'. When
the filetype is not supported, the function returns `None`.
:pa... | def function[check_compressed_file_type, parameter[filepath]]:
constant[Check if filename is a compressed file supported by the tool.
This function uses magic numbers (first four bytes) to determine
the type of the file. Supported types are 'gz' and 'bz2'. When
the filetype is not supported, the fu... | keyword[def] identifier[check_compressed_file_type] ( identifier[filepath] ):
literal[string]
keyword[def] identifier[compressed_file_type] ( identifier[content] ):
identifier[magic_dict] ={
literal[string] : literal[string] ,
literal[string] : literal[string] ,
literal... | def check_compressed_file_type(filepath):
"""Check if filename is a compressed file supported by the tool.
This function uses magic numbers (first four bytes) to determine
the type of the file. Supported types are 'gz' and 'bz2'. When
the filetype is not supported, the function returns `None`.
:pa... |
def del_properties(self, pathobj, props, recursive):
"""
Delete artifact properties
"""
if isinstance(props, str):
props = (props,)
url = '/'.join([pathobj.drive,
'api/storage',
str(pathobj.relative_to(pathobj.drive)).s... | def function[del_properties, parameter[self, pathobj, props, recursive]]:
constant[
Delete artifact properties
]
if call[name[isinstance], parameter[name[props], name[str]]] begin[:]
variable[props] assign[=] tuple[[<ast.Name object at 0x7da1b0f42230>]]
variable[u... | keyword[def] identifier[del_properties] ( identifier[self] , identifier[pathobj] , identifier[props] , identifier[recursive] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[props] , identifier[str] ):
identifier[props] =( identifier[props] ,)
identifier[ur... | def del_properties(self, pathobj, props, recursive):
"""
Delete artifact properties
"""
if isinstance(props, str):
props = (props,) # depends on [control=['if'], data=[]]
url = '/'.join([pathobj.drive, 'api/storage', str(pathobj.relative_to(pathobj.drive)).strip('/')])
params = ... |
def push_0(self, build_record_id, **kwargs):
"""
Build record push results.
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.
>>> def callb... | def function[push_0, parameter[self, build_record_id]]:
constant[
Build record push results.
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.
... | keyword[def] identifier[push_0] ( identifier[self] , identifier[build_record_id] ,** identifier[kwargs] ):
literal[string]
identifier[kwargs] [ literal[string] ]= keyword[True]
keyword[if] identifier[kwargs] . identifier[get] ( literal[string] ):
keyword[return] identifier[... | def push_0(self, build_record_id, **kwargs):
"""
Build record push results.
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.
>>> def callback_... |
def connection_factory_absent(name, both=True, server=None):
'''
Ensures the transaction factory is absent.
name
Name of the connection factory
both
Delete both the pool and the resource, defaults to ``true``
'''
ret = {'name': name, 'result': None, 'comment': None, 'changes': ... | def function[connection_factory_absent, parameter[name, both, server]]:
constant[
Ensures the transaction factory is absent.
name
Name of the connection factory
both
Delete both the pool and the resource, defaults to ``true``
]
variable[ret] assign[=] dictionary[[<ast.C... | keyword[def] identifier[connection_factory_absent] ( identifier[name] , identifier[both] = keyword[True] , identifier[server] = keyword[None] ):
literal[string]
identifier[ret] ={ literal[string] : identifier[name] , literal[string] : keyword[None] , literal[string] : keyword[None] , literal[string] :{}}
... | def connection_factory_absent(name, both=True, server=None):
"""
Ensures the transaction factory is absent.
name
Name of the connection factory
both
Delete both the pool and the resource, defaults to ``true``
"""
ret = {'name': name, 'result': None, 'comment': None, 'changes': ... |
def _compute_timestamp(stupid_cisco_output):
"""
Some fields such `uptime` are returned as: 23week(s) 3day(s)
This method will determine the epoch of the event.
e.g.: 23week(s) 3day(s) -> 1462248287
"""
if not stupid_cisco_output or stupid_cisco_output == "never":
... | def function[_compute_timestamp, parameter[stupid_cisco_output]]:
constant[
Some fields such `uptime` are returned as: 23week(s) 3day(s)
This method will determine the epoch of the event.
e.g.: 23week(s) 3day(s) -> 1462248287
]
if <ast.BoolOp object at 0x7da1b1ce88b0> beg... | keyword[def] identifier[_compute_timestamp] ( identifier[stupid_cisco_output] ):
literal[string]
keyword[if] keyword[not] identifier[stupid_cisco_output] keyword[or] identifier[stupid_cisco_output] == literal[string] :
keyword[return] - literal[int]
keyword[if] literal[... | def _compute_timestamp(stupid_cisco_output):
"""
Some fields such `uptime` are returned as: 23week(s) 3day(s)
This method will determine the epoch of the event.
e.g.: 23week(s) 3day(s) -> 1462248287
"""
if not stupid_cisco_output or stupid_cisco_output == 'never':
return ... |
def MeanVarEstEQ(y, x, covariates, tol=1e-8):
"""Perform the mean var calculation using estimated equestions
:param y: Outcomes
:param x: [genotypes, cov1, ..., covN]
:param tol: convergence criterion
"""
pcount = covariates.shape[0] + 2
N = y.shape[0]
beta_count = pcount * 2
X = ... | def function[MeanVarEstEQ, parameter[y, x, covariates, tol]]:
constant[Perform the mean var calculation using estimated equestions
:param y: Outcomes
:param x: [genotypes, cov1, ..., covN]
:param tol: convergence criterion
]
variable[pcount] assign[=] binary_operation[call[name[covaria... | keyword[def] identifier[MeanVarEstEQ] ( identifier[y] , identifier[x] , identifier[covariates] , identifier[tol] = literal[int] ):
literal[string]
identifier[pcount] = identifier[covariates] . identifier[shape] [ literal[int] ]+ literal[int]
identifier[N] = identifier[y] . identifier[shape] [ litera... | def MeanVarEstEQ(y, x, covariates, tol=1e-08):
"""Perform the mean var calculation using estimated equestions
:param y: Outcomes
:param x: [genotypes, cov1, ..., covN]
:param tol: convergence criterion
"""
pcount = covariates.shape[0] + 2
N = y.shape[0]
beta_count = pcount * 2
X = ... |
def _prepare_to_send_ack(self, path, ack_id):
'Return function that acknowledges the server'
return lambda *args: self._ack(path, ack_id, *args) | def function[_prepare_to_send_ack, parameter[self, path, ack_id]]:
constant[Return function that acknowledges the server]
return[<ast.Lambda object at 0x7da1b0677160>] | keyword[def] identifier[_prepare_to_send_ack] ( identifier[self] , identifier[path] , identifier[ack_id] ):
literal[string]
keyword[return] keyword[lambda] * identifier[args] : identifier[self] . identifier[_ack] ( identifier[path] , identifier[ack_id] ,* identifier[args] ) | def _prepare_to_send_ack(self, path, ack_id):
"""Return function that acknowledges the server"""
return lambda *args: self._ack(path, ack_id, *args) |
def write_worksheets(workbook, data_list, result_info_key, identifier_keys):
"""Writes rest of the worksheets to workbook.
Args:
workbook: workbook to write into
data_list: Analytics API data as a list of dicts
result_info_key: the key in api_data dicts that contains the data results
... | def function[write_worksheets, parameter[workbook, data_list, result_info_key, identifier_keys]]:
constant[Writes rest of the worksheets to workbook.
Args:
workbook: workbook to write into
data_list: Analytics API data as a list of dicts
result_info_key: the key in api_data dicts th... | keyword[def] identifier[write_worksheets] ( identifier[workbook] , identifier[data_list] , identifier[result_info_key] , identifier[identifier_keys] ):
literal[string]
identifier[worksheet_keys] = identifier[get_worksheet_keys] ( identifier[data_list] [ literal[int] ], identifier[result_info_key] )
... | def write_worksheets(workbook, data_list, result_info_key, identifier_keys):
"""Writes rest of the worksheets to workbook.
Args:
workbook: workbook to write into
data_list: Analytics API data as a list of dicts
result_info_key: the key in api_data dicts that contains the data results
... |
def get_groups_to_ack(groups_to_ack, init_sg_states, curr_sg_states):
"""Compares initial security group rules with current sg rules.
Given the groups that were successfully returned from
xapi_client.update_interfaces call, compare initial and current
security group rules to determine if an upd... | def function[get_groups_to_ack, parameter[groups_to_ack, init_sg_states, curr_sg_states]]:
constant[Compares initial security group rules with current sg rules.
Given the groups that were successfully returned from
xapi_client.update_interfaces call, compare initial and current
security gro... | keyword[def] identifier[get_groups_to_ack] ( identifier[groups_to_ack] , identifier[init_sg_states] , identifier[curr_sg_states] ):
literal[string]
identifier[security_groups_changed] =[]
keyword[for] identifier[vif] keyword[in] identifier[groups_to_ack] :
identifier[initial_state] = ... | def get_groups_to_ack(groups_to_ack, init_sg_states, curr_sg_states):
"""Compares initial security group rules with current sg rules.
Given the groups that were successfully returned from
xapi_client.update_interfaces call, compare initial and current
security group rules to determine if an upd... |
def _read_etc(etc_file):
"""Return information about table of content for each erd.
"""
etc_type = dtype([('offset', '<i'),
('samplestamp', '<i'),
('sample_num', '<i'),
('sample_span', '<h'),
('unknown', '<h')])
wit... | def function[_read_etc, parameter[etc_file]]:
constant[Return information about table of content for each erd.
]
variable[etc_type] assign[=] call[name[dtype], parameter[list[[<ast.Tuple object at 0x7da2047e85e0>, <ast.Tuple object at 0x7da2047ebfd0>, <ast.Tuple object at 0x7da2047e97e0>, <ast.Tuple... | keyword[def] identifier[_read_etc] ( identifier[etc_file] ):
literal[string]
identifier[etc_type] = identifier[dtype] ([( literal[string] , literal[string] ),
( literal[string] , literal[string] ),
( literal[string] , literal[string] ),
( literal[string] , literal[string] ),
( literal[strin... | def _read_etc(etc_file):
"""Return information about table of content for each erd.
"""
etc_type = dtype([('offset', '<i'), ('samplestamp', '<i'), ('sample_num', '<i'), ('sample_span', '<h'), ('unknown', '<h')])
with etc_file.open('rb') as f:
f.seek(352) # end of header
etc = fromfile(f... |
def xpath_should_match_x_times(self, xpath, count, error=None, loglevel='INFO'):
"""Verifies that the page contains the given number of elements located by the given ``xpath``.
One should not use the `xpath=` prefix for 'xpath'. XPath is assumed.
| *Correct:* |
| Xpath Should Mat... | def function[xpath_should_match_x_times, parameter[self, xpath, count, error, loglevel]]:
constant[Verifies that the page contains the given number of elements located by the given ``xpath``.
One should not use the `xpath=` prefix for 'xpath'. XPath is assumed.
| *Correct:* |
| Xpath S... | keyword[def] identifier[xpath_should_match_x_times] ( identifier[self] , identifier[xpath] , identifier[count] , identifier[error] = keyword[None] , identifier[loglevel] = literal[string] ):
literal[string]
identifier[actual_xpath_count] = identifier[len] ( identifier[self] . identifier[_element_... | def xpath_should_match_x_times(self, xpath, count, error=None, loglevel='INFO'):
"""Verifies that the page contains the given number of elements located by the given ``xpath``.
One should not use the `xpath=` prefix for 'xpath'. XPath is assumed.
| *Correct:* |
| Xpath Should Match X Times... |
def _get_site_scaling_term(self, C, vs30):
"""
Returns the site scaling. For sites with Vs30 > 1200 m/s the site
amplification for Vs30 = 1200 is used
"""
site_amp = C["xi"] * np.log(1200.0) * np.ones(len(vs30))
idx = vs30 < 1200.0
site_amp[idx] = C["xi"] * np.log... | def function[_get_site_scaling_term, parameter[self, C, vs30]]:
constant[
Returns the site scaling. For sites with Vs30 > 1200 m/s the site
amplification for Vs30 = 1200 is used
]
variable[site_amp] assign[=] binary_operation[binary_operation[call[name[C]][constant[xi]] * call[na... | keyword[def] identifier[_get_site_scaling_term] ( identifier[self] , identifier[C] , identifier[vs30] ):
literal[string]
identifier[site_amp] = identifier[C] [ literal[string] ]* identifier[np] . identifier[log] ( literal[int] )* identifier[np] . identifier[ones] ( identifier[len] ( identifier[vs30... | def _get_site_scaling_term(self, C, vs30):
"""
Returns the site scaling. For sites with Vs30 > 1200 m/s the site
amplification for Vs30 = 1200 is used
"""
site_amp = C['xi'] * np.log(1200.0) * np.ones(len(vs30))
idx = vs30 < 1200.0
site_amp[idx] = C['xi'] * np.log(vs30[idx])
... |
def retrieve_token(self, token):
"""
Retrieve Token details for a specific Token.
Args:
token: The identifier of the token.
Returns:
"""
headers = self.client._get_private_headers()
endpoint = '/tokens/{}'.format(token)
return self.client._... | def function[retrieve_token, parameter[self, token]]:
constant[
Retrieve Token details for a specific Token.
Args:
token: The identifier of the token.
Returns:
]
variable[headers] assign[=] call[name[self].client._get_private_headers, parameter[]]
... | keyword[def] identifier[retrieve_token] ( identifier[self] , identifier[token] ):
literal[string]
identifier[headers] = identifier[self] . identifier[client] . identifier[_get_private_headers] ()
identifier[endpoint] = literal[string] . identifier[format] ( identifier[token] )
key... | def retrieve_token(self, token):
"""
Retrieve Token details for a specific Token.
Args:
token: The identifier of the token.
Returns:
"""
headers = self.client._get_private_headers()
endpoint = '/tokens/{}'.format(token)
return self.client._get(self.client.... |
def python_to_jupyter_cli(args=None, namespace=None):
"""Exposes the jupyter notebook renderer to the command line
Takes the same arguments as ArgumentParser.parse_args
"""
from . import gen_gallery # To avoid circular import
parser = argparse.ArgumentParser(
description='Sphinx-Gallery No... | def function[python_to_jupyter_cli, parameter[args, namespace]]:
constant[Exposes the jupyter notebook renderer to the command line
Takes the same arguments as ArgumentParser.parse_args
]
from relative_module[None] import module[gen_gallery]
variable[parser] assign[=] call[name[argparse].Ar... | keyword[def] identifier[python_to_jupyter_cli] ( identifier[args] = keyword[None] , identifier[namespace] = keyword[None] ):
literal[string]
keyword[from] . keyword[import] identifier[gen_gallery]
identifier[parser] = identifier[argparse] . identifier[ArgumentParser] (
identifier[description] =... | def python_to_jupyter_cli(args=None, namespace=None):
"""Exposes the jupyter notebook renderer to the command line
Takes the same arguments as ArgumentParser.parse_args
"""
from . import gen_gallery # To avoid circular import
parser = argparse.ArgumentParser(description='Sphinx-Gallery Notebook co... |
def eventFilter(self, object, event):
"""Catch events from qpart
Move selection, select item, or close themselves
"""
if event.type() == QEvent.KeyPress and event.modifiers() == Qt.NoModifier:
if event.key() == Qt.Key_Escape:
self.closeMe.emit()
... | def function[eventFilter, parameter[self, object, event]]:
constant[Catch events from qpart
Move selection, select item, or close themselves
]
if <ast.BoolOp object at 0x7da20c76d300> begin[:]
if compare[call[name[event].key, parameter[]] equal[==] name[Qt].Key_Escape] be... | keyword[def] identifier[eventFilter] ( identifier[self] , identifier[object] , identifier[event] ):
literal[string]
keyword[if] identifier[event] . identifier[type] ()== identifier[QEvent] . identifier[KeyPress] keyword[and] identifier[event] . identifier[modifiers] ()== identifier[Qt] . identif... | def eventFilter(self, object, event):
"""Catch events from qpart
Move selection, select item, or close themselves
"""
if event.type() == QEvent.KeyPress and event.modifiers() == Qt.NoModifier:
if event.key() == Qt.Key_Escape:
self.closeMe.emit()
return True # dep... |
def fail_acs_response(request, *args, **kwargs):
""" Serves as a common mechanism for ending ACS in case of any SAML related failure.
Handling can be configured by setting the SAML_ACS_FAILURE_RESPONSE_FUNCTION as
suitable for the project.
The default behavior uses SAML specific template that is render... | def function[fail_acs_response, parameter[request]]:
constant[ Serves as a common mechanism for ending ACS in case of any SAML related failure.
Handling can be configured by setting the SAML_ACS_FAILURE_RESPONSE_FUNCTION as
suitable for the project.
The default behavior uses SAML specific template ... | keyword[def] identifier[fail_acs_response] ( identifier[request] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
identifier[failure_function] = identifier[import_string] ( identifier[get_custom_setting] ( literal[string] ,
literal[string] ))
keyword[return] identifier[failure_funct... | def fail_acs_response(request, *args, **kwargs):
""" Serves as a common mechanism for ending ACS in case of any SAML related failure.
Handling can be configured by setting the SAML_ACS_FAILURE_RESPONSE_FUNCTION as
suitable for the project.
The default behavior uses SAML specific template that is render... |
def iter_logical_lines(self, blob):
"""Returns an iterator of (start_line, stop_line, indent) for logical lines """
indent_stack = []
contents = []
line_number_start = None
for token in self.iter_tokens(blob):
token_type, token_text, token_start = token[0:3]
if token_type == tokenize.IND... | def function[iter_logical_lines, parameter[self, blob]]:
constant[Returns an iterator of (start_line, stop_line, indent) for logical lines ]
variable[indent_stack] assign[=] list[[]]
variable[contents] assign[=] list[[]]
variable[line_number_start] assign[=] constant[None]
for ta... | keyword[def] identifier[iter_logical_lines] ( identifier[self] , identifier[blob] ):
literal[string]
identifier[indent_stack] =[]
identifier[contents] =[]
identifier[line_number_start] = keyword[None]
keyword[for] identifier[token] keyword[in] identifier[self] . identifier[iter_tokens] (... | def iter_logical_lines(self, blob):
"""Returns an iterator of (start_line, stop_line, indent) for logical lines """
indent_stack = []
contents = []
line_number_start = None
for token in self.iter_tokens(blob):
(token_type, token_text, token_start) = token[0:3]
if token_type == tokeni... |
def register(self, plugin=None, plugin_file=None, directory=None, skip_types=None, override=False, activate=True):
"""
Register a plugin, or plugins to be managed and recognized by the plugin manager.
Will take a plugin instance, file where a plugin / plugin(s) reside, parent directory
t... | def function[register, parameter[self, plugin, plugin_file, directory, skip_types, override, activate]]:
constant[
Register a plugin, or plugins to be managed and recognized by the plugin manager.
Will take a plugin instance, file where a plugin / plugin(s) reside, parent directory
that ... | keyword[def] identifier[register] ( identifier[self] , identifier[plugin] = keyword[None] , identifier[plugin_file] = keyword[None] , identifier[directory] = keyword[None] , identifier[skip_types] = keyword[None] , identifier[override] = keyword[False] , identifier[activate] = keyword[True] ):
literal[string... | def register(self, plugin=None, plugin_file=None, directory=None, skip_types=None, override=False, activate=True):
"""
Register a plugin, or plugins to be managed and recognized by the plugin manager.
Will take a plugin instance, file where a plugin / plugin(s) reside, parent directory
that ... |
def run(self, profile='default', pillar=None, archive=None, output='nested'):
'''
Run Salt Support on the minion.
profile
Set available profile name. Default is "default".
pillar
Set available profile from the pillars.
archive
Override archi... | def function[run, parameter[self, profile, pillar, archive, output]]:
constant[
Run Salt Support on the minion.
profile
Set available profile name. Default is "default".
pillar
Set available profile from the pillars.
archive
Override archive... | keyword[def] identifier[run] ( identifier[self] , identifier[profile] = literal[string] , identifier[pillar] = keyword[None] , identifier[archive] = keyword[None] , identifier[output] = literal[string] ):
literal[string]
keyword[class] identifier[outputswitch] ( identifier[object] ):
... | def run(self, profile='default', pillar=None, archive=None, output='nested'):
"""
Run Salt Support on the minion.
profile
Set available profile name. Default is "default".
pillar
Set available profile from the pillars.
archive
Override archive n... |
def config(check):
"""Validate default configuration files."""
if check:
checks = [check]
else:
checks = sorted(get_valid_checks())
files_failed = {}
files_warned = {}
num_files = 0
echo_waiting('Validating default configuration files...')
for check in checks:
c... | def function[config, parameter[check]]:
constant[Validate default configuration files.]
if name[check] begin[:]
variable[checks] assign[=] list[[<ast.Name object at 0x7da20c6c64a0>]]
variable[files_failed] assign[=] dictionary[[], []]
variable[files_warned] assign[=] dict... | keyword[def] identifier[config] ( identifier[check] ):
literal[string]
keyword[if] identifier[check] :
identifier[checks] =[ identifier[check] ]
keyword[else] :
identifier[checks] = identifier[sorted] ( identifier[get_valid_checks] ())
identifier[files_failed] ={}
identif... | def config(check):
"""Validate default configuration files."""
if check:
checks = [check] # depends on [control=['if'], data=[]]
else:
checks = sorted(get_valid_checks())
files_failed = {}
files_warned = {}
num_files = 0
echo_waiting('Validating default configuration files..... |
def MA(df,title,figName,c, daType="counts",nbins=10,perc=.5,deg=3,eq=True,splines=True,spec=None,Targets=None,ylim=None,sizeRed=8):
"""
Plots an MA like plot GetData() outputs.
:param df: dataframe output of GetData()
:param title: plot title, 'Genes' or 'Transcripts'
:param figName: /path/to/saved... | def function[MA, parameter[df, title, figName, c, daType, nbins, perc, deg, eq, splines, spec, Targets, ylim, sizeRed]]:
constant[
Plots an MA like plot GetData() outputs.
:param df: dataframe output of GetData()
:param title: plot title, 'Genes' or 'Transcripts'
:param figName: /path/to/saved/... | keyword[def] identifier[MA] ( identifier[df] , identifier[title] , identifier[figName] , identifier[c] , identifier[daType] = literal[string] , identifier[nbins] = literal[int] , identifier[perc] = literal[int] , identifier[deg] = literal[int] , identifier[eq] = keyword[True] , identifier[splines] = keyword[True] , i... | def MA(df, title, figName, c, daType='counts', nbins=10, perc=0.5, deg=3, eq=True, splines=True, spec=None, Targets=None, ylim=None, sizeRed=8):
"""
Plots an MA like plot GetData() outputs.
:param df: dataframe output of GetData()
:param title: plot title, 'Genes' or 'Transcripts'
:param figName: /... |
def update_or_create(self, attributes, values=None, joining=None, touch=True):
"""
Create or update a related record matching the attributes, and fill it with values.
:param attributes: The attributes
:type attributes: dict
:param values: The values
:type values: dict
... | def function[update_or_create, parameter[self, attributes, values, joining, touch]]:
constant[
Create or update a related record matching the attributes, and fill it with values.
:param attributes: The attributes
:type attributes: dict
:param values: The values
:type va... | keyword[def] identifier[update_or_create] ( identifier[self] , identifier[attributes] , identifier[values] = keyword[None] , identifier[joining] = keyword[None] , identifier[touch] = keyword[True] ):
literal[string]
keyword[if] identifier[values] keyword[is] keyword[None] :
identifi... | def update_or_create(self, attributes, values=None, joining=None, touch=True):
"""
Create or update a related record matching the attributes, and fill it with values.
:param attributes: The attributes
:type attributes: dict
:param values: The values
:type values: dict
... |
def _convert_weekday_pattern(p_weekday):
"""
Converts a weekday name to an absolute date.
When today's day of the week is entered, it will return next week's date.
"""
day_value = {
'mo': 0,
'tu': 1,
'we': 2,
'th': 3,
'fr': 4,
'sa': 5,
'su': 6... | def function[_convert_weekday_pattern, parameter[p_weekday]]:
constant[
Converts a weekday name to an absolute date.
When today's day of the week is entered, it will return next week's date.
]
variable[day_value] assign[=] dictionary[[<ast.Constant object at 0x7da20c6c6110>, <ast.Constant o... | keyword[def] identifier[_convert_weekday_pattern] ( identifier[p_weekday] ):
literal[string]
identifier[day_value] ={
literal[string] : literal[int] ,
literal[string] : literal[int] ,
literal[string] : literal[int] ,
literal[string] : literal[int] ,
literal[string] : literal[int] ,... | def _convert_weekday_pattern(p_weekday):
"""
Converts a weekday name to an absolute date.
When today's day of the week is entered, it will return next week's date.
"""
day_value = {'mo': 0, 'tu': 1, 'we': 2, 'th': 3, 'fr': 4, 'sa': 5, 'su': 6}
target_day_string = p_weekday[:2].lower()
targe... |
def _print_beam(self,
sequences: mx.nd.NDArray,
accumulated_scores: mx.nd.NDArray,
finished: mx.nd.NDArray,
inactive: mx.nd.NDArray,
constraints: List[Optional[constrained.ConstrainedHypothesis]],
tim... | def function[_print_beam, parameter[self, sequences, accumulated_scores, finished, inactive, constraints, timestep]]:
constant[
Prints the beam for debugging purposes.
:param sequences: The beam histories (shape: batch_size * beam_size, max_output_len).
:param accumulated_scores: The ac... | keyword[def] identifier[_print_beam] ( identifier[self] ,
identifier[sequences] : identifier[mx] . identifier[nd] . identifier[NDArray] ,
identifier[accumulated_scores] : identifier[mx] . identifier[nd] . identifier[NDArray] ,
identifier[finished] : identifier[mx] . identifier[nd] . identifier[NDArray] ,
identifi... | def _print_beam(self, sequences: mx.nd.NDArray, accumulated_scores: mx.nd.NDArray, finished: mx.nd.NDArray, inactive: mx.nd.NDArray, constraints: List[Optional[constrained.ConstrainedHypothesis]], timestep: int) -> None:
"""
Prints the beam for debugging purposes.
:param sequences: The beam histori... |
def salt_ssh(project, target, module, args=None, kwargs=None):
"""
Execute a `salt-ssh` command
"""
cmd = ['salt-ssh']
cmd.extend(generate_salt_cmd(target, module, args, kwargs))
cmd.append('--state-output=mixed')
cmd.append('--roster-file=%s' % project.roster_path)
cmd.append('--config-... | def function[salt_ssh, parameter[project, target, module, args, kwargs]]:
constant[
Execute a `salt-ssh` command
]
variable[cmd] assign[=] list[[<ast.Constant object at 0x7da1b0af0730>]]
call[name[cmd].extend, parameter[call[name[generate_salt_cmd], parameter[name[target], name[module], ... | keyword[def] identifier[salt_ssh] ( identifier[project] , identifier[target] , identifier[module] , identifier[args] = keyword[None] , identifier[kwargs] = keyword[None] ):
literal[string]
identifier[cmd] =[ literal[string] ]
identifier[cmd] . identifier[extend] ( identifier[generate_salt_cmd] ( ident... | def salt_ssh(project, target, module, args=None, kwargs=None):
"""
Execute a `salt-ssh` command
"""
cmd = ['salt-ssh']
cmd.extend(generate_salt_cmd(target, module, args, kwargs))
cmd.append('--state-output=mixed')
cmd.append('--roster-file=%s' % project.roster_path)
cmd.append('--config-... |
def up(self, n=1, interval=0, pre_dl=None, post_dl=None):
"""Press up key n times.
**中文文档**
按上方向键 n 次。
"""
self.delay(pre_dl)
self.k.tap_key(self.k.up_key, n, interval)
self.delay(post_dl) | def function[up, parameter[self, n, interval, pre_dl, post_dl]]:
constant[Press up key n times.
**中文文档**
按上方向键 n 次。
]
call[name[self].delay, parameter[name[pre_dl]]]
call[name[self].k.tap_key, parameter[name[self].k.up_key, name[n], name[interval]]]
call[name[se... | keyword[def] identifier[up] ( identifier[self] , identifier[n] = literal[int] , identifier[interval] = literal[int] , identifier[pre_dl] = keyword[None] , identifier[post_dl] = keyword[None] ):
literal[string]
identifier[self] . identifier[delay] ( identifier[pre_dl] )
identifier[self] . i... | def up(self, n=1, interval=0, pre_dl=None, post_dl=None):
"""Press up key n times.
**中文文档**
按上方向键 n 次。
"""
self.delay(pre_dl)
self.k.tap_key(self.k.up_key, n, interval)
self.delay(post_dl) |
def convert_to_culled_timestep(self, timestep=1):
"""Convert this collection to one that only has datetimes that fit a timestep."""
valid_s = self.header.analysis_period.VALIDTIMESTEPS.keys()
assert timestep in valid_s, \
'timestep {} is not valid. Choose from: {}'.format(timestep, v... | def function[convert_to_culled_timestep, parameter[self, timestep]]:
constant[Convert this collection to one that only has datetimes that fit a timestep.]
variable[valid_s] assign[=] call[name[self].header.analysis_period.VALIDTIMESTEPS.keys, parameter[]]
assert[compare[name[timestep] in name[valid_... | keyword[def] identifier[convert_to_culled_timestep] ( identifier[self] , identifier[timestep] = literal[int] ):
literal[string]
identifier[valid_s] = identifier[self] . identifier[header] . identifier[analysis_period] . identifier[VALIDTIMESTEPS] . identifier[keys] ()
keyword[assert] iden... | def convert_to_culled_timestep(self, timestep=1):
"""Convert this collection to one that only has datetimes that fit a timestep."""
valid_s = self.header.analysis_period.VALIDTIMESTEPS.keys()
assert timestep in valid_s, 'timestep {} is not valid. Choose from: {}'.format(timestep, valid_s)
(new_ap, new_v... |
def info(self, message, domain=None):
"""
Shortcut function for `utils.loggable.info`
Args:
message: see `utils.loggable.info`
domain: see `utils.loggable.info`
"""
if domain is None:
domain = self.extension_name
info(message, domain) | def function[info, parameter[self, message, domain]]:
constant[
Shortcut function for `utils.loggable.info`
Args:
message: see `utils.loggable.info`
domain: see `utils.loggable.info`
]
if compare[name[domain] is constant[None]] begin[:]
va... | keyword[def] identifier[info] ( identifier[self] , identifier[message] , identifier[domain] = keyword[None] ):
literal[string]
keyword[if] identifier[domain] keyword[is] keyword[None] :
identifier[domain] = identifier[self] . identifier[extension_name]
identifier[info] ( i... | def info(self, message, domain=None):
"""
Shortcut function for `utils.loggable.info`
Args:
message: see `utils.loggable.info`
domain: see `utils.loggable.info`
"""
if domain is None:
domain = self.extension_name # depends on [control=['if'], data=['doma... |
def fastaReadHeaders(fasta):
"""Returns a list of fasta header lines, excluding
"""
headers = []
fileHandle = open(fasta, 'r')
line = fileHandle.readline()
while line != '':
assert line[-1] == '\n'
if line[0] == '>':
headers.append(line[1:-1])
line = fileHandl... | def function[fastaReadHeaders, parameter[fasta]]:
constant[Returns a list of fasta header lines, excluding
]
variable[headers] assign[=] list[[]]
variable[fileHandle] assign[=] call[name[open], parameter[name[fasta], constant[r]]]
variable[line] assign[=] call[name[fileHandle].readli... | keyword[def] identifier[fastaReadHeaders] ( identifier[fasta] ):
literal[string]
identifier[headers] =[]
identifier[fileHandle] = identifier[open] ( identifier[fasta] , literal[string] )
identifier[line] = identifier[fileHandle] . identifier[readline] ()
keyword[while] identifier[line] != l... | def fastaReadHeaders(fasta):
"""Returns a list of fasta header lines, excluding
"""
headers = []
fileHandle = open(fasta, 'r')
line = fileHandle.readline()
while line != '':
assert line[-1] == '\n'
if line[0] == '>':
headers.append(line[1:-1]) # depends on [control=[... |
def getElementsByAttr(self, attrName, attrValue, root='root', useIndex=True):
'''
getElementsByAttr - Searches the full tree for elements with a given attribute name and value combination. If you want multiple potential values, see getElementsWithAttrValues
If you want an index on a r... | def function[getElementsByAttr, parameter[self, attrName, attrValue, root, useIndex]]:
constant[
getElementsByAttr - Searches the full tree for elements with a given attribute name and value combination. If you want multiple potential values, see getElementsWithAttrValues
If you want ... | keyword[def] identifier[getElementsByAttr] ( identifier[self] , identifier[attrName] , identifier[attrValue] , identifier[root] = literal[string] , identifier[useIndex] = keyword[True] ):
literal[string]
( identifier[root] , identifier[isFromRoot] )= identifier[self] . identifier[_handleRootArg] ( i... | def getElementsByAttr(self, attrName, attrValue, root='root', useIndex=True):
"""
getElementsByAttr - Searches the full tree for elements with a given attribute name and value combination. If you want multiple potential values, see getElementsWithAttrValues
If you want an index on a rando... |
def get_all_tags(self, item):
"""
Get all tags of an item
:param item: an item
:type item: Item
:return: list of tags
:rtype: list
"""
all_tags = item.get_templates()
for template_id in item.templates:
template = self.templates[templa... | def function[get_all_tags, parameter[self, item]]:
constant[
Get all tags of an item
:param item: an item
:type item: Item
:return: list of tags
:rtype: list
]
variable[all_tags] assign[=] call[name[item].get_templates, parameter[]]
for taget[name... | keyword[def] identifier[get_all_tags] ( identifier[self] , identifier[item] ):
literal[string]
identifier[all_tags] = identifier[item] . identifier[get_templates] ()
keyword[for] identifier[template_id] keyword[in] identifier[item] . identifier[templates] :
identifier[temp... | def get_all_tags(self, item):
"""
Get all tags of an item
:param item: an item
:type item: Item
:return: list of tags
:rtype: list
"""
all_tags = item.get_templates()
for template_id in item.templates:
template = self.templates[template_id]
al... |
def split_host_port(cls, server):
"""
Return (host, port) from server.
Port defaults to 11211.
>>> split_host_port('127.0.0.1:11211')
('127.0.0.1', 11211)
>>> split_host_port('127.0.0.1')
('127.0.0.1', 11211)
"""
host, port = splitport(server)
... | def function[split_host_port, parameter[cls, server]]:
constant[
Return (host, port) from server.
Port defaults to 11211.
>>> split_host_port('127.0.0.1:11211')
('127.0.0.1', 11211)
>>> split_host_port('127.0.0.1')
('127.0.0.1', 11211)
]
<ast.Tup... | keyword[def] identifier[split_host_port] ( identifier[cls] , identifier[server] ):
literal[string]
identifier[host] , identifier[port] = identifier[splitport] ( identifier[server] )
keyword[if] identifier[port] keyword[is] keyword[None] :
identifier[port] = literal[int]
... | def split_host_port(cls, server):
"""
Return (host, port) from server.
Port defaults to 11211.
>>> split_host_port('127.0.0.1:11211')
('127.0.0.1', 11211)
>>> split_host_port('127.0.0.1')
('127.0.0.1', 11211)
"""
(host, port) = splitport(server)
if p... |
def is_implicit_value (value_string):
""" Returns true iff 'value_string' is a value_string
of an implicit feature.
"""
assert isinstance(value_string, basestring)
if value_string in __implicit_features:
return __implicit_features[value_string]
v = value_string.split('-')
if v[0] n... | def function[is_implicit_value, parameter[value_string]]:
constant[ Returns true iff 'value_string' is a value_string
of an implicit feature.
]
assert[call[name[isinstance], parameter[name[value_string], name[basestring]]]]
if compare[name[value_string] in name[__implicit_features]] begin[:]... | keyword[def] identifier[is_implicit_value] ( identifier[value_string] ):
literal[string]
keyword[assert] identifier[isinstance] ( identifier[value_string] , identifier[basestring] )
keyword[if] identifier[value_string] keyword[in] identifier[__implicit_features] :
keyword[return] identif... | def is_implicit_value(value_string):
""" Returns true iff 'value_string' is a value_string
of an implicit feature.
"""
assert isinstance(value_string, basestring)
if value_string in __implicit_features:
return __implicit_features[value_string] # depends on [control=['if'], data=['value_stri... |
def simxGetLastErrors(clientID, operationMode):
'''
Please have a look at the function description/documentation in the V-REP user manual
'''
errors =[]
errorCnt = ct.c_int()
errorStrings = ct.POINTER(ct.c_char)()
ret = c_GetLastErrors(clientID, ct.byref(errorCnt), ct.byref(errorStrings), op... | def function[simxGetLastErrors, parameter[clientID, operationMode]]:
constant[
Please have a look at the function description/documentation in the V-REP user manual
]
variable[errors] assign[=] list[[]]
variable[errorCnt] assign[=] call[name[ct].c_int, parameter[]]
variable[error... | keyword[def] identifier[simxGetLastErrors] ( identifier[clientID] , identifier[operationMode] ):
literal[string]
identifier[errors] =[]
identifier[errorCnt] = identifier[ct] . identifier[c_int] ()
identifier[errorStrings] = identifier[ct] . identifier[POINTER] ( identifier[ct] . identifier[c_char... | def simxGetLastErrors(clientID, operationMode):
"""
Please have a look at the function description/documentation in the V-REP user manual
"""
errors = []
errorCnt = ct.c_int()
errorStrings = ct.POINTER(ct.c_char)()
ret = c_GetLastErrors(clientID, ct.byref(errorCnt), ct.byref(errorStrings), o... |
def from_las(cls,
fname,
remap=None,
funcs=None,
data=True,
req=None,
alias=None,
encoding=None,
printfname=False
):
"""
Constructor. Essentially just ... | def function[from_las, parameter[cls, fname, remap, funcs, data, req, alias, encoding, printfname]]:
constant[
Constructor. Essentially just wraps ``from_lasio()``, but is more
convenient for most purposes.
Args:
fname (str): The path of the LAS file, or a URL to one.
... | keyword[def] identifier[from_las] ( identifier[cls] ,
identifier[fname] ,
identifier[remap] = keyword[None] ,
identifier[funcs] = keyword[None] ,
identifier[data] = keyword[True] ,
identifier[req] = keyword[None] ,
identifier[alias] = keyword[None] ,
identifier[encoding] = keyword[None] ,
identifier[printfnam... | def from_las(cls, fname, remap=None, funcs=None, data=True, req=None, alias=None, encoding=None, printfname=False):
"""
Constructor. Essentially just wraps ``from_lasio()``, but is more
convenient for most purposes.
Args:
fname (str): The path of the LAS file, or a URL to one.
... |
def run_step(context):
"""Run shell command without shell interpolation.
Context is a dictionary or dictionary-like.
Context must contain the following keys:
cmd: <<cmd string>> (command + args to execute.)
OR, as a dict
cmd:
run: str. mandatory. <<cmd string>> command + args to execu... | def function[run_step, parameter[context]]:
constant[Run shell command without shell interpolation.
Context is a dictionary or dictionary-like.
Context must contain the following keys:
cmd: <<cmd string>> (command + args to execute.)
OR, as a dict
cmd:
run: str. mandatory. <<cmd s... | keyword[def] identifier[run_step] ( identifier[context] ):
literal[string]
identifier[logger] . identifier[debug] ( literal[string] )
identifier[CmdStep] ( identifier[name] = identifier[__name__] , identifier[context] = identifier[context] ). identifier[run_step] ( identifier[is_shell] = keyword[True... | def run_step(context):
"""Run shell command without shell interpolation.
Context is a dictionary or dictionary-like.
Context must contain the following keys:
cmd: <<cmd string>> (command + args to execute.)
OR, as a dict
cmd:
run: str. mandatory. <<cmd string>> command + args to execu... |
def peopleTable(self, request, tag):
"""
Return a L{PersonScrollingFragment} which will display the L{Person}
items in the wrapped organizer.
"""
f = PersonScrollingFragment(
self.organizer, None, Person.name, self.wt)
f.setFragmentParent(self)
f.docFa... | def function[peopleTable, parameter[self, request, tag]]:
constant[
Return a L{PersonScrollingFragment} which will display the L{Person}
items in the wrapped organizer.
]
variable[f] assign[=] call[name[PersonScrollingFragment], parameter[name[self].organizer, constant[None], nam... | keyword[def] identifier[peopleTable] ( identifier[self] , identifier[request] , identifier[tag] ):
literal[string]
identifier[f] = identifier[PersonScrollingFragment] (
identifier[self] . identifier[organizer] , keyword[None] , identifier[Person] . identifier[name] , identifier[self] . ide... | def peopleTable(self, request, tag):
"""
Return a L{PersonScrollingFragment} which will display the L{Person}
items in the wrapped organizer.
"""
f = PersonScrollingFragment(self.organizer, None, Person.name, self.wt)
f.setFragmentParent(self)
f.docFactory = webtheme.getLoader(f.... |
def log_finished(self):
"""Log that this task is done."""
delta = time.perf_counter() - self.start_time
logger.log("Finished '", logger.cyan(self.name),
"' after ", logger.magenta(time_to_text(delta))) | def function[log_finished, parameter[self]]:
constant[Log that this task is done.]
variable[delta] assign[=] binary_operation[call[name[time].perf_counter, parameter[]] - name[self].start_time]
call[name[logger].log, parameter[constant[Finished '], call[name[logger].cyan, parameter[name[self].na... | keyword[def] identifier[log_finished] ( identifier[self] ):
literal[string]
identifier[delta] = identifier[time] . identifier[perf_counter] ()- identifier[self] . identifier[start_time]
identifier[logger] . identifier[log] ( literal[string] , identifier[logger] . identifier[cyan] ( identifier[self] . ident... | def log_finished(self):
"""Log that this task is done."""
delta = time.perf_counter() - self.start_time
logger.log("Finished '", logger.cyan(self.name), "' after ", logger.magenta(time_to_text(delta))) |
def execute_task(f, args, kwargs, user_ns):
"""
Deserialize the buffer and execute the task.
# Returns the result or exception.
"""
fname = getattr(f, '__name__', 'f')
prefix = "parsl_"
fname = prefix + "f"
argname = prefix + "args"
kwargname = prefix + "kwargs"
resultname = pre... | def function[execute_task, parameter[f, args, kwargs, user_ns]]:
constant[
Deserialize the buffer and execute the task.
# Returns the result or exception.
]
variable[fname] assign[=] call[name[getattr], parameter[name[f], constant[__name__], constant[f]]]
variable[prefix] assign[=] ... | keyword[def] identifier[execute_task] ( identifier[f] , identifier[args] , identifier[kwargs] , identifier[user_ns] ):
literal[string]
identifier[fname] = identifier[getattr] ( identifier[f] , literal[string] , literal[string] )
identifier[prefix] = literal[string]
identifier[fname] = identifier... | def execute_task(f, args, kwargs, user_ns):
"""
Deserialize the buffer and execute the task.
# Returns the result or exception.
"""
fname = getattr(f, '__name__', 'f')
prefix = 'parsl_'
fname = prefix + 'f'
argname = prefix + 'args'
kwargname = prefix + 'kwargs'
resultname = pre... |
def AddEventTag(self, event_tag):
"""Adds an event tag.
Args:
event_tag (EventTag): event tag.
Raises:
IOError: when the storage file is closed or read-only or
if the event identifier type is not supported.
OSError: when the storage file is closed or read-only or
if t... | def function[AddEventTag, parameter[self, event_tag]]:
constant[Adds an event tag.
Args:
event_tag (EventTag): event tag.
Raises:
IOError: when the storage file is closed or read-only or
if the event identifier type is not supported.
OSError: when the storage file is closed... | keyword[def] identifier[AddEventTag] ( identifier[self] , identifier[event_tag] ):
literal[string]
identifier[self] . identifier[_RaiseIfNotWritable] ()
identifier[event_identifier] = identifier[event_tag] . identifier[GetEventIdentifier] ()
keyword[if] keyword[not] identifier[isinstance] ( id... | def AddEventTag(self, event_tag):
"""Adds an event tag.
Args:
event_tag (EventTag): event tag.
Raises:
IOError: when the storage file is closed or read-only or
if the event identifier type is not supported.
OSError: when the storage file is closed or read-only or
if t... |
def _with_loc(f: ParseFunction):
"""Attach any available location information from the input form to
the node environment returned from the parsing function."""
@wraps(f)
def _parse_form(ctx: ParserContext, form: Union[LispForm, ISeq]) -> Node:
form_loc = _loc(form)
if form_loc is None:... | def function[_with_loc, parameter[f]]:
constant[Attach any available location information from the input form to
the node environment returned from the parsing function.]
def function[_parse_form, parameter[ctx, form]]:
variable[form_loc] assign[=] call[name[_loc], parameter[name[for... | keyword[def] identifier[_with_loc] ( identifier[f] : identifier[ParseFunction] ):
literal[string]
@ identifier[wraps] ( identifier[f] )
keyword[def] identifier[_parse_form] ( identifier[ctx] : identifier[ParserContext] , identifier[form] : identifier[Union] [ identifier[LispForm] , identifier[ISeq] ]... | def _with_loc(f: ParseFunction):
"""Attach any available location information from the input form to
the node environment returned from the parsing function."""
@wraps(f)
def _parse_form(ctx: ParserContext, form: Union[LispForm, ISeq]) -> Node:
form_loc = _loc(form)
if form_loc is None:... |
def is_subsumed_by(x, y):
"""
Returns true if y subsumes x (for example P(x) subsumes P(A) as it is more
abstract)
"""
varsX = __split_expression(x)[1]
theta = unify(x, y)
if theta is problem.FAILURE:
return False
return all(__is_variable(theta[var]) for var in theta.keys()
... | def function[is_subsumed_by, parameter[x, y]]:
constant[
Returns true if y subsumes x (for example P(x) subsumes P(A) as it is more
abstract)
]
variable[varsX] assign[=] call[call[name[__split_expression], parameter[name[x]]]][constant[1]]
variable[theta] assign[=] call[name[unify], ... | keyword[def] identifier[is_subsumed_by] ( identifier[x] , identifier[y] ):
literal[string]
identifier[varsX] = identifier[__split_expression] ( identifier[x] )[ literal[int] ]
identifier[theta] = identifier[unify] ( identifier[x] , identifier[y] )
keyword[if] identifier[theta] keyword[is] iden... | def is_subsumed_by(x, y):
"""
Returns true if y subsumes x (for example P(x) subsumes P(A) as it is more
abstract)
"""
varsX = __split_expression(x)[1]
theta = unify(x, y)
if theta is problem.FAILURE:
return False # depends on [control=['if'], data=[]]
return all((__is_variable(... |
def get_chunks(self, boundingbox=None):
"""
Return a list of all chunks. Use this function if you access the chunk
list frequently and want to cache the result.
Use iter_chunks() if you only want to loop through the chunks once or have a
very large world.
"""
if s... | def function[get_chunks, parameter[self, boundingbox]]:
constant[
Return a list of all chunks. Use this function if you access the chunk
list frequently and want to cache the result.
Use iter_chunks() if you only want to loop through the chunks once or have a
very large world.
... | keyword[def] identifier[get_chunks] ( identifier[self] , identifier[boundingbox] = keyword[None] ):
literal[string]
keyword[if] identifier[self] . identifier[chunks] == keyword[None] :
identifier[self] . identifier[chunks] = identifier[list] ( identifier[self] . identifier[iter_chunks... | def get_chunks(self, boundingbox=None):
"""
Return a list of all chunks. Use this function if you access the chunk
list frequently and want to cache the result.
Use iter_chunks() if you only want to loop through the chunks once or have a
very large world.
"""
if self.chun... |
def forum_topic_create(self, title, body, category=None):
"""Function to create topic (Requires login) (UNTESTED).
Parameters:
title (str): topic title.
body (str): Message of the initial post.
category (str): Can be: 0, 1, 2 (General, Tags, Bugs & Features
... | def function[forum_topic_create, parameter[self, title, body, category]]:
constant[Function to create topic (Requires login) (UNTESTED).
Parameters:
title (str): topic title.
body (str): Message of the initial post.
category (str): Can be: 0, 1, 2 (General, Tags, Bug... | keyword[def] identifier[forum_topic_create] ( identifier[self] , identifier[title] , identifier[body] , identifier[category] = keyword[None] ):
literal[string]
identifier[params] ={
literal[string] : identifier[title] ,
literal[string] : identifier[body] ,
literal[string]... | def forum_topic_create(self, title, body, category=None):
"""Function to create topic (Requires login) (UNTESTED).
Parameters:
title (str): topic title.
body (str): Message of the initial post.
category (str): Can be: 0, 1, 2 (General, Tags, Bugs & Features
... |
def get_color(self):
""" Return the array of rgba colors (same order as lStruct) """
col = np.full((self._dStruct['nObj'],4), np.nan)
ii = 0
for k in self._dStruct['lorder']:
k0, k1 = k.split('_')
col[ii,:] = self._dStruct['dObj'][k0][k1].get_color()
i... | def function[get_color, parameter[self]]:
constant[ Return the array of rgba colors (same order as lStruct) ]
variable[col] assign[=] call[name[np].full, parameter[tuple[[<ast.Subscript object at 0x7da1b0ba6710>, <ast.Constant object at 0x7da1b0ba7e20>]], name[np].nan]]
variable[ii] assign[=] co... | keyword[def] identifier[get_color] ( identifier[self] ):
literal[string]
identifier[col] = identifier[np] . identifier[full] (( identifier[self] . identifier[_dStruct] [ literal[string] ], literal[int] ), identifier[np] . identifier[nan] )
identifier[ii] = literal[int]
keyword[fo... | def get_color(self):
""" Return the array of rgba colors (same order as lStruct) """
col = np.full((self._dStruct['nObj'], 4), np.nan)
ii = 0
for k in self._dStruct['lorder']:
(k0, k1) = k.split('_')
col[ii, :] = self._dStruct['dObj'][k0][k1].get_color()
ii += 1 # depends on [co... |
def fit_left_censoring(
self,
durations,
event_observed=None,
timeline=None,
label=None,
alpha=None,
ci_labels=None,
show_progress=False,
entry=None,
weights=None,
): # pylint: disable=too-many-arguments
"""
Fit the mod... | def function[fit_left_censoring, parameter[self, durations, event_observed, timeline, label, alpha, ci_labels, show_progress, entry, weights]]:
constant[
Fit the model to a left-censored dataset
Parameters
----------
durations: an array, or pd.Series
length n, duration... | keyword[def] identifier[fit_left_censoring] (
identifier[self] ,
identifier[durations] ,
identifier[event_observed] = keyword[None] ,
identifier[timeline] = keyword[None] ,
identifier[label] = keyword[None] ,
identifier[alpha] = keyword[None] ,
identifier[ci_labels] = keyword[None] ,
identifier[show_progress]... | def fit_left_censoring(self, durations, event_observed=None, timeline=None, label=None, alpha=None, ci_labels=None, show_progress=False, entry=None, weights=None): # pylint: disable=too-many-arguments
'\n Fit the model to a left-censored dataset\n\n Parameters\n ----------\n durations: ... |
def https():
'''
Determines whether enough data has been provided in configuration
or relation data to configure HTTPS
.
returns: boolean
'''
use_https = config_get('use-https')
if use_https and bool_from_string(use_https):
return True
if config_get('ssl_cert') and config_get... | def function[https, parameter[]]:
constant[
Determines whether enough data has been provided in configuration
or relation data to configure HTTPS
.
returns: boolean
]
variable[use_https] assign[=] call[name[config_get], parameter[constant[use-https]]]
if <ast.BoolOp object at... | keyword[def] identifier[https] ():
literal[string]
identifier[use_https] = identifier[config_get] ( literal[string] )
keyword[if] identifier[use_https] keyword[and] identifier[bool_from_string] ( identifier[use_https] ):
keyword[return] keyword[True]
keyword[if] identifier[config_g... | def https():
"""
Determines whether enough data has been provided in configuration
or relation data to configure HTTPS
.
returns: boolean
"""
use_https = config_get('use-https')
if use_https and bool_from_string(use_https):
return True # depends on [control=['if'], data=[]]
... |
def load(self, key):
"""
Given a bucket key, load the corresponding bucket.
:param key: The bucket key. This may be either a string or a
BucketKey object.
:returns: A Bucket object.
"""
# Turn the key into a BucketKey
if isinstance(key, bas... | def function[load, parameter[self, key]]:
constant[
Given a bucket key, load the corresponding bucket.
:param key: The bucket key. This may be either a string or a
BucketKey object.
:returns: A Bucket object.
]
if call[name[isinstance], parameter[na... | keyword[def] identifier[load] ( identifier[self] , identifier[key] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[key] , identifier[basestring] ):
identifier[key] = identifier[BucketKey] . identifier[decode] ( identifier[key] )
keyw... | def load(self, key):
"""
Given a bucket key, load the corresponding bucket.
:param key: The bucket key. This may be either a string or a
BucketKey object.
:returns: A Bucket object.
"""
# Turn the key into a BucketKey
if isinstance(key, basestring):
... |
def get_version(self):
# type: () -> str
"""
Retrieves the bundle version, using the ``__version__`` or
``__version_info__`` attributes of its module.
:return: The bundle version, "0.0.0" by default
"""
# Get the version value
version = getattr(self.__mod... | def function[get_version, parameter[self]]:
constant[
Retrieves the bundle version, using the ``__version__`` or
``__version_info__`` attributes of its module.
:return: The bundle version, "0.0.0" by default
]
variable[version] assign[=] call[name[getattr], parameter[nam... | keyword[def] identifier[get_version] ( identifier[self] ):
literal[string]
identifier[version] = identifier[getattr] ( identifier[self] . identifier[__module] , literal[string] , keyword[None] )
keyword[if] identifier[version] :
keyword[return] identifier[version] ... | def get_version(self):
# type: () -> str
'\n Retrieves the bundle version, using the ``__version__`` or\n ``__version_info__`` attributes of its module.\n\n :return: The bundle version, "0.0.0" by default\n '
# Get the version value
version = getattr(self.__module, '__version... |
def get_data_classif(dataset, n, nz=.5, theta=0, random_state=None, **kwargs):
""" Deprecated see make_data_classif """
return make_data_classif(dataset, n, nz=.5, theta=0, random_state=None, **kwargs) | def function[get_data_classif, parameter[dataset, n, nz, theta, random_state]]:
constant[ Deprecated see make_data_classif ]
return[call[name[make_data_classif], parameter[name[dataset], name[n]]]] | keyword[def] identifier[get_data_classif] ( identifier[dataset] , identifier[n] , identifier[nz] = literal[int] , identifier[theta] = literal[int] , identifier[random_state] = keyword[None] ,** identifier[kwargs] ):
literal[string]
keyword[return] identifier[make_data_classif] ( identifier[dataset] , iden... | def get_data_classif(dataset, n, nz=0.5, theta=0, random_state=None, **kwargs):
""" Deprecated see make_data_classif """
return make_data_classif(dataset, n, nz=0.5, theta=0, random_state=None, **kwargs) |
def format_ffmpeg_filter(name, params):
""" Build a string to call a FFMpeg filter. """
return "%s=%s" % (name,
":".join("%s=%s" % (k, v) for k, v in params.items())) | def function[format_ffmpeg_filter, parameter[name, params]]:
constant[ Build a string to call a FFMpeg filter. ]
return[binary_operation[constant[%s=%s] <ast.Mod object at 0x7da2590d6920> tuple[[<ast.Name object at 0x7da1b060aa10>, <ast.Call object at 0x7da1b060b2e0>]]]] | keyword[def] identifier[format_ffmpeg_filter] ( identifier[name] , identifier[params] ):
literal[string]
keyword[return] literal[string] %( identifier[name] ,
literal[string] . identifier[join] ( literal[string] %( identifier[k] , identifier[v] ) keyword[for] identifier[k] , identifier[v] keyword[in] id... | def format_ffmpeg_filter(name, params):
""" Build a string to call a FFMpeg filter. """
return '%s=%s' % (name, ':'.join(('%s=%s' % (k, v) for (k, v) in params.items()))) |
def get_default(self, node):
"""
If not explicitly set, check if rset or rclr imply the value
"""
if node.inst.properties.get("rset", False):
return rdltypes.OnReadType.rset
elif node.inst.properties.get("rclr", False):
return rdltypes.OnReadType.rclr
... | def function[get_default, parameter[self, node]]:
constant[
If not explicitly set, check if rset or rclr imply the value
]
if call[name[node].inst.properties.get, parameter[constant[rset], constant[False]]] begin[:]
return[name[rdltypes].OnReadType.rset] | keyword[def] identifier[get_default] ( identifier[self] , identifier[node] ):
literal[string]
keyword[if] identifier[node] . identifier[inst] . identifier[properties] . identifier[get] ( literal[string] , keyword[False] ):
keyword[return] identifier[rdltypes] . identifier[OnReadType]... | def get_default(self, node):
"""
If not explicitly set, check if rset or rclr imply the value
"""
if node.inst.properties.get('rset', False):
return rdltypes.OnReadType.rset # depends on [control=['if'], data=[]]
elif node.inst.properties.get('rclr', False):
return rdltypes.... |
def ensure_ascii(str_or_unicode):
"""
tests, if the input is ``str`` or ``unicode``. if it is ``unicode``,
it will be encoded from ``unicode`` to 7-bit ``latin-1``.
otherwise, the input string is converted from ``utf-8`` to 7-bit
``latin-1``. 7-bit latin-1 doesn't even contain umlauts, but
XML/H... | def function[ensure_ascii, parameter[str_or_unicode]]:
constant[
tests, if the input is ``str`` or ``unicode``. if it is ``unicode``,
it will be encoded from ``unicode`` to 7-bit ``latin-1``.
otherwise, the input string is converted from ``utf-8`` to 7-bit
``latin-1``. 7-bit latin-1 doesn't even... | keyword[def] identifier[ensure_ascii] ( identifier[str_or_unicode] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[str_or_unicode] , identifier[str] ):
keyword[return] identifier[str_or_unicode] . identifier[decode] ( literal[string] ). identifier[encode] ( literal[string] ,
... | def ensure_ascii(str_or_unicode):
"""
tests, if the input is ``str`` or ``unicode``. if it is ``unicode``,
it will be encoded from ``unicode`` to 7-bit ``latin-1``.
otherwise, the input string is converted from ``utf-8`` to 7-bit
``latin-1``. 7-bit latin-1 doesn't even contain umlauts, but
XML/H... |
def _row(self, values):
"""Parse a row."""
row_id = self._to_id(values[ID])
row = self._spec.new_row(row_id, values, self)
if SAME_AS in values:
self._delay_inheritance(row, self._to_id(values[SAME_AS]))
self._delay_instructions(row)
self._id_cache[row_id] = r... | def function[_row, parameter[self, values]]:
constant[Parse a row.]
variable[row_id] assign[=] call[name[self]._to_id, parameter[call[name[values]][name[ID]]]]
variable[row] assign[=] call[name[self]._spec.new_row, parameter[name[row_id], name[values], name[self]]]
if compare[name[SAME_A... | keyword[def] identifier[_row] ( identifier[self] , identifier[values] ):
literal[string]
identifier[row_id] = identifier[self] . identifier[_to_id] ( identifier[values] [ identifier[ID] ])
identifier[row] = identifier[self] . identifier[_spec] . identifier[new_row] ( identifier[row_id] , i... | def _row(self, values):
"""Parse a row."""
row_id = self._to_id(values[ID])
row = self._spec.new_row(row_id, values, self)
if SAME_AS in values:
self._delay_inheritance(row, self._to_id(values[SAME_AS])) # depends on [control=['if'], data=['SAME_AS', 'values']]
self._delay_instructions(row)... |
def ParseMultiple(self, stat_entries, knowledge_base):
"""Parse the StatEntry objects."""
_ = knowledge_base
for stat_entry in stat_entries:
# TODO: `st_mode` has to be an `int`, not `StatMode`.
if stat.S_ISDIR(int(stat_entry.st_mode)):
homedir = stat_entry.pathspec.path
usernam... | def function[ParseMultiple, parameter[self, stat_entries, knowledge_base]]:
constant[Parse the StatEntry objects.]
variable[_] assign[=] name[knowledge_base]
for taget[name[stat_entry]] in starred[name[stat_entries]] begin[:]
if call[name[stat].S_ISDIR, parameter[call[name[int], ... | keyword[def] identifier[ParseMultiple] ( identifier[self] , identifier[stat_entries] , identifier[knowledge_base] ):
literal[string]
identifier[_] = identifier[knowledge_base]
keyword[for] identifier[stat_entry] keyword[in] identifier[stat_entries] :
keyword[if] identifier[stat] . id... | def ParseMultiple(self, stat_entries, knowledge_base):
"""Parse the StatEntry objects."""
_ = knowledge_base
for stat_entry in stat_entries:
# TODO: `st_mode` has to be an `int`, not `StatMode`.
if stat.S_ISDIR(int(stat_entry.st_mode)):
homedir = stat_entry.pathspec.path
... |
def local_manager_is_default(self, adm_gid, gid):
"""Check whether gid is default group for local manager group.
"""
config = self.root['settings']['ugm_localmanager'].attrs
rule = config[adm_gid]
if gid not in rule['target']:
raise Exception(u"group '%s' not managed ... | def function[local_manager_is_default, parameter[self, adm_gid, gid]]:
constant[Check whether gid is default group for local manager group.
]
variable[config] assign[=] call[call[name[self].root][constant[settings]]][constant[ugm_localmanager]].attrs
variable[rule] assign[=] call[name[co... | keyword[def] identifier[local_manager_is_default] ( identifier[self] , identifier[adm_gid] , identifier[gid] ):
literal[string]
identifier[config] = identifier[self] . identifier[root] [ literal[string] ][ literal[string] ]. identifier[attrs]
identifier[rule] = identifier[config] [ identi... | def local_manager_is_default(self, adm_gid, gid):
"""Check whether gid is default group for local manager group.
"""
config = self.root['settings']['ugm_localmanager'].attrs
rule = config[adm_gid]
if gid not in rule['target']:
raise Exception(u"group '%s' not managed by '%s'" % (gid, adm... |
def create_args(args, root):
"""
Encapsulates a set of custom command line arguments in key=value
or key.namespace=value form into a chain of Namespace objects,
where each next level is an attribute of the Namespace object on the
current level
Parameters
----------
args : list
A... | def function[create_args, parameter[args, root]]:
constant[
Encapsulates a set of custom command line arguments in key=value
or key.namespace=value form into a chain of Namespace objects,
where each next level is an attribute of the Namespace object on the
current level
Parameters
-----... | keyword[def] identifier[create_args] ( identifier[args] , identifier[root] ):
literal[string]
identifier[extension_args] ={}
keyword[for] identifier[arg] keyword[in] identifier[args] :
identifier[parse_extension_arg] ( identifier[arg] , identifier[extension_args] )
keyword[for] id... | def create_args(args, root):
"""
Encapsulates a set of custom command line arguments in key=value
or key.namespace=value form into a chain of Namespace objects,
where each next level is an attribute of the Namespace object on the
current level
Parameters
----------
args : list
A... |
def load(filename, default=None):
'''
Try to load @filename. If there is no loader for @filename's filetype,
return @default.
'''
ext = get_ext(filename)
if ext in ldict:
return ldict[ext](filename)
else:
return default | def function[load, parameter[filename, default]]:
constant[
Try to load @filename. If there is no loader for @filename's filetype,
return @default.
]
variable[ext] assign[=] call[name[get_ext], parameter[name[filename]]]
if compare[name[ext] in name[ldict]] begin[:]
return[c... | keyword[def] identifier[load] ( identifier[filename] , identifier[default] = keyword[None] ):
literal[string]
identifier[ext] = identifier[get_ext] ( identifier[filename] )
keyword[if] identifier[ext] keyword[in] identifier[ldict] :
keyword[return] identifier[ldict] [ identifier[ext] ]( i... | def load(filename, default=None):
"""
Try to load @filename. If there is no loader for @filename's filetype,
return @default.
"""
ext = get_ext(filename)
if ext in ldict:
return ldict[ext](filename) # depends on [control=['if'], data=['ext', 'ldict']]
else:
return default |
def compare(self, other, filter_fcn=None):
"""Returns True if properties can be compared in terms of eq.
Entity's Fields can be filtered accordingly to 'filter_fcn'.
This callable receives field's name as first parameter and field itself
as second parameter.
It must return True i... | def function[compare, parameter[self, other, filter_fcn]]:
constant[Returns True if properties can be compared in terms of eq.
Entity's Fields can be filtered accordingly to 'filter_fcn'.
This callable receives field's name as first parameter and field itself
as second parameter.
... | keyword[def] identifier[compare] ( identifier[self] , identifier[other] , identifier[filter_fcn] = keyword[None] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[other] , identifier[type] ( identifier[self] )):
keyword[return] keyword[False]
... | def compare(self, other, filter_fcn=None):
"""Returns True if properties can be compared in terms of eq.
Entity's Fields can be filtered accordingly to 'filter_fcn'.
This callable receives field's name as first parameter and field itself
as second parameter.
It must return True if fi... |
def load_mplstyle():
"""Try to load conf.plot.mplstyle matplotlib style."""
plt = importlib.import_module('matplotlib.pyplot')
if conf.plot.mplstyle:
for style in conf.plot.mplstyle.split():
stfile = config.CONFIG_DIR / (style + '.mplstyle')
if stfile.is_file():
... | def function[load_mplstyle, parameter[]]:
constant[Try to load conf.plot.mplstyle matplotlib style.]
variable[plt] assign[=] call[name[importlib].import_module, parameter[constant[matplotlib.pyplot]]]
if name[conf].plot.mplstyle begin[:]
for taget[name[style]] in starred[call[nam... | keyword[def] identifier[load_mplstyle] ():
literal[string]
identifier[plt] = identifier[importlib] . identifier[import_module] ( literal[string] )
keyword[if] identifier[conf] . identifier[plot] . identifier[mplstyle] :
keyword[for] identifier[style] keyword[in] identifier[conf] . identif... | def load_mplstyle():
"""Try to load conf.plot.mplstyle matplotlib style."""
plt = importlib.import_module('matplotlib.pyplot')
if conf.plot.mplstyle:
for style in conf.plot.mplstyle.split():
stfile = config.CONFIG_DIR / (style + '.mplstyle')
if stfile.is_file():
... |
def _batch_json_to_instances(self, json_dicts: List[JsonDict]) -> List[Instance]:
"""
Converts a list of JSON objects into a list of :class:`~allennlp.data.instance.Instance`s.
By default, this expects that a "batch" consists of a list of JSON blobs which would
individually be predicted ... | def function[_batch_json_to_instances, parameter[self, json_dicts]]:
constant[
Converts a list of JSON objects into a list of :class:`~allennlp.data.instance.Instance`s.
By default, this expects that a "batch" consists of a list of JSON blobs which would
individually be predicted by :fun... | keyword[def] identifier[_batch_json_to_instances] ( identifier[self] , identifier[json_dicts] : identifier[List] [ identifier[JsonDict] ])-> identifier[List] [ identifier[Instance] ]:
literal[string]
identifier[instances] =[]
keyword[for] identifier[json_dict] keyword[in] identifier[jso... | def _batch_json_to_instances(self, json_dicts: List[JsonDict]) -> List[Instance]:
"""
Converts a list of JSON objects into a list of :class:`~allennlp.data.instance.Instance`s.
By default, this expects that a "batch" consists of a list of JSON blobs which would
individually be predicted by :... |
def backward_char(self, e): # (C-b)
u"""Move back a character. """
self.l_buffer.backward_char(self.argument_reset)
self.finalize() | def function[backward_char, parameter[self, e]]:
constant[Move back a character. ]
call[name[self].l_buffer.backward_char, parameter[name[self].argument_reset]]
call[name[self].finalize, parameter[]] | keyword[def] identifier[backward_char] ( identifier[self] , identifier[e] ):
literal[string]
identifier[self] . identifier[l_buffer] . identifier[backward_char] ( identifier[self] . identifier[argument_reset] )
identifier[self] . identifier[finalize] () | def backward_char(self, e): # (C-b)
u'Move back a character. '
self.l_buffer.backward_char(self.argument_reset)
self.finalize() |
def approve(self, access_level=gitlab.DEVELOPER_ACCESS, **kwargs):
"""Approve an access request.
Args:
access_level (int): The access level for the user
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentic... | def function[approve, parameter[self, access_level]]:
constant[Approve an access request.
Args:
access_level (int): The access level for the user
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication i... | keyword[def] identifier[approve] ( identifier[self] , identifier[access_level] = identifier[gitlab] . identifier[DEVELOPER_ACCESS] ,** identifier[kwargs] ):
literal[string]
identifier[path] = literal[string] %( identifier[self] . identifier[manager] . identifier[path] , identifier[self] . identifi... | def approve(self, access_level=gitlab.DEVELOPER_ACCESS, **kwargs):
"""Approve an access request.
Args:
access_level (int): The access level for the user
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authenticatio... |
def list_nodes_full(mask='mask[id]', call=None):
'''
Return a list of the VMs that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f or --function.'
)
ret = {}
conn = get_conn(service='SoftLay... | def function[list_nodes_full, parameter[mask, call]]:
constant[
Return a list of the VMs that are on the provider
]
if compare[name[call] equal[==] constant[action]] begin[:]
<ast.Raise object at 0x7da1b2136500>
variable[ret] assign[=] dictionary[[], []]
variable[conn] as... | keyword[def] identifier[list_nodes_full] ( identifier[mask] = literal[string] , identifier[call] = keyword[None] ):
literal[string]
keyword[if] identifier[call] == literal[string] :
keyword[raise] identifier[SaltCloudSystemExit] (
literal[string]
)
identifier[ret] ={}
... | def list_nodes_full(mask='mask[id]', call=None):
"""
Return a list of the VMs that are on the provider
"""
if call == 'action':
raise SaltCloudSystemExit('The list_nodes_full function must be called with -f or --function.') # depends on [control=['if'], data=[]]
ret = {}
conn = get_conn... |
def get_as_datadict(self):
"""
Get information about this object as a dictionary. Used by WebSocket interface to pass some
relevant information to client applications.
"""
return dict(type=self.__class__.__name__, tags=list(self.tags)) | def function[get_as_datadict, parameter[self]]:
constant[
Get information about this object as a dictionary. Used by WebSocket interface to pass some
relevant information to client applications.
]
return[call[name[dict], parameter[]]] | keyword[def] identifier[get_as_datadict] ( identifier[self] ):
literal[string]
keyword[return] identifier[dict] ( identifier[type] = identifier[self] . identifier[__class__] . identifier[__name__] , identifier[tags] = identifier[list] ( identifier[self] . identifier[tags] )) | def get_as_datadict(self):
"""
Get information about this object as a dictionary. Used by WebSocket interface to pass some
relevant information to client applications.
"""
return dict(type=self.__class__.__name__, tags=list(self.tags)) |
def find_logs(
self,
user_name,
first_date,
start_time,
last_date,
end_time,
action,
functionality,
parameter,
pagination):
"""
Search all logs, filtering by the given parameters.
... | def function[find_logs, parameter[self, user_name, first_date, start_time, last_date, end_time, action, functionality, parameter, pagination]]:
constant[
Search all logs, filtering by the given parameters.
:param user_name: Filter by user_name
:param first_date: Sets initial date for beg... | keyword[def] identifier[find_logs] (
identifier[self] ,
identifier[user_name] ,
identifier[first_date] ,
identifier[start_time] ,
identifier[last_date] ,
identifier[end_time] ,
identifier[action] ,
identifier[functionality] ,
identifier[parameter] ,
identifier[pagination] ):
literal[string]
... | def find_logs(self, user_name, first_date, start_time, last_date, end_time, action, functionality, parameter, pagination):
"""
Search all logs, filtering by the given parameters.
:param user_name: Filter by user_name
:param first_date: Sets initial date for begin of the filter
:param... |
def get(self, ring, angle):
"""Get RGB color tuple of color at index pixel"""
pixel = self.angleToPixel(angle, ring)
return self._get_base(pixel) | def function[get, parameter[self, ring, angle]]:
constant[Get RGB color tuple of color at index pixel]
variable[pixel] assign[=] call[name[self].angleToPixel, parameter[name[angle], name[ring]]]
return[call[name[self]._get_base, parameter[name[pixel]]]] | keyword[def] identifier[get] ( identifier[self] , identifier[ring] , identifier[angle] ):
literal[string]
identifier[pixel] = identifier[self] . identifier[angleToPixel] ( identifier[angle] , identifier[ring] )
keyword[return] identifier[self] . identifier[_get_base] ( identifier[pixel] ) | def get(self, ring, angle):
"""Get RGB color tuple of color at index pixel"""
pixel = self.angleToPixel(angle, ring)
return self._get_base(pixel) |
def stream_command(cmd, no_newline_regexp="Progess", sudo=False):
'''stream a command (yield) back to the user, as each line is available.
# Example usage:
results = []
for line in stream_command(cmd):
print(line, end="")
results.append(line)
Parameters
===... | def function[stream_command, parameter[cmd, no_newline_regexp, sudo]]:
constant[stream a command (yield) back to the user, as each line is available.
# Example usage:
results = []
for line in stream_command(cmd):
print(line, end="")
results.append(line)
Parame... | keyword[def] identifier[stream_command] ( identifier[cmd] , identifier[no_newline_regexp] = literal[string] , identifier[sudo] = keyword[False] ):
literal[string]
keyword[if] identifier[sudo] keyword[is] keyword[True] :
identifier[cmd] =[ literal[string] ]+ identifier[cmd]
identifier[pro... | def stream_command(cmd, no_newline_regexp='Progess', sudo=False):
"""stream a command (yield) back to the user, as each line is available.
# Example usage:
results = []
for line in stream_command(cmd):
print(line, end="")
results.append(line)
Parameters
===... |
def short_version(version=None):
"""
Return short application version. For example: `1.0.0`.
"""
v = version or __version__
return '.'.join([str(x) for x in v[:3]]) | def function[short_version, parameter[version]]:
constant[
Return short application version. For example: `1.0.0`.
]
variable[v] assign[=] <ast.BoolOp object at 0x7da18bc71120>
return[call[constant[.].join, parameter[<ast.ListComp object at 0x7da18bc716c0>]]] | keyword[def] identifier[short_version] ( identifier[version] = keyword[None] ):
literal[string]
identifier[v] = identifier[version] keyword[or] identifier[__version__]
keyword[return] literal[string] . identifier[join] ([ identifier[str] ( identifier[x] ) keyword[for] identifier[x] keyword[in] ... | def short_version(version=None):
"""
Return short application version. For example: `1.0.0`.
"""
v = version or __version__
return '.'.join([str(x) for x in v[:3]]) |
def configure(self, options, config):
"""Configure the plugin and system, based on selected options.
attr and eval_attr may each be lists.
self.attribs will be a list of lists of tuples. In that list, each
list is a group of attributes, all of which must match for the rule to
m... | def function[configure, parameter[self, options, config]]:
constant[Configure the plugin and system, based on selected options.
attr and eval_attr may each be lists.
self.attribs will be a list of lists of tuples. In that list, each
list is a group of attributes, all of which must matc... | keyword[def] identifier[configure] ( identifier[self] , identifier[options] , identifier[config] ):
literal[string]
identifier[self] . identifier[attribs] =[]
keyword[if] identifier[compat_24] keyword[and] identifier[options] . identifier[eval_attr] :
identifier[e... | def configure(self, options, config):
"""Configure the plugin and system, based on selected options.
attr and eval_attr may each be lists.
self.attribs will be a list of lists of tuples. In that list, each
list is a group of attributes, all of which must match for the rule to
match... |
def mapping_to_str(mapping):
"""Convert mapping to string"""
result = ["<"]
for i, (key, value) in enumerate(mapping.items()):
if i > 0:
result.append(",")
result += [key, "=", serialize_for_header(key, value)]
result += [">"]
return "".join(result) | def function[mapping_to_str, parameter[mapping]]:
constant[Convert mapping to string]
variable[result] assign[=] list[[<ast.Constant object at 0x7da18f58df00>]]
for taget[tuple[[<ast.Name object at 0x7da18f58c940>, <ast.Tuple object at 0x7da18f58ed70>]]] in starred[call[name[enumerate], paramete... | keyword[def] identifier[mapping_to_str] ( identifier[mapping] ):
literal[string]
identifier[result] =[ literal[string] ]
keyword[for] identifier[i] ,( identifier[key] , identifier[value] ) keyword[in] identifier[enumerate] ( identifier[mapping] . identifier[items] ()):
keyword[if] identifi... | def mapping_to_str(mapping):
"""Convert mapping to string"""
result = ['<']
for (i, (key, value)) in enumerate(mapping.items()):
if i > 0:
result.append(',') # depends on [control=['if'], data=[]]
result += [key, '=', serialize_for_header(key, value)] # depends on [control=['fo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.