code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def from_vertices(cls, data):
"""
Uses Delauney triangulation to compute triangle simplices for
each point.
"""
try:
from scipy.spatial import Delaunay
except:
raise ImportError("Generating triangles from points requires, "
... | def function[from_vertices, parameter[cls, data]]:
constant[
Uses Delauney triangulation to compute triangle simplices for
each point.
]
<ast.Try object at 0x7da18bcc8ee0>
if <ast.UnaryOp object at 0x7da18bcc9e10> begin[:]
variable[data] assign[=] call[name[Po... | keyword[def] identifier[from_vertices] ( identifier[cls] , identifier[data] ):
literal[string]
keyword[try] :
keyword[from] identifier[scipy] . identifier[spatial] keyword[import] identifier[Delaunay]
keyword[except] :
keyword[raise] identifier[ImportError] (... | def from_vertices(cls, data):
"""
Uses Delauney triangulation to compute triangle simplices for
each point.
"""
try:
from scipy.spatial import Delaunay # depends on [control=['try'], data=[]]
except:
raise ImportError('Generating triangles from points requires, SciPy... |
def reflect(x, y, x0, y0, d=1.0, a=180):
""" Returns the reflection of a point through origin (x0,y0).
"""
return coordinates(x0, y0, d * distance(x0, y0, x, y),
a + angle(x0, y0, x, y)) | def function[reflect, parameter[x, y, x0, y0, d, a]]:
constant[ Returns the reflection of a point through origin (x0,y0).
]
return[call[name[coordinates], parameter[name[x0], name[y0], binary_operation[name[d] * call[name[distance], parameter[name[x0], name[y0], name[x], name[y]]]], binary_operation[nam... | keyword[def] identifier[reflect] ( identifier[x] , identifier[y] , identifier[x0] , identifier[y0] , identifier[d] = literal[int] , identifier[a] = literal[int] ):
literal[string]
keyword[return] identifier[coordinates] ( identifier[x0] , identifier[y0] , identifier[d] * identifier[distance] ( identifie... | def reflect(x, y, x0, y0, d=1.0, a=180):
""" Returns the reflection of a point through origin (x0,y0).
"""
return coordinates(x0, y0, d * distance(x0, y0, x, y), a + angle(x0, y0, x, y)) |
def lraise(self,message):
"""log an exception, close the log file, then raise the exception
Parameters
----------
message : str
the exception message
Raises
------
exception with message
"""
s = str(datetime.now()) + " ERROR: " + ... | def function[lraise, parameter[self, message]]:
constant[log an exception, close the log file, then raise the exception
Parameters
----------
message : str
the exception message
Raises
------
exception with message
]
variable[s] a... | keyword[def] identifier[lraise] ( identifier[self] , identifier[message] ):
literal[string]
identifier[s] = identifier[str] ( identifier[datetime] . identifier[now] ())+ literal[string] + identifier[message] + literal[string]
identifier[print] ( identifier[s] , identifier[end] = literal[s... | def lraise(self, message):
"""log an exception, close the log file, then raise the exception
Parameters
----------
message : str
the exception message
Raises
------
exception with message
"""
s = str(datetime.now()) + ' ERROR: ' + message... |
def stat(self):
"""
Return disk usage information for the partition in :py:class:`Fstat`
format. If disk usage information is not available, then ``None`` is
returned. Disk usage information is only available for regular
filesystems that are mounted.
"""
try:
... | def function[stat, parameter[self]]:
constant[
Return disk usage information for the partition in :py:class:`Fstat`
format. If disk usage information is not available, then ``None`` is
returned. Disk usage information is only available for regular
filesystems that are mounted.
... | keyword[def] identifier[stat] ( identifier[self] ):
literal[string]
keyword[try] :
identifier[mp] = identifier[self] . identifier[mount_points] [- literal[int] ]
keyword[except] identifier[IndexError] :
keyword[return] keyword[None]
... | def stat(self):
"""
Return disk usage information for the partition in :py:class:`Fstat`
format. If disk usage information is not available, then ``None`` is
returned. Disk usage information is only available for regular
filesystems that are mounted.
"""
try:
# Al... |
def register_filter(self, attr_name, filterimage_cls):
"""
Register a new FilteredImage subclass (`filterimage_cls`).
To be used via the attribute (filters.`attr_name`)
"""
if attr_name.startswith('_'):
raise UnallowedFilterName(
'`%s` is an unallowed... | def function[register_filter, parameter[self, attr_name, filterimage_cls]]:
constant[
Register a new FilteredImage subclass (`filterimage_cls`).
To be used via the attribute (filters.`attr_name`)
]
if call[name[attr_name].startswith, parameter[constant[_]]] begin[:]
<ast... | keyword[def] identifier[register_filter] ( identifier[self] , identifier[attr_name] , identifier[filterimage_cls] ):
literal[string]
keyword[if] identifier[attr_name] . identifier[startswith] ( literal[string] ):
keyword[raise] identifier[UnallowedFilterName] (
literal[s... | def register_filter(self, attr_name, filterimage_cls):
"""
Register a new FilteredImage subclass (`filterimage_cls`).
To be used via the attribute (filters.`attr_name`)
"""
if attr_name.startswith('_'):
raise UnallowedFilterName('`%s` is an unallowed Filter name. Filter names ca... |
def container_running(self, container_name):
"""
Finds out if a container with name ``container_name`` is running.
:return: :class:`Container <docker.models.containers.Container>` if it's running, ``None`` otherwise.
:rtype: Optional[docker.models.container.Container]
"""
... | def function[container_running, parameter[self, container_name]]:
constant[
Finds out if a container with name ``container_name`` is running.
:return: :class:`Container <docker.models.containers.Container>` if it's running, ``None`` otherwise.
:rtype: Optional[docker.models.container.Co... | keyword[def] identifier[container_running] ( identifier[self] , identifier[container_name] ):
literal[string]
identifier[filters] ={
literal[string] : identifier[container_name] ,
literal[string] : literal[string] ,
}
keyword[for] identifier[container] keyword[... | def container_running(self, container_name):
"""
Finds out if a container with name ``container_name`` is running.
:return: :class:`Container <docker.models.containers.Container>` if it's running, ``None`` otherwise.
:rtype: Optional[docker.models.container.Container]
"""
filter... |
def data(cls, cube, weighted, prune):
"""Return ndarray representing table index by margin."""
return cls()._data(cube, weighted, prune) | def function[data, parameter[cls, cube, weighted, prune]]:
constant[Return ndarray representing table index by margin.]
return[call[call[name[cls], parameter[]]._data, parameter[name[cube], name[weighted], name[prune]]]] | keyword[def] identifier[data] ( identifier[cls] , identifier[cube] , identifier[weighted] , identifier[prune] ):
literal[string]
keyword[return] identifier[cls] (). identifier[_data] ( identifier[cube] , identifier[weighted] , identifier[prune] ) | def data(cls, cube, weighted, prune):
"""Return ndarray representing table index by margin."""
return cls()._data(cube, weighted, prune) |
def qs_field(
model_class,
field,
filters=None,
formatter=queryset_formatter,
manager_name='objects',
):
"""
Show computed fields based on QuerySet's.
This is a workaround since sometimes some filtering is involved to see if a user
owns and object, is a student, etc.
Example
... | def function[qs_field, parameter[model_class, field, filters, formatter, manager_name]]:
constant[
Show computed fields based on QuerySet's.
This is a workaround since sometimes some filtering is involved to see if a user
owns and object, is a student, etc.
Example
-------
class MyMode... | keyword[def] identifier[qs_field] (
identifier[model_class] ,
identifier[field] ,
identifier[filters] = keyword[None] ,
identifier[formatter] = identifier[queryset_formatter] ,
identifier[manager_name] = literal[string] ,
):
literal[string]
keyword[if] identifier[filters] keyword[is] keyword[None] ... | def qs_field(model_class, field, filters=None, formatter=queryset_formatter, manager_name='objects'):
"""
Show computed fields based on QuerySet's.
This is a workaround since sometimes some filtering is involved to see if a user
owns and object, is a student, etc.
Example
-------
class MyM... |
def _create_minimum_needs_action(self):
"""Create action for minimum needs dialog."""
icon = resources_path('img', 'icons', 'show-minimum-needs.svg')
self.action_minimum_needs = QAction(
QIcon(icon),
self.tr('Minimum Needs Calculator'), self.iface.mainWindow())
se... | def function[_create_minimum_needs_action, parameter[self]]:
constant[Create action for minimum needs dialog.]
variable[icon] assign[=] call[name[resources_path], parameter[constant[img], constant[icons], constant[show-minimum-needs.svg]]]
name[self].action_minimum_needs assign[=] call[name[QAct... | keyword[def] identifier[_create_minimum_needs_action] ( identifier[self] ):
literal[string]
identifier[icon] = identifier[resources_path] ( literal[string] , literal[string] , literal[string] )
identifier[self] . identifier[action_minimum_needs] = identifier[QAction] (
identifier[... | def _create_minimum_needs_action(self):
"""Create action for minimum needs dialog."""
icon = resources_path('img', 'icons', 'show-minimum-needs.svg')
self.action_minimum_needs = QAction(QIcon(icon), self.tr('Minimum Needs Calculator'), self.iface.mainWindow())
self.action_minimum_needs.setStatusTip(self... |
def widgetEdited(self, event=None, val=None, action='entry', skipDups=True):
""" A general method for firing any applicable triggers when
a value has been set. This is meant to be easily callable from any
part of this class (or its subclasses), so that it can be called
as so... | def function[widgetEdited, parameter[self, event, val, action, skipDups]]:
constant[ A general method for firing any applicable triggers when
a value has been set. This is meant to be easily callable from any
part of this class (or its subclasses), so that it can be called
a... | keyword[def] identifier[widgetEdited] ( identifier[self] , identifier[event] = keyword[None] , identifier[val] = keyword[None] , identifier[action] = literal[string] , identifier[skipDups] = keyword[True] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[_editedC... | def widgetEdited(self, event=None, val=None, action='entry', skipDups=True):
""" A general method for firing any applicable triggers when
a value has been set. This is meant to be easily callable from any
part of this class (or its subclasses), so that it can be called
as soon a... |
def page_list(
request, template_name='wakawaka/page_list.html', extra_context=None
):
"""
Displays all Pages
"""
page_list = WikiPage.objects.all()
page_list = page_list.order_by('slug')
template_context = {
'page_list': page_list,
'index_slug': getattr(settings, 'WAKAWAKA_... | def function[page_list, parameter[request, template_name, extra_context]]:
constant[
Displays all Pages
]
variable[page_list] assign[=] call[name[WikiPage].objects.all, parameter[]]
variable[page_list] assign[=] call[name[page_list].order_by, parameter[constant[slug]]]
variable[t... | keyword[def] identifier[page_list] (
identifier[request] , identifier[template_name] = literal[string] , identifier[extra_context] = keyword[None]
):
literal[string]
identifier[page_list] = identifier[WikiPage] . identifier[objects] . identifier[all] ()
identifier[page_list] = identifier[page_list] ... | def page_list(request, template_name='wakawaka/page_list.html', extra_context=None):
"""
Displays all Pages
"""
page_list = WikiPage.objects.all()
page_list = page_list.order_by('slug')
template_context = {'page_list': page_list, 'index_slug': getattr(settings, 'WAKAWAKA_DEFAULT_INDEX', 'WikiInd... |
def Group(expressions, final_function, inbetweens, name=""):
""" Group expressions together with ``inbetweens`` and with the output of a ``final_functions``.
"""
lengths = []
functions = []
regex = ""
i = 0
for expression in expressions:
regex += inbetweens[i]
regex += "(?:" ... | def function[Group, parameter[expressions, final_function, inbetweens, name]]:
constant[ Group expressions together with ``inbetweens`` and with the output of a ``final_functions``.
]
variable[lengths] assign[=] list[[]]
variable[functions] assign[=] list[[]]
variable[regex] assign[=... | keyword[def] identifier[Group] ( identifier[expressions] , identifier[final_function] , identifier[inbetweens] , identifier[name] = literal[string] ):
literal[string]
identifier[lengths] =[]
identifier[functions] =[]
identifier[regex] = literal[string]
identifier[i] = literal[int]
key... | def Group(expressions, final_function, inbetweens, name=''):
""" Group expressions together with ``inbetweens`` and with the output of a ``final_functions``.
"""
lengths = []
functions = []
regex = ''
i = 0
for expression in expressions:
regex += inbetweens[i]
regex += '(?:' ... |
def remove_volatile(type_):
"""removes volatile from the type definition
If type is not volatile type, it will be returned as is
"""
nake_type = remove_alias(type_)
if not is_volatile(nake_type):
return type_
else:
if isinstance(nake_type, cpptypes.array_t):
is_c = i... | def function[remove_volatile, parameter[type_]]:
constant[removes volatile from the type definition
If type is not volatile type, it will be returned as is
]
variable[nake_type] assign[=] call[name[remove_alias], parameter[name[type_]]]
if <ast.UnaryOp object at 0x7da18dc9a7d0> begin[:]... | keyword[def] identifier[remove_volatile] ( identifier[type_] ):
literal[string]
identifier[nake_type] = identifier[remove_alias] ( identifier[type_] )
keyword[if] keyword[not] identifier[is_volatile] ( identifier[nake_type] ):
keyword[return] identifier[type_]
keyword[else] :
... | def remove_volatile(type_):
"""removes volatile from the type definition
If type is not volatile type, it will be returned as is
"""
nake_type = remove_alias(type_)
if not is_volatile(nake_type):
return type_ # depends on [control=['if'], data=[]]
else:
if isinstance(nake_type,... |
def lex_count(self, low, high):
"""
Count the number of members in a sorted set between a given
lexicographical range.
"""
return self.database.zlexcount(self.key, low, high) | def function[lex_count, parameter[self, low, high]]:
constant[
Count the number of members in a sorted set between a given
lexicographical range.
]
return[call[name[self].database.zlexcount, parameter[name[self].key, name[low], name[high]]]] | keyword[def] identifier[lex_count] ( identifier[self] , identifier[low] , identifier[high] ):
literal[string]
keyword[return] identifier[self] . identifier[database] . identifier[zlexcount] ( identifier[self] . identifier[key] , identifier[low] , identifier[high] ) | def lex_count(self, low, high):
"""
Count the number of members in a sorted set between a given
lexicographical range.
"""
return self.database.zlexcount(self.key, low, high) |
def copyidfobject(self, idfobject):
"""Add an IDF object to the IDF.
Parameters
----------
idfobject : EpBunch object
The IDF object to remove. This usually comes from another idf file,
or it can be used to copy within this idf file.
"""
return a... | def function[copyidfobject, parameter[self, idfobject]]:
constant[Add an IDF object to the IDF.
Parameters
----------
idfobject : EpBunch object
The IDF object to remove. This usually comes from another idf file,
or it can be used to copy within this idf file.
... | keyword[def] identifier[copyidfobject] ( identifier[self] , identifier[idfobject] ):
literal[string]
keyword[return] identifier[addthisbunch] ( identifier[self] . identifier[idfobjects] ,
identifier[self] . identifier[model] ,
identifier[self] . identifier[idd_info] ,
id... | def copyidfobject(self, idfobject):
"""Add an IDF object to the IDF.
Parameters
----------
idfobject : EpBunch object
The IDF object to remove. This usually comes from another idf file,
or it can be used to copy within this idf file.
"""
return addthisbu... |
def garud_h(h):
"""Compute the H1, H12, H123 and H2/H1 statistics for detecting signatures
of soft sweeps, as defined in Garud et al. (2015).
Parameters
----------
h : array_like, int, shape (n_variants, n_haplotypes)
Haplotype array.
Returns
-------
h1 : float
H1 stati... | def function[garud_h, parameter[h]]:
constant[Compute the H1, H12, H123 and H2/H1 statistics for detecting signatures
of soft sweeps, as defined in Garud et al. (2015).
Parameters
----------
h : array_like, int, shape (n_variants, n_haplotypes)
Haplotype array.
Returns
-------
... | keyword[def] identifier[garud_h] ( identifier[h] ):
literal[string]
identifier[h] = identifier[HaplotypeArray] ( identifier[h] , identifier[copy] = keyword[False] )
identifier[f] = identifier[h] . identifier[distinct_frequencies] ()
identifier[h1] = identifier[np] . identifier[s... | def garud_h(h):
"""Compute the H1, H12, H123 and H2/H1 statistics for detecting signatures
of soft sweeps, as defined in Garud et al. (2015).
Parameters
----------
h : array_like, int, shape (n_variants, n_haplotypes)
Haplotype array.
Returns
-------
h1 : float
H1 stati... |
def list_metafeatures(cls, group="all"):
"""
Returns a list of metafeatures computable by the Metafeatures class.
"""
# todo make group for intractable metafeatures for wide datasets or
# datasets with high cardinality categorical columns:
# PredPCA1, PredPCA2, PredPCA3, ... | def function[list_metafeatures, parameter[cls, group]]:
constant[
Returns a list of metafeatures computable by the Metafeatures class.
]
if compare[name[group] equal[==] constant[all]] begin[:]
return[call[name[copy].deepcopy, parameter[name[cls].IDS]]] | keyword[def] identifier[list_metafeatures] ( identifier[cls] , identifier[group] = literal[string] ):
literal[string]
keyword[if] identifier[group] == literal[string] :
keyword[return] identifier[copy] . identifier[deepcopy] ( identifier[c... | def list_metafeatures(cls, group='all'):
"""
Returns a list of metafeatures computable by the Metafeatures class.
"""
# todo make group for intractable metafeatures for wide datasets or
# datasets with high cardinality categorical columns:
# PredPCA1, PredPCA2, PredPCA3, PredEigen1, Pred... |
def doc(elt):
"Show `show_doc` info in preview window along with link to full docs."
global use_relative_links
use_relative_links = False
elt = getattr(elt, '__func__', elt)
md = show_doc(elt, markdown=False)
if is_fastai_class(elt):
md += f'\n\n<a href="{get_fn_link(elt)}" target="_blan... | def function[doc, parameter[elt]]:
constant[Show `show_doc` info in preview window along with link to full docs.]
<ast.Global object at 0x7da18ede4f10>
variable[use_relative_links] assign[=] constant[False]
variable[elt] assign[=] call[name[getattr], parameter[name[elt], constant[__func__], ... | keyword[def] identifier[doc] ( identifier[elt] ):
literal[string]
keyword[global] identifier[use_relative_links]
identifier[use_relative_links] = keyword[False]
identifier[elt] = identifier[getattr] ( identifier[elt] , literal[string] , identifier[elt] )
identifier[md] = identifier[show_d... | def doc(elt):
"""Show `show_doc` info in preview window along with link to full docs."""
global use_relative_links
use_relative_links = False
elt = getattr(elt, '__func__', elt)
md = show_doc(elt, markdown=False)
if is_fastai_class(elt):
md += f'\n\n<a href="{get_fn_link(elt)}" target="_... |
def scaled_pressure3_send(self, time_boot_ms, press_abs, press_diff, temperature, force_mavlink1=False):
'''
Barometer readings for 3rd barometer
time_boot_ms : Timestamp (milliseconds since system boot) (uint32_t)
press_abs :... | def function[scaled_pressure3_send, parameter[self, time_boot_ms, press_abs, press_diff, temperature, force_mavlink1]]:
constant[
Barometer readings for 3rd barometer
time_boot_ms : Timestamp (milliseconds since system boot) (uint32_t)
press_abs ... | keyword[def] identifier[scaled_pressure3_send] ( identifier[self] , identifier[time_boot_ms] , identifier[press_abs] , identifier[press_diff] , identifier[temperature] , identifier[force_mavlink1] = keyword[False] ):
literal[string]
keyword[return] identifier[self] . identifier[sen... | def scaled_pressure3_send(self, time_boot_ms, press_abs, press_diff, temperature, force_mavlink1=False):
"""
Barometer readings for 3rd barometer
time_boot_ms : Timestamp (milliseconds since system boot) (uint32_t)
press_abs : Absolute pr... |
def error_response(
error_type="Internal server error",
error_text="",
status=400,
participant=None,
simple=False,
request_data="",
):
"""Return a generic server error response."""
last_exception = sys.exc_info()
if last_exception[0]:
db.logger.error(
"Failure for... | def function[error_response, parameter[error_type, error_text, status, participant, simple, request_data]]:
constant[Return a generic server error response.]
variable[last_exception] assign[=] call[name[sys].exc_info, parameter[]]
if call[name[last_exception]][constant[0]] begin[:]
... | keyword[def] identifier[error_response] (
identifier[error_type] = literal[string] ,
identifier[error_text] = literal[string] ,
identifier[status] = literal[int] ,
identifier[participant] = keyword[None] ,
identifier[simple] = keyword[False] ,
identifier[request_data] = literal[string] ,
):
literal[string]... | def error_response(error_type='Internal server error', error_text='', status=400, participant=None, simple=False, request_data=''):
"""Return a generic server error response."""
last_exception = sys.exc_info()
if last_exception[0]:
db.logger.error('Failure for request: {!r}'.format(dict(request.args... |
def add_speaker(self, **kwargs):
"""
Creates a new BGPSpeaker instance.
Usage:
======= ================
Method URI
======= ================
POST /vtep/speakers
======= ================
Request parameters:
===... | def function[add_speaker, parameter[self]]:
constant[
Creates a new BGPSpeaker instance.
Usage:
======= ================
Method URI
======= ================
POST /vtep/speakers
======= ================
Request parameters:... | keyword[def] identifier[add_speaker] ( identifier[self] ,** identifier[kwargs] ):
literal[string]
keyword[try] :
identifier[body] = identifier[self] . identifier[vtep_app] . identifier[add_speaker] (** identifier[kwargs] )
keyword[except] identifier[DatapathNotFound] keyword... | def add_speaker(self, **kwargs):
"""
Creates a new BGPSpeaker instance.
Usage:
======= ================
Method URI
======= ================
POST /vtep/speakers
======= ================
Request parameters:
=======... |
def mrc_to_marc(mrc):
"""
Convert MRC data format to MARC XML.
Args:
mrc (str): MRC as string.
Returns:
str: XML with MARC.
"""
# ignore blank lines
lines = [
line
for line in mrc.splitlines()
if line.strip()
]
def split_to_parts(lines):
... | def function[mrc_to_marc, parameter[mrc]]:
constant[
Convert MRC data format to MARC XML.
Args:
mrc (str): MRC as string.
Returns:
str: XML with MARC.
]
variable[lines] assign[=] <ast.ListComp object at 0x7da18dc9b760>
def function[split_to_parts, parameter[line... | keyword[def] identifier[mrc_to_marc] ( identifier[mrc] ):
literal[string]
identifier[lines] =[
identifier[line]
keyword[for] identifier[line] keyword[in] identifier[mrc] . identifier[splitlines] ()
keyword[if] identifier[line] . identifier[strip] ()
]
keyword[def] identi... | def mrc_to_marc(mrc):
"""
Convert MRC data format to MARC XML.
Args:
mrc (str): MRC as string.
Returns:
str: XML with MARC.
"""
# ignore blank lines
lines = [line for line in mrc.splitlines() if line.strip()]
def split_to_parts(lines):
for line in lines:
... |
def _get_domain_id(self, domain_text_element): # pylint: disable=no-self-use
"""Return the easyname id of the domain."""
try:
# Hierarchy: TR > TD > SPAN > Domain Text
tr_anchor = domain_text_element.parent.parent.parent
td_anchor = tr_anchor.find('td', {'class': 'td... | def function[_get_domain_id, parameter[self, domain_text_element]]:
constant[Return the easyname id of the domain.]
<ast.Try object at 0x7da1b1d22170> | keyword[def] identifier[_get_domain_id] ( identifier[self] , identifier[domain_text_element] ):
literal[string]
keyword[try] :
identifier[tr_anchor] = identifier[domain_text_element] . identifier[parent] . identifier[parent] . identifier[parent]
identifier[td_anc... | def _get_domain_id(self, domain_text_element): # pylint: disable=no-self-use
'Return the easyname id of the domain.'
try:
# Hierarchy: TR > TD > SPAN > Domain Text
tr_anchor = domain_text_element.parent.parent.parent
td_anchor = tr_anchor.find('td', {'class': 'td_2'})
link = td_... |
def get_prefix():
"""Global prefix to identify ncluster created resources name used to identify ncluster created resources,
(name of EFS, VPC, keypair prefixes), can be changed through $NCLUSTER_PREFIX for debugging purposes. """
name = os.environ.get('NCLUSTER_PREFIX', DEFAULT_PREFIX)
if name != DEFAULT_PREFI... | def function[get_prefix, parameter[]]:
constant[Global prefix to identify ncluster created resources name used to identify ncluster created resources,
(name of EFS, VPC, keypair prefixes), can be changed through $NCLUSTER_PREFIX for debugging purposes. ]
variable[name] assign[=] call[name[os].environ.... | keyword[def] identifier[get_prefix] ():
literal[string]
identifier[name] = identifier[os] . identifier[environ] . identifier[get] ( literal[string] , identifier[DEFAULT_PREFIX] )
keyword[if] identifier[name] != identifier[DEFAULT_PREFIX] :
identifier[validate_prefix] ( identifier[name] )
keyword[r... | def get_prefix():
"""Global prefix to identify ncluster created resources name used to identify ncluster created resources,
(name of EFS, VPC, keypair prefixes), can be changed through $NCLUSTER_PREFIX for debugging purposes. """
name = os.environ.get('NCLUSTER_PREFIX', DEFAULT_PREFIX)
if name != DEFAULT_... |
def do_scan_all(self, line):
"""Call ScanAllObjects. Command syntax is: scan_all"""
self.application.master.ScanAllObjects(opendnp3.GroupVariationID(2, 1), opendnp3.TaskConfig().Default()) | def function[do_scan_all, parameter[self, line]]:
constant[Call ScanAllObjects. Command syntax is: scan_all]
call[name[self].application.master.ScanAllObjects, parameter[call[name[opendnp3].GroupVariationID, parameter[constant[2], constant[1]]], call[call[name[opendnp3].TaskConfig, parameter[]].Default,... | keyword[def] identifier[do_scan_all] ( identifier[self] , identifier[line] ):
literal[string]
identifier[self] . identifier[application] . identifier[master] . identifier[ScanAllObjects] ( identifier[opendnp3] . identifier[GroupVariationID] ( literal[int] , literal[int] ), identifier[opendnp3] . id... | def do_scan_all(self, line):
"""Call ScanAllObjects. Command syntax is: scan_all"""
self.application.master.ScanAllObjects(opendnp3.GroupVariationID(2, 1), opendnp3.TaskConfig().Default()) |
def intersection(self, table):
"""
Select nuclei which also belong to ``table``
Parameters
----------
table: Table, Table object
Example:
----------
Table('AME2003').intersection(Table('AME1995'))
"""
idx = self.df.index & table.df.index
... | def function[intersection, parameter[self, table]]:
constant[
Select nuclei which also belong to ``table``
Parameters
----------
table: Table, Table object
Example:
----------
Table('AME2003').intersection(Table('AME1995'))
]
variable[idx... | keyword[def] identifier[intersection] ( identifier[self] , identifier[table] ):
literal[string]
identifier[idx] = identifier[self] . identifier[df] . identifier[index] & identifier[table] . identifier[df] . identifier[index]
keyword[return] identifier[Table] ( identifier[df] = identifier... | def intersection(self, table):
"""
Select nuclei which also belong to ``table``
Parameters
----------
table: Table, Table object
Example:
----------
Table('AME2003').intersection(Table('AME1995'))
"""
idx = self.df.index & table.df.index
retu... |
def makeOrmValuesSubqueryCondition(ormSession, column, values: List[Union[int, str]]):
""" Make Orm Values Subquery
:param ormSession: The orm session instance
:param column: The column from the Declarative table, eg TableItem.colName
:param values: A list of string or int values
"""
if isPostG... | def function[makeOrmValuesSubqueryCondition, parameter[ormSession, column, values]]:
constant[ Make Orm Values Subquery
:param ormSession: The orm session instance
:param column: The column from the Declarative table, eg TableItem.colName
:param values: A list of string or int values
]
... | keyword[def] identifier[makeOrmValuesSubqueryCondition] ( identifier[ormSession] , identifier[column] , identifier[values] : identifier[List] [ identifier[Union] [ identifier[int] , identifier[str] ]]):
literal[string]
keyword[if] identifier[isPostGreSQLDialect] ( identifier[ormSession] . identifier[bind]... | def makeOrmValuesSubqueryCondition(ormSession, column, values: List[Union[int, str]]):
""" Make Orm Values Subquery
:param ormSession: The orm session instance
:param column: The column from the Declarative table, eg TableItem.colName
:param values: A list of string or int values
"""
if isPostG... |
def authenticate_credentials(self, payload):
"""Get or create an active user with the username contained in the payload."""
username = payload.get('preferred_username') or payload.get('username')
if username is None:
raise exceptions.AuthenticationFailed('JWT must include a preferre... | def function[authenticate_credentials, parameter[self, payload]]:
constant[Get or create an active user with the username contained in the payload.]
variable[username] assign[=] <ast.BoolOp object at 0x7da1b04d5990>
if compare[name[username] is constant[None]] begin[:]
<ast.Raise object ... | keyword[def] identifier[authenticate_credentials] ( identifier[self] , identifier[payload] ):
literal[string]
identifier[username] = identifier[payload] . identifier[get] ( literal[string] ) keyword[or] identifier[payload] . identifier[get] ( literal[string] )
keyword[if] identifier[use... | def authenticate_credentials(self, payload):
"""Get or create an active user with the username contained in the payload."""
username = payload.get('preferred_username') or payload.get('username')
if username is None:
raise exceptions.AuthenticationFailed('JWT must include a preferred_username or use... |
def exists(self, relpath, rsc=None, useFilepath=None):
"""
Checks to see if the inputed path represents an existing file or directory.
:param relpath | <str>
rsc | <str>
useFilepath | <bool> or None
"""
path = self... | def function[exists, parameter[self, relpath, rsc, useFilepath]]:
constant[
Checks to see if the inputed path represents an existing file or directory.
:param relpath | <str>
rsc | <str>
useFilepath | <bool> or None
]
vari... | keyword[def] identifier[exists] ( identifier[self] , identifier[relpath] , identifier[rsc] = keyword[None] , identifier[useFilepath] = keyword[None] ):
literal[string]
identifier[path] = identifier[self] . identifier[find] ( identifier[relpath] , identifier[rsc] , identifier[useFilepath] )
... | def exists(self, relpath, rsc=None, useFilepath=None):
"""
Checks to see if the inputed path represents an existing file or directory.
:param relpath | <str>
rsc | <str>
useFilepath | <bool> or None
"""
path = self.find(relpath, r... |
def restore_env(env_dict):
'''Set environment variables in the current python process from a dict
containing envvars and values.'''
if hasattr(sys, 'real_prefix'):
sys.prefix = sys.real_prefix
del(sys.real_prefix)
replace_osenviron(expand_envvars(dict_to_env(env_dict))) | def function[restore_env, parameter[env_dict]]:
constant[Set environment variables in the current python process from a dict
containing envvars and values.]
if call[name[hasattr], parameter[name[sys], constant[real_prefix]]] begin[:]
name[sys].prefix assign[=] name[sys].real_prefix
... | keyword[def] identifier[restore_env] ( identifier[env_dict] ):
literal[string]
keyword[if] identifier[hasattr] ( identifier[sys] , literal[string] ):
identifier[sys] . identifier[prefix] = identifier[sys] . identifier[real_prefix]
keyword[del] ( identifier[sys] . identifier[real_prefix... | def restore_env(env_dict):
"""Set environment variables in the current python process from a dict
containing envvars and values."""
if hasattr(sys, 'real_prefix'):
sys.prefix = sys.real_prefix
del sys.real_prefix # depends on [control=['if'], data=[]]
replace_osenviron(expand_envvars(di... |
def _get_text(self):
"""
Get the current metadatas
"""
device = self._get_device()
if device is None:
return (UNKNOWN_DEVICE, self.py3.COLOR_BAD)
if not device["isReachable"] or not device["isTrusted"]:
return (
self.py3.safe_forma... | def function[_get_text, parameter[self]]:
constant[
Get the current metadatas
]
variable[device] assign[=] call[name[self]._get_device, parameter[]]
if compare[name[device] is constant[None]] begin[:]
return[tuple[[<ast.Name object at 0x7da2041d9b40>, <ast.Attribute objec... | keyword[def] identifier[_get_text] ( identifier[self] ):
literal[string]
identifier[device] = identifier[self] . identifier[_get_device] ()
keyword[if] identifier[device] keyword[is] keyword[None] :
keyword[return] ( identifier[UNKNOWN_DEVICE] , identifier[self] . identifie... | def _get_text(self):
"""
Get the current metadatas
"""
device = self._get_device()
if device is None:
return (UNKNOWN_DEVICE, self.py3.COLOR_BAD) # depends on [control=['if'], data=[]]
if not device['isReachable'] or not device['isTrusted']:
return (self.py3.safe_format(... |
def get_mutations_size(self):
""" Gets the total mutations size for current row
For example:
.. literalinclude:: snippets_table.py
:start-after: [START bigtable_row_get_mutations_size]
:end-before: [END bigtable_row_get_mutations_size]
"""
mutation_siz... | def function[get_mutations_size, parameter[self]]:
constant[ Gets the total mutations size for current row
For example:
.. literalinclude:: snippets_table.py
:start-after: [START bigtable_row_get_mutations_size]
:end-before: [END bigtable_row_get_mutations_size]
... | keyword[def] identifier[get_mutations_size] ( identifier[self] ):
literal[string]
identifier[mutation_size] = literal[int]
keyword[for] identifier[mutation] keyword[in] identifier[self] . identifier[_get_mutations] ():
identifier[mutation_size] += identifier[mutation] . i... | def get_mutations_size(self):
""" Gets the total mutations size for current row
For example:
.. literalinclude:: snippets_table.py
:start-after: [START bigtable_row_get_mutations_size]
:end-before: [END bigtable_row_get_mutations_size]
"""
mutation_size = 0
... |
def run_display_profile(self, program_main):
"""Print profile name with programMain.
Args:
program_main (str): The executable name.
"""
install_json = self.profile.get('install_json')
output = 'Profile: '
output += '{}{}{}{} '.format(
c.Style.BRI... | def function[run_display_profile, parameter[self, program_main]]:
constant[Print profile name with programMain.
Args:
program_main (str): The executable name.
]
variable[install_json] assign[=] call[name[self].profile.get, parameter[constant[install_json]]]
variable[... | keyword[def] identifier[run_display_profile] ( identifier[self] , identifier[program_main] ):
literal[string]
identifier[install_json] = identifier[self] . identifier[profile] . identifier[get] ( literal[string] )
identifier[output] = literal[string]
identifier[output] += litera... | def run_display_profile(self, program_main):
"""Print profile name with programMain.
Args:
program_main (str): The executable name.
"""
install_json = self.profile.get('install_json')
output = 'Profile: '
output += '{}{}{}{} '.format(c.Style.BRIGHT, c.Fore.CYAN, self.profile... |
def call_for_each_tower(
towers, func, devices=None, use_vs=None):
"""
Run `func` on all GPUs (towers) and return the results.
Args:
towers (list[int]): a list of GPU id.
func: a lambda to be called inside each tower
devices: a list of devices to ... | def function[call_for_each_tower, parameter[towers, func, devices, use_vs]]:
constant[
Run `func` on all GPUs (towers) and return the results.
Args:
towers (list[int]): a list of GPU id.
func: a lambda to be called inside each tower
devices: a list of devices... | keyword[def] identifier[call_for_each_tower] (
identifier[towers] , identifier[func] , identifier[devices] = keyword[None] , identifier[use_vs] = keyword[None] ):
literal[string]
identifier[ret] =[]
keyword[if] identifier[devices] keyword[is] keyword[not] keyword[None] :
... | def call_for_each_tower(towers, func, devices=None, use_vs=None):
"""
Run `func` on all GPUs (towers) and return the results.
Args:
towers (list[int]): a list of GPU id.
func: a lambda to be called inside each tower
devices: a list of devices to be used. By defau... |
def _calc_block_mean_variance(image, mask, blocksize):
"""Adaptively determines image background.
Args:
image: image converted 1-channel image.
mask: 1-channel mask, same size as image.
blocksize: adaptive algorithm parameter.
Returns:
image of same size as input with foreg... | def function[_calc_block_mean_variance, parameter[image, mask, blocksize]]:
constant[Adaptively determines image background.
Args:
image: image converted 1-channel image.
mask: 1-channel mask, same size as image.
blocksize: adaptive algorithm parameter.
Returns:
image o... | keyword[def] identifier[_calc_block_mean_variance] ( identifier[image] , identifier[mask] , identifier[blocksize] ):
literal[string]
identifier[I] = identifier[image] . identifier[copy] ()
identifier[I_f] = identifier[I] . identifier[astype] ( identifier[np] . identifier[float32] )/ literal[int]
... | def _calc_block_mean_variance(image, mask, blocksize):
"""Adaptively determines image background.
Args:
image: image converted 1-channel image.
mask: 1-channel mask, same size as image.
blocksize: adaptive algorithm parameter.
Returns:
image of same size as input with foreg... |
def cached_property():
"""
Handy utility to build caching properties in your classes.
Decorated code will be run only once and then result will be stored in private class property
with the given name. When called for the second time, property will return cached value.
:param storage_var_name: Name... | def function[cached_property, parameter[]]:
constant[
Handy utility to build caching properties in your classes.
Decorated code will be run only once and then result will be stored in private class property
with the given name. When called for the second time, property will return cached value.
... | keyword[def] identifier[cached_property] ():
literal[string]
keyword[def] identifier[_stored_value] ( identifier[f] ):
identifier[storage_var_name] = literal[string] . identifier[format] ( identifier[f] . identifier[__name__] )
keyword[def] identifier[_wrapper] ( identifier[self] ,* id... | def cached_property():
"""
Handy utility to build caching properties in your classes.
Decorated code will be run only once and then result will be stored in private class property
with the given name. When called for the second time, property will return cached value.
:param storage_var_name: Name... |
def start_task(self, task_tag, skip_unresolved=False):
""" Check dependency for the given task_tag and start task. For dependency checking see
:meth:`.WTaskDependencyRegistryStorage.dependency_check`. If task is already started then it must be
stopped before it will be started again.
:param task_tag: task to s... | def function[start_task, parameter[self, task_tag, skip_unresolved]]:
constant[ Check dependency for the given task_tag and start task. For dependency checking see
:meth:`.WTaskDependencyRegistryStorage.dependency_check`. If task is already started then it must be
stopped before it will be started again.
... | keyword[def] identifier[start_task] ( identifier[self] , identifier[task_tag] , identifier[skip_unresolved] = keyword[False] ):
literal[string]
keyword[if] identifier[self] . identifier[started_tasks] ( identifier[task_registry_id] = identifier[task_tag] ) keyword[is] keyword[not] keyword[None] :
keywor... | def start_task(self, task_tag, skip_unresolved=False):
""" Check dependency for the given task_tag and start task. For dependency checking see
:meth:`.WTaskDependencyRegistryStorage.dependency_check`. If task is already started then it must be
stopped before it will be started again.
:param task_tag: task to... |
def get_all(self, page=None, per_page=None, include_totals=False):
"""Retrieves all resource servers
Args:
page (int, optional): The result's page number (zero based).
per_page (int, optional): The amount of entries per page.
include_totals (bool, optional): True i... | def function[get_all, parameter[self, page, per_page, include_totals]]:
constant[Retrieves all resource servers
Args:
page (int, optional): The result's page number (zero based).
per_page (int, optional): The amount of entries per page.
include_totals (bool, option... | keyword[def] identifier[get_all] ( identifier[self] , identifier[page] = keyword[None] , identifier[per_page] = keyword[None] , identifier[include_totals] = keyword[False] ):
literal[string]
identifier[params] ={
literal[string] : identifier[page] ,
literal[string] : identifier[p... | def get_all(self, page=None, per_page=None, include_totals=False):
"""Retrieves all resource servers
Args:
page (int, optional): The result's page number (zero based).
per_page (int, optional): The amount of entries per page.
include_totals (bool, optional): True if th... |
def sampleVRVT(self,R,n=1,nsigma=None,target=True):
"""
NAME:
sampleVRVT
PURPOSE:
sample a radial and azimuthal velocity at R
INPUT:
R - Galactocentric distance (can be Quantity)
n= number of distances to sample
nsigma= number... | def function[sampleVRVT, parameter[self, R, n, nsigma, target]]:
constant[
NAME:
sampleVRVT
PURPOSE:
sample a radial and azimuthal velocity at R
INPUT:
R - Galactocentric distance (can be Quantity)
n= number of distances to sample
... | keyword[def] identifier[sampleVRVT] ( identifier[self] , identifier[R] , identifier[n] = literal[int] , identifier[nsigma] = keyword[None] , identifier[target] = keyword[True] ):
literal[string]
identifier[maxVR] = literal[int]
identifier[maxVT] = identifier[optimize] . identifie... | def sampleVRVT(self, R, n=1, nsigma=None, target=True):
"""
NAME:
sampleVRVT
PURPOSE:
sample a radial and azimuthal velocity at R
INPUT:
R - Galactocentric distance (can be Quantity)
n= number of distances to sample
nsigma= number... |
def issub(path):
"""
Returns #True if *path* is a relative path that does not point outside
of its parent directory or is equal to its parent directory (thus, this
function will also return False for a path like `./`).
"""
if isabs(path):
return False
if path.startswith(curdir + sep) or path.startswi... | def function[issub, parameter[path]]:
constant[
Returns #True if *path* is a relative path that does not point outside
of its parent directory or is equal to its parent directory (thus, this
function will also return False for a path like `./`).
]
if call[name[isabs], parameter[name[path]]] begi... | keyword[def] identifier[issub] ( identifier[path] ):
literal[string]
keyword[if] identifier[isabs] ( identifier[path] ):
keyword[return] keyword[False]
keyword[if] identifier[path] . identifier[startswith] ( identifier[curdir] + identifier[sep] ) keyword[or] identifier[path] . identifier[startswi... | def issub(path):
"""
Returns #True if *path* is a relative path that does not point outside
of its parent directory or is equal to its parent directory (thus, this
function will also return False for a path like `./`).
"""
if isabs(path):
return False # depends on [control=['if'], data=[]]
... |
def discretize(self, intervals, slope_thresh=1500, cents_thresh=50):
"""
This function takes the pitch data and returns it quantized to given
set of intervals. All transactions must happen in cent scale.
slope_thresh is the bound beyond which the pitch contour is said to transit
... | def function[discretize, parameter[self, intervals, slope_thresh, cents_thresh]]:
constant[
This function takes the pitch data and returns it quantized to given
set of intervals. All transactions must happen in cent scale.
slope_thresh is the bound beyond which the pitch contour is said... | keyword[def] identifier[discretize] ( identifier[self] , identifier[intervals] , identifier[slope_thresh] = literal[int] , identifier[cents_thresh] = literal[int] ):
literal[string]
identifier[self] . identifier[pitch] = identifier[median_filter] ( identifier[self] . identifier[... | def discretize(self, intervals, slope_thresh=1500, cents_thresh=50):
"""
This function takes the pitch data and returns it quantized to given
set of intervals. All transactions must happen in cent scale.
slope_thresh is the bound beyond which the pitch contour is said to transit
fro... |
def _read_wrapper(data):
"""Ensure unicode always returned on read."""
# Paramiko (strangely) in PY3 returns an int here.
if isinstance(data, int):
data = chr(data)
# Ensure unicode
return py23_compat.text_type(data) | def function[_read_wrapper, parameter[data]]:
constant[Ensure unicode always returned on read.]
if call[name[isinstance], parameter[name[data], name[int]]] begin[:]
variable[data] assign[=] call[name[chr], parameter[name[data]]]
return[call[name[py23_compat].text_type, parameter[name... | keyword[def] identifier[_read_wrapper] ( identifier[data] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[data] , identifier[int] ):
identifier[data] = identifier[chr] ( identifier[data] )
keyword[return] identifier[py23_compat] . ide... | def _read_wrapper(data):
"""Ensure unicode always returned on read."""
# Paramiko (strangely) in PY3 returns an int here.
if isinstance(data, int):
data = chr(data) # depends on [control=['if'], data=[]]
# Ensure unicode
return py23_compat.text_type(data) |
def printcodelist(codelist, to=sys.stdout):
"""Get a code list. Print it nicely."""
labeldict = {}
pendinglabels = []
for i, (op, arg) in enumerate(codelist):
if isinstance(op, Label):
pendinglabels.append(op)
elif op is SetLineno:
pass
else:
... | def function[printcodelist, parameter[codelist, to]]:
constant[Get a code list. Print it nicely.]
variable[labeldict] assign[=] dictionary[[], []]
variable[pendinglabels] assign[=] list[[]]
for taget[tuple[[<ast.Name object at 0x7da1b11bc1f0>, <ast.Tuple object at 0x7da1b11bf250>]]] in s... | keyword[def] identifier[printcodelist] ( identifier[codelist] , identifier[to] = identifier[sys] . identifier[stdout] ):
literal[string]
identifier[labeldict] ={}
identifier[pendinglabels] =[]
keyword[for] identifier[i] ,( identifier[op] , identifier[arg] ) keyword[in] identifier[enumerate] ( ... | def printcodelist(codelist, to=sys.stdout):
"""Get a code list. Print it nicely."""
labeldict = {}
pendinglabels = []
for (i, (op, arg)) in enumerate(codelist):
if isinstance(op, Label):
pendinglabels.append(op) # depends on [control=['if'], data=[]]
elif op is SetLineno:
... |
def get_next_step(self):
"""Find the proper step when user clicks the Next button.
:returns: The step to be switched to
:rtype: WizardStep
"""
layer_purpose = self.parent.step_kw_purpose.selected_purpose()
if layer_purpose != layer_purpose_aggregation:
subcat... | def function[get_next_step, parameter[self]]:
constant[Find the proper step when user clicks the Next button.
:returns: The step to be switched to
:rtype: WizardStep
]
variable[layer_purpose] assign[=] call[name[self].parent.step_kw_purpose.selected_purpose, parameter[]]
... | keyword[def] identifier[get_next_step] ( identifier[self] ):
literal[string]
identifier[layer_purpose] = identifier[self] . identifier[parent] . identifier[step_kw_purpose] . identifier[selected_purpose] ()
keyword[if] identifier[layer_purpose] != identifier[layer_purpose_aggregation] :
... | def get_next_step(self):
"""Find the proper step when user clicks the Next button.
:returns: The step to be switched to
:rtype: WizardStep
"""
layer_purpose = self.parent.step_kw_purpose.selected_purpose()
if layer_purpose != layer_purpose_aggregation:
subcategory = self.par... |
def get_store_credit_by_id(cls, store_credit_id, **kwargs):
"""Find StoreCredit
Return single instance of StoreCredit by its ID.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.get_store_credi... | def function[get_store_credit_by_id, parameter[cls, store_credit_id]]:
constant[Find StoreCredit
Return single instance of StoreCredit by its ID.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = ap... | keyword[def] identifier[get_store_credit_by_id] ( identifier[cls] , identifier[store_credit_id] ,** identifier[kwargs] ):
literal[string]
identifier[kwargs] [ literal[string] ]= keyword[True]
keyword[if] identifier[kwargs] . identifier[get] ( literal[string] ):
keyword[retur... | def get_store_credit_by_id(cls, store_credit_id, **kwargs):
"""Find StoreCredit
Return single instance of StoreCredit by its ID.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.get_store_credit_by... |
def static_workflow_declaration(job, config, normal_bam, normal_bai, tumor_bam, tumor_bai):
"""
Statically declare workflow so sections can be modularly repurposed
:param JobFunctionWrappingJob job: passed automatically by Toil
:param Namespace config: Argparse Namespace object containing argument inpu... | def function[static_workflow_declaration, parameter[job, config, normal_bam, normal_bai, tumor_bam, tumor_bai]]:
constant[
Statically declare workflow so sections can be modularly repurposed
:param JobFunctionWrappingJob job: passed automatically by Toil
:param Namespace config: Argparse Namespace ... | keyword[def] identifier[static_workflow_declaration] ( identifier[job] , identifier[config] , identifier[normal_bam] , identifier[normal_bai] , identifier[tumor_bam] , identifier[tumor_bai] ):
literal[string]
identifier[memory] = literal[string] keyword[if] identifier[config] . identifier[ci_test] ... | def static_workflow_declaration(job, config, normal_bam, normal_bai, tumor_bam, tumor_bai):
"""
Statically declare workflow so sections can be modularly repurposed
:param JobFunctionWrappingJob job: passed automatically by Toil
:param Namespace config: Argparse Namespace object containing argument inpu... |
def process (self, input_symbol):
'''This is the main method that you call to process input. This may
cause the FSM to change state and call an action. This method calls
get_transition() to find the action and next_state associated with the
input_symbol and current_state. If the action ... | def function[process, parameter[self, input_symbol]]:
constant[This is the main method that you call to process input. This may
cause the FSM to change state and call an action. This method calls
get_transition() to find the action and next_state associated with the
input_symbol and curr... | keyword[def] identifier[process] ( identifier[self] , identifier[input_symbol] ):
literal[string]
identifier[self] . identifier[input_symbol] = identifier[input_symbol]
( identifier[self] . identifier[action] , identifier[self] . identifier[next_state] )= identifier[self] . identifier[ge... | def process(self, input_symbol):
"""This is the main method that you call to process input. This may
cause the FSM to change state and call an action. This method calls
get_transition() to find the action and next_state associated with the
input_symbol and current_state. If the action is Non... |
def create_sink(
self,
parent,
sink,
unique_writer_identity=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Creates a sink that exports specified log entries to a desti... | def function[create_sink, parameter[self, parent, sink, unique_writer_identity, retry, timeout, metadata]]:
constant[
Creates a sink that exports specified log entries to a destination. The
export of newly-ingested log entries begins immediately, unless the
sink's ``writer_identity`` is ... | keyword[def] identifier[create_sink] (
identifier[self] ,
identifier[parent] ,
identifier[sink] ,
identifier[unique_writer_identity] = keyword[None] ,
identifier[retry] = identifier[google] . identifier[api_core] . identifier[gapic_v1] . identifier[method] . identifier[DEFAULT] ,
identifier[timeout] = identifie... | def create_sink(self, parent, sink, unique_writer_identity=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None):
"""
Creates a sink that exports specified log entries to a destination. The
export of newly-ingested log entries begins imm... |
def swap(args):
"""
%prog swap agpfile
Swap objects and components. Will add gap lines. This is often used in
conjuction with formats.chain.fromagp() to convert between different
coordinate systems.
"""
from jcvi.utils.range import range_interleave
p = OptionParser(swap.__doc__)
op... | def function[swap, parameter[args]]:
constant[
%prog swap agpfile
Swap objects and components. Will add gap lines. This is often used in
conjuction with formats.chain.fromagp() to convert between different
coordinate systems.
]
from relative_module[jcvi.utils.range] import module[range_... | keyword[def] identifier[swap] ( identifier[args] ):
literal[string]
keyword[from] identifier[jcvi] . identifier[utils] . identifier[range] keyword[import] identifier[range_interleave]
identifier[p] = identifier[OptionParser] ( identifier[swap] . identifier[__doc__] )
identifier[opts] , ident... | def swap(args):
"""
%prog swap agpfile
Swap objects and components. Will add gap lines. This is often used in
conjuction with formats.chain.fromagp() to convert between different
coordinate systems.
"""
from jcvi.utils.range import range_interleave
p = OptionParser(swap.__doc__)
(op... |
def visibility_changed(self, enable):
"""DockWidget visibility has changed"""
SpyderPluginWidget.visibility_changed(self, enable)
if self.dockwidget is None:
return
if self.dockwidget.isWindow():
self.dock_toolbar.show()
else:
self.dock... | def function[visibility_changed, parameter[self, enable]]:
constant[DockWidget visibility has changed]
call[name[SpyderPluginWidget].visibility_changed, parameter[name[self], name[enable]]]
if compare[name[self].dockwidget is constant[None]] begin[:]
return[None]
if call[name[sel... | keyword[def] identifier[visibility_changed] ( identifier[self] , identifier[enable] ):
literal[string]
identifier[SpyderPluginWidget] . identifier[visibility_changed] ( identifier[self] , identifier[enable] )
keyword[if] identifier[self] . identifier[dockwidget] keyword[is] keyword[N... | def visibility_changed(self, enable):
"""DockWidget visibility has changed"""
SpyderPluginWidget.visibility_changed(self, enable)
if self.dockwidget is None:
return # depends on [control=['if'], data=[]]
if self.dockwidget.isWindow():
self.dock_toolbar.show() # depends on [control=['if... |
def retrieve_seq_length_op(data):
"""An op to compute the length of a sequence from input shape of [batch_size, n_step(max), n_features],
it can be used when the features of padding (on right hand side) are all zeros.
Parameters
-----------
data : tensor
[batch_size, n_step(max), n_features... | def function[retrieve_seq_length_op, parameter[data]]:
constant[An op to compute the length of a sequence from input shape of [batch_size, n_step(max), n_features],
it can be used when the features of padding (on right hand side) are all zeros.
Parameters
-----------
data : tensor
[batc... | keyword[def] identifier[retrieve_seq_length_op] ( identifier[data] ):
literal[string]
keyword[with] identifier[tf] . identifier[name_scope] ( literal[string] ):
identifier[used] = identifier[tf] . identifier[sign] ( identifier[tf] . identifier[reduce_max] ( identifier[tf] . identifier[abs] ( iden... | def retrieve_seq_length_op(data):
"""An op to compute the length of a sequence from input shape of [batch_size, n_step(max), n_features],
it can be used when the features of padding (on right hand side) are all zeros.
Parameters
-----------
data : tensor
[batch_size, n_step(max), n_features... |
def load_and_dump(create_loader, create_dumper, load_and_dump_):
""":return: a function that has the doc string of
:paramref:`load_and_dump_`
additional arguments to this function are passed on to
:paramref:`load_and_dump_`.
:param create_loader: a loader, e.g.
:class:`knittingpattern.L... | def function[load_and_dump, parameter[create_loader, create_dumper, load_and_dump_]]:
constant[:return: a function that has the doc string of
:paramref:`load_and_dump_`
additional arguments to this function are passed on to
:paramref:`load_and_dump_`.
:param create_loader: a loader, e.g.
... | keyword[def] identifier[load_and_dump] ( identifier[create_loader] , identifier[create_dumper] , identifier[load_and_dump_] ):
literal[string]
@ identifier[wraps] ( identifier[load_and_dump_] )
keyword[def] identifier[load_and_dump__] (* identifier[args1] ,** identifier[kw] ):
literal[string]... | def load_and_dump(create_loader, create_dumper, load_and_dump_):
""":return: a function that has the doc string of
:paramref:`load_and_dump_`
additional arguments to this function are passed on to
:paramref:`load_and_dump_`.
:param create_loader: a loader, e.g.
:class:`knittingpattern.L... |
def check(self, options=None):
"""check for ambiguous keys and move attributes into dict"""
self.check_values(options)
self.check_attributes(options)
self.check_values(options)
return self | def function[check, parameter[self, options]]:
constant[check for ambiguous keys and move attributes into dict]
call[name[self].check_values, parameter[name[options]]]
call[name[self].check_attributes, parameter[name[options]]]
call[name[self].check_values, parameter[name[options]]]
... | keyword[def] identifier[check] ( identifier[self] , identifier[options] = keyword[None] ):
literal[string]
identifier[self] . identifier[check_values] ( identifier[options] )
identifier[self] . identifier[check_attributes] ( identifier[options] )
identifier[self] . identifier[chec... | def check(self, options=None):
"""check for ambiguous keys and move attributes into dict"""
self.check_values(options)
self.check_attributes(options)
self.check_values(options)
return self |
def save_state_machine_as(path=None, recent_opened_notification=False, as_copy=False):
""" Store selected state machine to path
If there is no handed path the interface dialog "create folder" is used to collect one. The state machine finally
is stored by the save_state_machine function.
:param str p... | def function[save_state_machine_as, parameter[path, recent_opened_notification, as_copy]]:
constant[ Store selected state machine to path
If there is no handed path the interface dialog "create folder" is used to collect one. The state machine finally
is stored by the save_state_machine function.
... | keyword[def] identifier[save_state_machine_as] ( identifier[path] = keyword[None] , identifier[recent_opened_notification] = keyword[False] , identifier[as_copy] = keyword[False] ):
literal[string]
identifier[state_machine_manager_model] = identifier[rafcon] . identifier[gui] . identifier[singleton] . ide... | def save_state_machine_as(path=None, recent_opened_notification=False, as_copy=False):
""" Store selected state machine to path
If there is no handed path the interface dialog "create folder" is used to collect one. The state machine finally
is stored by the save_state_machine function.
:param str p... |
def _setup_axes(cls, axes, info_axis=None, stat_axis=None, aliases=None,
slicers=None, axes_are_reversed=False, build_axes=True,
ns=None, docs=None):
"""Provide axes setup for the major PandasObjects.
Parameters
----------
axes : the names of the ... | def function[_setup_axes, parameter[cls, axes, info_axis, stat_axis, aliases, slicers, axes_are_reversed, build_axes, ns, docs]]:
constant[Provide axes setup for the major PandasObjects.
Parameters
----------
axes : the names of the axes in order (lowest to highest)
info_axis_nu... | keyword[def] identifier[_setup_axes] ( identifier[cls] , identifier[axes] , identifier[info_axis] = keyword[None] , identifier[stat_axis] = keyword[None] , identifier[aliases] = keyword[None] ,
identifier[slicers] = keyword[None] , identifier[axes_are_reversed] = keyword[False] , identifier[build_axes] = keyword[Tru... | def _setup_axes(cls, axes, info_axis=None, stat_axis=None, aliases=None, slicers=None, axes_are_reversed=False, build_axes=True, ns=None, docs=None):
"""Provide axes setup for the major PandasObjects.
Parameters
----------
axes : the names of the axes in order (lowest to highest)
in... |
def from_dict(d):
"""
Re-create the noise model from a dictionary representation.
:param Dict[str,Any] d: The dictionary representation.
:return: The restored noise model.
:rtype: NoiseModel
"""
return NoiseModel(
gates=[KrausModel.from_dict(t) for t ... | def function[from_dict, parameter[d]]:
constant[
Re-create the noise model from a dictionary representation.
:param Dict[str,Any] d: The dictionary representation.
:return: The restored noise model.
:rtype: NoiseModel
]
return[call[name[NoiseModel], parameter[]]] | keyword[def] identifier[from_dict] ( identifier[d] ):
literal[string]
keyword[return] identifier[NoiseModel] (
identifier[gates] =[ identifier[KrausModel] . identifier[from_dict] ( identifier[t] ) keyword[for] identifier[t] keyword[in] identifier[d] [ literal[string] ]],
ident... | def from_dict(d):
"""
Re-create the noise model from a dictionary representation.
:param Dict[str,Any] d: The dictionary representation.
:return: The restored noise model.
:rtype: NoiseModel
"""
return NoiseModel(gates=[KrausModel.from_dict(t) for t in d['gates']], assig... |
def r(self,*args,**kwargs):
"""
NAME:
r
PURPOSE:
return spherical radius at time t
INPUT:
t - (optional) time at which to get the radius
ro= (Object-wide default) physical scale for distances to use to convert
use_physical= use to ov... | def function[r, parameter[self]]:
constant[
NAME:
r
PURPOSE:
return spherical radius at time t
INPUT:
t - (optional) time at which to get the radius
ro= (Object-wide default) physical scale for distances to use to convert
use_physica... | keyword[def] identifier[r] ( identifier[self] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
identifier[thiso] = identifier[self] (* identifier[args] ,** identifier[kwargs] )
identifier[onet] =( identifier[len] ( identifier[thiso] . identifier[shape] )== literal[int] )
... | def r(self, *args, **kwargs):
"""
NAME:
r
PURPOSE:
return spherical radius at time t
INPUT:
t - (optional) time at which to get the radius
ro= (Object-wide default) physical scale for distances to use to convert
use_physical= use to over... |
def preorder_iter_with_position(expression):
"""Iterate over the expression in preorder.
Also yields the position of each subexpression.
"""
yield expression, ()
if isinstance(expression, Operation):
for i, operand in enumerate(op_iter(expression)):
for child, pos in preorder_it... | def function[preorder_iter_with_position, parameter[expression]]:
constant[Iterate over the expression in preorder.
Also yields the position of each subexpression.
]
<ast.Yield object at 0x7da207f005e0>
if call[name[isinstance], parameter[name[expression], name[Operation]]] begin[:]
... | keyword[def] identifier[preorder_iter_with_position] ( identifier[expression] ):
literal[string]
keyword[yield] identifier[expression] ,()
keyword[if] identifier[isinstance] ( identifier[expression] , identifier[Operation] ):
keyword[for] identifier[i] , identifier[operand] keyword[in] i... | def preorder_iter_with_position(expression):
"""Iterate over the expression in preorder.
Also yields the position of each subexpression.
"""
yield (expression, ())
if isinstance(expression, Operation):
for (i, operand) in enumerate(op_iter(expression)):
for (child, pos) in preor... |
def iou(preds, labels, C, EMPTY=1., ignore=None, per_image=False):
"""
Array of IoU for each (non ignored) class
"""
if not per_image:
preds, labels = (preds,), (labels,)
ious = []
for pred, label in zip(preds, labels):
iou = []
for i in range(C):
if i != ... | def function[iou, parameter[preds, labels, C, EMPTY, ignore, per_image]]:
constant[
Array of IoU for each (non ignored) class
]
if <ast.UnaryOp object at 0x7da1b216cd90> begin[:]
<ast.Tuple object at 0x7da1b216f760> assign[=] tuple[[<ast.Tuple object at 0x7da1b216d7e0>, <ast.Tupl... | keyword[def] identifier[iou] ( identifier[preds] , identifier[labels] , identifier[C] , identifier[EMPTY] = literal[int] , identifier[ignore] = keyword[None] , identifier[per_image] = keyword[False] ):
literal[string]
keyword[if] keyword[not] identifier[per_image] :
identifier[preds] , identifie... | def iou(preds, labels, C, EMPTY=1.0, ignore=None, per_image=False):
"""
Array of IoU for each (non ignored) class
"""
if not per_image:
(preds, labels) = ((preds,), (labels,)) # depends on [control=['if'], data=[]]
ious = []
for (pred, label) in zip(preds, labels):
iou = []
... |
def gen_chunks(self, gen):
"""Generates byte chunks of a given size.
Takes a bytes generator and yields chunks of a maximum of
``chunk_size`` bytes.
Parameters
----------
gen : generator
The bytes generator that produces the bytes
"""
for dat... | def function[gen_chunks, parameter[self, gen]]:
constant[Generates byte chunks of a given size.
Takes a bytes generator and yields chunks of a maximum of
``chunk_size`` bytes.
Parameters
----------
gen : generator
The bytes generator that produces the bytes
... | keyword[def] identifier[gen_chunks] ( identifier[self] , identifier[gen] ):
literal[string]
keyword[for] identifier[data] keyword[in] identifier[gen] :
identifier[size] = identifier[len] ( identifier[data] )
keyword[if] identifier[size] < identifier[self] . identifier[... | def gen_chunks(self, gen):
"""Generates byte chunks of a given size.
Takes a bytes generator and yields chunks of a maximum of
``chunk_size`` bytes.
Parameters
----------
gen : generator
The bytes generator that produces the bytes
"""
for data in gen... |
def parse_manifest(cls, session, url_or_manifest, **args):
"""
Attempt to parse a DASH manifest file and return its streams
:param session: Streamlink session instance
:param url_or_manifest: URL of the manifest file or an XML manifest string
:return: a dict of name -> DASHStrea... | def function[parse_manifest, parameter[cls, session, url_or_manifest]]:
constant[
Attempt to parse a DASH manifest file and return its streams
:param session: Streamlink session instance
:param url_or_manifest: URL of the manifest file or an XML manifest string
:return: a dict o... | keyword[def] identifier[parse_manifest] ( identifier[cls] , identifier[session] , identifier[url_or_manifest] ,** identifier[args] ):
literal[string]
identifier[ret] ={}
keyword[if] identifier[url_or_manifest] . identifier[startswith] ( literal[string] ):
identifier[mpd] = i... | def parse_manifest(cls, session, url_or_manifest, **args):
"""
Attempt to parse a DASH manifest file and return its streams
:param session: Streamlink session instance
:param url_or_manifest: URL of the manifest file or an XML manifest string
:return: a dict of name -> DASHStream in... |
def git_list_tags(repo_dir, with_messages=False):
"""Return a list of git tags for the git repo in `repo_dir`."""
command = ['git', 'tag', '-l']
if with_messages:
command.append('-n1')
raw = execute_git_command(command, repo_dir=repo_dir).splitlines()
output = [l.strip() for l in raw if l.st... | def function[git_list_tags, parameter[repo_dir, with_messages]]:
constant[Return a list of git tags for the git repo in `repo_dir`.]
variable[command] assign[=] list[[<ast.Constant object at 0x7da1b09e85e0>, <ast.Constant object at 0x7da1b09eb220>, <ast.Constant object at 0x7da1b09ea890>]]
if na... | keyword[def] identifier[git_list_tags] ( identifier[repo_dir] , identifier[with_messages] = keyword[False] ):
literal[string]
identifier[command] =[ literal[string] , literal[string] , literal[string] ]
keyword[if] identifier[with_messages] :
identifier[command] . identifier[append] ( litera... | def git_list_tags(repo_dir, with_messages=False):
"""Return a list of git tags for the git repo in `repo_dir`."""
command = ['git', 'tag', '-l']
if with_messages:
command.append('-n1') # depends on [control=['if'], data=[]]
raw = execute_git_command(command, repo_dir=repo_dir).splitlines()
... |
def _read_frame(self):
"""Read one frame"""
# Read the first line, ignore the title and try to get the time. The
# time field is optional.
line = self._get_line()
pos = line.rfind("t=")
if pos >= 0:
time = float(line[pos+2:])*picosecond
else:
... | def function[_read_frame, parameter[self]]:
constant[Read one frame]
variable[line] assign[=] call[name[self]._get_line, parameter[]]
variable[pos] assign[=] call[name[line].rfind, parameter[constant[t=]]]
if compare[name[pos] greater_or_equal[>=] constant[0]] begin[:]
va... | keyword[def] identifier[_read_frame] ( identifier[self] ):
literal[string]
identifier[line] = identifier[self] . identifier[_get_line] ()
identifier[pos] = identifier[line] . identifier[rfind] ( literal[string] )
keyword[if] identifier[pos] >= literal[int] :
... | def _read_frame(self):
"""Read one frame"""
# Read the first line, ignore the title and try to get the time. The
# time field is optional.
line = self._get_line()
pos = line.rfind('t=')
if pos >= 0:
time = float(line[pos + 2:]) * picosecond # depends on [control=['if'], data=['pos']]
... |
def from_int(cls, integer):
"""
Constructs a `Deleted` using the `tinyint` value of the `rev_deleted`
column of the `revision` MariaDB table.
* DELETED_TEXT = 1
* DELETED_COMMENT = 2
* DELETED_USER = 4
* DELETED_RESTRICTED = 8
"""
bin_string = bin... | def function[from_int, parameter[cls, integer]]:
constant[
Constructs a `Deleted` using the `tinyint` value of the `rev_deleted`
column of the `revision` MariaDB table.
* DELETED_TEXT = 1
* DELETED_COMMENT = 2
* DELETED_USER = 4
* DELETED_RESTRICTED = 8
]... | keyword[def] identifier[from_int] ( identifier[cls] , identifier[integer] ):
literal[string]
identifier[bin_string] = identifier[bin] ( identifier[integer] )
keyword[return] identifier[cls] (
identifier[text] = identifier[len] ( identifier[bin_string] )>= literal[int] keyword[a... | def from_int(cls, integer):
"""
Constructs a `Deleted` using the `tinyint` value of the `rev_deleted`
column of the `revision` MariaDB table.
* DELETED_TEXT = 1
* DELETED_COMMENT = 2
* DELETED_USER = 4
* DELETED_RESTRICTED = 8
"""
bin_string = bin(integer... |
def serve(path=None, host=None, port=None, user_content=False, context=None,
username=None, password=None, render_offline=False,
render_wide=False, render_inline=False, api_url=None, title=None,
autorefresh=True, browser=False, quiet=None, grip_class=None):
"""
Starts a server to r... | def function[serve, parameter[path, host, port, user_content, context, username, password, render_offline, render_wide, render_inline, api_url, title, autorefresh, browser, quiet, grip_class]]:
constant[
Starts a server to render the specified file or directory containing
a README.
]
variabl... | keyword[def] identifier[serve] ( identifier[path] = keyword[None] , identifier[host] = keyword[None] , identifier[port] = keyword[None] , identifier[user_content] = keyword[False] , identifier[context] = keyword[None] ,
identifier[username] = keyword[None] , identifier[password] = keyword[None] , identifier[render_o... | def serve(path=None, host=None, port=None, user_content=False, context=None, username=None, password=None, render_offline=False, render_wide=False, render_inline=False, api_url=None, title=None, autorefresh=True, browser=False, quiet=None, grip_class=None):
"""
Starts a server to render the specified file or di... |
def DynamicCmd(name, plugins):
"""
Returns a cmd with the added plugins,
:param name: TODO:
:param plugins: list of plugins
"""
exec('class %s(cmd.Cmd):\n prompt="cm> "' % name)
plugin_objects = []
for plugin in plugins:
classprefix = plugin['class']
plugin_list =... | def function[DynamicCmd, parameter[name, plugins]]:
constant[
Returns a cmd with the added plugins,
:param name: TODO:
:param plugins: list of plugins
]
call[name[exec], parameter[binary_operation[constant[class %s(cmd.Cmd):
prompt="cm> "] <ast.Mod object at 0x7da2590d6920> name... | keyword[def] identifier[DynamicCmd] ( identifier[name] , identifier[plugins] ):
literal[string]
identifier[exec] ( literal[string] % identifier[name] )
identifier[plugin_objects] =[]
keyword[for] identifier[plugin] keyword[in] identifier[plugins] :
identifier[classprefix] = identifier... | def DynamicCmd(name, plugins):
"""
Returns a cmd with the added plugins,
:param name: TODO:
:param plugins: list of plugins
"""
exec('class %s(cmd.Cmd):\n prompt="cm> "' % name)
plugin_objects = []
for plugin in plugins:
classprefix = plugin['class']
plugin_list =... |
def csv_dumper(**kwargs):
"""dump data to csv"""
logging.info("dumping to csv")
barn = kwargs["barn"]
farms = kwargs["farms"]
experiments = kwargs["experiments"]
for experiment, farm in zip(experiments, farms):
name = experiment.journal.name
project = experiment.journal.project
... | def function[csv_dumper, parameter[]]:
constant[dump data to csv]
call[name[logging].info, parameter[constant[dumping to csv]]]
variable[barn] assign[=] call[name[kwargs]][constant[barn]]
variable[farms] assign[=] call[name[kwargs]][constant[farms]]
variable[experiments] assign[=... | keyword[def] identifier[csv_dumper] (** identifier[kwargs] ):
literal[string]
identifier[logging] . identifier[info] ( literal[string] )
identifier[barn] = identifier[kwargs] [ literal[string] ]
identifier[farms] = identifier[kwargs] [ literal[string] ]
identifier[experiments] = identifier[k... | def csv_dumper(**kwargs):
"""dump data to csv"""
logging.info('dumping to csv')
barn = kwargs['barn']
farms = kwargs['farms']
experiments = kwargs['experiments']
for (experiment, farm) in zip(experiments, farms):
name = experiment.journal.name
project = experiment.journal.project... |
def update(self, other):
"""
Updates this cache mixin with results discovered by the other split off one.
"""
acceptable_models = [ m for m in other._models if set(m.model.keys()) == self.variables ]
self._models.update(acceptable_models)
self._eval_exhausted.update(othe... | def function[update, parameter[self, other]]:
constant[
Updates this cache mixin with results discovered by the other split off one.
]
variable[acceptable_models] assign[=] <ast.ListComp object at 0x7da18dc99960>
call[name[self]._models.update, parameter[name[acceptable_models]]]... | keyword[def] identifier[update] ( identifier[self] , identifier[other] ):
literal[string]
identifier[acceptable_models] =[ identifier[m] keyword[for] identifier[m] keyword[in] identifier[other] . identifier[_models] keyword[if] identifier[set] ( identifier[m] . identifier[model] . identifier... | def update(self, other):
"""
Updates this cache mixin with results discovered by the other split off one.
"""
acceptable_models = [m for m in other._models if set(m.model.keys()) == self.variables]
self._models.update(acceptable_models)
self._eval_exhausted.update(other._eval_exhausted)
... |
def load_scoring_function(scoring_func):
"""
converts mymodule.myfunc in the myfunc
object itself so tpot receives a scoring function
"""
if scoring_func and ("." in scoring_func):
try:
module_name, func_name = scoring_func.rsplit('.', 1)
module_path = os.getcwd()
... | def function[load_scoring_function, parameter[scoring_func]]:
constant[
converts mymodule.myfunc in the myfunc
object itself so tpot receives a scoring function
]
if <ast.BoolOp object at 0x7da2043467a0> begin[:]
<ast.Try object at 0x7da2043454b0>
return[name[scoring_func]] | keyword[def] identifier[load_scoring_function] ( identifier[scoring_func] ):
literal[string]
keyword[if] identifier[scoring_func] keyword[and] ( literal[string] keyword[in] identifier[scoring_func] ):
keyword[try] :
identifier[module_name] , identifier[func_name] = identifier[scor... | def load_scoring_function(scoring_func):
"""
converts mymodule.myfunc in the myfunc
object itself so tpot receives a scoring function
"""
if scoring_func and '.' in scoring_func:
try:
(module_name, func_name) = scoring_func.rsplit('.', 1)
module_path = os.getcwd()
... |
def draw_chimera_yield(G, **kwargs):
"""Draws the given graph G with highlighted faults, according to layout.
Parameters
----------
G : NetworkX graph
The graph to be parsed for faults
unused_color : tuple or color string (optional, default (0.9,0.9,0.9,1.0))
The color to use for n... | def function[draw_chimera_yield, parameter[G]]:
constant[Draws the given graph G with highlighted faults, according to layout.
Parameters
----------
G : NetworkX graph
The graph to be parsed for faults
unused_color : tuple or color string (optional, default (0.9,0.9,0.9,1.0))
T... | keyword[def] identifier[draw_chimera_yield] ( identifier[G] ,** identifier[kwargs] ):
literal[string]
keyword[try] :
keyword[assert] ( identifier[G] . identifier[graph] [ literal[string] ]== literal[string] )
identifier[m] = identifier[G] . identifier[graph] [ literal[string] ]
i... | def draw_chimera_yield(G, **kwargs):
"""Draws the given graph G with highlighted faults, according to layout.
Parameters
----------
G : NetworkX graph
The graph to be parsed for faults
unused_color : tuple or color string (optional, default (0.9,0.9,0.9,1.0))
The color to use for n... |
def WriteVarBytes(self, value, endian="<"):
"""
Write an integer value in a space saving way to the stream.
Read more about variable size encoding here: http://docs.neo.org/en-us/node/network-protocol.html#convention
Args:
value (bytes):
endian (str): specify the... | def function[WriteVarBytes, parameter[self, value, endian]]:
constant[
Write an integer value in a space saving way to the stream.
Read more about variable size encoding here: http://docs.neo.org/en-us/node/network-protocol.html#convention
Args:
value (bytes):
en... | keyword[def] identifier[WriteVarBytes] ( identifier[self] , identifier[value] , identifier[endian] = literal[string] ):
literal[string]
identifier[length] = identifier[len] ( identifier[value] )
identifier[self] . identifier[WriteVarInt] ( identifier[length] , identifier[endian] )
... | def WriteVarBytes(self, value, endian='<'):
"""
Write an integer value in a space saving way to the stream.
Read more about variable size encoding here: http://docs.neo.org/en-us/node/network-protocol.html#convention
Args:
value (bytes):
endian (str): specify the end... |
def error(self, msg, n):
"""Raise a SyntaxError with the lineno and col_offset set to n's."""
raise SyntaxError(msg, n.lineno, n.col_offset,
filename=self.compile_info.filename) | def function[error, parameter[self, msg, n]]:
constant[Raise a SyntaxError with the lineno and col_offset set to n's.]
<ast.Raise object at 0x7da2054a78e0> | keyword[def] identifier[error] ( identifier[self] , identifier[msg] , identifier[n] ):
literal[string]
keyword[raise] identifier[SyntaxError] ( identifier[msg] , identifier[n] . identifier[lineno] , identifier[n] . identifier[col_offset] ,
identifier[filename] = identifier[self] . identif... | def error(self, msg, n):
"""Raise a SyntaxError with the lineno and col_offset set to n's."""
raise SyntaxError(msg, n.lineno, n.col_offset, filename=self.compile_info.filename) |
def basic_word_sim(word1, word2):
"""
Simple measure of similarity: Number of letters in common / max length
"""
return sum([1 for c in word1 if c in word2]) / max(len(word1), len(word2)) | def function[basic_word_sim, parameter[word1, word2]]:
constant[
Simple measure of similarity: Number of letters in common / max length
]
return[binary_operation[call[name[sum], parameter[<ast.ListComp object at 0x7da2054a7790>]] / call[name[max], parameter[call[name[len], parameter[name[word1]]], c... | keyword[def] identifier[basic_word_sim] ( identifier[word1] , identifier[word2] ):
literal[string]
keyword[return] identifier[sum] ([ literal[int] keyword[for] identifier[c] keyword[in] identifier[word1] keyword[if] identifier[c] keyword[in] identifier[word2] ])/ identifier[max] ( identifier[len] ... | def basic_word_sim(word1, word2):
"""
Simple measure of similarity: Number of letters in common / max length
"""
return sum([1 for c in word1 if c in word2]) / max(len(word1), len(word2)) |
def route_sns_task(event, context):
"""
Gets SNS Message, deserialises the message,
imports the function, calls the function with args
"""
record = event['Records'][0]
message = json.loads(
record['Sns']['Message']
)
return run_message(message) | def function[route_sns_task, parameter[event, context]]:
constant[
Gets SNS Message, deserialises the message,
imports the function, calls the function with args
]
variable[record] assign[=] call[call[name[event]][constant[Records]]][constant[0]]
variable[message] assign[=] call[name... | keyword[def] identifier[route_sns_task] ( identifier[event] , identifier[context] ):
literal[string]
identifier[record] = identifier[event] [ literal[string] ][ literal[int] ]
identifier[message] = identifier[json] . identifier[loads] (
identifier[record] [ literal[string] ][ literal[string] ]
... | def route_sns_task(event, context):
"""
Gets SNS Message, deserialises the message,
imports the function, calls the function with args
"""
record = event['Records'][0]
message = json.loads(record['Sns']['Message'])
return run_message(message) |
def getElementType(self, elementKw):
""" return type name for given element keyword,
e.g. getElementType('Q01') should return string: 'QUAD'
"""
try:
etype = list(self.all_elements.get(elementKw.upper()).keys())[0]
except:
etype = self.all_elements.get... | def function[getElementType, parameter[self, elementKw]]:
constant[ return type name for given element keyword,
e.g. getElementType('Q01') should return string: 'QUAD'
]
<ast.Try object at 0x7da1b09bece0>
return[call[name[etype].upper, parameter[]]] | keyword[def] identifier[getElementType] ( identifier[self] , identifier[elementKw] ):
literal[string]
keyword[try] :
identifier[etype] = identifier[list] ( identifier[self] . identifier[all_elements] . identifier[get] ( identifier[elementKw] . identifier[upper] ()). identifier[keys] ()... | def getElementType(self, elementKw):
""" return type name for given element keyword,
e.g. getElementType('Q01') should return string: 'QUAD'
"""
try:
etype = list(self.all_elements.get(elementKw.upper()).keys())[0] # depends on [control=['try'], data=[]]
except:
etype = ... |
def expand(self, normalization='4pi', csphase=1, **kwargs):
"""
Expand the grid into spherical harmonics.
Usage
-----
clm = x.expand([normalization, csphase, lmax_calc])
Returns
-------
clm : SHCoeffs class instance
Parameters
----------... | def function[expand, parameter[self, normalization, csphase]]:
constant[
Expand the grid into spherical harmonics.
Usage
-----
clm = x.expand([normalization, csphase, lmax_calc])
Returns
-------
clm : SHCoeffs class instance
Parameters
-... | keyword[def] identifier[expand] ( identifier[self] , identifier[normalization] = literal[string] , identifier[csphase] = literal[int] ,** identifier[kwargs] ):
literal[string]
keyword[if] identifier[type] ( identifier[normalization] )!= identifier[str] :
keyword[raise] identifier[Val... | def expand(self, normalization='4pi', csphase=1, **kwargs):
"""
Expand the grid into spherical harmonics.
Usage
-----
clm = x.expand([normalization, csphase, lmax_calc])
Returns
-------
clm : SHCoeffs class instance
Parameters
----------
... |
def alter_field(self, model, old_field, new_field, strict=False):
"""Ran when the configuration on a field changed."""
is_old_field_hstore = isinstance(old_field, HStoreField)
is_new_field_hstore = isinstance(new_field, HStoreField)
if not is_old_field_hstore and not is_new_field_hstor... | def function[alter_field, parameter[self, model, old_field, new_field, strict]]:
constant[Ran when the configuration on a field changed.]
variable[is_old_field_hstore] assign[=] call[name[isinstance], parameter[name[old_field], name[HStoreField]]]
variable[is_new_field_hstore] assign[=] call[nam... | keyword[def] identifier[alter_field] ( identifier[self] , identifier[model] , identifier[old_field] , identifier[new_field] , identifier[strict] = keyword[False] ):
literal[string]
identifier[is_old_field_hstore] = identifier[isinstance] ( identifier[old_field] , identifier[HStoreField] )
... | def alter_field(self, model, old_field, new_field, strict=False):
"""Ran when the configuration on a field changed."""
is_old_field_hstore = isinstance(old_field, HStoreField)
is_new_field_hstore = isinstance(new_field, HStoreField)
if not is_old_field_hstore and (not is_new_field_hstore):
retur... |
def conf_int(self, alpha=0.05, **kwargs):
r"""Returns the confidence interval of the fitted parameters.
Returns
-------
alpha : float, optional (default=0.05)
The significance level for the confidence interval. ie.,
the default alpha = .05 returns a 95% confidenc... | def function[conf_int, parameter[self, alpha]]:
constant[Returns the confidence interval of the fitted parameters.
Returns
-------
alpha : float, optional (default=0.05)
The significance level for the confidence interval. ie.,
the default alpha = .05 returns a 95... | keyword[def] identifier[conf_int] ( identifier[self] , identifier[alpha] = literal[int] ,** identifier[kwargs] ):
literal[string]
keyword[return] identifier[self] . identifier[arima_res_] . identifier[conf_int] ( identifier[alpha] = identifier[alpha] ,** identifier[kwargs] ) | def conf_int(self, alpha=0.05, **kwargs):
"""Returns the confidence interval of the fitted parameters.
Returns
-------
alpha : float, optional (default=0.05)
The significance level for the confidence interval. ie.,
the default alpha = .05 returns a 95% confidence int... |
def download_object(self, obj_name, directory, structure=True):
"""
Alias for self.download(); included for backwards compatibility
"""
return self.download(obj=obj_name, directory=directory,
structure=structure) | def function[download_object, parameter[self, obj_name, directory, structure]]:
constant[
Alias for self.download(); included for backwards compatibility
]
return[call[name[self].download, parameter[]]] | keyword[def] identifier[download_object] ( identifier[self] , identifier[obj_name] , identifier[directory] , identifier[structure] = keyword[True] ):
literal[string]
keyword[return] identifier[self] . identifier[download] ( identifier[obj] = identifier[obj_name] , identifier[directory] = identifie... | def download_object(self, obj_name, directory, structure=True):
"""
Alias for self.download(); included for backwards compatibility
"""
return self.download(obj=obj_name, directory=directory, structure=structure) |
def delete_files_within_dir(directory: str, filenames: List[str]) -> None:
"""
Delete files within ``directory`` whose filename *exactly* matches one of
``filenames``.
"""
for dirpath, dirnames, fnames in os.walk(directory):
for f in fnames:
if f in filenames:
ful... | def function[delete_files_within_dir, parameter[directory, filenames]]:
constant[
Delete files within ``directory`` whose filename *exactly* matches one of
``filenames``.
]
for taget[tuple[[<ast.Name object at 0x7da1b189e2f0>, <ast.Name object at 0x7da1b189d990>, <ast.Name object at 0x7da1b1... | keyword[def] identifier[delete_files_within_dir] ( identifier[directory] : identifier[str] , identifier[filenames] : identifier[List] [ identifier[str] ])-> keyword[None] :
literal[string]
keyword[for] identifier[dirpath] , identifier[dirnames] , identifier[fnames] keyword[in] identifier[os] . identifie... | def delete_files_within_dir(directory: str, filenames: List[str]) -> None:
"""
Delete files within ``directory`` whose filename *exactly* matches one of
``filenames``.
"""
for (dirpath, dirnames, fnames) in os.walk(directory):
for f in fnames:
if f in filenames:
f... |
def _normalize_tags_type(self, tags, device_name=None, metric_name=None):
"""
Normalize tags contents and type:
- append `device_name` as `device:` tag
- normalize tags type
- doesn't mutate the passed list, returns a new list
"""
normalized_tags = []
if ... | def function[_normalize_tags_type, parameter[self, tags, device_name, metric_name]]:
constant[
Normalize tags contents and type:
- append `device_name` as `device:` tag
- normalize tags type
- doesn't mutate the passed list, returns a new list
]
variable[normalize... | keyword[def] identifier[_normalize_tags_type] ( identifier[self] , identifier[tags] , identifier[device_name] = keyword[None] , identifier[metric_name] = keyword[None] ):
literal[string]
identifier[normalized_tags] =[]
keyword[if] identifier[device_name] :
identifier[self] .... | def _normalize_tags_type(self, tags, device_name=None, metric_name=None):
"""
Normalize tags contents and type:
- append `device_name` as `device:` tag
- normalize tags type
- doesn't mutate the passed list, returns a new list
"""
normalized_tags = []
if device_name:
... |
def assess_itx_resistance(job, gene_expression, univ_options, reports_options):
"""
Assess the prevalence of the various genes in various cancer pathways and return a report in the txt
format.
:param toil.fileStore.FileID gene_expression: fsID for the rsem gene expression file
:param dict univ_opti... | def function[assess_itx_resistance, parameter[job, gene_expression, univ_options, reports_options]]:
constant[
Assess the prevalence of the various genes in various cancer pathways and return a report in the txt
format.
:param toil.fileStore.FileID gene_expression: fsID for the rsem gene expression... | keyword[def] identifier[assess_itx_resistance] ( identifier[job] , identifier[gene_expression] , identifier[univ_options] , identifier[reports_options] ):
literal[string]
identifier[work_dir] = identifier[os] . identifier[getcwd] ()
identifier[tumor_type] = identifier[univ_options] [ literal[string] ... | def assess_itx_resistance(job, gene_expression, univ_options, reports_options):
"""
Assess the prevalence of the various genes in various cancer pathways and return a report in the txt
format.
:param toil.fileStore.FileID gene_expression: fsID for the rsem gene expression file
:param dict univ_opti... |
def to_add_link(self, ):
'''
To add link
'''
if self.check_post_role()['ADD']:
pass
else:
return False
kwd = {
'pager': '',
'uid': '',
}
self.render('misc/link/link_add.html',
topmenu='',
... | def function[to_add_link, parameter[self]]:
constant[
To add link
]
if call[call[name[self].check_post_role, parameter[]]][constant[ADD]] begin[:]
pass
variable[kwd] assign[=] dictionary[[<ast.Constant object at 0x7da1b04f8820>, <ast.Constant object at 0x7da1b04f9e10>], [... | keyword[def] identifier[to_add_link] ( identifier[self] ,):
literal[string]
keyword[if] identifier[self] . identifier[check_post_role] ()[ literal[string] ]:
keyword[pass]
keyword[else] :
keyword[return] keyword[False]
identifier[kwd] ={
lite... | def to_add_link(self):
"""
To add link
"""
if self.check_post_role()['ADD']:
pass # depends on [control=['if'], data=[]]
else:
return False
kwd = {'pager': '', 'uid': ''}
self.render('misc/link/link_add.html', topmenu='', kwd=kwd, userinfo=self.userinfo) |
def add_price_entity(self, price: dal.Price):
""" Adds the price """
from decimal import Decimal
# check if the price already exists in db.
repo = self.get_price_repository()
existing = (
repo.query
.filter(dal.Price.namespace == price.namespace)
... | def function[add_price_entity, parameter[self, price]]:
constant[ Adds the price ]
from relative_module[decimal] import module[Decimal]
variable[repo] assign[=] call[name[self].get_price_repository, parameter[]]
variable[existing] assign[=] call[call[call[call[call[name[repo].query.filter, p... | keyword[def] identifier[add_price_entity] ( identifier[self] , identifier[price] : identifier[dal] . identifier[Price] ):
literal[string]
keyword[from] identifier[decimal] keyword[import] identifier[Decimal]
identifier[repo] = identifier[self] . identifier[get_price_repositor... | def add_price_entity(self, price: dal.Price):
""" Adds the price """
from decimal import Decimal
# check if the price already exists in db.
repo = self.get_price_repository()
existing = repo.query.filter(dal.Price.namespace == price.namespace).filter(dal.Price.symbol == price.symbol).filter(dal.Pric... |
def advanced_wrap(f, wrapper):
"""
Wrap a decorated function while keeping the same keyword arguments
"""
f_sig = list(inspect.getargspec(f))
wrap_sig = list(inspect.getargspec(wrapper))
# Update the keyword arguments of the wrapper
if f_sig[3] is None or f_sig[3] == []:
f_sig[3], f... | def function[advanced_wrap, parameter[f, wrapper]]:
constant[
Wrap a decorated function while keeping the same keyword arguments
]
variable[f_sig] assign[=] call[name[list], parameter[call[name[inspect].getargspec, parameter[name[f]]]]]
variable[wrap_sig] assign[=] call[name[list], param... | keyword[def] identifier[advanced_wrap] ( identifier[f] , identifier[wrapper] ):
literal[string]
identifier[f_sig] = identifier[list] ( identifier[inspect] . identifier[getargspec] ( identifier[f] ))
identifier[wrap_sig] = identifier[list] ( identifier[inspect] . identifier[getargspec] ( identifier[wra... | def advanced_wrap(f, wrapper):
"""
Wrap a decorated function while keeping the same keyword arguments
"""
f_sig = list(inspect.getargspec(f))
wrap_sig = list(inspect.getargspec(wrapper))
# Update the keyword arguments of the wrapper
if f_sig[3] is None or f_sig[3] == []:
(f_sig[3], f... |
def import_module(module_name):
"""
Given a dotted Python path, imports & returns the module.
If not found, raises ``UnknownModuleError``.
Ex::
mod = import_module('random')
:param module_name: The dotted Python path
:type module_name: string
:returns: module
"""
try:
... | def function[import_module, parameter[module_name]]:
constant[
Given a dotted Python path, imports & returns the module.
If not found, raises ``UnknownModuleError``.
Ex::
mod = import_module('random')
:param module_name: The dotted Python path
:type module_name: string
:retu... | keyword[def] identifier[import_module] ( identifier[module_name] ):
literal[string]
keyword[try] :
keyword[return] identifier[importlib] . identifier[import_module] ( identifier[module_name] )
keyword[except] identifier[ImportError] keyword[as] identifier[err] :
keyword[raise] i... | def import_module(module_name):
"""
Given a dotted Python path, imports & returns the module.
If not found, raises ``UnknownModuleError``.
Ex::
mod = import_module('random')
:param module_name: The dotted Python path
:type module_name: string
:returns: module
"""
try:
... |
def flattened(value, split=None):
"""
Args:
value: Possibly nested arguments (sequence of lists, nested lists)
split (int | str | unicode | (str | unicode, int) | None): How to split values:
- None: simply flatten, no further processing
- one char string: split() on speci... | def function[flattened, parameter[value, split]]:
constant[
Args:
value: Possibly nested arguments (sequence of lists, nested lists)
split (int | str | unicode | (str | unicode, int) | None): How to split values:
- None: simply flatten, no further processing
- one cha... | keyword[def] identifier[flattened] ( identifier[value] , identifier[split] = keyword[None] ):
literal[string]
identifier[result] =[]
identifier[separator] = keyword[None]
identifier[mode] = literal[int]
keyword[if] identifier[isinstance] ( identifier[split] , identifier[tuple] ):
... | def flattened(value, split=None):
"""
Args:
value: Possibly nested arguments (sequence of lists, nested lists)
split (int | str | unicode | (str | unicode, int) | None): How to split values:
- None: simply flatten, no further processing
- one char string: split() on speci... |
def write_fpga_reg(self, fpga_num, addr, value, cabinet, frame, board):
"""Write the value of an FPGA (SPI) register.
See the SpI/O project's spinnaker_fpga design's `README`_ for a listing
of FPGA registers. The SpI/O project can be found on GitHub at:
https://github.com/SpiNNakerManch... | def function[write_fpga_reg, parameter[self, fpga_num, addr, value, cabinet, frame, board]]:
constant[Write the value of an FPGA (SPI) register.
See the SpI/O project's spinnaker_fpga design's `README`_ for a listing
of FPGA registers. The SpI/O project can be found on GitHub at:
https:... | keyword[def] identifier[write_fpga_reg] ( identifier[self] , identifier[fpga_num] , identifier[addr] , identifier[value] , identifier[cabinet] , identifier[frame] , identifier[board] ):
literal[string]
identifier[arg1] = identifier[addr] &(~ literal[int] )
identifier[arg2] = literal[int]
... | def write_fpga_reg(self, fpga_num, addr, value, cabinet, frame, board):
"""Write the value of an FPGA (SPI) register.
See the SpI/O project's spinnaker_fpga design's `README`_ for a listing
of FPGA registers. The SpI/O project can be found on GitHub at:
https://github.com/SpiNNakerMancheste... |
def rpc_get_usages(self, filename, source, offset):
"""Return the uses of the symbol at offset.
Returns a list of occurrences of the symbol, as dicts with the
fields name, filename, and offset.
"""
line, column = pos_to_linecol(source, offset)
uses = run_with_debug(jedi... | def function[rpc_get_usages, parameter[self, filename, source, offset]]:
constant[Return the uses of the symbol at offset.
Returns a list of occurrences of the symbol, as dicts with the
fields name, filename, and offset.
]
<ast.Tuple object at 0x7da1b16be1d0> assign[=] call[nam... | keyword[def] identifier[rpc_get_usages] ( identifier[self] , identifier[filename] , identifier[source] , identifier[offset] ):
literal[string]
identifier[line] , identifier[column] = identifier[pos_to_linecol] ( identifier[source] , identifier[offset] )
identifier[uses] = identifier[run_wi... | def rpc_get_usages(self, filename, source, offset):
"""Return the uses of the symbol at offset.
Returns a list of occurrences of the symbol, as dicts with the
fields name, filename, and offset.
"""
(line, column) = pos_to_linecol(source, offset)
uses = run_with_debug(jedi, 'usages'... |
def get_map_location(self):
"""Get the location of the player, converted to world coordinates.
:return: a tuple (x, y, z).
"""
map_data = self.get_map()
(bounds_e, bounds_n), (bounds_w, bounds_s) = map_data["continent_rect"]
(map_e, map_n), (map_w, map_s) = map_data["ma... | def function[get_map_location, parameter[self]]:
constant[Get the location of the player, converted to world coordinates.
:return: a tuple (x, y, z).
]
variable[map_data] assign[=] call[name[self].get_map, parameter[]]
<ast.Tuple object at 0x7da204347040> assign[=] call[name[ma... | keyword[def] identifier[get_map_location] ( identifier[self] ):
literal[string]
identifier[map_data] = identifier[self] . identifier[get_map] ()
( identifier[bounds_e] , identifier[bounds_n] ),( identifier[bounds_w] , identifier[bounds_s] )= identifier[map_data] [ literal[string] ]
... | def get_map_location(self):
"""Get the location of the player, converted to world coordinates.
:return: a tuple (x, y, z).
"""
map_data = self.get_map()
((bounds_e, bounds_n), (bounds_w, bounds_s)) = map_data['continent_rect']
((map_e, map_n), (map_w, map_s)) = map_data['map_rect']
... |
def com_google_fonts_check_monospace(ttFont, glyph_metrics_stats):
"""Checking correctness of monospaced metadata.
There are various metadata in the OpenType spec to specify if
a font is monospaced or not. If the font is not trully monospaced,
then no monospaced metadata should be set (as sometimes
they mist... | def function[com_google_fonts_check_monospace, parameter[ttFont, glyph_metrics_stats]]:
constant[Checking correctness of monospaced metadata.
There are various metadata in the OpenType spec to specify if
a font is monospaced or not. If the font is not trully monospaced,
then no monospaced metadata should... | keyword[def] identifier[com_google_fonts_check_monospace] ( identifier[ttFont] , identifier[glyph_metrics_stats] ):
literal[string]
keyword[from] identifier[fontbakery] . identifier[constants] keyword[import] ( identifier[IsFixedWidth] ,
identifier[PANOSE_Proportion] )
identifier[failed] = keyword[Fals... | def com_google_fonts_check_monospace(ttFont, glyph_metrics_stats):
"""Checking correctness of monospaced metadata.
There are various metadata in the OpenType spec to specify if
a font is monospaced or not. If the font is not trully monospaced,
then no monospaced metadata should be set (as sometimes
they mi... |
def load_vi_open_in_editor_bindings():
"""
Pressing 'v' in navigation mode will open the buffer in an external editor.
"""
registry = Registry()
navigation_mode = ViNavigationMode()
registry.add_binding('v', filter=navigation_mode)(
get_by_name('edit-and-execute-command'))
return re... | def function[load_vi_open_in_editor_bindings, parameter[]]:
constant[
Pressing 'v' in navigation mode will open the buffer in an external editor.
]
variable[registry] assign[=] call[name[Registry], parameter[]]
variable[navigation_mode] assign[=] call[name[ViNavigationMode], parameter[]]... | keyword[def] identifier[load_vi_open_in_editor_bindings] ():
literal[string]
identifier[registry] = identifier[Registry] ()
identifier[navigation_mode] = identifier[ViNavigationMode] ()
identifier[registry] . identifier[add_binding] ( literal[string] , identifier[filter] = identifier[navigation_... | def load_vi_open_in_editor_bindings():
"""
Pressing 'v' in navigation mode will open the buffer in an external editor.
"""
registry = Registry()
navigation_mode = ViNavigationMode()
registry.add_binding('v', filter=navigation_mode)(get_by_name('edit-and-execute-command'))
return registry |
def classview_for(self, action='view'):
"""
Return the classview that contains the viewhandler for the specified action
"""
app = current_app._get_current_object()
return self.view_for_endpoints[app][action][0](self) | def function[classview_for, parameter[self, action]]:
constant[
Return the classview that contains the viewhandler for the specified action
]
variable[app] assign[=] call[name[current_app]._get_current_object, parameter[]]
return[call[call[call[call[name[self].view_for_endpoints][nam... | keyword[def] identifier[classview_for] ( identifier[self] , identifier[action] = literal[string] ):
literal[string]
identifier[app] = identifier[current_app] . identifier[_get_current_object] ()
keyword[return] identifier[self] . identifier[view_for_endpoints] [ identifier[app] ][ identif... | def classview_for(self, action='view'):
"""
Return the classview that contains the viewhandler for the specified action
"""
app = current_app._get_current_object()
return self.view_for_endpoints[app][action][0](self) |
def make_regression(func, n_samples=100, n_features=1, bias=0.0, noise=0.0,
random_state=None):
"""
Make dataset for a regression problem.
Examples
--------
>>> f = lambda x: 0.5*x + np.sin(2*x)
>>> X, y = make_regression(f, bias=.5, noise=1., random_state=1)
>>> X.shape... | def function[make_regression, parameter[func, n_samples, n_features, bias, noise, random_state]]:
constant[
Make dataset for a regression problem.
Examples
--------
>>> f = lambda x: 0.5*x + np.sin(2*x)
>>> X, y = make_regression(f, bias=.5, noise=1., random_state=1)
>>> X.shape
(10... | keyword[def] identifier[make_regression] ( identifier[func] , identifier[n_samples] = literal[int] , identifier[n_features] = literal[int] , identifier[bias] = literal[int] , identifier[noise] = literal[int] ,
identifier[random_state] = keyword[None] ):
literal[string]
identifier[generator] = identifier[c... | def make_regression(func, n_samples=100, n_features=1, bias=0.0, noise=0.0, random_state=None):
"""
Make dataset for a regression problem.
Examples
--------
>>> f = lambda x: 0.5*x + np.sin(2*x)
>>> X, y = make_regression(f, bias=.5, noise=1., random_state=1)
>>> X.shape
(100, 1)
>>... |
def newDoc(version):
"""Creates a new XML document """
ret = libxml2mod.xmlNewDoc(version)
if ret is None:raise treeError('xmlNewDoc() failed')
return xmlDoc(_obj=ret) | def function[newDoc, parameter[version]]:
constant[Creates a new XML document ]
variable[ret] assign[=] call[name[libxml2mod].xmlNewDoc, parameter[name[version]]]
if compare[name[ret] is constant[None]] begin[:]
<ast.Raise object at 0x7da1b1f61f60>
return[call[name[xmlDoc], parameter... | keyword[def] identifier[newDoc] ( identifier[version] ):
literal[string]
identifier[ret] = identifier[libxml2mod] . identifier[xmlNewDoc] ( identifier[version] )
keyword[if] identifier[ret] keyword[is] keyword[None] : keyword[raise] identifier[treeError] ( literal[string] )
keyword[return] i... | def newDoc(version):
"""Creates a new XML document """
ret = libxml2mod.xmlNewDoc(version)
if ret is None:
raise treeError('xmlNewDoc() failed') # depends on [control=['if'], data=[]]
return xmlDoc(_obj=ret) |
def build_xlsx_response(wb, title="report"):
""" Take a workbook and return a xlsx file response """
title = generate_filename(title, '.xlsx')
myfile = BytesIO()
myfile.write(save_virtual_workbook(wb))
response = HttpResponse(
myfile.getvalue(),
content_type='application/vnd.openxmlf... | def function[build_xlsx_response, parameter[wb, title]]:
constant[ Take a workbook and return a xlsx file response ]
variable[title] assign[=] call[name[generate_filename], parameter[name[title], constant[.xlsx]]]
variable[myfile] assign[=] call[name[BytesIO], parameter[]]
call[name[myfi... | keyword[def] identifier[build_xlsx_response] ( identifier[wb] , identifier[title] = literal[string] ):
literal[string]
identifier[title] = identifier[generate_filename] ( identifier[title] , literal[string] )
identifier[myfile] = identifier[BytesIO] ()
identifier[myfile] . identifier[write] ( ide... | def build_xlsx_response(wb, title='report'):
""" Take a workbook and return a xlsx file response """
title = generate_filename(title, '.xlsx')
myfile = BytesIO()
myfile.write(save_virtual_workbook(wb))
response = HttpResponse(myfile.getvalue(), content_type='application/vnd.openxmlformats-officedocu... |
def _process_image_msg(self, msg):
""" Process an image message and return a numpy array with the image data
Returns
-------
:obj:`numpy.ndarray` containing the image in the image message
Raises
------
CvBridgeError
If the bridge is not able to conver... | def function[_process_image_msg, parameter[self, msg]]:
constant[ Process an image message and return a numpy array with the image data
Returns
-------
:obj:`numpy.ndarray` containing the image in the image message
Raises
------
CvBridgeError
If the b... | keyword[def] identifier[_process_image_msg] ( identifier[self] , identifier[msg] ):
literal[string]
identifier[encoding] = identifier[msg] . identifier[encoding]
keyword[try] :
identifier[image] = identifier[self] . identifier[_bridge] . identifier[imgmsg_to_cv2] ( identifier... | def _process_image_msg(self, msg):
""" Process an image message and return a numpy array with the image data
Returns
-------
:obj:`numpy.ndarray` containing the image in the image message
Raises
------
CvBridgeError
If the bridge is not able to convert th... |
def vector_norm(data, axis=None, out=None):
"""Return length, i.e. Euclidean norm, of ndarray along axis.
>>> v = np.random.random(3)
>>> n = vector_norm(v)
>>> np.allclose(n, np.linalg.norm(v))
True
>>> v = np.random.rand(6, 5, 3)
>>> n = vector_norm(v, axis=-1)
>>> np.allclose(n, np.s... | def function[vector_norm, parameter[data, axis, out]]:
constant[Return length, i.e. Euclidean norm, of ndarray along axis.
>>> v = np.random.random(3)
>>> n = vector_norm(v)
>>> np.allclose(n, np.linalg.norm(v))
True
>>> v = np.random.rand(6, 5, 3)
>>> n = vector_norm(v, axis=-1)
>>... | keyword[def] identifier[vector_norm] ( identifier[data] , identifier[axis] = keyword[None] , identifier[out] = keyword[None] ):
literal[string]
identifier[data] = identifier[np] . identifier[array] ( identifier[data] , identifier[dtype] = identifier[np] . identifier[float64] , identifier[copy] = keyword[Tr... | def vector_norm(data, axis=None, out=None):
"""Return length, i.e. Euclidean norm, of ndarray along axis.
>>> v = np.random.random(3)
>>> n = vector_norm(v)
>>> np.allclose(n, np.linalg.norm(v))
True
>>> v = np.random.rand(6, 5, 3)
>>> n = vector_norm(v, axis=-1)
>>> np.allclose(n, np.s... |
def repeat(self, n=2, oscillate=False, callback=None):
"""
Returns a list that is a repetition of the given list.
When oscillate is True,
moves from the end back to the beginning,
and then from the beginning to the end, and so on.
"""
colorlist = ColorList()
... | def function[repeat, parameter[self, n, oscillate, callback]]:
constant[
Returns a list that is a repetition of the given list.
When oscillate is True,
moves from the end back to the beginning,
and then from the beginning to the end, and so on.
]
variable[colorli... | keyword[def] identifier[repeat] ( identifier[self] , identifier[n] = literal[int] , identifier[oscillate] = keyword[False] , identifier[callback] = keyword[None] ):
literal[string]
identifier[colorlist] = identifier[ColorList] ()
identifier[colors] = identifier[ColorList] . identifier[copy... | def repeat(self, n=2, oscillate=False, callback=None):
"""
Returns a list that is a repetition of the given list.
When oscillate is True,
moves from the end back to the beginning,
and then from the beginning to the end, and so on.
"""
colorlist = ColorList()
colors =... |
def write(self, attr_name, prefix=None):
'''Write attribute's value to a file.
:param str attr_name:
Attribute's name to be logged
:param str prefix:
Optional. Attribute's name that is prefixed to logging message,
defaults to ``None``.
:returns: mes... | def function[write, parameter[self, attr_name, prefix]]:
constant[Write attribute's value to a file.
:param str attr_name:
Attribute's name to be logged
:param str prefix:
Optional. Attribute's name that is prefixed to logging message,
defaults to ``None``.
... | keyword[def] identifier[write] ( identifier[self] , identifier[attr_name] , identifier[prefix] = keyword[None] ):
literal[string]
keyword[if] identifier[self] . identifier[_folder] keyword[is] keyword[None] :
keyword[return]
identifier[separator] = literal[string]
... | def write(self, attr_name, prefix=None):
"""Write attribute's value to a file.
:param str attr_name:
Attribute's name to be logged
:param str prefix:
Optional. Attribute's name that is prefixed to logging message,
defaults to ``None``.
:returns: message... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.