code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def return_single_features_base(dbpath, set_object, object_id):
"""
Generic function which returns the features of an object specified by the object_id
Parameters
----------
dbpath : string, path to SQLite database file
set_object : object (either TestSet or TrainSet) which is stored in the dat... | def function[return_single_features_base, parameter[dbpath, set_object, object_id]]:
constant[
Generic function which returns the features of an object specified by the object_id
Parameters
----------
dbpath : string, path to SQLite database file
set_object : object (either TestSet or Train... | keyword[def] identifier[return_single_features_base] ( identifier[dbpath] , identifier[set_object] , identifier[object_id] ):
literal[string]
identifier[engine] = identifier[create_engine] ( literal[string] + identifier[dbpath] )
identifier[session_cl] = identifier[sessionmaker] ( identifier[bind] = i... | def return_single_features_base(dbpath, set_object, object_id):
"""
Generic function which returns the features of an object specified by the object_id
Parameters
----------
dbpath : string, path to SQLite database file
set_object : object (either TestSet or TrainSet) which is stored in the dat... |
def get_requirements(opts):
''' Get the proper requirements file based on the optional argument '''
if opts.dev:
name = 'requirements_dev.txt'
elif opts.doc:
name = 'requirements_doc.txt'
else:
name = 'requirements.txt'
requirements_file = os.path.join(os.path.dirname(__fil... | def function[get_requirements, parameter[opts]]:
constant[ Get the proper requirements file based on the optional argument ]
if name[opts].dev begin[:]
variable[name] assign[=] constant[requirements_dev.txt]
variable[requirements_file] assign[=] call[name[os].path.join, parameter... | keyword[def] identifier[get_requirements] ( identifier[opts] ):
literal[string]
keyword[if] identifier[opts] . identifier[dev] :
identifier[name] = literal[string]
keyword[elif] identifier[opts] . identifier[doc] :
identifier[name] = literal[string]
keyword[else] :
... | def get_requirements(opts):
""" Get the proper requirements file based on the optional argument """
if opts.dev:
name = 'requirements_dev.txt' # depends on [control=['if'], data=[]]
elif opts.doc:
name = 'requirements_doc.txt' # depends on [control=['if'], data=[]]
else:
name =... |
def lessons(self):
"""
返回lessons,如果未调用过``get_lesson()``会自动调用
:return: list of lessons
:rtype: list
"""
if hasattr(self, '_lessons'):
return self._lessons
else:
self.get_lesson()
return self._lessons | def function[lessons, parameter[self]]:
constant[
返回lessons,如果未调用过``get_lesson()``会自动调用
:return: list of lessons
:rtype: list
]
if call[name[hasattr], parameter[name[self], constant[_lessons]]] begin[:]
return[name[self]._lessons] | keyword[def] identifier[lessons] ( identifier[self] ):
literal[string]
keyword[if] identifier[hasattr] ( identifier[self] , literal[string] ):
keyword[return] identifier[self] . identifier[_lessons]
keyword[else] :
identifier[self] . identifier[get_lesson] ()
... | def lessons(self):
"""
返回lessons,如果未调用过``get_lesson()``会自动调用
:return: list of lessons
:rtype: list
"""
if hasattr(self, '_lessons'):
return self._lessons # depends on [control=['if'], data=[]]
else:
self.get_lesson()
return self._lessons |
def transcript_to_gene(gtf):
"""
return a dictionary keyed by transcript_id of the associated gene_id
"""
gene_lookup = {}
for feature in complete_features(get_gtf_db(gtf)):
gene_id = feature.attributes.get('gene_id', [None])[0]
transcript_id = feature.attributes.get('transcript_id',... | def function[transcript_to_gene, parameter[gtf]]:
constant[
return a dictionary keyed by transcript_id of the associated gene_id
]
variable[gene_lookup] assign[=] dictionary[[], []]
for taget[name[feature]] in starred[call[name[complete_features], parameter[call[name[get_gtf_db], paramet... | keyword[def] identifier[transcript_to_gene] ( identifier[gtf] ):
literal[string]
identifier[gene_lookup] ={}
keyword[for] identifier[feature] keyword[in] identifier[complete_features] ( identifier[get_gtf_db] ( identifier[gtf] )):
identifier[gene_id] = identifier[feature] . identifier[attr... | def transcript_to_gene(gtf):
"""
return a dictionary keyed by transcript_id of the associated gene_id
"""
gene_lookup = {}
for feature in complete_features(get_gtf_db(gtf)):
gene_id = feature.attributes.get('gene_id', [None])[0]
transcript_id = feature.attributes.get('transcript_id',... |
def network_interfaces_list(resource_group, **kwargs):
'''
.. versionadded:: 2019.2.0
List all network interfaces within a resource group.
:param resource_group: The resource group name to list network
interfaces within.
CLI Example:
.. code-block:: bash
salt-call azurearm_n... | def function[network_interfaces_list, parameter[resource_group]]:
constant[
.. versionadded:: 2019.2.0
List all network interfaces within a resource group.
:param resource_group: The resource group name to list network
interfaces within.
CLI Example:
.. code-block:: bash
... | keyword[def] identifier[network_interfaces_list] ( identifier[resource_group] ,** identifier[kwargs] ):
literal[string]
identifier[result] ={}
identifier[netconn] = identifier[__utils__] [ literal[string] ]( literal[string] ,** identifier[kwargs] )
keyword[try] :
identifier[nics] = ident... | def network_interfaces_list(resource_group, **kwargs):
"""
.. versionadded:: 2019.2.0
List all network interfaces within a resource group.
:param resource_group: The resource group name to list network
interfaces within.
CLI Example:
.. code-block:: bash
salt-call azurearm_n... |
def ShowErrorBarCaps(ax):
"""Show error bar caps.
Seaborn paper style hides error bar caps. Call this function on an axes
object to make them visible again.
"""
for ch in ax.get_children():
if str(ch).startswith('Line2D'):
ch.set_markeredgewidth(1)
ch.set_markersiz... | def function[ShowErrorBarCaps, parameter[ax]]:
constant[Show error bar caps.
Seaborn paper style hides error bar caps. Call this function on an axes
object to make them visible again.
]
for taget[name[ch]] in starred[call[name[ax].get_children, parameter[]]] begin[:]
if ca... | keyword[def] identifier[ShowErrorBarCaps] ( identifier[ax] ):
literal[string]
keyword[for] identifier[ch] keyword[in] identifier[ax] . identifier[get_children] ():
keyword[if] identifier[str] ( identifier[ch] ). identifier[startswith] ( literal[string] ):
identifier[ch] . identifi... | def ShowErrorBarCaps(ax):
"""Show error bar caps.
\xa0\xa0
Seaborn paper style hides error bar caps. Call this function on an axes
object to make them visible again.
"""
for ch in ax.get_children():
if str(ch).startswith('Line2D'):
ch.set_markeredgewidth(1)
ch.set_mar... |
def pass_feature(*feature_names):
"""Injects a feature instance into the kwargs
"""
def decorator(f):
@functools.wraps(f)
def wrapper(*args, **kwargs):
for name in feature_names:
kwargs[name] = feature_proxy(name)
return f(*args, **kwargs)
retu... | def function[pass_feature, parameter[]]:
constant[Injects a feature instance into the kwargs
]
def function[decorator, parameter[f]]:
def function[wrapper, parameter[]]:
for taget[name[name]] in starred[name[feature_names]] begin[:]
... | keyword[def] identifier[pass_feature] (* identifier[feature_names] ):
literal[string]
keyword[def] identifier[decorator] ( identifier[f] ):
@ identifier[functools] . identifier[wraps] ( identifier[f] )
keyword[def] identifier[wrapper] (* identifier[args] ,** identifier[kwargs] ):
... | def pass_feature(*feature_names):
"""Injects a feature instance into the kwargs
"""
def decorator(f):
@functools.wraps(f)
def wrapper(*args, **kwargs):
for name in feature_names:
kwargs[name] = feature_proxy(name) # depends on [control=['for'], data=['name']]
... |
def _construct_sparse_features(self, x):
""" Helper to construct a sparse representation of the features. """
I, J, K = x.shape
new_array_height = (x != 0).sum(axis=2).max()
index_array = -np.ones((I, J, new_array_height), dtype='int64')
value_array = -np.ones((I, J, new_array_he... | def function[_construct_sparse_features, parameter[self, x]]:
constant[ Helper to construct a sparse representation of the features. ]
<ast.Tuple object at 0x7da1b253c070> assign[=] name[x].shape
variable[new_array_height] assign[=] call[call[compare[name[x] not_equal[!=] constant[0]].sum, param... | keyword[def] identifier[_construct_sparse_features] ( identifier[self] , identifier[x] ):
literal[string]
identifier[I] , identifier[J] , identifier[K] = identifier[x] . identifier[shape]
identifier[new_array_height] =( identifier[x] != literal[int] ). identifier[sum] ( identifier[axis] =... | def _construct_sparse_features(self, x):
""" Helper to construct a sparse representation of the features. """
(I, J, K) = x.shape
new_array_height = (x != 0).sum(axis=2).max()
index_array = -np.ones((I, J, new_array_height), dtype='int64')
value_array = -np.ones((I, J, new_array_height), dtype='floa... |
def normalised_autocorrelation_function(chain, index=0, burn=None,
limit=None, fig=None, figsize=None):
"""
Plot the autocorrelation function for each parameter of a sampler chain.
:param chain:
The sampled parameter values.
:type chain:
:class:`numpy.ndarray`
:param index: [... | def function[normalised_autocorrelation_function, parameter[chain, index, burn, limit, fig, figsize]]:
constant[
Plot the autocorrelation function for each parameter of a sampler chain.
:param chain:
The sampled parameter values.
:type chain:
:class:`numpy.ndarray`
:param inde... | keyword[def] identifier[normalised_autocorrelation_function] ( identifier[chain] , identifier[index] = literal[int] , identifier[burn] = keyword[None] ,
identifier[limit] = keyword[None] , identifier[fig] = keyword[None] , identifier[figsize] = keyword[None] ):
literal[string]
identifier[factor] = litera... | def normalised_autocorrelation_function(chain, index=0, burn=None, limit=None, fig=None, figsize=None):
"""
Plot the autocorrelation function for each parameter of a sampler chain.
:param chain:
The sampled parameter values.
:type chain:
:class:`numpy.ndarray`
:param index: [optio... |
def validate(self):
""" validate: Makes sure node is valid
Args: None
Returns: boolean indicating if node is valid
"""
from .files import File
assert self.source_id is not None, "Assumption Failed: Node must have a source_id"
assert isinstance(self.title,... | def function[validate, parameter[self]]:
constant[ validate: Makes sure node is valid
Args: None
Returns: boolean indicating if node is valid
]
from relative_module[files] import module[File]
assert[compare[name[self].source_id is_not constant[None]]]
assert[call[name... | keyword[def] identifier[validate] ( identifier[self] ):
literal[string]
keyword[from] . identifier[files] keyword[import] identifier[File]
keyword[assert] identifier[self] . identifier[source_id] keyword[is] keyword[not] keyword[None] , literal[string]
keyword[assert] id... | def validate(self):
""" validate: Makes sure node is valid
Args: None
Returns: boolean indicating if node is valid
"""
from .files import File
assert self.source_id is not None, 'Assumption Failed: Node must have a source_id'
assert isinstance(self.title, str), 'Assumptio... |
def event(self, utype, **kw):
'''
Make a meta-event with a utype of @type. **@kw works the same as for
pygame.event.Event().
'''
d = {'utype': utype}
d.update(kw)
pygame.event.post(pygame.event.Event(METAEVENT, d)) | def function[event, parameter[self, utype]]:
constant[
Make a meta-event with a utype of @type. **@kw works the same as for
pygame.event.Event().
]
variable[d] assign[=] dictionary[[<ast.Constant object at 0x7da204565a50>], [<ast.Name object at 0x7da204565ab0>]]
call[nam... | keyword[def] identifier[event] ( identifier[self] , identifier[utype] ,** identifier[kw] ):
literal[string]
identifier[d] ={ literal[string] : identifier[utype] }
identifier[d] . identifier[update] ( identifier[kw] )
identifier[pygame] . identifier[event] . identifier[post] ( iden... | def event(self, utype, **kw):
"""
Make a meta-event with a utype of @type. **@kw works the same as for
pygame.event.Event().
"""
d = {'utype': utype}
d.update(kw)
pygame.event.post(pygame.event.Event(METAEVENT, d)) |
def get_function(self, name):
"""
Get a ValueRef pointing to the function named *name*.
NameError is raised if the symbol isn't found.
"""
p = ffi.lib.LLVMPY_GetNamedFunction(self, _encode_string(name))
if not p:
raise NameError(name)
return ValueRef(p... | def function[get_function, parameter[self, name]]:
constant[
Get a ValueRef pointing to the function named *name*.
NameError is raised if the symbol isn't found.
]
variable[p] assign[=] call[name[ffi].lib.LLVMPY_GetNamedFunction, parameter[name[self], call[name[_encode_string], p... | keyword[def] identifier[get_function] ( identifier[self] , identifier[name] ):
literal[string]
identifier[p] = identifier[ffi] . identifier[lib] . identifier[LLVMPY_GetNamedFunction] ( identifier[self] , identifier[_encode_string] ( identifier[name] ))
keyword[if] keyword[not] identifier... | def get_function(self, name):
"""
Get a ValueRef pointing to the function named *name*.
NameError is raised if the symbol isn't found.
"""
p = ffi.lib.LLVMPY_GetNamedFunction(self, _encode_string(name))
if not p:
raise NameError(name) # depends on [control=['if'], data=[]]
... |
def computeNormals(self):
"""Compute cell and vertex normals for the actor's mesh.
.. warning:: Mesh gets modified, can have a different nr. of vertices.
"""
poly = self.polydata(False)
pnormals = poly.GetPointData().GetNormals()
cnormals = poly.GetCellData().GetNormals(... | def function[computeNormals, parameter[self]]:
constant[Compute cell and vertex normals for the actor's mesh.
.. warning:: Mesh gets modified, can have a different nr. of vertices.
]
variable[poly] assign[=] call[name[self].polydata, parameter[constant[False]]]
variable[pnormals... | keyword[def] identifier[computeNormals] ( identifier[self] ):
literal[string]
identifier[poly] = identifier[self] . identifier[polydata] ( keyword[False] )
identifier[pnormals] = identifier[poly] . identifier[GetPointData] (). identifier[GetNormals] ()
identifier[cnormals] = ident... | def computeNormals(self):
"""Compute cell and vertex normals for the actor's mesh.
.. warning:: Mesh gets modified, can have a different nr. of vertices.
"""
poly = self.polydata(False)
pnormals = poly.GetPointData().GetNormals()
cnormals = poly.GetCellData().GetNormals()
if pnormal... |
def _get_optimal_thresholds(nd_dict, quantized_dtype, num_bins=8001, num_quantized_bins=255, logger=None):
"""Given a ndarray dict, find the optimal threshold for quantizing each value of the key."""
if stats is None:
raise ImportError('scipy.stats is required for running entropy mode of calculating'
... | def function[_get_optimal_thresholds, parameter[nd_dict, quantized_dtype, num_bins, num_quantized_bins, logger]]:
constant[Given a ndarray dict, find the optimal threshold for quantizing each value of the key.]
if compare[name[stats] is constant[None]] begin[:]
<ast.Raise object at 0x7da1b1f211e... | keyword[def] identifier[_get_optimal_thresholds] ( identifier[nd_dict] , identifier[quantized_dtype] , identifier[num_bins] = literal[int] , identifier[num_quantized_bins] = literal[int] , identifier[logger] = keyword[None] ):
literal[string]
keyword[if] identifier[stats] keyword[is] keyword[None] :
... | def _get_optimal_thresholds(nd_dict, quantized_dtype, num_bins=8001, num_quantized_bins=255, logger=None):
"""Given a ndarray dict, find the optimal threshold for quantizing each value of the key."""
if stats is None:
raise ImportError('scipy.stats is required for running entropy mode of calculating the... |
def to_vobject(self, filename=None, uid=None):
"""Return the vCard corresponding to the uid
filename -- unused, for API compatibility only
uid -- the UID to get (required)
"""
self._update()
return self._to_vcard(self._book[uid.split('@')[0]]) | def function[to_vobject, parameter[self, filename, uid]]:
constant[Return the vCard corresponding to the uid
filename -- unused, for API compatibility only
uid -- the UID to get (required)
]
call[name[self]._update, parameter[]]
return[call[name[self]._to_vcard, parameter[ca... | keyword[def] identifier[to_vobject] ( identifier[self] , identifier[filename] = keyword[None] , identifier[uid] = keyword[None] ):
literal[string]
identifier[self] . identifier[_update] ()
keyword[return] identifier[self] . identifier[_to_vcard] ( identifier[self] . identifier[_book] [ id... | def to_vobject(self, filename=None, uid=None):
"""Return the vCard corresponding to the uid
filename -- unused, for API compatibility only
uid -- the UID to get (required)
"""
self._update()
return self._to_vcard(self._book[uid.split('@')[0]]) |
def InitFromApiFlow(self, f, cron_job_id=None):
"""Shortcut method for easy legacy cron jobs support."""
if f.flow_id:
self.run_id = f.flow_id
elif f.urn:
self.run_id = f.urn.Basename()
self.started_at = f.started_at
self.cron_job_id = cron_job_id
flow_state_enum = api_plugins_flow.... | def function[InitFromApiFlow, parameter[self, f, cron_job_id]]:
constant[Shortcut method for easy legacy cron jobs support.]
if name[f].flow_id begin[:]
name[self].run_id assign[=] name[f].flow_id
name[self].started_at assign[=] name[f].started_at
name[self].cron_job_id a... | keyword[def] identifier[InitFromApiFlow] ( identifier[self] , identifier[f] , identifier[cron_job_id] = keyword[None] ):
literal[string]
keyword[if] identifier[f] . identifier[flow_id] :
identifier[self] . identifier[run_id] = identifier[f] . identifier[flow_id]
keyword[elif] identifier[f] .... | def InitFromApiFlow(self, f, cron_job_id=None):
"""Shortcut method for easy legacy cron jobs support."""
if f.flow_id:
self.run_id = f.flow_id # depends on [control=['if'], data=[]]
elif f.urn:
self.run_id = f.urn.Basename() # depends on [control=['if'], data=[]]
self.started_at = f.st... |
def disease_comment(self, comment=None, entry_name=None, limit=None, as_df=False):
"""Method to query :class:`.models.DiseaseComment` objects in database
:param comment: Comment(s) to disease
:type comment: str or tuple(str) or None
:param entry_name: name(s) in :class:`.models.Entry`
... | def function[disease_comment, parameter[self, comment, entry_name, limit, as_df]]:
constant[Method to query :class:`.models.DiseaseComment` objects in database
:param comment: Comment(s) to disease
:type comment: str or tuple(str) or None
:param entry_name: name(s) in :class:`.models.E... | keyword[def] identifier[disease_comment] ( identifier[self] , identifier[comment] = keyword[None] , identifier[entry_name] = keyword[None] , identifier[limit] = keyword[None] , identifier[as_df] = keyword[False] ):
literal[string]
identifier[q] = identifier[self] . identifier[session] . identifier[... | def disease_comment(self, comment=None, entry_name=None, limit=None, as_df=False):
"""Method to query :class:`.models.DiseaseComment` objects in database
:param comment: Comment(s) to disease
:type comment: str or tuple(str) or None
:param entry_name: name(s) in :class:`.models.Entry`
... |
def _set_enhanced_voq_max_queue_depth(self, v, load=False):
"""
Setter method for enhanced_voq_max_queue_depth, mapped from YANG variable /telemetry/profile/enhanced_voq_max_queue_depth (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_enhanced_voq_max_queue_depth i... | def function[_set_enhanced_voq_max_queue_depth, parameter[self, v, load]]:
constant[
Setter method for enhanced_voq_max_queue_depth, mapped from YANG variable /telemetry/profile/enhanced_voq_max_queue_depth (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_enhan... | keyword[def] identifier[_set_enhanced_voq_max_queue_depth] ( identifier[self] , identifier[v] , identifier[load] = keyword[False] ):
literal[string]
keyword[if] identifier[hasattr] ( identifier[v] , literal[string] ):
identifier[v] = identifier[v] . identifier[_utype] ( identifier[v] )
keyword... | def _set_enhanced_voq_max_queue_depth(self, v, load=False):
"""
Setter method for enhanced_voq_max_queue_depth, mapped from YANG variable /telemetry/profile/enhanced_voq_max_queue_depth (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_enhanced_voq_max_queue_depth i... |
def sort_schemas(schemas):
"""Sort a list of SQL schemas in order"""
def keyfun(v):
x = SQL_SCHEMA_REGEXP.match(v).groups()
# x3: 'DEV' should come before ''
return (int(x[0]), x[1], int(x[2]) if x[2] else None,
x[3] if x[3] else 'zzz', int(x[4]))
return sorted(schem... | def function[sort_schemas, parameter[schemas]]:
constant[Sort a list of SQL schemas in order]
def function[keyfun, parameter[v]]:
variable[x] assign[=] call[call[name[SQL_SCHEMA_REGEXP].match, parameter[name[v]]].groups, parameter[]]
return[tuple[[<ast.Call object at 0x7da18fe933... | keyword[def] identifier[sort_schemas] ( identifier[schemas] ):
literal[string]
keyword[def] identifier[keyfun] ( identifier[v] ):
identifier[x] = identifier[SQL_SCHEMA_REGEXP] . identifier[match] ( identifier[v] ). identifier[groups] ()
keyword[return] ( identifier[int] ( identi... | def sort_schemas(schemas):
"""Sort a list of SQL schemas in order"""
def keyfun(v):
x = SQL_SCHEMA_REGEXP.match(v).groups()
# x3: 'DEV' should come before ''
return (int(x[0]), x[1], int(x[2]) if x[2] else None, x[3] if x[3] else 'zzz', int(x[4]))
return sorted(schemas, key=keyfun) |
def textbox(message='', title='', text='', codebox=0):
"""Original doc: Display some text in a proportional font with line wrapping at word breaks.
This function is suitable for displaying general written text.
The text parameter should be a string, or a list or tuple of lines to be
display... | def function[textbox, parameter[message, title, text, codebox]]:
constant[Original doc: Display some text in a proportional font with line wrapping at word breaks.
This function is suitable for displaying general written text.
The text parameter should be a string, or a list or tuple of lines t... | keyword[def] identifier[textbox] ( identifier[message] = literal[string] , identifier[title] = literal[string] , identifier[text] = literal[string] , identifier[codebox] = literal[int] ):
literal[string]
keyword[return] identifier[psidialogs] . identifier[text] ( identifier[message] = identifier[message] ... | def textbox(message='', title='', text='', codebox=0):
"""Original doc: Display some text in a proportional font with line wrapping at word breaks.
This function is suitable for displaying general written text.
The text parameter should be a string, or a list or tuple of lines to be
display... |
def contains(self, name):
"""Checks if the specified bucket exists.
Args:
name: the name of the bucket to lookup.
Returns:
True if the bucket exists; False otherwise.
Raises:
Exception if there was an error requesting information about the bucket.
"""
try:
self._api.buck... | def function[contains, parameter[self, name]]:
constant[Checks if the specified bucket exists.
Args:
name: the name of the bucket to lookup.
Returns:
True if the bucket exists; False otherwise.
Raises:
Exception if there was an error requesting information about the bucket.
]
... | keyword[def] identifier[contains] ( identifier[self] , identifier[name] ):
literal[string]
keyword[try] :
identifier[self] . identifier[_api] . identifier[buckets_get] ( identifier[name] )
keyword[except] identifier[google] . identifier[datalab] . identifier[utils] . identifier[RequestExceptio... | def contains(self, name):
"""Checks if the specified bucket exists.
Args:
name: the name of the bucket to lookup.
Returns:
True if the bucket exists; False otherwise.
Raises:
Exception if there was an error requesting information about the bucket.
"""
try:
self._api.bu... |
def _vertically_size_cells(rendered_rows):
"""Grow row heights to cater for vertically spanned cells that do not
fit in the available space."""
for r, rendered_row in enumerate(rendered_rows):
for rendered_cell in rendered_row:
if rendered_cell.rowspan > 1:
... | def function[_vertically_size_cells, parameter[rendered_rows]]:
constant[Grow row heights to cater for vertically spanned cells that do not
fit in the available space.]
for taget[tuple[[<ast.Name object at 0x7da1b26ad270>, <ast.Name object at 0x7da1b26ac3d0>]]] in starred[call[name[enumerate], p... | keyword[def] identifier[_vertically_size_cells] ( identifier[rendered_rows] ):
literal[string]
keyword[for] identifier[r] , identifier[rendered_row] keyword[in] identifier[enumerate] ( identifier[rendered_rows] ):
keyword[for] identifier[rendered_cell] keyword[in] identifier[rend... | def _vertically_size_cells(rendered_rows):
"""Grow row heights to cater for vertically spanned cells that do not
fit in the available space."""
for (r, rendered_row) in enumerate(rendered_rows):
for rendered_cell in rendered_row:
if rendered_cell.rowspan > 1:
row_heig... |
def get_enum_doc(elt, full_name:str)->str:
"Formatted enum documentation."
vals = ', '.join(elt.__members__.keys())
return f'{code_esc(full_name)}',f'<code>Enum</code> = [{vals}]' | def function[get_enum_doc, parameter[elt, full_name]]:
constant[Formatted enum documentation.]
variable[vals] assign[=] call[constant[, ].join, parameter[call[name[elt].__members__.keys, parameter[]]]]
return[tuple[[<ast.JoinedStr object at 0x7da1b1e9a710>, <ast.JoinedStr object at 0x7da1b1e9ac80>]]... | keyword[def] identifier[get_enum_doc] ( identifier[elt] , identifier[full_name] : identifier[str] )-> identifier[str] :
literal[string]
identifier[vals] = literal[string] . identifier[join] ( identifier[elt] . identifier[__members__] . identifier[keys] ())
keyword[return] literal[string] , literal[st... | def get_enum_doc(elt, full_name: str) -> str:
"""Formatted enum documentation."""
vals = ', '.join(elt.__members__.keys())
return (f'{code_esc(full_name)}', f'<code>Enum</code> = [{vals}]') |
def GetEntries(self, parser_mediator, top_level=None, **unused_kwargs):
"""Simple method to exact date values from a Plist.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
top_level (dict[str, object]): plist t... | def function[GetEntries, parameter[self, parser_mediator, top_level]]:
constant[Simple method to exact date values from a Plist.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
top_level (dict[str, object])... | keyword[def] identifier[GetEntries] ( identifier[self] , identifier[parser_mediator] , identifier[top_level] = keyword[None] ,** identifier[unused_kwargs] ):
literal[string]
keyword[for] identifier[root] , identifier[key] , identifier[datetime_value] keyword[in] identifier[interface] . identifier[Recurs... | def GetEntries(self, parser_mediator, top_level=None, **unused_kwargs):
"""Simple method to exact date values from a Plist.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
top_level (dict[str, object]): plist t... |
def collision_rate(Temperature, element, isotope):
r"""This function recieves the temperature of an atomic vapour (in Kelvin),
the element, and the isotope of the atoms, and returns the angular
frequency rate of collisions (in rad/s) in a vapour assuming a
Maxwell-Boltzmann velocity distribution, and ta... | def function[collision_rate, parameter[Temperature, element, isotope]]:
constant[This function recieves the temperature of an atomic vapour (in Kelvin),
the element, and the isotope of the atoms, and returns the angular
frequency rate of collisions (in rad/s) in a vapour assuming a
Maxwell-Boltzmann... | keyword[def] identifier[collision_rate] ( identifier[Temperature] , identifier[element] , identifier[isotope] ):
literal[string]
identifier[atom] = identifier[Atom] ( identifier[element] , identifier[isotope] )
identifier[sigma] = identifier[pi] *( literal[int] * identifier[atom] . identifier[radius]... | def collision_rate(Temperature, element, isotope):
"""This function recieves the temperature of an atomic vapour (in Kelvin),
the element, and the isotope of the atoms, and returns the angular
frequency rate of collisions (in rad/s) in a vapour assuming a
Maxwell-Boltzmann velocity distribution, and tak... |
def remove_factualitylayer_layer(self):
"""
Removes the factualitylayer layer (the old version) (if exists) of the object (in memory)
"""
if self.factuality_layer is not None:
this_node = self.factuality_layer.get_node()
self.root.remove(this_node)
sel... | def function[remove_factualitylayer_layer, parameter[self]]:
constant[
Removes the factualitylayer layer (the old version) (if exists) of the object (in memory)
]
if compare[name[self].factuality_layer is_not constant[None]] begin[:]
variable[this_node] assign[=] call[nam... | keyword[def] identifier[remove_factualitylayer_layer] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[factuality_layer] keyword[is] keyword[not] keyword[None] :
identifier[this_node] = identifier[self] . identifier[factuality_layer] . identifier[get_... | def remove_factualitylayer_layer(self):
"""
Removes the factualitylayer layer (the old version) (if exists) of the object (in memory)
"""
if self.factuality_layer is not None:
this_node = self.factuality_layer.get_node()
self.root.remove(this_node)
self.factuality_layer =... |
def is_present_no_wait(self, locator):
"""
Determines whether an element is present on the page with no wait
@type locator: webdriverwrapper.support.locator.Locator
@param locator: the locator or css string used to query the element
"""
# first attempt to locate the el... | def function[is_present_no_wait, parameter[self, locator]]:
constant[
Determines whether an element is present on the page with no wait
@type locator: webdriverwrapper.support.locator.Locator
@param locator: the locator or css string used to query the element
]
def func... | keyword[def] identifier[is_present_no_wait] ( identifier[self] , identifier[locator] ):
literal[string]
keyword[def] identifier[execute] ():
literal[string]
keyword[return] keyword[True] keyword[if] identifier[len] ( identifier[self] . identifier[locator_ha... | def is_present_no_wait(self, locator):
"""
Determines whether an element is present on the page with no wait
@type locator: webdriverwrapper.support.locator.Locator
@param locator: the locator or css string used to query the element
"""
# first attempt to locate the element
... |
def process_exception(self, request, exception):
"""Report exceptions from requests via Exreporter.
"""
gc = GithubCredentials(
user=settings.EXREPORTER_GITHUB_USER,
repo=settings.EXREPORTER_GITHUB_REPO,
auth_token=settings.EXREPORTER_GITHUB_AUTH_TOKEN)
... | def function[process_exception, parameter[self, request, exception]]:
constant[Report exceptions from requests via Exreporter.
]
variable[gc] assign[=] call[name[GithubCredentials], parameter[]]
variable[gs] assign[=] call[name[GithubStore], parameter[]]
variable[reporter] assign... | keyword[def] identifier[process_exception] ( identifier[self] , identifier[request] , identifier[exception] ):
literal[string]
identifier[gc] = identifier[GithubCredentials] (
identifier[user] = identifier[settings] . identifier[EXREPORTER_GITHUB_USER] ,
identifier[repo] = identif... | def process_exception(self, request, exception):
"""Report exceptions from requests via Exreporter.
"""
gc = GithubCredentials(user=settings.EXREPORTER_GITHUB_USER, repo=settings.EXREPORTER_GITHUB_REPO, auth_token=settings.EXREPORTER_GITHUB_AUTH_TOKEN)
gs = GithubStore(credentials=gc)
reporter =... |
def create_direct_channel(current):
"""
Create a One-To-One channel between current and selected user.
.. code-block:: python
# request:
{
'view':'_zops_create_direct_channel',
'user_key': key,
}
# response:
{
'des... | def function[create_direct_channel, parameter[current]]:
constant[
Create a One-To-One channel between current and selected user.
.. code-block:: python
# request:
{
'view':'_zops_create_direct_channel',
'user_key': key,
}
# response:... | keyword[def] identifier[create_direct_channel] ( identifier[current] ):
literal[string]
identifier[channel] , identifier[sub_name] = identifier[Channel] . identifier[get_or_create_direct_channel] ( identifier[current] . identifier[user_id] ,
identifier[current] . identifier[input] [ literal[string] ])... | def create_direct_channel(current):
"""
Create a One-To-One channel between current and selected user.
.. code-block:: python
# request:
{
'view':'_zops_create_direct_channel',
'user_key': key,
}
# response:
{
'des... |
def stdout_encode(u, default='utf-8'):
""" Encodes a given string with the proper standard out encoding
If sys.stdout.encoding isn't specified, it this defaults to @default
@default: default encoding
-> #str with standard out encoding
"""
# from http://stackoverflow.com/questions/3... | def function[stdout_encode, parameter[u, default]]:
constant[ Encodes a given string with the proper standard out encoding
If sys.stdout.encoding isn't specified, it this defaults to @default
@default: default encoding
-> #str with standard out encoding
]
variable[encoding]... | keyword[def] identifier[stdout_encode] ( identifier[u] , identifier[default] = literal[string] ):
literal[string]
identifier[encoding] = identifier[sys] . identifier[stdout] . identifier[encoding] keyword[or] identifier[default]
keyword[return] identifier[u] . identifier[encode] ( identi... | def stdout_encode(u, default='utf-8'):
""" Encodes a given string with the proper standard out encoding
If sys.stdout.encoding isn't specified, it this defaults to @default
@default: default encoding
-> #str with standard out encoding
"""
# from http://stackoverflow.com/questions/3... |
def set_property(self, prop, value):
"""Change value of a DAAP property, e.g. volume or media position."""
cmd_url = 'ctrl-int/1/setproperty?{}={}&[AUTH]'.format(
prop, value)
return self.daap.post(cmd_url) | def function[set_property, parameter[self, prop, value]]:
constant[Change value of a DAAP property, e.g. volume or media position.]
variable[cmd_url] assign[=] call[constant[ctrl-int/1/setproperty?{}={}&[AUTH]].format, parameter[name[prop], name[value]]]
return[call[name[self].daap.post, parameter[n... | keyword[def] identifier[set_property] ( identifier[self] , identifier[prop] , identifier[value] ):
literal[string]
identifier[cmd_url] = literal[string] . identifier[format] (
identifier[prop] , identifier[value] )
keyword[return] identifier[self] . identifier[daap] . identifier[... | def set_property(self, prop, value):
"""Change value of a DAAP property, e.g. volume or media position."""
cmd_url = 'ctrl-int/1/setproperty?{}={}&[AUTH]'.format(prop, value)
return self.daap.post(cmd_url) |
def get_random_path(graph) -> List[BaseEntity]:
"""Get a random path from the graph as a list of nodes.
:param pybel.BELGraph graph: A BEL graph
"""
wg = graph.to_undirected()
nodes = wg.nodes()
def pick_random_pair() -> Tuple[BaseEntity, BaseEntity]:
"""Get a pair of random nodes."""... | def function[get_random_path, parameter[graph]]:
constant[Get a random path from the graph as a list of nodes.
:param pybel.BELGraph graph: A BEL graph
]
variable[wg] assign[=] call[name[graph].to_undirected, parameter[]]
variable[nodes] assign[=] call[name[wg].nodes, parameter[]]
... | keyword[def] identifier[get_random_path] ( identifier[graph] )-> identifier[List] [ identifier[BaseEntity] ]:
literal[string]
identifier[wg] = identifier[graph] . identifier[to_undirected] ()
identifier[nodes] = identifier[wg] . identifier[nodes] ()
keyword[def] identifier[pick_random_pair] ()... | def get_random_path(graph) -> List[BaseEntity]:
"""Get a random path from the graph as a list of nodes.
:param pybel.BELGraph graph: A BEL graph
"""
wg = graph.to_undirected()
nodes = wg.nodes()
def pick_random_pair() -> Tuple[BaseEntity, BaseEntity]:
"""Get a pair of random nodes."""
... |
def get_closest_points(self, max_distance=None, origin_index=0, origin_raw=None):
"""
Get closest points to a given origin. Returns a list of 2 element tuples where first element is the destination and the second is the distance.
"""
if not self.dict_response['distance']['value']:
... | def function[get_closest_points, parameter[self, max_distance, origin_index, origin_raw]]:
constant[
Get closest points to a given origin. Returns a list of 2 element tuples where first element is the destination and the second is the distance.
]
if <ast.UnaryOp object at 0x7da1b265f790>... | keyword[def] identifier[get_closest_points] ( identifier[self] , identifier[max_distance] = keyword[None] , identifier[origin_index] = literal[int] , identifier[origin_raw] = keyword[None] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[dict_response] [ literal[string] ]... | def get_closest_points(self, max_distance=None, origin_index=0, origin_raw=None):
"""
Get closest points to a given origin. Returns a list of 2 element tuples where first element is the destination and the second is the distance.
"""
if not self.dict_response['distance']['value']:
self.g... |
def include_revision(revision_num, skip_factor=1.1):
"""Decide whether to include a revision.
If the number of revisions is large, we exclude some revisions to avoid
a quadratic blowup in runtime, since the article is likely also large.
We make the ratio between consecutive included revision numbers
appprox... | def function[include_revision, parameter[revision_num, skip_factor]]:
constant[Decide whether to include a revision.
If the number of revisions is large, we exclude some revisions to avoid
a quadratic blowup in runtime, since the article is likely also large.
We make the ratio between consecutive includ... | keyword[def] identifier[include_revision] ( identifier[revision_num] , identifier[skip_factor] = literal[int] ):
literal[string]
keyword[if] identifier[skip_factor] <= literal[int] :
keyword[return] keyword[True]
keyword[return] ( identifier[int] ( identifier[math] . identifier[log1p] ( identifier[r... | def include_revision(revision_num, skip_factor=1.1):
"""Decide whether to include a revision.
If the number of revisions is large, we exclude some revisions to avoid
a quadratic blowup in runtime, since the article is likely also large.
We make the ratio between consecutive included revision numbers
apppr... |
def get_managed_policies(group, **conn):
"""Get a list of the managed policy names that are attached to the group."""
managed_policies = list_attached_group_managed_policies(group['GroupName'], **conn)
managed_policy_names = []
for policy in managed_policies:
managed_policy_names.append(policy... | def function[get_managed_policies, parameter[group]]:
constant[Get a list of the managed policy names that are attached to the group.]
variable[managed_policies] assign[=] call[name[list_attached_group_managed_policies], parameter[call[name[group]][constant[GroupName]]]]
variable[managed_policy_... | keyword[def] identifier[get_managed_policies] ( identifier[group] ,** identifier[conn] ):
literal[string]
identifier[managed_policies] = identifier[list_attached_group_managed_policies] ( identifier[group] [ literal[string] ],** identifier[conn] )
identifier[managed_policy_names] =[]
keyword[fo... | def get_managed_policies(group, **conn):
"""Get a list of the managed policy names that are attached to the group."""
managed_policies = list_attached_group_managed_policies(group['GroupName'], **conn)
managed_policy_names = []
for policy in managed_policies:
managed_policy_names.append(policy['... |
def __job_complete_dict(complete_status, manager, job_id):
""" Build final dictionary describing completed job for consumption by
Pulsar client.
"""
return_code = manager.return_code(job_id)
if return_code == PULSAR_UNKNOWN_RETURN_CODE:
return_code = None
stdout_contents = manager.stdout... | def function[__job_complete_dict, parameter[complete_status, manager, job_id]]:
constant[ Build final dictionary describing completed job for consumption by
Pulsar client.
]
variable[return_code] assign[=] call[name[manager].return_code, parameter[name[job_id]]]
if compare[name[return_co... | keyword[def] identifier[__job_complete_dict] ( identifier[complete_status] , identifier[manager] , identifier[job_id] ):
literal[string]
identifier[return_code] = identifier[manager] . identifier[return_code] ( identifier[job_id] )
keyword[if] identifier[return_code] == identifier[PULSAR_UNKNOWN_RETU... | def __job_complete_dict(complete_status, manager, job_id):
""" Build final dictionary describing completed job for consumption by
Pulsar client.
"""
return_code = manager.return_code(job_id)
if return_code == PULSAR_UNKNOWN_RETURN_CODE:
return_code = None # depends on [control=['if'], data=... |
def get_ajax(self, request, *args, **kwargs):
""" Called when accessed via AJAX on the request method specified by the Datatable. """
response_data = self.get_json_response_object(self._datatable)
response = HttpResponse(self.serialize_to_json(response_data),
con... | def function[get_ajax, parameter[self, request]]:
constant[ Called when accessed via AJAX on the request method specified by the Datatable. ]
variable[response_data] assign[=] call[name[self].get_json_response_object, parameter[name[self]._datatable]]
variable[response] assign[=] call[name[HttpR... | keyword[def] identifier[get_ajax] ( identifier[self] , identifier[request] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
identifier[response_data] = identifier[self] . identifier[get_json_response_object] ( identifier[self] . identifier[_datatable] )
identifier[response] =... | def get_ajax(self, request, *args, **kwargs):
""" Called when accessed via AJAX on the request method specified by the Datatable. """
response_data = self.get_json_response_object(self._datatable)
response = HttpResponse(self.serialize_to_json(response_data), content_type='application/json')
return resp... |
def cublasZgemm(handle, transa, transb, m, n, k, alpha, A, lda, B, ldb, beta, C, ldc):
"""
Matrix-matrix product for complex general matrix.
"""
status = _libcublas.cublasZgemm_v2(handle,
_CUBLAS_OP[transa],
_CUBLAS_OP[trans... | def function[cublasZgemm, parameter[handle, transa, transb, m, n, k, alpha, A, lda, B, ldb, beta, C, ldc]]:
constant[
Matrix-matrix product for complex general matrix.
]
variable[status] assign[=] call[name[_libcublas].cublasZgemm_v2, parameter[name[handle], call[name[_CUBLAS_OP]][name[transa]]... | keyword[def] identifier[cublasZgemm] ( identifier[handle] , identifier[transa] , identifier[transb] , identifier[m] , identifier[n] , identifier[k] , identifier[alpha] , identifier[A] , identifier[lda] , identifier[B] , identifier[ldb] , identifier[beta] , identifier[C] , identifier[ldc] ):
literal[string]
... | def cublasZgemm(handle, transa, transb, m, n, k, alpha, A, lda, B, ldb, beta, C, ldc):
"""
Matrix-matrix product for complex general matrix.
"""
status = _libcublas.cublasZgemm_v2(handle, _CUBLAS_OP[transa], _CUBLAS_OP[transb], m, n, k, ctypes.byref(cuda.cuDoubleComplex(alpha.real, alpha.imag)), int(A)... |
def nameTuple(s: Influence) -> Tuple[str, str]:
""" Returns a 2-tuple consisting of the top groundings of the subj and obj
of an Influence statement. """
return top_grounding(s.subj), top_grounding(s.obj) | def function[nameTuple, parameter[s]]:
constant[ Returns a 2-tuple consisting of the top groundings of the subj and obj
of an Influence statement. ]
return[tuple[[<ast.Call object at 0x7da20c6aba90>, <ast.Call object at 0x7da20c6ab460>]]] | keyword[def] identifier[nameTuple] ( identifier[s] : identifier[Influence] )-> identifier[Tuple] [ identifier[str] , identifier[str] ]:
literal[string]
keyword[return] identifier[top_grounding] ( identifier[s] . identifier[subj] ), identifier[top_grounding] ( identifier[s] . identifier[obj] ) | def nameTuple(s: Influence) -> Tuple[str, str]:
""" Returns a 2-tuple consisting of the top groundings of the subj and obj
of an Influence statement. """
return (top_grounding(s.subj), top_grounding(s.obj)) |
def awaitTermination(self, timeout=None):
"""Wait for context to stop.
:param float timeout: in seconds
"""
if timeout is not None:
IOLoop.current().call_later(timeout, self.stop)
IOLoop.current().start()
IOLoop.clear_current() | def function[awaitTermination, parameter[self, timeout]]:
constant[Wait for context to stop.
:param float timeout: in seconds
]
if compare[name[timeout] is_not constant[None]] begin[:]
call[call[name[IOLoop].current, parameter[]].call_later, parameter[name[timeout], name... | keyword[def] identifier[awaitTermination] ( identifier[self] , identifier[timeout] = keyword[None] ):
literal[string]
keyword[if] identifier[timeout] keyword[is] keyword[not] keyword[None] :
identifier[IOLoop] . identifier[current] (). identifier[call_later] ( identifier[timeout] ... | def awaitTermination(self, timeout=None):
"""Wait for context to stop.
:param float timeout: in seconds
"""
if timeout is not None:
IOLoop.current().call_later(timeout, self.stop) # depends on [control=['if'], data=['timeout']]
IOLoop.current().start()
IOLoop.clear_current() |
def parse(self):
'''
The first method that should be called after creating an ExhaleRoot object. The
Breathe graph is parsed first, followed by the Doxygen xml documents. By the
end of this method, all of the ``self.<breathe_kind>``, ``self.all_compounds``,
and ``self.all_nodes... | def function[parse, parameter[self]]:
constant[
The first method that should be called after creating an ExhaleRoot object. The
Breathe graph is parsed first, followed by the Doxygen xml documents. By the
end of this method, all of the ``self.<breathe_kind>``, ``self.all_compounds``,
... | keyword[def] identifier[parse] ( identifier[self] ):
literal[string]
identifier[self] . identifier[discoverAllNodes] ()
identifier[self] . identifier[reparentAll] ()
keyword[for] identifier[n] keyword[in] identifier[self] . identifi... | def parse(self):
"""
The first method that should be called after creating an ExhaleRoot object. The
Breathe graph is parsed first, followed by the Doxygen xml documents. By the
end of this method, all of the ``self.<breathe_kind>``, ``self.all_compounds``,
and ``self.all_nodes`` l... |
def extract_aes(self, payload, master_pub=True):
'''
Return the AES key received from the master after the minion has been
successfully authenticated.
:param dict payload: The incoming payload. This is a dictionary which may have the following keys:
'aes': The shared AES key... | def function[extract_aes, parameter[self, payload, master_pub]]:
constant[
Return the AES key received from the master after the minion has been
successfully authenticated.
:param dict payload: The incoming payload. This is a dictionary which may have the following keys:
'ae... | keyword[def] identifier[extract_aes] ( identifier[self] , identifier[payload] , identifier[master_pub] = keyword[True] ):
literal[string]
keyword[if] identifier[master_pub] :
keyword[try] :
identifier[aes] , identifier[token] = identifier[self] . identifier[decrypt_ae... | def extract_aes(self, payload, master_pub=True):
"""
Return the AES key received from the master after the minion has been
successfully authenticated.
:param dict payload: The incoming payload. This is a dictionary which may have the following keys:
'aes': The shared AES key
... |
def arraylike_to_numpy(array_like):
"""Convert a 1d array-like (e.g,. list, tensor, etc.) to an np.ndarray"""
orig_type = type(array_like)
# Convert to np.ndarray
if isinstance(array_like, np.ndarray):
pass
elif isinstance(array_like, list):
array_like = np.array(array_like)
el... | def function[arraylike_to_numpy, parameter[array_like]]:
constant[Convert a 1d array-like (e.g,. list, tensor, etc.) to an np.ndarray]
variable[orig_type] assign[=] call[name[type], parameter[name[array_like]]]
if call[name[isinstance], parameter[name[array_like], name[np].ndarray]] begin[:]
... | keyword[def] identifier[arraylike_to_numpy] ( identifier[array_like] ):
literal[string]
identifier[orig_type] = identifier[type] ( identifier[array_like] )
keyword[if] identifier[isinstance] ( identifier[array_like] , identifier[np] . identifier[ndarray] ):
keyword[pass]
keyword... | def arraylike_to_numpy(array_like):
"""Convert a 1d array-like (e.g,. list, tensor, etc.) to an np.ndarray"""
orig_type = type(array_like)
# Convert to np.ndarray
if isinstance(array_like, np.ndarray):
pass # depends on [control=['if'], data=[]]
elif isinstance(array_like, list):
ar... |
def dcdict2rdfpy(dc_dict):
"""Convert a DC dictionary into an RDF Python object."""
ark_prefix = 'ark: ark:'
uri = URIRef('')
# Create the RDF Python object.
rdf_py = ConjunctiveGraph()
# Set DC namespace definition.
DC = Namespace('http://purl.org/dc/elements/1.1/')
# Get the ark for th... | def function[dcdict2rdfpy, parameter[dc_dict]]:
constant[Convert a DC dictionary into an RDF Python object.]
variable[ark_prefix] assign[=] constant[ark: ark:]
variable[uri] assign[=] call[name[URIRef], parameter[constant[]]]
variable[rdf_py] assign[=] call[name[ConjunctiveGraph], parame... | keyword[def] identifier[dcdict2rdfpy] ( identifier[dc_dict] ):
literal[string]
identifier[ark_prefix] = literal[string]
identifier[uri] = identifier[URIRef] ( literal[string] )
identifier[rdf_py] = identifier[ConjunctiveGraph] ()
identifier[DC] = identifier[Namespace] ( literal[st... | def dcdict2rdfpy(dc_dict):
"""Convert a DC dictionary into an RDF Python object."""
ark_prefix = 'ark: ark:'
uri = URIRef('')
# Create the RDF Python object.
rdf_py = ConjunctiveGraph()
# Set DC namespace definition.
DC = Namespace('http://purl.org/dc/elements/1.1/')
# Get the ark for th... |
def section(self, regex, config='running_config'):
"""Returns a section of the config
Args:
regex (str): A valid regular expression used to select sections
of configuration to return
config (str): The configuration to return. Valid values for config
... | def function[section, parameter[self, regex, config]]:
constant[Returns a section of the config
Args:
regex (str): A valid regular expression used to select sections
of configuration to return
config (str): The configuration to return. Valid values for config
... | keyword[def] identifier[section] ( identifier[self] , identifier[regex] , identifier[config] = literal[string] ):
literal[string]
keyword[if] identifier[config] keyword[in] [ literal[string] , literal[string] ]:
identifier[config] = identifier[getattr] ( identifier[self] , identifier... | def section(self, regex, config='running_config'):
"""Returns a section of the config
Args:
regex (str): A valid regular expression used to select sections
of configuration to return
config (str): The configuration to return. Valid values for config
... |
def ExtractEvents(self, parser_mediator, registry_key, **kwargs):
"""Extracts events from a Windows Registry key.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
registry_key (dfwinreg.WinRegistryKey): Windows ... | def function[ExtractEvents, parameter[self, parser_mediator, registry_key]]:
constant[Extracts events from a Windows Registry key.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
registry_key (dfwinreg.WinR... | keyword[def] identifier[ExtractEvents] ( identifier[self] , identifier[parser_mediator] , identifier[registry_key] ,** identifier[kwargs] ):
literal[string]
keyword[for] identifier[subkey] keyword[in] identifier[registry_key] . identifier[GetSubkeys] ():
identifier[values_dict] ={}
identif... | def ExtractEvents(self, parser_mediator, registry_key, **kwargs):
"""Extracts events from a Windows Registry key.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
registry_key (dfwinreg.WinRegistryKey): Windows ... |
def _F_indegree(H, F):
"""Returns the result of a function F applied to the list of indegrees in
in the hypergraph.
:param H: the hypergraph whose indegrees will be operated on.
:param F: function to execute on the list of indegrees in the hypergraph.
:returns: result of the given function F.
:... | def function[_F_indegree, parameter[H, F]]:
constant[Returns the result of a function F applied to the list of indegrees in
in the hypergraph.
:param H: the hypergraph whose indegrees will be operated on.
:param F: function to execute on the list of indegrees in the hypergraph.
:returns: result... | keyword[def] identifier[_F_indegree] ( identifier[H] , identifier[F] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[H] , identifier[DirectedHypergraph] ):
keyword[raise] identifier[TypeError] ( literal[string] )
keyword[return] identifier[F] ([ identifier... | def _F_indegree(H, F):
"""Returns the result of a function F applied to the list of indegrees in
in the hypergraph.
:param H: the hypergraph whose indegrees will be operated on.
:param F: function to execute on the list of indegrees in the hypergraph.
:returns: result of the given function F.
:... |
def bearing_to_nearest_place(feature, parent):
"""If the impact layer has a distance field, it will return the bearing
to the nearest place in degrees.
e.g. bearing_to_nearest_place() -> 280
"""
_ = feature, parent # NOQA
layer = exposure_summary_layer()
if not layer:
return None
... | def function[bearing_to_nearest_place, parameter[feature, parent]]:
constant[If the impact layer has a distance field, it will return the bearing
to the nearest place in degrees.
e.g. bearing_to_nearest_place() -> 280
]
variable[_] assign[=] tuple[[<ast.Name object at 0x7da1b0c453f0>, <ast.... | keyword[def] identifier[bearing_to_nearest_place] ( identifier[feature] , identifier[parent] ):
literal[string]
identifier[_] = identifier[feature] , identifier[parent]
identifier[layer] = identifier[exposure_summary_layer] ()
keyword[if] keyword[not] identifier[layer] :
keyword[retu... | def bearing_to_nearest_place(feature, parent):
"""If the impact layer has a distance field, it will return the bearing
to the nearest place in degrees.
e.g. bearing_to_nearest_place() -> 280
"""
_ = (feature, parent) # NOQA
layer = exposure_summary_layer()
if not layer:
return None... |
def calculate_wer(reference, hypothesis):
"""
Calculation of WER with Levenshtein distance.
Works only for iterables up to 254 elements (uint8).
O(nm) time and space complexity.
>>> calculate_wer("who is there".split(), "is there".split())
1
>>> calculate_wer("who is... | def function[calculate_wer, parameter[reference, hypothesis]]:
constant[
Calculation of WER with Levenshtein distance.
Works only for iterables up to 254 elements (uint8).
O(nm) time and space complexity.
>>> calculate_wer("who is there".split(), "is there".split())
1
... | keyword[def] identifier[calculate_wer] ( identifier[reference] , identifier[hypothesis] ):
literal[string]
keyword[import] identifier[numpy]
identifier[d] = identifier[numpy] . identifier[zeros] (( identifier[len] ( identifier[reference] )+ literal[int] )*( identifier[len] ( identifier[hypothes... | def calculate_wer(reference, hypothesis):
"""
Calculation of WER with Levenshtein distance.
Works only for iterables up to 254 elements (uint8).
O(nm) time and space complexity.
>>> calculate_wer("who is there".split(), "is there".split())
1
>>> calculate_wer("who is... |
def date_from_duration(base_date, number_as_string, unit, duration, base_time=None):
"""
Find dates from duration
Eg: 20 days from now
Currently does not support strings like "20 days from last monday".
"""
# Check if query is `2 days before yesterday` or `day before yesterday`
if base_time ... | def function[date_from_duration, parameter[base_date, number_as_string, unit, duration, base_time]]:
constant[
Find dates from duration
Eg: 20 days from now
Currently does not support strings like "20 days from last monday".
]
if compare[name[base_time] is_not constant[None]] begin[:]
... | keyword[def] identifier[date_from_duration] ( identifier[base_date] , identifier[number_as_string] , identifier[unit] , identifier[duration] , identifier[base_time] = keyword[None] ):
literal[string]
keyword[if] identifier[base_time] keyword[is] keyword[not] keyword[None] :
identifier[bas... | def date_from_duration(base_date, number_as_string, unit, duration, base_time=None):
"""
Find dates from duration
Eg: 20 days from now
Currently does not support strings like "20 days from last monday".
"""
# Check if query is `2 days before yesterday` or `day before yesterday`
if base_time ... |
def _rectForce(x,pot,t=0.):
"""
NAME:
_rectForce
PURPOSE:
returns the force in the rectangular frame
INPUT:
x - current position
t - current time
pot - (list of) Potential instance(s)
OUTPUT:
force
HISTORY:
2011-02-02 - Written - Bovy (NYU)
""... | def function[_rectForce, parameter[x, pot, t]]:
constant[
NAME:
_rectForce
PURPOSE:
returns the force in the rectangular frame
INPUT:
x - current position
t - current time
pot - (list of) Potential instance(s)
OUTPUT:
force
HISTORY:
2011-02-02... | keyword[def] identifier[_rectForce] ( identifier[x] , identifier[pot] , identifier[t] = literal[int] ):
literal[string]
identifier[R] = identifier[nu] . identifier[sqrt] ( identifier[x] [ literal[int] ]** literal[int] + identifier[x] [ literal[int] ]** literal[int] )
identifier[phi] = identifier[... | def _rectForce(x, pot, t=0.0):
"""
NAME:
_rectForce
PURPOSE:
returns the force in the rectangular frame
INPUT:
x - current position
t - current time
pot - (list of) Potential instance(s)
OUTPUT:
force
HISTORY:
2011-02-02 - Written - Bovy (NYU)
... |
def bisect(seq, func=bool):
"""
Split a sequence into two sequences: the first is elements that
return False for func(element) and the second for True for
func(element).
By default, func is ``bool``, so uses the truth value of the object.
>>> is_odd = lambda n: n%2
>>> even, odd = bisect(range(5), is_odd)
>>>... | def function[bisect, parameter[seq, func]]:
constant[
Split a sequence into two sequences: the first is elements that
return False for func(element) and the second for True for
func(element).
By default, func is ``bool``, so uses the truth value of the object.
>>> is_odd = lambda n: n%2
>>> even, odd = ... | keyword[def] identifier[bisect] ( identifier[seq] , identifier[func] = identifier[bool] ):
literal[string]
identifier[queues] = identifier[GroupbySaved] ( identifier[seq] , identifier[func] )
keyword[return] identifier[queues] . identifier[get_first_n_queues] ( literal[int] ) | def bisect(seq, func=bool):
"""
Split a sequence into two sequences: the first is elements that
return False for func(element) and the second for True for
func(element).
By default, func is ``bool``, so uses the truth value of the object.
>>> is_odd = lambda n: n%2
>>> even, odd = bisect(range(5), is_odd)
... |
def instance_path(cls, project, instance):
"""Return a fully-qualified instance string."""
return google.api_core.path_template.expand(
"projects/{project}/instances/{instance}",
project=project,
instance=instance,
) | def function[instance_path, parameter[cls, project, instance]]:
constant[Return a fully-qualified instance string.]
return[call[name[google].api_core.path_template.expand, parameter[constant[projects/{project}/instances/{instance}]]]] | keyword[def] identifier[instance_path] ( identifier[cls] , identifier[project] , identifier[instance] ):
literal[string]
keyword[return] identifier[google] . identifier[api_core] . identifier[path_template] . identifier[expand] (
literal[string] ,
identifier[project] = identifier... | def instance_path(cls, project, instance):
"""Return a fully-qualified instance string."""
return google.api_core.path_template.expand('projects/{project}/instances/{instance}', project=project, instance=instance) |
def get_all_usb_devices(idVendor, idProduct):
""" Returns a list of all the usb devices matching the provided vendor ID and product ID."""
all_dev = list(usb.core.find(find_all = True, idVendor = idVendor, idProduct = idProduct))
for dev in all_dev:
try:
dev.detach_ke... | def function[get_all_usb_devices, parameter[idVendor, idProduct]]:
constant[ Returns a list of all the usb devices matching the provided vendor ID and product ID.]
variable[all_dev] assign[=] call[name[list], parameter[call[name[usb].core.find, parameter[]]]]
for taget[name[dev]] in starred[name... | keyword[def] identifier[get_all_usb_devices] ( identifier[idVendor] , identifier[idProduct] ):
literal[string]
identifier[all_dev] = identifier[list] ( identifier[usb] . identifier[core] . identifier[find] ( identifier[find_all] = keyword[True] , identifier[idVendor] = identifier[idVendor] , identi... | def get_all_usb_devices(idVendor, idProduct):
""" Returns a list of all the usb devices matching the provided vendor ID and product ID."""
all_dev = list(usb.core.find(find_all=True, idVendor=idVendor, idProduct=idProduct))
for dev in all_dev:
try:
dev.detach_kernel_driver(0) # depends ... |
def summary(model, input_size):
""" Print summary of the model """
def register_hook(module):
def hook(module, input, output):
class_name = str(module.__class__).split('.')[-1].split("'")[0]
module_idx = len(summary)
m_key = '%s-%i' % (class_name, module_idx + 1)
... | def function[summary, parameter[model, input_size]]:
constant[ Print summary of the model ]
def function[register_hook, parameter[module]]:
def function[hook, parameter[module, input, output]]:
variable[class_name] assign[=] call[call[call[call[call[name[str], par... | keyword[def] identifier[summary] ( identifier[model] , identifier[input_size] ):
literal[string]
keyword[def] identifier[register_hook] ( identifier[module] ):
keyword[def] identifier[hook] ( identifier[module] , identifier[input] , identifier[output] ):
identifier[class_name] = ide... | def summary(model, input_size):
""" Print summary of the model """
def register_hook(module):
def hook(module, input, output):
class_name = str(module.__class__).split('.')[-1].split("'")[0]
module_idx = len(summary)
m_key = '%s-%i' % (class_name, module_idx + 1)
... |
def _set_fcoe_config(self, v, load=False):
"""
Setter method for fcoe_config, mapped from YANG variable /rbridge_id/fcoe_config (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_fcoe_config is considered as a private
method. Backends looking to populate thi... | def function[_set_fcoe_config, parameter[self, v, load]]:
constant[
Setter method for fcoe_config, mapped from YANG variable /rbridge_id/fcoe_config (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_fcoe_config is considered as a private
method. Backend... | keyword[def] identifier[_set_fcoe_config] ( identifier[self] , identifier[v] , identifier[load] = keyword[False] ):
literal[string]
keyword[if] identifier[hasattr] ( identifier[v] , literal[string] ):
identifier[v] = identifier[v] . identifier[_utype] ( identifier[v] )
keyword[try] :
id... | def _set_fcoe_config(self, v, load=False):
"""
Setter method for fcoe_config, mapped from YANG variable /rbridge_id/fcoe_config (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_fcoe_config is considered as a private
method. Backends looking to populate thi... |
def archive(context, clear_log, items, path, name):
"""
Archive the history log and all results/log files.
After archive is created optionally clear the history log.
"""
history_log = context.obj['history_log']
no_color = context.obj['no_color']
with open(history_log, 'r') as f:
# ... | def function[archive, parameter[context, clear_log, items, path, name]]:
constant[
Archive the history log and all results/log files.
After archive is created optionally clear the history log.
]
variable[history_log] assign[=] call[name[context].obj][constant[history_log]]
variable[... | keyword[def] identifier[archive] ( identifier[context] , identifier[clear_log] , identifier[items] , identifier[path] , identifier[name] ):
literal[string]
identifier[history_log] = identifier[context] . identifier[obj] [ literal[string] ]
identifier[no_color] = identifier[context] . identifier[obj] [... | def archive(context, clear_log, items, path, name):
"""
Archive the history log and all results/log files.
After archive is created optionally clear the history log.
"""
history_log = context.obj['history_log']
no_color = context.obj['no_color']
with open(history_log, 'r') as f:
# G... |
def slice(string, separator="-", start=None, end=None):
"""Slice out a segment of a string, which is splitted on both the wildcards
and the separator passed in, if any
"""
# split by wildcards/keywords first
# AR-{sampleType}-{parentId}{alpha:3a2d}
segments = filter(None, re.split('(\{.+?\})', s... | def function[slice, parameter[string, separator, start, end]]:
constant[Slice out a segment of a string, which is splitted on both the wildcards
and the separator passed in, if any
]
variable[segments] assign[=] call[name[filter], parameter[constant[None], call[name[re].split, parameter[constant... | keyword[def] identifier[slice] ( identifier[string] , identifier[separator] = literal[string] , identifier[start] = keyword[None] , identifier[end] = keyword[None] ):
literal[string]
identifier[segments] = identifier[filter] ( keyword[None] , identifier[re] . identifier[split] ( literal[string] ,... | def slice(string, separator='-', start=None, end=None):
"""Slice out a segment of a string, which is splitted on both the wildcards
and the separator passed in, if any
"""
# split by wildcards/keywords first
# AR-{sampleType}-{parentId}{alpha:3a2d}
segments = filter(None, re.split('(\\{.+?\\})',... |
def creator(request, slug):
"""
:param request: Django request object.
:param event_id: The `id` associated with the event.
:param is_preview: Should the listing page be generated as a preview? This
will allow preview specific actions to be done in the
templ... | def function[creator, parameter[request, slug]]:
constant[
:param request: Django request object.
:param event_id: The `id` associated with the event.
:param is_preview: Should the listing page be generated as a preview? This
will allow preview specific actions to be done in t... | keyword[def] identifier[creator] ( identifier[request] , identifier[slug] ):
literal[string]
identifier[item] = identifier[get_object_or_404] ( identifier[models] . identifier[CreatorBase] . identifier[objects] . identifier[visible] (), identifier[slug] = identifier[slug] )
keyword[if] keyword[... | def creator(request, slug):
"""
:param request: Django request object.
:param event_id: The `id` associated with the event.
:param is_preview: Should the listing page be generated as a preview? This
will allow preview specific actions to be done in the
templ... |
def _GetNextLogCountPerToken(token):
"""Wrapper for _log_counter_per_token.
Args:
token: The token for which to look up the count.
Returns:
The number of times this function has been called with
*token* as an argument (starting at 0)
"""
global _log_counter_per_token # pylint: disable... | def function[_GetNextLogCountPerToken, parameter[token]]:
constant[Wrapper for _log_counter_per_token.
Args:
token: The token for which to look up the count.
Returns:
The number of times this function has been called with
*token* as an argument (starting at 0)
]
<ast.Global object ... | keyword[def] identifier[_GetNextLogCountPerToken] ( identifier[token] ):
literal[string]
keyword[global] identifier[_log_counter_per_token]
identifier[_log_counter_per_token] [ identifier[token] ]= literal[int] + identifier[_log_counter_per_token] . identifier[get] ( identifier[token] ,- literal[int... | def _GetNextLogCountPerToken(token):
"""Wrapper for _log_counter_per_token.
Args:
token: The token for which to look up the count.
Returns:
The number of times this function has been called with
*token* as an argument (starting at 0)
"""
global _log_counter_per_token # pylint: disable... |
def parse(self, string, parent):
"""Parses all the value code elements from the specified string."""
result = {}
for member in self.RE_MEMBERS.finditer(string):
mems = self._process_member(member, parent, string)
#The regex match could contain multiple members that were d... | def function[parse, parameter[self, string, parent]]:
constant[Parses all the value code elements from the specified string.]
variable[result] assign[=] dictionary[[], []]
for taget[name[member]] in starred[call[name[self].RE_MEMBERS.finditer, parameter[name[string]]]] begin[:]
v... | keyword[def] identifier[parse] ( identifier[self] , identifier[string] , identifier[parent] ):
literal[string]
identifier[result] ={}
keyword[for] identifier[member] keyword[in] identifier[self] . identifier[RE_MEMBERS] . identifier[finditer] ( identifier[string] ):
identif... | def parse(self, string, parent):
"""Parses all the value code elements from the specified string."""
result = {}
for member in self.RE_MEMBERS.finditer(string):
mems = self._process_member(member, parent, string)
#The regex match could contain multiple members that were defined
#on t... |
def render(self, **kwargs):
"""Renders the HTML representation of the element."""
if isinstance(self._parent, GeoJson):
keys = tuple(self._parent.data['features'][0]['properties'].keys())
self.warn_for_geometry_collections()
elif isinstance(self._parent, TopoJson):
... | def function[render, parameter[self]]:
constant[Renders the HTML representation of the element.]
if call[name[isinstance], parameter[name[self]._parent, name[GeoJson]]] begin[:]
variable[keys] assign[=] call[name[tuple], parameter[call[call[call[call[name[self]._parent.data][constant[fea... | keyword[def] identifier[render] ( identifier[self] ,** identifier[kwargs] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[self] . identifier[_parent] , identifier[GeoJson] ):
identifier[keys] = identifier[tuple] ( identifier[self] . identifier[_parent] . identifier[... | def render(self, **kwargs):
"""Renders the HTML representation of the element."""
if isinstance(self._parent, GeoJson):
keys = tuple(self._parent.data['features'][0]['properties'].keys())
self.warn_for_geometry_collections() # depends on [control=['if'], data=[]]
elif isinstance(self._paren... |
def glimpse(self, *tags, compact = False):
"""Creates a printable table with the most frequently occurring values of each of the requested _tags_, or if none are provided the top authors, journals and citations. The table will be as wide and as tall as the terminal (or 80x24 if there is no terminal) so `print(R... | def function[glimpse, parameter[self]]:
constant[Creates a printable table with the most frequently occurring values of each of the requested _tags_, or if none are provided the top authors, journals and citations. The table will be as wide and as tall as the terminal (or 80x24 if there is no terminal) so `prin... | keyword[def] identifier[glimpse] ( identifier[self] ,* identifier[tags] , identifier[compact] = keyword[False] ):
literal[string]
keyword[return] identifier[_glimpse] ( identifier[self] ,* identifier[tags] , identifier[compact] = identifier[compact] ) | def glimpse(self, *tags, compact=False):
"""Creates a printable table with the most frequently occurring values of each of the requested _tags_, or if none are provided the top authors, journals and citations. The table will be as wide and as tall as the terminal (or 80x24 if there is no terminal) so `print(RC.glim... |
def from_file(cls, image_descriptor):
"""
Return a new |Image| subclass instance loaded from the image file
identified by *image_descriptor*, a path or file-like object.
"""
if is_string(image_descriptor):
path = image_descriptor
with open(path, 'rb') as f... | def function[from_file, parameter[cls, image_descriptor]]:
constant[
Return a new |Image| subclass instance loaded from the image file
identified by *image_descriptor*, a path or file-like object.
]
if call[name[is_string], parameter[name[image_descriptor]]] begin[:]
... | keyword[def] identifier[from_file] ( identifier[cls] , identifier[image_descriptor] ):
literal[string]
keyword[if] identifier[is_string] ( identifier[image_descriptor] ):
identifier[path] = identifier[image_descriptor]
keyword[with] identifier[open] ( identifier[path] ,... | def from_file(cls, image_descriptor):
"""
Return a new |Image| subclass instance loaded from the image file
identified by *image_descriptor*, a path or file-like object.
"""
if is_string(image_descriptor):
path = image_descriptor
with open(path, 'rb') as f:
bl... |
def _group_by_area(self, datasets):
"""Group datasets by their area."""
def _area_id(area_def):
return area_def.name + str(area_def.area_extent) + str(area_def.shape)
# get all of the datasets stored by area
area_datasets = {}
for x in datasets:
area_id =... | def function[_group_by_area, parameter[self, datasets]]:
constant[Group datasets by their area.]
def function[_area_id, parameter[area_def]]:
return[binary_operation[binary_operation[name[area_def].name + call[name[str], parameter[name[area_def].area_extent]]] + call[name[str], parameter[name[ar... | keyword[def] identifier[_group_by_area] ( identifier[self] , identifier[datasets] ):
literal[string]
keyword[def] identifier[_area_id] ( identifier[area_def] ):
keyword[return] identifier[area_def] . identifier[name] + identifier[str] ( identifier[area_def] . identifier[area_extent] ... | def _group_by_area(self, datasets):
"""Group datasets by their area."""
def _area_id(area_def):
return area_def.name + str(area_def.area_extent) + str(area_def.shape)
# get all of the datasets stored by area
area_datasets = {}
for x in datasets:
area_id = _area_id(x.attrs['area'])
... |
def restart_local(drain=False):
'''
Restart the traffic_manager and traffic_server processes on the local node.
drain
This option modifies the restart behavior such that
``traffic_server`` is not shut down until the number of
active client connections drops to the number given by th... | def function[restart_local, parameter[drain]]:
constant[
Restart the traffic_manager and traffic_server processes on the local node.
drain
This option modifies the restart behavior such that
``traffic_server`` is not shut down until the number of
active client connections drops ... | keyword[def] identifier[restart_local] ( identifier[drain] = keyword[False] ):
literal[string]
keyword[if] identifier[_TRAFFICCTL] :
identifier[cmd] = identifier[_traffic_ctl] ( literal[string] , literal[string] , literal[string] )
keyword[else] :
identifier[cmd] = identifier[_traff... | def restart_local(drain=False):
"""
Restart the traffic_manager and traffic_server processes on the local node.
drain
This option modifies the restart behavior such that
``traffic_server`` is not shut down until the number of
active client connections drops to the number given by th... |
def walk_files(mgr):
"""
Iterate over all files visible to ``mgr``.
"""
for dir_, subdirs, files in walk_files(mgr):
for file_ in files:
yield file_ | def function[walk_files, parameter[mgr]]:
constant[
Iterate over all files visible to ``mgr``.
]
for taget[tuple[[<ast.Name object at 0x7da20c6e4a90>, <ast.Name object at 0x7da18ede4f10>, <ast.Name object at 0x7da18ede4a60>]]] in starred[call[name[walk_files], parameter[name[mgr]]]] begin[:]
... | keyword[def] identifier[walk_files] ( identifier[mgr] ):
literal[string]
keyword[for] identifier[dir_] , identifier[subdirs] , identifier[files] keyword[in] identifier[walk_files] ( identifier[mgr] ):
keyword[for] identifier[file_] keyword[in] identifier[files] :
keyword[yield] ... | def walk_files(mgr):
"""
Iterate over all files visible to ``mgr``.
"""
for (dir_, subdirs, files) in walk_files(mgr):
for file_ in files:
yield file_ # depends on [control=['for'], data=['file_']] # depends on [control=['for'], data=[]] |
def setup_model(self,model,org_model_ws,new_model_ws):
""" setup the flopy.mbase instance for use with multipler parameters.
Changes model_ws, sets external_path and writes new MODFLOW input
files
Parameters
----------
model : flopy.mbase
flopy model instance... | def function[setup_model, parameter[self, model, org_model_ws, new_model_ws]]:
constant[ setup the flopy.mbase instance for use with multipler parameters.
Changes model_ws, sets external_path and writes new MODFLOW input
files
Parameters
----------
model : flopy.mbase
... | keyword[def] identifier[setup_model] ( identifier[self] , identifier[model] , identifier[org_model_ws] , identifier[new_model_ws] ):
literal[string]
identifier[split_new_mws] =[ identifier[i] keyword[for] identifier[i] keyword[in] identifier[os] . identifier[path] . identifier[split] ( identifi... | def setup_model(self, model, org_model_ws, new_model_ws):
""" setup the flopy.mbase instance for use with multipler parameters.
Changes model_ws, sets external_path and writes new MODFLOW input
files
Parameters
----------
model : flopy.mbase
flopy model instance
... |
def create_dataset(group, name, data, units='', datatype=DataTypes.UNDEFINED,
chunks=True, maxshape=None, compression=None,
**attributes):
"""Create an ARF dataset under group, setting required attributes
Required arguments:
name -- the name of dataset in which to st... | def function[create_dataset, parameter[group, name, data, units, datatype, chunks, maxshape, compression]]:
constant[Create an ARF dataset under group, setting required attributes
Required arguments:
name -- the name of dataset in which to store the data
data -- the data to store
Data can ... | keyword[def] identifier[create_dataset] ( identifier[group] , identifier[name] , identifier[data] , identifier[units] = literal[string] , identifier[datatype] = identifier[DataTypes] . identifier[UNDEFINED] ,
identifier[chunks] = keyword[True] , identifier[maxshape] = keyword[None] , identifier[compression] = keywor... | def create_dataset(group, name, data, units='', datatype=DataTypes.UNDEFINED, chunks=True, maxshape=None, compression=None, **attributes):
"""Create an ARF dataset under group, setting required attributes
Required arguments:
name -- the name of dataset in which to store the data
data -- the data to... |
def categorical_partition_data(data):
"""Convenience method for creating weights from categorical data.
Args:
data (list-like): The data from which to construct the estimate.
Returns:
A new partition object::
{
"partition": (list) The categorical values present... | def function[categorical_partition_data, parameter[data]]:
constant[Convenience method for creating weights from categorical data.
Args:
data (list-like): The data from which to construct the estimate.
Returns:
A new partition object::
{
"partition": (list)... | keyword[def] identifier[categorical_partition_data] ( identifier[data] ):
literal[string]
identifier[series] = identifier[pd] . identifier[Series] ( identifier[data] )
identifier[value_counts] = identifier[series] . identifier[value_counts] ( identifier[dropna] = keyword[True] )
ident... | def categorical_partition_data(data):
"""Convenience method for creating weights from categorical data.
Args:
data (list-like): The data from which to construct the estimate.
Returns:
A new partition object::
{
"partition": (list) The categorical values present... |
def write(self, keyArgs):
""" Write specified key arguments into data structure. """
# bytearray doesn't work with fcntl
args = array.array('B', (0,) * self.size)
self._struct.pack_into(args, 0, *list(self.yieldArgs(keyArgs)))
return args | def function[write, parameter[self, keyArgs]]:
constant[ Write specified key arguments into data structure. ]
variable[args] assign[=] call[name[array].array, parameter[constant[B], binary_operation[tuple[[<ast.Constant object at 0x7da1b28f5540>]] * name[self].size]]]
call[name[self]._struct.pac... | keyword[def] identifier[write] ( identifier[self] , identifier[keyArgs] ):
literal[string]
identifier[args] = identifier[array] . identifier[array] ( literal[string] ,( literal[int] ,)* identifier[self] . identifier[size] )
identifier[self] . identifier[_struct] . identifier[pack_... | def write(self, keyArgs):
""" Write specified key arguments into data structure. """
# bytearray doesn't work with fcntl
args = array.array('B', (0,) * self.size)
self._struct.pack_into(args, 0, *list(self.yieldArgs(keyArgs)))
return args |
def apply_effect(layer, image):
"""Apply effect to the image.
..note: Correct effect order is the following. All the effects are first
applied to the original image then blended together.
* dropshadow
* outerglow
* (original)
* patternoverlay
* gradientoverlay
... | def function[apply_effect, parameter[layer, image]]:
constant[Apply effect to the image.
..note: Correct effect order is the following. All the effects are first
applied to the original image then blended together.
* dropshadow
* outerglow
* (original)
* patternover... | keyword[def] identifier[apply_effect] ( identifier[layer] , identifier[image] ):
literal[string]
keyword[for] identifier[effect] keyword[in] identifier[layer] . identifier[effects] :
keyword[if] identifier[effect] . identifier[__class__] . identifier[__name__] == literal[string] :
... | def apply_effect(layer, image):
"""Apply effect to the image.
..note: Correct effect order is the following. All the effects are first
applied to the original image then blended together.
* dropshadow
* outerglow
* (original)
* patternoverlay
* gradientoverlay
... |
def get_source_var_declaration(self, var):
""" Return the source mapping where the variable is declared
Args:
var (str): variable name
Returns:
(dict): sourceMapping
"""
return next((x.source_mapping for x in self.variables if x.name == var)) | def function[get_source_var_declaration, parameter[self, var]]:
constant[ Return the source mapping where the variable is declared
Args:
var (str): variable name
Returns:
(dict): sourceMapping
]
return[call[name[next], parameter[<ast.GeneratorExp object at 0x... | keyword[def] identifier[get_source_var_declaration] ( identifier[self] , identifier[var] ):
literal[string]
keyword[return] identifier[next] (( identifier[x] . identifier[source_mapping] keyword[for] identifier[x] keyword[in] identifier[self] . identifier[variables] keyword[if] identifier[x]... | def get_source_var_declaration(self, var):
""" Return the source mapping where the variable is declared
Args:
var (str): variable name
Returns:
(dict): sourceMapping
"""
return next((x.source_mapping for x in self.variables if x.name == var)) |
def _iter_step_func_decorators(self):
"""Find functions with step decorator in parsed file."""
for node in self.py_tree.find_all('def'):
for decorator in node.decorators:
if decorator.name.value == 'step':
yield node, decorator
break | def function[_iter_step_func_decorators, parameter[self]]:
constant[Find functions with step decorator in parsed file.]
for taget[name[node]] in starred[call[name[self].py_tree.find_all, parameter[constant[def]]]] begin[:]
for taget[name[decorator]] in starred[name[node].decorators] begi... | keyword[def] identifier[_iter_step_func_decorators] ( identifier[self] ):
literal[string]
keyword[for] identifier[node] keyword[in] identifier[self] . identifier[py_tree] . identifier[find_all] ( literal[string] ):
keyword[for] identifier[decorator] keyword[in] identifier[node] .... | def _iter_step_func_decorators(self):
"""Find functions with step decorator in parsed file."""
for node in self.py_tree.find_all('def'):
for decorator in node.decorators:
if decorator.name.value == 'step':
yield (node, decorator)
break # depends on [control=[... |
def route_level(root, level):
"""
Helper method to recurse the current node and return
the specified routing node level.
"""
def recurse(nodes):
for node in nodes:
if node.level == level:
routing_node.append(node)
else:
recurse(node)
... | def function[route_level, parameter[root, level]]:
constant[
Helper method to recurse the current node and return
the specified routing node level.
]
def function[recurse, parameter[nodes]]:
for taget[name[node]] in starred[name[nodes]] begin[:]
if com... | keyword[def] identifier[route_level] ( identifier[root] , identifier[level] ):
literal[string]
keyword[def] identifier[recurse] ( identifier[nodes] ):
keyword[for] identifier[node] keyword[in] identifier[nodes] :
keyword[if] identifier[node] . identifier[level] == identifier[leve... | def route_level(root, level):
"""
Helper method to recurse the current node and return
the specified routing node level.
"""
def recurse(nodes):
for node in nodes:
if node.level == level:
routing_node.append(node) # depends on [control=['if'], data=[]]
... |
def convert_data_array(arr, filter_func=None, converter_func=None):
'''Filter and convert any given data array of any dtype.
Parameters
----------
arr : numpy.array
Data array of any dtype.
filter_func : function
Function that takes array and returns true or false for each i... | def function[convert_data_array, parameter[arr, filter_func, converter_func]]:
constant[Filter and convert any given data array of any dtype.
Parameters
----------
arr : numpy.array
Data array of any dtype.
filter_func : function
Function that takes array and returns true or fal... | keyword[def] identifier[convert_data_array] ( identifier[arr] , identifier[filter_func] = keyword[None] , identifier[converter_func] = keyword[None] ):
literal[string]
keyword[if] identifier[filter_func] :
identifier[array] = identifier[arr] [ identifier[filter_func] ( identi... | def convert_data_array(arr, filter_func=None, converter_func=None):
"""Filter and convert any given data array of any dtype.
Parameters
----------
arr : numpy.array
Data array of any dtype.
filter_func : function
Function that takes array and returns true or false for each item in a... |
def generate_help(self, filename="", command=""):
"""
:type command str
"""
"{} [{}]\n\n".format(filename, "|".join(self.available_command_list))
help_str = """Available commands:
"""
command_list = self.available_command_list if command == "" else [command]
for command in command_lis... | def function[generate_help, parameter[self, filename, command]]:
constant[
:type command str
]
call[constant[{} [{}]
].format, parameter[name[filename], call[constant[|].join, parameter[name[self].available_command_list]]]]
variable[help_str] assign[=] constant[Available commands:
... | keyword[def] identifier[generate_help] ( identifier[self] , identifier[filename] = literal[string] , identifier[command] = literal[string] ):
literal[string]
literal[string] . identifier[format] ( identifier[filename] , literal[string] . identifier[join] ( identifier[self] . identifier[available_command_li... | def generate_help(self, filename='', command=''):
"""
:type command str
"""
'{} [{}]\n\n'.format(filename, '|'.join(self.available_command_list))
help_str = 'Available commands:\n\n '
command_list = self.available_command_list if command == '' else [command]
for command in command_list:
... |
def destroy(self, request, *args, **kwargs):
"""
Deletion of a project is done through sending a **DELETE** request to the project instance URI.
Please note, that if a project has connected instances, deletion request will fail with 409 response code.
Valid request example (token is use... | def function[destroy, parameter[self, request]]:
constant[
Deletion of a project is done through sending a **DELETE** request to the project instance URI.
Please note, that if a project has connected instances, deletion request will fail with 409 response code.
Valid request example (to... | keyword[def] identifier[destroy] ( identifier[self] , identifier[request] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
keyword[return] identifier[super] ( identifier[ProjectViewSet] , identifier[self] ). identifier[destroy] ( identifier[request] ,* identifier[args] ,** identifier[... | def destroy(self, request, *args, **kwargs):
"""
Deletion of a project is done through sending a **DELETE** request to the project instance URI.
Please note, that if a project has connected instances, deletion request will fail with 409 response code.
Valid request example (token is user sp... |
def slt(computation: BaseComputation) -> None:
"""
Signed Lesser Comparison
"""
left, right = map(
unsigned_to_signed,
computation.stack_pop(num_items=2, type_hint=constants.UINT256),
)
if left < right:
result = 1
else:
result = 0
computation.stack_push(... | def function[slt, parameter[computation]]:
constant[
Signed Lesser Comparison
]
<ast.Tuple object at 0x7da1b17f93f0> assign[=] call[name[map], parameter[name[unsigned_to_signed], call[name[computation].stack_pop, parameter[]]]]
if compare[name[left] less[<] name[right]] begin[:]
... | keyword[def] identifier[slt] ( identifier[computation] : identifier[BaseComputation] )-> keyword[None] :
literal[string]
identifier[left] , identifier[right] = identifier[map] (
identifier[unsigned_to_signed] ,
identifier[computation] . identifier[stack_pop] ( identifier[num_items] = literal[int]... | def slt(computation: BaseComputation) -> None:
"""
Signed Lesser Comparison
"""
(left, right) = map(unsigned_to_signed, computation.stack_pop(num_items=2, type_hint=constants.UINT256))
if left < right:
result = 1 # depends on [control=['if'], data=[]]
else:
result = 0
comput... |
def warning(self, message, print_location=True):
"""Displays warning message. Uses exshared for current location of parsing"""
msg = "Warning"
if print_location and (exshared.location != None):
wline = lineno(exshared.location, exshared.text)
wcol = col(exshared.loca... | def function[warning, parameter[self, message, print_location]]:
constant[Displays warning message. Uses exshared for current location of parsing]
variable[msg] assign[=] constant[Warning]
if <ast.BoolOp object at 0x7da18c4cf100> begin[:]
variable[wline] assign[=] call[name[linen... | keyword[def] identifier[warning] ( identifier[self] , identifier[message] , identifier[print_location] = keyword[True] ):
literal[string]
identifier[msg] = literal[string]
keyword[if] identifier[print_location] keyword[and] ( identifier[exshared] . identifier[location] != keyword[Non... | def warning(self, message, print_location=True):
"""Displays warning message. Uses exshared for current location of parsing"""
msg = 'Warning'
if print_location and exshared.location != None:
wline = lineno(exshared.location, exshared.text)
wcol = col(exshared.location, exshared.text)
... |
def as_graph(self, depth=0):
"""
Create a graph with self as node, cache it, return it.
Args:
depth (int): depth of the graph.
Returns:
Graph: an instance of Graph.
"""
if depth in self._graph_cache:
return self._graph_cache[depth]
... | def function[as_graph, parameter[self, depth]]:
constant[
Create a graph with self as node, cache it, return it.
Args:
depth (int): depth of the graph.
Returns:
Graph: an instance of Graph.
]
if compare[name[depth] in name[self]._graph_cache] beg... | keyword[def] identifier[as_graph] ( identifier[self] , identifier[depth] = literal[int] ):
literal[string]
keyword[if] identifier[depth] keyword[in] identifier[self] . identifier[_graph_cache] :
keyword[return] identifier[self] . identifier[_graph_cache] [ identifier[depth] ]
... | def as_graph(self, depth=0):
"""
Create a graph with self as node, cache it, return it.
Args:
depth (int): depth of the graph.
Returns:
Graph: an instance of Graph.
"""
if depth in self._graph_cache:
return self._graph_cache[depth] # depends on ... |
def posthoc_nemenyi_friedman(a, y_col=None, block_col=None, group_col=None, melted=False, sort=False):
'''Calculate pairwise comparisons using Nemenyi post hoc test for
unreplicated blocked data. This test is usually conducted post hoc if
significant results of the Friedman's test are obtained. The statist... | def function[posthoc_nemenyi_friedman, parameter[a, y_col, block_col, group_col, melted, sort]]:
constant[Calculate pairwise comparisons using Nemenyi post hoc test for
unreplicated blocked data. This test is usually conducted post hoc if
significant results of the Friedman's test are obtained. The stat... | keyword[def] identifier[posthoc_nemenyi_friedman] ( identifier[a] , identifier[y_col] = keyword[None] , identifier[block_col] = keyword[None] , identifier[group_col] = keyword[None] , identifier[melted] = keyword[False] , identifier[sort] = keyword[False] ):
literal[string]
keyword[if] identifier[melted... | def posthoc_nemenyi_friedman(a, y_col=None, block_col=None, group_col=None, melted=False, sort=False):
"""Calculate pairwise comparisons using Nemenyi post hoc test for
unreplicated blocked data. This test is usually conducted post hoc if
significant results of the Friedman's test are obtained. The statisti... |
def instantiate(data, blueprint):
"""
Instantiate the given data using the blueprinter.
Arguments
---------
blueprint (collections.Mapping):
a blueprint (JSON Schema with Seep properties)
"""
Validator = jsonschema.validators.validator_for(blueprint)
blueprinter = ext... | def function[instantiate, parameter[data, blueprint]]:
constant[
Instantiate the given data using the blueprinter.
Arguments
---------
blueprint (collections.Mapping):
a blueprint (JSON Schema with Seep properties)
]
variable[Validator] assign[=] call[name[jsonsche... | keyword[def] identifier[instantiate] ( identifier[data] , identifier[blueprint] ):
literal[string]
identifier[Validator] = identifier[jsonschema] . identifier[validators] . identifier[validator_for] ( identifier[blueprint] )
identifier[blueprinter] = identifier[extend] ( identifier[Validator] )( iden... | def instantiate(data, blueprint):
"""
Instantiate the given data using the blueprinter.
Arguments
---------
blueprint (collections.Mapping):
a blueprint (JSON Schema with Seep properties)
"""
Validator = jsonschema.validators.validator_for(blueprint)
blueprinter = exte... |
def _generate_create_callable(name, display_name, arguments, regex, doc, supported, post_arguments, is_action):
"""
Returns a callable which conjures the URL for the resource and POSTs data
"""
def f(self, *args, **kwargs):
for key, value in args[-1].items():
if type(value) == file:
... | def function[_generate_create_callable, parameter[name, display_name, arguments, regex, doc, supported, post_arguments, is_action]]:
constant[
Returns a callable which conjures the URL for the resource and POSTs data
]
def function[f, parameter[self]]:
for taget[tuple[[<ast.Name ... | keyword[def] identifier[_generate_create_callable] ( identifier[name] , identifier[display_name] , identifier[arguments] , identifier[regex] , identifier[doc] , identifier[supported] , identifier[post_arguments] , identifier[is_action] ):
literal[string]
keyword[def] identifier[f] ( identifier[self] ,* id... | def _generate_create_callable(name, display_name, arguments, regex, doc, supported, post_arguments, is_action):
"""
Returns a callable which conjures the URL for the resource and POSTs data
"""
def f(self, *args, **kwargs):
for (key, value) in args[-1].items():
if type(value) == fil... |
def getoutputfile(self, loadmetadata=True, client=None,requiremetadata=False):
"""Grabs one output file (raises a StopIteration exception if there is none). Shortcut for getoutputfiles()"""
return next(self.getoutputfiles(loadmetadata,client,requiremetadata)) | def function[getoutputfile, parameter[self, loadmetadata, client, requiremetadata]]:
constant[Grabs one output file (raises a StopIteration exception if there is none). Shortcut for getoutputfiles()]
return[call[name[next], parameter[call[name[self].getoutputfiles, parameter[name[loadmetadata], name[client]... | keyword[def] identifier[getoutputfile] ( identifier[self] , identifier[loadmetadata] = keyword[True] , identifier[client] = keyword[None] , identifier[requiremetadata] = keyword[False] ):
literal[string]
keyword[return] identifier[next] ( identifier[self] . identifier[getoutputfiles] ( identifier[... | def getoutputfile(self, loadmetadata=True, client=None, requiremetadata=False):
"""Grabs one output file (raises a StopIteration exception if there is none). Shortcut for getoutputfiles()"""
return next(self.getoutputfiles(loadmetadata, client, requiremetadata)) |
def rows_above_layout(self):
"""
Return the number of rows visible in the terminal above the layout.
"""
if self._in_alternate_screen:
return 0
elif self._min_available_height > 0:
total_rows = self.output.get_size().rows
last_screen_height = s... | def function[rows_above_layout, parameter[self]]:
constant[
Return the number of rows visible in the terminal above the layout.
]
if name[self]._in_alternate_screen begin[:]
return[constant[0]] | keyword[def] identifier[rows_above_layout] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[_in_alternate_screen] :
keyword[return] literal[int]
keyword[elif] identifier[self] . identifier[_min_available_height] > literal[int] :
... | def rows_above_layout(self):
"""
Return the number of rows visible in the terminal above the layout.
"""
if self._in_alternate_screen:
return 0 # depends on [control=['if'], data=[]]
elif self._min_available_height > 0:
total_rows = self.output.get_size().rows
last_s... |
def _value_and_batch_jacobian(f, x):
"""Enables uniform interface to value and batch jacobian calculation.
Works in both eager and graph modes.
Arguments:
f: The scalar function to evaluate.
x: The value at which to compute the value and the batch jacobian.
Returns:
A tuple (f(x), J(x)), where J(... | def function[_value_and_batch_jacobian, parameter[f, x]]:
constant[Enables uniform interface to value and batch jacobian calculation.
Works in both eager and graph modes.
Arguments:
f: The scalar function to evaluate.
x: The value at which to compute the value and the batch jacobian.
Returns:
... | keyword[def] identifier[_value_and_batch_jacobian] ( identifier[f] , identifier[x] ):
literal[string]
keyword[if] identifier[tf] . identifier[executing_eagerly] ():
keyword[with] identifier[tf] . identifier[GradientTape] () keyword[as] identifier[tape] :
identifier[tape] . identifier[watch] ( id... | def _value_and_batch_jacobian(f, x):
"""Enables uniform interface to value and batch jacobian calculation.
Works in both eager and graph modes.
Arguments:
f: The scalar function to evaluate.
x: The value at which to compute the value and the batch jacobian.
Returns:
A tuple (f(x), J(x)), where ... |
def get_revocation_reason(self):
"""Get the revocation reason of this certificate."""
if self.revoked is False:
return
if self.revoked_reason == '' or self.revoked_reason is None:
return x509.ReasonFlags.unspecified
else:
return getattr(x509.ReasonFla... | def function[get_revocation_reason, parameter[self]]:
constant[Get the revocation reason of this certificate.]
if compare[name[self].revoked is constant[False]] begin[:]
return[None]
if <ast.BoolOp object at 0x7da2044c08b0> begin[:]
return[name[x509].ReasonFlags.unspecified] | keyword[def] identifier[get_revocation_reason] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[revoked] keyword[is] keyword[False] :
keyword[return]
keyword[if] identifier[self] . identifier[revoked_reason] == literal[string] keyword[or] ... | def get_revocation_reason(self):
"""Get the revocation reason of this certificate."""
if self.revoked is False:
return # depends on [control=['if'], data=[]]
if self.revoked_reason == '' or self.revoked_reason is None:
return x509.ReasonFlags.unspecified # depends on [control=['if'], data=... |
def read_input(buf, has_header = True):
"""Read the input from the given buffer (or stdin if no buffer)
is supplied. An optional header may be present as well"""
# Use stdin if there is no supplied buffer
if buf is None:
buf = sys.stdin
# Attempt to read a header if necessary
header = ... | def function[read_input, parameter[buf, has_header]]:
constant[Read the input from the given buffer (or stdin if no buffer)
is supplied. An optional header may be present as well]
if compare[name[buf] is constant[None]] begin[:]
variable[buf] assign[=] name[sys].stdin
variabl... | keyword[def] identifier[read_input] ( identifier[buf] , identifier[has_header] = keyword[True] ):
literal[string]
keyword[if] identifier[buf] keyword[is] keyword[None] :
identifier[buf] = identifier[sys] . identifier[stdin]
identifier[header] ={}
keyword[if] identifi... | def read_input(buf, has_header=True):
"""Read the input from the given buffer (or stdin if no buffer)
is supplied. An optional header may be present as well"""
# Use stdin if there is no supplied buffer
if buf is None:
buf = sys.stdin # depends on [control=['if'], data=['buf']]
# Attempt to... |
def to_ascii_equivalent(text):
""" Converts any non-ASCII characters (accents, etc.) to their best-fit ASCII equivalents """
if text is None:
return None
elif isinstance(text, binary_type):
text = text.decode(DEFAULT_ENCODING)
elif not isinstance(text, text_type):
text = text_ty... | def function[to_ascii_equivalent, parameter[text]]:
constant[ Converts any non-ASCII characters (accents, etc.) to their best-fit ASCII equivalents ]
if compare[name[text] is constant[None]] begin[:]
return[constant[None]]
variable[text] assign[=] call[name[EMPTY_STR].join, parameter[<as... | keyword[def] identifier[to_ascii_equivalent] ( identifier[text] ):
literal[string]
keyword[if] identifier[text] keyword[is] keyword[None] :
keyword[return] keyword[None]
keyword[elif] identifier[isinstance] ( identifier[text] , identifier[binary_type] ):
identifier[text] = ide... | def to_ascii_equivalent(text):
""" Converts any non-ASCII characters (accents, etc.) to their best-fit ASCII equivalents """
if text is None:
return None # depends on [control=['if'], data=[]]
elif isinstance(text, binary_type):
text = text.decode(DEFAULT_ENCODING) # depends on [control=['... |
def meanangledAngle(self,dangle,smallest=False):
"""
NAME:
meanangledAngle
PURPOSE:
calculate the mean perpendicular angle at a given angle
INPUT:
dangle - angle offset along the stream
smallest= (False) calculate for smallest eigenvalue ... | def function[meanangledAngle, parameter[self, dangle, smallest]]:
constant[
NAME:
meanangledAngle
PURPOSE:
calculate the mean perpendicular angle at a given angle
INPUT:
dangle - angle offset along the stream
smallest= (False) calculate f... | keyword[def] identifier[meanangledAngle] ( identifier[self] , identifier[dangle] , identifier[smallest] = keyword[False] ):
literal[string]
keyword[if] identifier[smallest] : identifier[eigIndx] = literal[int]
keyword[else] : identifier[eigIndx] = literal[int]
identifier[aplow]... | def meanangledAngle(self, dangle, smallest=False):
"""
NAME:
meanangledAngle
PURPOSE:
calculate the mean perpendicular angle at a given angle
INPUT:
dangle - angle offset along the stream
smallest= (False) calculate for smallest eigenvalue di... |
def seperate_end_page_links(stream_data):
'''
Seperate out page blocks at the end of a StreamField.
Accepts: List of streamfield blocks
Returns: Tuple of 2 lists of blocks - (remaining body, final article)
'''
stream_data_copy = list(stream_data)
end_page_links = []
for block in stream... | def function[seperate_end_page_links, parameter[stream_data]]:
constant[
Seperate out page blocks at the end of a StreamField.
Accepts: List of streamfield blocks
Returns: Tuple of 2 lists of blocks - (remaining body, final article)
]
variable[stream_data_copy] assign[=] call[name[list]... | keyword[def] identifier[seperate_end_page_links] ( identifier[stream_data] ):
literal[string]
identifier[stream_data_copy] = identifier[list] ( identifier[stream_data] )
identifier[end_page_links] =[]
keyword[for] identifier[block] keyword[in] identifier[stream_data_copy] [::- literal[int] ]:... | def seperate_end_page_links(stream_data):
"""
Seperate out page blocks at the end of a StreamField.
Accepts: List of streamfield blocks
Returns: Tuple of 2 lists of blocks - (remaining body, final article)
"""
stream_data_copy = list(stream_data)
end_page_links = []
for block in stream_... |
def _generate_config(self):
"""Generate a configuration that can be sent to the Hottop roaster.
Configuration settings need to be represented inside of a byte array
that is then written to the serial interface. Much of the configuration
is static, but control settings are also included ... | def function[_generate_config, parameter[self]]:
constant[Generate a configuration that can be sent to the Hottop roaster.
Configuration settings need to be represented inside of a byte array
that is then written to the serial interface. Much of the configuration
is static, but control ... | keyword[def] identifier[_generate_config] ( identifier[self] ):
literal[string]
identifier[config] = identifier[bytearray] ([ literal[int] ]* literal[int] )
identifier[config] [ literal[int] ]= literal[int]
identifier[config] [ literal[int] ]= literal[int]
identifier[co... | def _generate_config(self):
"""Generate a configuration that can be sent to the Hottop roaster.
Configuration settings need to be represented inside of a byte array
that is then written to the serial interface. Much of the configuration
is static, but control settings are also included and ... |
def _update_from_pb(self, app_profile_pb):
"""Refresh self from the server-provided protobuf.
Helper for :meth:`from_pb` and :meth:`reload`.
"""
self.routing_policy_type = None
self.allow_transactional_writes = None
self.cluster_id = None
self.description = app_p... | def function[_update_from_pb, parameter[self, app_profile_pb]]:
constant[Refresh self from the server-provided protobuf.
Helper for :meth:`from_pb` and :meth:`reload`.
]
name[self].routing_policy_type assign[=] constant[None]
name[self].allow_transactional_writes assign[=] consta... | keyword[def] identifier[_update_from_pb] ( identifier[self] , identifier[app_profile_pb] ):
literal[string]
identifier[self] . identifier[routing_policy_type] = keyword[None]
identifier[self] . identifier[allow_transactional_writes] = keyword[None]
identifier[self] . identifier[... | def _update_from_pb(self, app_profile_pb):
"""Refresh self from the server-provided protobuf.
Helper for :meth:`from_pb` and :meth:`reload`.
"""
self.routing_policy_type = None
self.allow_transactional_writes = None
self.cluster_id = None
self.description = app_profile_pb.description... |
def add_serverconnection_methods(cls):
"""Add a bunch of methods to an :class:`irc.client.SimpleIRCClient`
to send commands and messages.
Basically it wraps a bunch of methdos from
:class:`irc.client.ServerConnection` to be
:meth:`irc.schedule.IScheduler.execute_after`.
That way, you can easily... | def function[add_serverconnection_methods, parameter[cls]]:
constant[Add a bunch of methods to an :class:`irc.client.SimpleIRCClient`
to send commands and messages.
Basically it wraps a bunch of methdos from
:class:`irc.client.ServerConnection` to be
:meth:`irc.schedule.IScheduler.execute_after... | keyword[def] identifier[add_serverconnection_methods] ( identifier[cls] ):
literal[string]
identifier[methods] =[ literal[string] , literal[string] , literal[string] , literal[string] , literal[string] ,
literal[string] , literal[string] , literal[string] , literal[string] , literal[string] ,
lit... | def add_serverconnection_methods(cls):
"""Add a bunch of methods to an :class:`irc.client.SimpleIRCClient`
to send commands and messages.
Basically it wraps a bunch of methdos from
:class:`irc.client.ServerConnection` to be
:meth:`irc.schedule.IScheduler.execute_after`.
That way, you can easily... |
def upload(self, media_type, media_file):
"""
上传临时素材
详情请参考
http://mp.weixin.qq.com/wiki/5/963fc70b80dc75483a271298a76a8d59.html
:param media_type: 媒体文件类型,分别有图片(image)、语音(voice)、视频(video)和缩略图(thumb)
:param media_file: 要上传的文件,一个 File-object
:return: 返回的 JSON 数据包
... | def function[upload, parameter[self, media_type, media_file]]:
constant[
上传临时素材
详情请参考
http://mp.weixin.qq.com/wiki/5/963fc70b80dc75483a271298a76a8d59.html
:param media_type: 媒体文件类型,分别有图片(image)、语音(voice)、视频(video)和缩略图(thumb)
:param media_file: 要上传的文件,一个 File-object
... | keyword[def] identifier[upload] ( identifier[self] , identifier[media_type] , identifier[media_file] ):
literal[string]
keyword[return] identifier[self] . identifier[_post] (
identifier[url] = literal[string] ,
identifier[params] ={
literal[string] : identifier[media_typ... | def upload(self, media_type, media_file):
"""
上传临时素材
详情请参考
http://mp.weixin.qq.com/wiki/5/963fc70b80dc75483a271298a76a8d59.html
:param media_type: 媒体文件类型,分别有图片(image)、语音(voice)、视频(video)和缩略图(thumb)
:param media_file: 要上传的文件,一个 File-object
:return: 返回的 JSON 数据包
... |
def export_original_data(self):
"""
Get the original data
"""
return {key: self.get_original_field_value(key) for key in self.__original_data__.keys()} | def function[export_original_data, parameter[self]]:
constant[
Get the original data
]
return[<ast.DictComp object at 0x7da1b0b6f700>] | keyword[def] identifier[export_original_data] ( identifier[self] ):
literal[string]
keyword[return] { identifier[key] : identifier[self] . identifier[get_original_field_value] ( identifier[key] ) keyword[for] identifier[key] keyword[in] identifier[self] . identifier[__original_data__] . identif... | def export_original_data(self):
"""
Get the original data
"""
return {key: self.get_original_field_value(key) for key in self.__original_data__.keys()} |
def get(self, name: str, sig: Tuple) -> Optional[object]:
"""
Return the object representing name if it is cached
:param name: name of object
:param sig: unique signature of object
:return: object if exists and signature matches
"""
if name not in self._cache:
... | def function[get, parameter[self, name, sig]]:
constant[
Return the object representing name if it is cached
:param name: name of object
:param sig: unique signature of object
:return: object if exists and signature matches
]
if compare[name[name] <ast.NotIn objec... | keyword[def] identifier[get] ( identifier[self] , identifier[name] : identifier[str] , identifier[sig] : identifier[Tuple] )-> identifier[Optional] [ identifier[object] ]:
literal[string]
keyword[if] identifier[name] keyword[not] keyword[in] identifier[self] . identifier[_cache] :
... | def get(self, name: str, sig: Tuple) -> Optional[object]:
"""
Return the object representing name if it is cached
:param name: name of object
:param sig: unique signature of object
:return: object if exists and signature matches
"""
if name not in self._cache:
ret... |
def GetArchiveTypeIndicators(cls, path_spec, resolver_context=None):
"""Determines if a file contains a supported archive types.
Args:
path_spec (PathSpec): path specification.
resolver_context (Optional[Context]): resolver context, where None
represents the built-in context which is not ... | def function[GetArchiveTypeIndicators, parameter[cls, path_spec, resolver_context]]:
constant[Determines if a file contains a supported archive types.
Args:
path_spec (PathSpec): path specification.
resolver_context (Optional[Context]): resolver context, where None
represents the buil... | keyword[def] identifier[GetArchiveTypeIndicators] ( identifier[cls] , identifier[path_spec] , identifier[resolver_context] = keyword[None] ):
literal[string]
keyword[if] ( identifier[cls] . identifier[_archive_remainder_list] keyword[is] keyword[None] keyword[or]
identifier[cls] . identifier[_arch... | def GetArchiveTypeIndicators(cls, path_spec, resolver_context=None):
"""Determines if a file contains a supported archive types.
Args:
path_spec (PathSpec): path specification.
resolver_context (Optional[Context]): resolver context, where None
represents the built-in context which is not ... |
def certify_bool(value, required=True):
"""
Certifier for boolean values.
:param value:
The value to be certified.
:param bool required:
Whether the value can be `None`. Defaults to True.
:raises CertifierTypeError:
The type is invalid
"""
if certify_required(
... | def function[certify_bool, parameter[value, required]]:
constant[
Certifier for boolean values.
:param value:
The value to be certified.
:param bool required:
Whether the value can be `None`. Defaults to True.
:raises CertifierTypeError:
The type is invalid
]
... | keyword[def] identifier[certify_bool] ( identifier[value] , identifier[required] = keyword[True] ):
literal[string]
keyword[if] identifier[certify_required] (
identifier[value] = identifier[value] ,
identifier[required] = identifier[required] ,
):
keyword[return]
keyword[if] ... | def certify_bool(value, required=True):
"""
Certifier for boolean values.
:param value:
The value to be certified.
:param bool required:
Whether the value can be `None`. Defaults to True.
:raises CertifierTypeError:
The type is invalid
"""
if certify_required(value=... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.