code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def check_page(fn):
"Decorator to protect drawing methods"
@wraps(fn)
def wrapper(self, *args, **kwargs):
if not self.page and not kwargs.get('split_only'):
self.error("No page open, you need to call add_page() first")
else:
return fn(self,... | def function[check_page, parameter[fn]]:
constant[Decorator to protect drawing methods]
def function[wrapper, parameter[self]]:
if <ast.BoolOp object at 0x7da2044c1cc0> begin[:]
call[name[self].error, parameter[constant[No page open, you need to call add_page() fi... | keyword[def] identifier[check_page] ( identifier[fn] ):
literal[string]
@ identifier[wraps] ( identifier[fn] )
keyword[def] identifier[wrapper] ( identifier[self] ,* identifier[args] ,** identifier[kwargs] ):
keyword[if] keyword[not] identifier[self] . identifier[page] keyw... | def check_page(fn):
"""Decorator to protect drawing methods"""
@wraps(fn)
def wrapper(self, *args, **kwargs):
if not self.page and (not kwargs.get('split_only')):
self.error('No page open, you need to call add_page() first') # depends on [control=['if'], data=[]]
else:
... |
def HumanReadableStartType(self):
"""Return a human readable string describing the start type value.
Returns:
str: human readable description of the start type value.
"""
if isinstance(self.start_type, py2to3.STRING_TYPES):
return self.start_type
return human_readable_service_enums.SERV... | def function[HumanReadableStartType, parameter[self]]:
constant[Return a human readable string describing the start type value.
Returns:
str: human readable description of the start type value.
]
if call[name[isinstance], parameter[name[self].start_type, name[py2to3].STRING_TYPES]] begin[... | keyword[def] identifier[HumanReadableStartType] ( identifier[self] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[self] . identifier[start_type] , identifier[py2to3] . identifier[STRING_TYPES] ):
keyword[return] identifier[self] . identifier[start_type]
keyword[return] i... | def HumanReadableStartType(self):
"""Return a human readable string describing the start type value.
Returns:
str: human readable description of the start type value.
"""
if isinstance(self.start_type, py2to3.STRING_TYPES):
return self.start_type # depends on [control=['if'], data=[]]
... |
def print(self):
"""
prints to terminal the summray statistics
"""
print("TOTALS -------------------------------------------")
print(json.dumps(self.counts, indent=4, sort_keys=True))
if self.sub_total:
print("\nSUB TOTALS --- based on '%s' ---------" % self.s... | def function[print, parameter[self]]:
constant[
prints to terminal the summray statistics
]
call[name[print], parameter[constant[TOTALS -------------------------------------------]]]
call[name[print], parameter[call[name[json].dumps, parameter[name[self].counts]]]]
if nam... | keyword[def] identifier[print] ( identifier[self] ):
literal[string]
identifier[print] ( literal[string] )
identifier[print] ( identifier[json] . identifier[dumps] ( identifier[self] . identifier[counts] , identifier[indent] = literal[int] , identifier[sort_keys] = keyword[True] ))
... | def print(self):
"""
prints to terminal the summray statistics
"""
print('TOTALS -------------------------------------------')
print(json.dumps(self.counts, indent=4, sort_keys=True))
if self.sub_total:
print("\nSUB TOTALS --- based on '%s' ---------" % self.sub_total)
pr... |
def group_by(self, *args):
"""
Indica los campos para agrupación
"""
if len(args) == 1:
self.raw_fields_group = args[0].split(',')
else:
self.raw_fields_group = list(args)
return self | def function[group_by, parameter[self]]:
constant[
Indica los campos para agrupación
]
if compare[call[name[len], parameter[name[args]]] equal[==] constant[1]] begin[:]
name[self].raw_fields_group assign[=] call[call[name[args]][constant[0]].split, parameter[constant[,]]]... | keyword[def] identifier[group_by] ( identifier[self] ,* identifier[args] ):
literal[string]
keyword[if] identifier[len] ( identifier[args] )== literal[int] :
identifier[self] . identifier[raw_fields_group] = identifier[args] [ literal[int] ]. identifier[split] ( literal[string] )
... | def group_by(self, *args):
"""
Indica los campos para agrupación
"""
if len(args) == 1:
self.raw_fields_group = args[0].split(',') # depends on [control=['if'], data=[]]
else:
self.raw_fields_group = list(args)
return self |
def when(self, case_expr, result_expr):
"""
Add a new case-result pair.
Parameters
----------
case : Expr
Expression to equality-compare with base expression. Must be
comparable with the base.
result : Expr
Value when the case predicate eval... | def function[when, parameter[self, case_expr, result_expr]]:
constant[
Add a new case-result pair.
Parameters
----------
case : Expr
Expression to equality-compare with base expression. Must be
comparable with the base.
result : Expr
Value w... | keyword[def] identifier[when] ( identifier[self] , identifier[case_expr] , identifier[result_expr] ):
literal[string]
identifier[case_expr] = identifier[ir] . identifier[as_value_expr] ( identifier[case_expr] )
identifier[result_expr] = identifier[ir] . identifier[as_value_expr] ( identifi... | def when(self, case_expr, result_expr):
"""
Add a new case-result pair.
Parameters
----------
case : Expr
Expression to equality-compare with base expression. Must be
comparable with the base.
result : Expr
Value when the case predicate evaluate... |
def from_points_list(cls, points):
"""
Create a mesh object from a collection of points.
:param point:
List of :class:`~openquake.hazardlib.geo.point.Point` objects.
:returns:
An instance of :class:`Mesh` with one-dimensional arrays
of coordinates fro... | def function[from_points_list, parameter[cls, points]]:
constant[
Create a mesh object from a collection of points.
:param point:
List of :class:`~openquake.hazardlib.geo.point.Point` objects.
:returns:
An instance of :class:`Mesh` with one-dimensional arrays
... | keyword[def] identifier[from_points_list] ( identifier[cls] , identifier[points] ):
literal[string]
identifier[lons] = identifier[numpy] . identifier[zeros] ( identifier[len] ( identifier[points] ), identifier[dtype] = identifier[float] )
identifier[lats] = identifier[lons] . identifier[co... | def from_points_list(cls, points):
"""
Create a mesh object from a collection of points.
:param point:
List of :class:`~openquake.hazardlib.geo.point.Point` objects.
:returns:
An instance of :class:`Mesh` with one-dimensional arrays
of coordinates from ``... |
def doc(self):
"""
Return the root Doc element (if there is one)
"""
guess = self
while guess is not None and guess.tag != 'Doc':
guess = guess.parent # If no parent, this will be None
return guess | def function[doc, parameter[self]]:
constant[
Return the root Doc element (if there is one)
]
variable[guess] assign[=] name[self]
while <ast.BoolOp object at 0x7da18dc992d0> begin[:]
variable[guess] assign[=] name[guess].parent
return[name[guess]] | keyword[def] identifier[doc] ( identifier[self] ):
literal[string]
identifier[guess] = identifier[self]
keyword[while] identifier[guess] keyword[is] keyword[not] keyword[None] keyword[and] identifier[guess] . identifier[tag] != literal[string] :
identifier[guess] = iden... | def doc(self):
"""
Return the root Doc element (if there is one)
"""
guess = self
while guess is not None and guess.tag != 'Doc':
guess = guess.parent # If no parent, this will be None # depends on [control=['while'], data=[]]
return guess |
def simple_lmm(snps,pheno,K=None,covs=None, test='lrt',NumIntervalsDelta0=100,NumIntervalsDeltaAlt=0,searchDelta=False):
"""
Univariate fixed effects linear mixed model test for all SNPs
Args:
snps: [N x S] SP.array of S SNPs for N individuals
pheno: [N x 1] SP.array of 1 phenotype for N... | def function[simple_lmm, parameter[snps, pheno, K, covs, test, NumIntervalsDelta0, NumIntervalsDeltaAlt, searchDelta]]:
constant[
Univariate fixed effects linear mixed model test for all SNPs
Args:
snps: [N x S] SP.array of S SNPs for N individuals
pheno: [N x 1] SP.array of 1 phenot... | keyword[def] identifier[simple_lmm] ( identifier[snps] , identifier[pheno] , identifier[K] = keyword[None] , identifier[covs] = keyword[None] , identifier[test] = literal[string] , identifier[NumIntervalsDelta0] = literal[int] , identifier[NumIntervalsDeltaAlt] = literal[int] , identifier[searchDelta] = keyword[False... | def simple_lmm(snps, pheno, K=None, covs=None, test='lrt', NumIntervalsDelta0=100, NumIntervalsDeltaAlt=0, searchDelta=False):
"""
Univariate fixed effects linear mixed model test for all SNPs
Args:
snps: [N x S] SP.array of S SNPs for N individuals
pheno: [N x 1] SP.array of 1 phenotype... |
def load_and_print_resfile(filename, info_dict=None):
"""Load a raw data file and print information.
Args:
filename (str): name of the resfile.
info_dict (dict):
Returns:
info (str): string describing something.
"""
# self.test_no = None
# self.mass = 1.0 # mass of (a... | def function[load_and_print_resfile, parameter[filename, info_dict]]:
constant[Load a raw data file and print information.
Args:
filename (str): name of the resfile.
info_dict (dict):
Returns:
info (str): string describing something.
]
if compare[name[info_dict] is ... | keyword[def] identifier[load_and_print_resfile] ( identifier[filename] , identifier[info_dict] = keyword[None] ):
literal[string]
keyword[if] identif... | def load_and_print_resfile(filename, info_dict=None):
"""Load a raw data file and print information.
Args:
filename (str): name of the resfile.
info_dict (dict):
Returns:
info (str): string describing something.
"""
# self.test_no = None
# self.mass = 1.0 # mass of (ac... |
def doc2md(docstr, title, min_level=1, more_info=False, toc=True, maxdepth=0):
"""
Convert a docstring to a markdown text.
"""
text = doctrim(docstr)
lines = text.split('\n')
sections = find_sections(lines)
if sections:
level = min(n for n,t in sections) - 1
else:
level ... | def function[doc2md, parameter[docstr, title, min_level, more_info, toc, maxdepth]]:
constant[
Convert a docstring to a markdown text.
]
variable[text] assign[=] call[name[doctrim], parameter[name[docstr]]]
variable[lines] assign[=] call[name[text].split, parameter[constant[
]]]
... | keyword[def] identifier[doc2md] ( identifier[docstr] , identifier[title] , identifier[min_level] = literal[int] , identifier[more_info] = keyword[False] , identifier[toc] = keyword[True] , identifier[maxdepth] = literal[int] ):
literal[string]
identifier[text] = identifier[doctrim] ( identifier[docstr] )
... | def doc2md(docstr, title, min_level=1, more_info=False, toc=True, maxdepth=0):
"""
Convert a docstring to a markdown text.
"""
text = doctrim(docstr)
lines = text.split('\n')
sections = find_sections(lines)
if sections:
level = min((n for (n, t) in sections)) - 1 # depends on [contr... |
def autodiscover():
"""
Perform an autodiscover of an api.py file in the installed apps to
generate the routes of the registered viewsets.
"""
for app in settings.INSTALLED_APPS:
try:
import_module('.'.join((app, 'api')))
except ImportError as e:
if e.msg != "... | def function[autodiscover, parameter[]]:
constant[
Perform an autodiscover of an api.py file in the installed apps to
generate the routes of the registered viewsets.
]
for taget[name[app]] in starred[name[settings].INSTALLED_APPS] begin[:]
<ast.Try object at 0x7da20c6a85e0> | keyword[def] identifier[autodiscover] ():
literal[string]
keyword[for] identifier[app] keyword[in] identifier[settings] . identifier[INSTALLED_APPS] :
keyword[try] :
identifier[import_module] ( literal[string] . identifier[join] (( identifier[app] , literal[string] )))
key... | def autodiscover():
"""
Perform an autodiscover of an api.py file in the installed apps to
generate the routes of the registered viewsets.
"""
for app in settings.INSTALLED_APPS:
try:
import_module('.'.join((app, 'api'))) # depends on [control=['try'], data=[]]
except Im... |
def version():
'''
Return the system version for this minion
.. versionchanged:: 2016.11.4
Added support for AIX
.. versionchanged:: 2018.3.0
Added support for OpenBSD
CLI Example:
.. code-block:: bash
salt '*' status.version
'''
def linux_version():
... | def function[version, parameter[]]:
constant[
Return the system version for this minion
.. versionchanged:: 2016.11.4
Added support for AIX
.. versionchanged:: 2018.3.0
Added support for OpenBSD
CLI Example:
.. code-block:: bash
salt '*' status.version
]
... | keyword[def] identifier[version] ():
literal[string]
keyword[def] identifier[linux_version] ():
literal[string]
keyword[try] :
keyword[with] identifier[salt] . identifier[utils] . identifier[files] . identifier[fopen] ( literal[string] , literal[string] ) keyword[as] iden... | def version():
"""
Return the system version for this minion
.. versionchanged:: 2016.11.4
Added support for AIX
.. versionchanged:: 2018.3.0
Added support for OpenBSD
CLI Example:
.. code-block:: bash
salt '*' status.version
"""
def linux_version():
... |
def approve_announcement_view(request, req_id):
"""The approve announcement page. Teachers will be linked to this page from an email.
req_id: The ID of the AnnouncementRequest
"""
req = get_object_or_404(AnnouncementRequest, id=req_id)
requested_teachers = req.teachers_requested.all()
logger.... | def function[approve_announcement_view, parameter[request, req_id]]:
constant[The approve announcement page. Teachers will be linked to this page from an email.
req_id: The ID of the AnnouncementRequest
]
variable[req] assign[=] call[name[get_object_or_404], parameter[name[AnnouncementRequest]... | keyword[def] identifier[approve_announcement_view] ( identifier[request] , identifier[req_id] ):
literal[string]
identifier[req] = identifier[get_object_or_404] ( identifier[AnnouncementRequest] , identifier[id] = identifier[req_id] )
identifier[requested_teachers] = identifier[req] . identifier[teac... | def approve_announcement_view(request, req_id):
"""The approve announcement page. Teachers will be linked to this page from an email.
req_id: The ID of the AnnouncementRequest
"""
req = get_object_or_404(AnnouncementRequest, id=req_id)
requested_teachers = req.teachers_requested.all()
logger.d... |
def storagePath(self, location):
"""
Returns the path associated with this application and user for the
given location.
:param location | <QtGui.QDesktopServices.StandardLocation>
:return <str>
"""
default = nativestring(QtGui.Q... | def function[storagePath, parameter[self, location]]:
constant[
Returns the path associated with this application and user for the
given location.
:param location | <QtGui.QDesktopServices.StandardLocation>
:return <str>
]
variable[defau... | keyword[def] identifier[storagePath] ( identifier[self] , identifier[location] ):
literal[string]
identifier[default] = identifier[nativestring] ( identifier[QtGui] . identifier[QDesktopServices] . identifier[storageLocation] ( identifier[location] ))
keyword[return] identifier[self] .... | def storagePath(self, location):
"""
Returns the path associated with this application and user for the
given location.
:param location | <QtGui.QDesktopServices.StandardLocation>
:return <str>
"""
default = nativestring(QtGui.QDesktopServices.s... |
def run(self):
"""
This method is the actual implementation of the job. By default, it calls
the target function specified in the #Job constructor.
"""
if self.__target is not None:
return self.__target(self, *self.__args, **self.__kwargs)
raise NotImplementedError | def function[run, parameter[self]]:
constant[
This method is the actual implementation of the job. By default, it calls
the target function specified in the #Job constructor.
]
if compare[name[self].__target is_not constant[None]] begin[:]
return[call[name[self].__target, parameter[n... | keyword[def] identifier[run] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[__target] keyword[is] keyword[not] keyword[None] :
keyword[return] identifier[self] . identifier[__target] ( identifier[self] ,* identifier[self] . identifier[__args] ,** identifier[sel... | def run(self):
"""
This method is the actual implementation of the job. By default, it calls
the target function specified in the #Job constructor.
"""
if self.__target is not None:
return self.__target(self, *self.__args, **self.__kwargs) # depends on [control=['if'], data=[]]
raise No... |
def main() -> None:
"""
Command-line processor. See ``--help`` for details.
"""
main_only_quicksetup_rootlogger(level=logging.DEBUG)
parser = argparse.ArgumentParser(
formatter_class=argparse.ArgumentDefaultsHelpFormatter
)
parser.add_argument(
"input_file",
help="Inp... | def function[main, parameter[]]:
constant[
Command-line processor. See ``--help`` for details.
]
call[name[main_only_quicksetup_rootlogger], parameter[]]
variable[parser] assign[=] call[name[argparse].ArgumentParser, parameter[]]
call[name[parser].add_argument, parameter[constant... | keyword[def] identifier[main] ()-> keyword[None] :
literal[string]
identifier[main_only_quicksetup_rootlogger] ( identifier[level] = identifier[logging] . identifier[DEBUG] )
identifier[parser] = identifier[argparse] . identifier[ArgumentParser] (
identifier[formatter_class] = identifier[argparse... | def main() -> None:
"""
Command-line processor. See ``--help`` for details.
"""
main_only_quicksetup_rootlogger(level=logging.DEBUG)
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('input_file', help='Input PDF (which is not modified b... |
def clear_mode(self, mode, value=None):
"""Clear mode on the channel.
Arguments:
mode -- The mode (a single-character string).
value -- Value
"""
try:
if mode in self.user_modes:
del self.mode_users[mode][value]
else:
... | def function[clear_mode, parameter[self, mode, value]]:
constant[Clear mode on the channel.
Arguments:
mode -- The mode (a single-character string).
value -- Value
]
<ast.Try object at 0x7da2049607c0> | keyword[def] identifier[clear_mode] ( identifier[self] , identifier[mode] , identifier[value] = keyword[None] ):
literal[string]
keyword[try] :
keyword[if] identifier[mode] keyword[in] identifier[self] . identifier[user_modes] :
keyword[del] identifier[self] . iden... | def clear_mode(self, mode, value=None):
"""Clear mode on the channel.
Arguments:
mode -- The mode (a single-character string).
value -- Value
"""
try:
if mode in self.user_modes:
del self.mode_users[mode][value] # depends on [control=['if'], data=[... |
def get_scan_results_xml(self, scan_id, pop_res):
""" Gets scan_id scan's results in XML format.
@return: String of scan results in xml.
"""
results = Element('results')
for result in self.scan_collection.results_iterator(scan_id, pop_res):
results.append(get_result_... | def function[get_scan_results_xml, parameter[self, scan_id, pop_res]]:
constant[ Gets scan_id scan's results in XML format.
@return: String of scan results in xml.
]
variable[results] assign[=] call[name[Element], parameter[constant[results]]]
for taget[name[result]] in starred[... | keyword[def] identifier[get_scan_results_xml] ( identifier[self] , identifier[scan_id] , identifier[pop_res] ):
literal[string]
identifier[results] = identifier[Element] ( literal[string] )
keyword[for] identifier[result] keyword[in] identifier[self] . identifier[scan_collection] . iden... | def get_scan_results_xml(self, scan_id, pop_res):
""" Gets scan_id scan's results in XML format.
@return: String of scan results in xml.
"""
results = Element('results')
for result in self.scan_collection.results_iterator(scan_id, pop_res):
results.append(get_result_xml(result)) # ... |
def parse_fn(fn):
""" This parses the file name and returns the coordinates of the tile
Parameters
-----------
fn : str
Filename of a GEOTIFF
Returns
--------
coords = [LLC.lat, LLC.lon, URC.lat, URC.lon]
"""
try:
parts = os.path.splitext(os.path.split(fn)[-1])[0].r... | def function[parse_fn, parameter[fn]]:
constant[ This parses the file name and returns the coordinates of the tile
Parameters
-----------
fn : str
Filename of a GEOTIFF
Returns
--------
coords = [LLC.lat, LLC.lon, URC.lat, URC.lon]
]
<ast.Try object at 0x7da2041db5e0>
... | keyword[def] identifier[parse_fn] ( identifier[fn] ):
literal[string]
keyword[try] :
identifier[parts] = identifier[os] . identifier[path] . identifier[splitext] ( identifier[os] . identifier[path] . identifier[split] ( identifier[fn] )[- literal[int] ])[ literal[int] ]. identifier[replace] ( lite... | def parse_fn(fn):
""" This parses the file name and returns the coordinates of the tile
Parameters
-----------
fn : str
Filename of a GEOTIFF
Returns
--------
coords = [LLC.lat, LLC.lon, URC.lat, URC.lon]
"""
try:
parts = os.path.splitext(os.path.split(fn)[-1])[0].r... |
def html_page(title="Page Title", body=""):
"""Create HTML page as string."""
html = "<html>\n<head><title>%s</title></head>\n<body>\n" % (title)
html += "<h1>%s</h1>\n" % (title)
html += body
html += "</body>\n</html>\n"
return html | def function[html_page, parameter[title, body]]:
constant[Create HTML page as string.]
variable[html] assign[=] binary_operation[constant[<html>
<head><title>%s</title></head>
<body>
] <ast.Mod object at 0x7da2590d6920> name[title]]
<ast.AugAssign object at 0x7da20c76c1c0>
<ast.AugAssign object ... | keyword[def] identifier[html_page] ( identifier[title] = literal[string] , identifier[body] = literal[string] ):
literal[string]
identifier[html] = literal[string] %( identifier[title] )
identifier[html] += literal[string] %( identifier[title] )
identifier[html] += identifier[body]
identifi... | def html_page(title='Page Title', body=''):
"""Create HTML page as string."""
html = '<html>\n<head><title>%s</title></head>\n<body>\n' % title
html += '<h1>%s</h1>\n' % title
html += body
html += '</body>\n</html>\n'
return html |
def _init_log(level=logging.DEBUG):
"""Initialise the logging object.
Args:
level (int): Logging level.
Returns:
Logger: Python logging object.
"""
log = logging.getLogger(__file__)
log.setLevel(level)
handler = logging.StreamHandler(sys.stdout)
handler.setLevel(level)
... | def function[_init_log, parameter[level]]:
constant[Initialise the logging object.
Args:
level (int): Logging level.
Returns:
Logger: Python logging object.
]
variable[log] assign[=] call[name[logging].getLogger, parameter[name[__file__]]]
call[name[log].setLevel, par... | keyword[def] identifier[_init_log] ( identifier[level] = identifier[logging] . identifier[DEBUG] ):
literal[string]
identifier[log] = identifier[logging] . identifier[getLogger] ( identifier[__file__] )
identifier[log] . identifier[setLevel] ( identifier[level] )
identifier[handler] = identifier[... | def _init_log(level=logging.DEBUG):
"""Initialise the logging object.
Args:
level (int): Logging level.
Returns:
Logger: Python logging object.
"""
log = logging.getLogger(__file__)
log.setLevel(level)
handler = logging.StreamHandler(sys.stdout)
handler.setLevel(level)
... |
def listRoles(self, *args, **kwargs):
"""
List Roles
Get a list of all roles, each role object also includes the list of
scopes it expands to.
This method gives output: ``v1/list-roles-response.json#``
This method is ``stable``
"""
return self._makeApi... | def function[listRoles, parameter[self]]:
constant[
List Roles
Get a list of all roles, each role object also includes the list of
scopes it expands to.
This method gives output: ``v1/list-roles-response.json#``
This method is ``stable``
]
return[call[name[... | keyword[def] identifier[listRoles] ( identifier[self] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
keyword[return] identifier[self] . identifier[_makeApiCall] ( identifier[self] . identifier[funcinfo] [ literal[string] ],* identifier[args] ,** identifier[kwargs] ) | def listRoles(self, *args, **kwargs):
"""
List Roles
Get a list of all roles, each role object also includes the list of
scopes it expands to.
This method gives output: ``v1/list-roles-response.json#``
This method is ``stable``
"""
return self._makeApiCall(self... |
def get_icon_for(self, brain_or_object):
"""Get the navigation portlet icon for the brain or object
The cache key ensures that the lookup is done only once per domain name
"""
portal_types = api.get_tool("portal_types")
fti = portal_types.getTypeInfo(api.get_portal_type(brain_or... | def function[get_icon_for, parameter[self, brain_or_object]]:
constant[Get the navigation portlet icon for the brain or object
The cache key ensures that the lookup is done only once per domain name
]
variable[portal_types] assign[=] call[name[api].get_tool, parameter[constant[portal_ty... | keyword[def] identifier[get_icon_for] ( identifier[self] , identifier[brain_or_object] ):
literal[string]
identifier[portal_types] = identifier[api] . identifier[get_tool] ( literal[string] )
identifier[fti] = identifier[portal_types] . identifier[getTypeInfo] ( identifier[api] . identifie... | def get_icon_for(self, brain_or_object):
"""Get the navigation portlet icon for the brain or object
The cache key ensures that the lookup is done only once per domain name
"""
portal_types = api.get_tool('portal_types')
fti = portal_types.getTypeInfo(api.get_portal_type(brain_or_object))
... |
def clinsig_human(variant_obj):
"""Convert to human readable version of CLINSIG evaluation."""
for clinsig_obj in variant_obj['clnsig']:
# The clinsig objects allways have a accession
if isinstance(clinsig_obj['accession'], int):
# New version
link = "https://www.ncbi.nlm... | def function[clinsig_human, parameter[variant_obj]]:
constant[Convert to human readable version of CLINSIG evaluation.]
for taget[name[clinsig_obj]] in starred[call[name[variant_obj]][constant[clnsig]]] begin[:]
if call[name[isinstance], parameter[call[name[clinsig_obj]][constant[accessi... | keyword[def] identifier[clinsig_human] ( identifier[variant_obj] ):
literal[string]
keyword[for] identifier[clinsig_obj] keyword[in] identifier[variant_obj] [ literal[string] ]:
keyword[if] identifier[isinstance] ( identifier[clinsig_obj] [ literal[string] ], identifier[int] ):
... | def clinsig_human(variant_obj):
"""Convert to human readable version of CLINSIG evaluation."""
for clinsig_obj in variant_obj['clnsig']:
# The clinsig objects allways have a accession
if isinstance(clinsig_obj['accession'], int):
# New version
link = 'https://www.ncbi.nlm... |
def reset(self):
"""Reset the service to its' initial state."""
logger.debug('StackInABoxService ({0}): Reset'
.format(self.__id, self.name))
self.base_url = '/{0}'.format(self.name)
logger.debug('StackInABoxService ({0}): Hosting Service {1}'
.f... | def function[reset, parameter[self]]:
constant[Reset the service to its' initial state.]
call[name[logger].debug, parameter[call[constant[StackInABoxService ({0}): Reset].format, parameter[name[self].__id, name[self].name]]]]
name[self].base_url assign[=] call[constant[/{0}].format, parameter[na... | keyword[def] identifier[reset] ( identifier[self] ):
literal[string]
identifier[logger] . identifier[debug] ( literal[string]
. identifier[format] ( identifier[self] . identifier[__id] , identifier[self] . identifier[name] ))
identifier[self] . identifier[base_url] = literal[strin... | def reset(self):
"""Reset the service to its' initial state."""
logger.debug('StackInABoxService ({0}): Reset'.format(self.__id, self.name))
self.base_url = '/{0}'.format(self.name)
logger.debug('StackInABoxService ({0}): Hosting Service {1}'.format(self.__id, self.name)) |
def invoke_hook_emit(self, values, stream_id, out_tasks):
"""invoke task hooks for every time a tuple is emitted in spout/bolt
:type values: list
:param values: values emitted
:type stream_id: str
:param stream_id: stream id into which tuple is emitted
:type out_tasks: list
:param out_tasks... | def function[invoke_hook_emit, parameter[self, values, stream_id, out_tasks]]:
constant[invoke task hooks for every time a tuple is emitted in spout/bolt
:type values: list
:param values: values emitted
:type stream_id: str
:param stream_id: stream id into which tuple is emitted
:type out_t... | keyword[def] identifier[invoke_hook_emit] ( identifier[self] , identifier[values] , identifier[stream_id] , identifier[out_tasks] ):
literal[string]
keyword[if] identifier[len] ( identifier[self] . identifier[task_hooks] )> literal[int] :
identifier[emit_info] = identifier[EmitInfo] ( identifier[va... | def invoke_hook_emit(self, values, stream_id, out_tasks):
"""invoke task hooks for every time a tuple is emitted in spout/bolt
:type values: list
:param values: values emitted
:type stream_id: str
:param stream_id: stream id into which tuple is emitted
:type out_tasks: list
:param out_tasks... |
def get_projects(limit=100, offset=0, last_id=None):
"""Return a list of registered projects.
:param limit: Number of returned items, default 100
:type limit: integer
:param offset: Offset for the query, default 0
:type offset: integer
:param last_id: id of the last project, used for pagination... | def function[get_projects, parameter[limit, offset, last_id]]:
constant[Return a list of registered projects.
:param limit: Number of returned items, default 100
:type limit: integer
:param offset: Offset for the query, default 0
:type offset: integer
:param last_id: id of the last project,... | keyword[def] identifier[get_projects] ( identifier[limit] = literal[int] , identifier[offset] = literal[int] , identifier[last_id] = keyword[None] ):
literal[string]
keyword[if] identifier[last_id] keyword[is] keyword[not] keyword[None] :
identifier[params] = identifier[dict] ( identifier[limi... | def get_projects(limit=100, offset=0, last_id=None):
"""Return a list of registered projects.
:param limit: Number of returned items, default 100
:type limit: integer
:param offset: Offset for the query, default 0
:type offset: integer
:param last_id: id of the last project, used for pagination... |
def _adjust_merged_values_orm(env, model_name, record_ids, target_record_id,
field_spec):
"""This method deals with the values on the records to be merged +
the target record, performing operations that makes sense on the meaning
of the model.
:param field_spec: Dictionary... | def function[_adjust_merged_values_orm, parameter[env, model_name, record_ids, target_record_id, field_spec]]:
constant[This method deals with the values on the records to be merged +
the target record, performing operations that makes sense on the meaning
of the model.
:param field_spec: Dictionar... | keyword[def] identifier[_adjust_merged_values_orm] ( identifier[env] , identifier[model_name] , identifier[record_ids] , identifier[target_record_id] ,
identifier[field_spec] ):
literal[string]
identifier[model] = identifier[env] [ identifier[model_name] ]
identifier[fields] = identifier[model] . ide... | def _adjust_merged_values_orm(env, model_name, record_ids, target_record_id, field_spec):
"""This method deals with the values on the records to be merged +
the target record, performing operations that makes sense on the meaning
of the model.
:param field_spec: Dictionary with field names as keys and ... |
def max_sharpe(self, risk_free_rate=0.02):
"""
Maximise the Sharpe Ratio. The result is also referred to as the tangency portfolio,
as it is the tangent to the efficient frontier curve that intercepts the risk-free
rate.
:param risk_free_rate: risk-free rate of borrowing/lending... | def function[max_sharpe, parameter[self, risk_free_rate]]:
constant[
Maximise the Sharpe Ratio. The result is also referred to as the tangency portfolio,
as it is the tangent to the efficient frontier curve that intercepts the risk-free
rate.
:param risk_free_rate: risk-free rat... | keyword[def] identifier[max_sharpe] ( identifier[self] , identifier[risk_free_rate] = literal[int] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[risk_free_rate] ,( identifier[int] , identifier[float] )):
keyword[raise] identifier[ValueError] ( liter... | def max_sharpe(self, risk_free_rate=0.02):
"""
Maximise the Sharpe Ratio. The result is also referred to as the tangency portfolio,
as it is the tangent to the efficient frontier curve that intercepts the risk-free
rate.
:param risk_free_rate: risk-free rate of borrowing/lending, de... |
def function_call_prepare_action(self, text, loc, fun):
"""Code executed after recognising a function call (type and function name)"""
exshared.setpos(loc, text)
if DEBUG > 0:
print("FUN_PREP:",fun)
if DEBUG == 2: self.symtab.display()
if DEBUG > 2: retu... | def function[function_call_prepare_action, parameter[self, text, loc, fun]]:
constant[Code executed after recognising a function call (type and function name)]
call[name[exshared].setpos, parameter[name[loc], name[text]]]
if compare[name[DEBUG] greater[>] constant[0]] begin[:]
ca... | keyword[def] identifier[function_call_prepare_action] ( identifier[self] , identifier[text] , identifier[loc] , identifier[fun] ):
literal[string]
identifier[exshared] . identifier[setpos] ( identifier[loc] , identifier[text] )
keyword[if] identifier[DEBUG] > literal[int] :
... | def function_call_prepare_action(self, text, loc, fun):
"""Code executed after recognising a function call (type and function name)"""
exshared.setpos(loc, text)
if DEBUG > 0:
print('FUN_PREP:', fun)
if DEBUG == 2:
self.symtab.display() # depends on [control=['if'], data=[]]
... |
def process_new_issues(self, volumes, existing_issues):
"""Takes a dict of existing volumes missing tags and a dict of existing issues, and finds any new or updated
issues.
Args:
volumes (:obj:`dict` of `str`: `EBSVolume`): Dict of current volumes with issues
existing_is... | def function[process_new_issues, parameter[self, volumes, existing_issues]]:
constant[Takes a dict of existing volumes missing tags and a dict of existing issues, and finds any new or updated
issues.
Args:
volumes (:obj:`dict` of `str`: `EBSVolume`): Dict of current volumes with iss... | keyword[def] identifier[process_new_issues] ( identifier[self] , identifier[volumes] , identifier[existing_issues] ):
literal[string]
identifier[new_issues] ={}
keyword[for] identifier[issue_id] , identifier[volume] keyword[in] identifier[volumes] . identifier[items] ():
id... | def process_new_issues(self, volumes, existing_issues):
"""Takes a dict of existing volumes missing tags and a dict of existing issues, and finds any new or updated
issues.
Args:
volumes (:obj:`dict` of `str`: `EBSVolume`): Dict of current volumes with issues
existing_issues... |
def search(self, base_dn, search_filter, attributes=()):
"""Perform an AD search
:param str base_dn: The base DN to search within
:param str search_filter: The search filter to apply, such as:
*objectClass=person*
:param list attributes: Object attributes to populate, defaults... | def function[search, parameter[self, base_dn, search_filter, attributes]]:
constant[Perform an AD search
:param str base_dn: The base DN to search within
:param str search_filter: The search filter to apply, such as:
*objectClass=person*
:param list attributes: Object attribut... | keyword[def] identifier[search] ( identifier[self] , identifier[base_dn] , identifier[search_filter] , identifier[attributes] =()):
literal[string]
identifier[results] =[]
identifier[page] = literal[int]
keyword[while] identifier[page] == literal[int] keyword[or] identifier[se... | def search(self, base_dn, search_filter, attributes=()):
"""Perform an AD search
:param str base_dn: The base DN to search within
:param str search_filter: The search filter to apply, such as:
*objectClass=person*
:param list attributes: Object attributes to populate, defaults to ... |
def reps_to_intensity(reps, slope=-4.8, constant=97.5, quadratic=True):
"""A function mapping from repetitions in the range 1 to 12
to intensities in the range 0 to 100.
Parameters
----------
reps
The number of repetitions to map to the intensity range.
slope
Slope for the linea... | def function[reps_to_intensity, parameter[reps, slope, constant, quadratic]]:
constant[A function mapping from repetitions in the range 1 to 12
to intensities in the range 0 to 100.
Parameters
----------
reps
The number of repetitions to map to the intensity range.
slope
Slo... | keyword[def] identifier[reps_to_intensity] ( identifier[reps] , identifier[slope] =- literal[int] , identifier[constant] = literal[int] , identifier[quadratic] = keyword[True] ):
literal[string]
identifier[intensity] = identifier[constant] + identifier[slope] *( identifier[reps] - literal[int] )
keywo... | def reps_to_intensity(reps, slope=-4.8, constant=97.5, quadratic=True):
"""A function mapping from repetitions in the range 1 to 12
to intensities in the range 0 to 100.
Parameters
----------
reps
The number of repetitions to map to the intensity range.
slope
Slope for the linea... |
def cmd_link_ports(self):
'''show available ports'''
ports = mavutil.auto_detect_serial(preferred_list=['*FTDI*',"*Arduino_Mega_2560*", "*3D_Robotics*", "*USB_to_UART*", '*PX4*', '*FMU*'])
for p in ports:
print("%s : %s : %s" % (p.device, p.description, p.hwid)) | def function[cmd_link_ports, parameter[self]]:
constant[show available ports]
variable[ports] assign[=] call[name[mavutil].auto_detect_serial, parameter[]]
for taget[name[p]] in starred[name[ports]] begin[:]
call[name[print], parameter[binary_operation[constant[%s : %s : %s] <ast... | keyword[def] identifier[cmd_link_ports] ( identifier[self] ):
literal[string]
identifier[ports] = identifier[mavutil] . identifier[auto_detect_serial] ( identifier[preferred_list] =[ literal[string] , literal[string] , literal[string] , literal[string] , literal[string] , literal[string] ])
... | def cmd_link_ports(self):
"""show available ports"""
ports = mavutil.auto_detect_serial(preferred_list=['*FTDI*', '*Arduino_Mega_2560*', '*3D_Robotics*', '*USB_to_UART*', '*PX4*', '*FMU*'])
for p in ports:
print('%s : %s : %s' % (p.device, p.description, p.hwid)) # depends on [control=['for'], data... |
def encode(self, word):
"""Return the Russell Index (integer output) of a word.
Parameters
----------
word : str
The word to transform
Returns
-------
int
The Russell Index value
Examples
--------
>>> pe = Russell... | def function[encode, parameter[self, word]]:
constant[Return the Russell Index (integer output) of a word.
Parameters
----------
word : str
The word to transform
Returns
-------
int
The Russell Index value
Examples
------... | keyword[def] identifier[encode] ( identifier[self] , identifier[word] ):
literal[string]
identifier[word] = identifier[unicode_normalize] ( literal[string] , identifier[text_type] ( identifier[word] . identifier[upper] ()))
identifier[word] = identifier[word] . identifier[replace] ( litera... | def encode(self, word):
"""Return the Russell Index (integer output) of a word.
Parameters
----------
word : str
The word to transform
Returns
-------
int
The Russell Index value
Examples
--------
>>> pe = RussellInde... |
def get_subpath(self, subpath: str):
"""Search a file or directory relative to the base path"""
for d in self._path:
if os.path.exists(os.path.join(d, subpath)):
return os.path.join(d, subpath)
raise FileNotFoundError | def function[get_subpath, parameter[self, subpath]]:
constant[Search a file or directory relative to the base path]
for taget[name[d]] in starred[name[self]._path] begin[:]
if call[name[os].path.exists, parameter[call[name[os].path.join, parameter[name[d], name[subpath]]]]] begin[:]
... | keyword[def] identifier[get_subpath] ( identifier[self] , identifier[subpath] : identifier[str] ):
literal[string]
keyword[for] identifier[d] keyword[in] identifier[self] . identifier[_path] :
keyword[if] identifier[os] . identifier[path] . identifier[exists] ( identifier[os] . ide... | def get_subpath(self, subpath: str):
"""Search a file or directory relative to the base path"""
for d in self._path:
if os.path.exists(os.path.join(d, subpath)):
return os.path.join(d, subpath) # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['d']]
raise File... |
def find(self, username):
"""
Find user with given username.
Args:
username Username of the user to search for
Raises:
ldap_tools.exceptions.NoUserFound: No users returned by LDAP
ldap_tools.exceptions.TooManyResults:
Multiple users r... | def function[find, parameter[self, username]]:
constant[
Find user with given username.
Args:
username Username of the user to search for
Raises:
ldap_tools.exceptions.NoUserFound: No users returned by LDAP
ldap_tools.exceptions.TooManyResults:
... | keyword[def] identifier[find] ( identifier[self] , identifier[username] ):
literal[string]
identifier[filter] =[ literal[string] . identifier[format] ( identifier[username] )]
identifier[results] = identifier[self] . identifier[client] . identifier[search] ( identifier[filter] )
... | def find(self, username):
"""
Find user with given username.
Args:
username Username of the user to search for
Raises:
ldap_tools.exceptions.NoUserFound: No users returned by LDAP
ldap_tools.exceptions.TooManyResults:
Multiple users retur... |
def _prnt_min_max_val(var, text, verb):
r"""Print variable; if more than three, just min/max, unless verb > 3."""
if var.size > 3:
print(text, _strvar(var.min()), "-", _strvar(var.max()),
":", _strvar(var.size), " [min-max; #]")
if verb > 3:
print(" : ... | def function[_prnt_min_max_val, parameter[var, text, verb]]:
constant[Print variable; if more than three, just min/max, unless verb > 3.]
if compare[name[var].size greater[>] constant[3]] begin[:]
call[name[print], parameter[name[text], call[name[_strvar], parameter[call[name[var].min, p... | keyword[def] identifier[_prnt_min_max_val] ( identifier[var] , identifier[text] , identifier[verb] ):
literal[string]
keyword[if] identifier[var] . identifier[size] > literal[int] :
identifier[print] ( identifier[text] , identifier[_strvar] ( identifier[var] . identifier[min] ()), literal[string]... | def _prnt_min_max_val(var, text, verb):
"""Print variable; if more than three, just min/max, unless verb > 3."""
if var.size > 3:
print(text, _strvar(var.min()), '-', _strvar(var.max()), ':', _strvar(var.size), ' [min-max; #]')
if verb > 3:
print(' : ', _strvar(var)... |
def ReqUserLogout(self):
"""退出接口"""
self.logined = False
time.sleep(3)
self.t.ReqUserLogout(BrokerID=self.broker, UserID=self.investor)
self.t.RegisterSpi(None)
self.t.Release()
threading.Thread(target=self.OnDisConnected, args=(self, 0)).start() | def function[ReqUserLogout, parameter[self]]:
constant[退出接口]
name[self].logined assign[=] constant[False]
call[name[time].sleep, parameter[constant[3]]]
call[name[self].t.ReqUserLogout, parameter[]]
call[name[self].t.RegisterSpi, parameter[constant[None]]]
call[name[self]... | keyword[def] identifier[ReqUserLogout] ( identifier[self] ):
literal[string]
identifier[self] . identifier[logined] = keyword[False]
identifier[time] . identifier[sleep] ( literal[int] )
identifier[self] . identifier[t] . identifier[ReqUserLogout] ( identifier[BrokerID] = identif... | def ReqUserLogout(self):
"""退出接口"""
self.logined = False
time.sleep(3)
self.t.ReqUserLogout(BrokerID=self.broker, UserID=self.investor)
self.t.RegisterSpi(None)
self.t.Release()
threading.Thread(target=self.OnDisConnected, args=(self, 0)).start() |
def Replace(self, resource, path, type, id, initial_headers, options=None):
"""Replaces a Azure Cosmos resource and returns it.
:param dict resource:
:param str path:
:param str type:
:param str id:
:param dict initial_headers:
:param dict options:
Th... | def function[Replace, parameter[self, resource, path, type, id, initial_headers, options]]:
constant[Replaces a Azure Cosmos resource and returns it.
:param dict resource:
:param str path:
:param str type:
:param str id:
:param dict initial_headers:
:param dict o... | keyword[def] identifier[Replace] ( identifier[self] , identifier[resource] , identifier[path] , identifier[type] , identifier[id] , identifier[initial_headers] , identifier[options] = keyword[None] ):
literal[string]
keyword[if] identifier[options] keyword[is] keyword[None] :
identi... | def Replace(self, resource, path, type, id, initial_headers, options=None):
"""Replaces a Azure Cosmos resource and returns it.
:param dict resource:
:param str path:
:param str type:
:param str id:
:param dict initial_headers:
:param dict options:
The re... |
def _create_cpe_parts(self, system, components):
"""
Create the structure to store the input type of system associated
with components of CPE Name (hardware, operating system and software).
:param string system: type of system associated with CPE Name
:param dict components: CPE... | def function[_create_cpe_parts, parameter[self, system, components]]:
constant[
Create the structure to store the input type of system associated
with components of CPE Name (hardware, operating system and software).
:param string system: type of system associated with CPE Name
... | keyword[def] identifier[_create_cpe_parts] ( identifier[self] , identifier[system] , identifier[components] ):
literal[string]
keyword[if] identifier[system] keyword[not] keyword[in] identifier[CPEComponent] . identifier[SYSTEM_VALUES] :
identifier[errmsg] = literal[string] . iden... | def _create_cpe_parts(self, system, components):
"""
Create the structure to store the input type of system associated
with components of CPE Name (hardware, operating system and software).
:param string system: type of system associated with CPE Name
:param dict components: CPE Nam... |
def _verify_docker_image_size(self, image_name):
"""Verifies size of Docker image.
Args:
image_name: name of the Docker image.
Returns:
True if image size is within the limits, False otherwise.
"""
shell_call(['docker', 'pull', image_name])
try:
image_size = subprocess.check_... | def function[_verify_docker_image_size, parameter[self, image_name]]:
constant[Verifies size of Docker image.
Args:
image_name: name of the Docker image.
Returns:
True if image size is within the limits, False otherwise.
]
call[name[shell_call], parameter[list[[<ast.Constant ob... | keyword[def] identifier[_verify_docker_image_size] ( identifier[self] , identifier[image_name] ):
literal[string]
identifier[shell_call] ([ literal[string] , literal[string] , identifier[image_name] ])
keyword[try] :
identifier[image_size] = identifier[subprocess] . identifier[check_output] (
... | def _verify_docker_image_size(self, image_name):
"""Verifies size of Docker image.
Args:
image_name: name of the Docker image.
Returns:
True if image size is within the limits, False otherwise.
"""
shell_call(['docker', 'pull', image_name])
try:
image_size = subprocess.chec... |
def make_options_frame(self):
""" make the frame that allows for configuration and classification"""
self.tab_frame = ttk.Notebook(self.option_frame, width=800)
self.tab_configure = tk.Frame(self.tab_frame)
self.tab_classify = tk.Frame(self.tab_frame)
self.make_configure_tab()
... | def function[make_options_frame, parameter[self]]:
constant[ make the frame that allows for configuration and classification]
name[self].tab_frame assign[=] call[name[ttk].Notebook, parameter[name[self].option_frame]]
name[self].tab_configure assign[=] call[name[tk].Frame, parameter[name[self].t... | keyword[def] identifier[make_options_frame] ( identifier[self] ):
literal[string]
identifier[self] . identifier[tab_frame] = identifier[ttk] . identifier[Notebook] ( identifier[self] . identifier[option_frame] , identifier[width] = literal[int] )
identifier[self] . identifier[tab_configure... | def make_options_frame(self):
""" make the frame that allows for configuration and classification"""
self.tab_frame = ttk.Notebook(self.option_frame, width=800)
self.tab_configure = tk.Frame(self.tab_frame)
self.tab_classify = tk.Frame(self.tab_frame)
self.make_configure_tab()
self.make_classify... |
def from_file(self, ifile, codec='ascii'):
"""Read textgrid from stream.
:param file ifile: Stream to read from.
:param str codec: Text encoding for the input. Note that this will be
ignored for binary TextGrids.
"""
if ifile.read(12) == b'ooBinaryFile':
... | def function[from_file, parameter[self, ifile, codec]]:
constant[Read textgrid from stream.
:param file ifile: Stream to read from.
:param str codec: Text encoding for the input. Note that this will be
ignored for binary TextGrids.
]
if compare[call[name[ifile].read,... | keyword[def] identifier[from_file] ( identifier[self] , identifier[ifile] , identifier[codec] = literal[string] ):
literal[string]
keyword[if] identifier[ifile] . identifier[read] ( literal[int] )== literal[string] :
keyword[def] identifier[bin2str] ( identifier[ifile] ):
... | def from_file(self, ifile, codec='ascii'):
"""Read textgrid from stream.
:param file ifile: Stream to read from.
:param str codec: Text encoding for the input. Note that this will be
ignored for binary TextGrids.
"""
if ifile.read(12) == b'ooBinaryFile':
def bin2str... |
def Nu_Yamagata(Re, Pr, Pr_pc=None, Cp_avg=None, Cp_b=None, T_b=None,
T_w=None, T_pc=None):
r'''Calculates internal convection Nusselt number for turbulent vertical
upward flow in a pipe under supercritical conditions according to [1]_.
.. math::
Nu_b = 0.0138 Re_b^{0.85}Pr_b... | def function[Nu_Yamagata, parameter[Re, Pr, Pr_pc, Cp_avg, Cp_b, T_b, T_w, T_pc]]:
constant[Calculates internal convection Nusselt number for turbulent vertical
upward flow in a pipe under supercritical conditions according to [1]_.
.. math::
Nu_b = 0.0138 Re_b^{0.85}Pr_b^{0.8}F
... | keyword[def] identifier[Nu_Yamagata] ( identifier[Re] , identifier[Pr] , identifier[Pr_pc] = keyword[None] , identifier[Cp_avg] = keyword[None] , identifier[Cp_b] = keyword[None] , identifier[T_b] = keyword[None] ,
identifier[T_w] = keyword[None] , identifier[T_pc] = keyword[None] ):
literal[string]
ident... | def Nu_Yamagata(Re, Pr, Pr_pc=None, Cp_avg=None, Cp_b=None, T_b=None, T_w=None, T_pc=None):
"""Calculates internal convection Nusselt number for turbulent vertical
upward flow in a pipe under supercritical conditions according to [1]_.
.. math::
Nu_b = 0.0138 Re_b^{0.85}Pr_b^{0.8}F
... |
def get_hpkp_pin(cls, certificate: cryptography.x509.Certificate) -> str:
"""Generate the HTTP Public Key Pinning hash (RFC 7469) for the given certificate.
"""
return b64encode(cls.get_public_key_sha256(certificate)).decode('utf-8') | def function[get_hpkp_pin, parameter[cls, certificate]]:
constant[Generate the HTTP Public Key Pinning hash (RFC 7469) for the given certificate.
]
return[call[call[name[b64encode], parameter[call[name[cls].get_public_key_sha256, parameter[name[certificate]]]]].decode, parameter[constant[utf-8]]]] | keyword[def] identifier[get_hpkp_pin] ( identifier[cls] , identifier[certificate] : identifier[cryptography] . identifier[x509] . identifier[Certificate] )-> identifier[str] :
literal[string]
keyword[return] identifier[b64encode] ( identifier[cls] . identifier[get_public_key_sha256] ( identifier[c... | def get_hpkp_pin(cls, certificate: cryptography.x509.Certificate) -> str:
"""Generate the HTTP Public Key Pinning hash (RFC 7469) for the given certificate.
"""
return b64encode(cls.get_public_key_sha256(certificate)).decode('utf-8') |
def detectMidpCapable(self):
"""Return detection of a MIDP mobile Java-capable device
Detects if the current device supports MIDP, a mobile Java technology.
"""
return UAgentInfo.deviceMidp in self.__userAgent \
or UAgentInfo.deviceMidp in self.__httpAccept | def function[detectMidpCapable, parameter[self]]:
constant[Return detection of a MIDP mobile Java-capable device
Detects if the current device supports MIDP, a mobile Java technology.
]
return[<ast.BoolOp object at 0x7da1b0b6f490>] | keyword[def] identifier[detectMidpCapable] ( identifier[self] ):
literal[string]
keyword[return] identifier[UAgentInfo] . identifier[deviceMidp] keyword[in] identifier[self] . identifier[__userAgent] keyword[or] identifier[UAgentInfo] . identifier[deviceMidp] keyword[in] identifier[self] . i... | def detectMidpCapable(self):
"""Return detection of a MIDP mobile Java-capable device
Detects if the current device supports MIDP, a mobile Java technology.
"""
return UAgentInfo.deviceMidp in self.__userAgent or UAgentInfo.deviceMidp in self.__httpAccept |
def delete_guest_property(self, name):
"""Deletes an entry from the machine's guest property store.
in name of type str
The name of the property to delete.
raises :class:`VBoxErrorInvalidVmState`
Machine session is not open.
"""
if not isinstanc... | def function[delete_guest_property, parameter[self, name]]:
constant[Deletes an entry from the machine's guest property store.
in name of type str
The name of the property to delete.
raises :class:`VBoxErrorInvalidVmState`
Machine session is not open.
]... | keyword[def] identifier[delete_guest_property] ( identifier[self] , identifier[name] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[name] , identifier[basestring] ):
keyword[raise] identifier[TypeError] ( literal[string] )
identifier[self] .... | def delete_guest_property(self, name):
"""Deletes an entry from the machine's guest property store.
in name of type str
The name of the property to delete.
raises :class:`VBoxErrorInvalidVmState`
Machine session is not open.
"""
if not isinstance(name, ... |
def get_player_verify(self, tag: crtag, apikey: str, timeout=None):
"""Check the API Key of a player.
This endpoint has been **restricted** to
certain members of the community
Raises BadRequest if the apikey is invalid
Parameters
----------
tag: str
... | def function[get_player_verify, parameter[self, tag, apikey, timeout]]:
constant[Check the API Key of a player.
This endpoint has been **restricted** to
certain members of the community
Raises BadRequest if the apikey is invalid
Parameters
----------
tag: str
... | keyword[def] identifier[get_player_verify] ( identifier[self] , identifier[tag] : identifier[crtag] , identifier[apikey] : identifier[str] , identifier[timeout] = keyword[None] ):
literal[string]
identifier[url] = identifier[self] . identifier[api] . identifier[PLAYER] + literal[string] + identifie... | def get_player_verify(self, tag: crtag, apikey: str, timeout=None):
"""Check the API Key of a player.
This endpoint has been **restricted** to
certain members of the community
Raises BadRequest if the apikey is invalid
Parameters
----------
tag: str
A va... |
def mode(series):
"""
pandas mode is "empty if nothing has 2+ occurrences."
this method always returns something:
nan if the series is empty/nan), breaking ties arbitrarily
"""
if series.notnull().sum() == 0:
return np.nan
else:
return series.value_counts().idxmax() | def function[mode, parameter[series]]:
constant[
pandas mode is "empty if nothing has 2+ occurrences."
this method always returns something:
nan if the series is empty/nan), breaking ties arbitrarily
]
if compare[call[call[name[series].notnull, parameter[]].sum, parameter[]] equal[==... | keyword[def] identifier[mode] ( identifier[series] ):
literal[string]
keyword[if] identifier[series] . identifier[notnull] (). identifier[sum] ()== literal[int] :
keyword[return] identifier[np] . identifier[nan]
keyword[else] :
keyword[return] identifier[series] . identifier[valu... | def mode(series):
"""
pandas mode is "empty if nothing has 2+ occurrences."
this method always returns something:
nan if the series is empty/nan), breaking ties arbitrarily
"""
if series.notnull().sum() == 0:
return np.nan # depends on [control=['if'], data=[]]
else:
ret... |
def wipe_partition(self, partition):
""" Deletes analysis result of partition, e.g. so a repeat
optimisation of the same partition can be done with a
different model """
for grp in partition.get_membership():
grpid = self.scorer.get_id(grp)
cache_dir = self.scorer... | def function[wipe_partition, parameter[self, partition]]:
constant[ Deletes analysis result of partition, e.g. so a repeat
optimisation of the same partition can be done with a
different model ]
for taget[name[grp]] in starred[call[name[partition].get_membership, parameter[]]] begin[:]
... | keyword[def] identifier[wipe_partition] ( identifier[self] , identifier[partition] ):
literal[string]
keyword[for] identifier[grp] keyword[in] identifier[partition] . identifier[get_membership] ():
identifier[grpid] = identifier[self] . identifier[scorer] . identifier[get_id] ( iden... | def wipe_partition(self, partition):
""" Deletes analysis result of partition, e.g. so a repeat
optimisation of the same partition can be done with a
different model """
for grp in partition.get_membership():
grpid = self.scorer.get_id(grp)
cache_dir = self.scorer.cache_dir
... |
def get_id(id):
"""Get a new id if the provided one is None."""
if id == None:
id = wx.NewId()
logger.debug('Generated new ID %s.', id)
else:
logger.debug('Using provided id %s.', id)
return id | def function[get_id, parameter[id]]:
constant[Get a new id if the provided one is None.]
if compare[name[id] equal[==] constant[None]] begin[:]
variable[id] assign[=] call[name[wx].NewId, parameter[]]
call[name[logger].debug, parameter[constant[Generated new ID %s.], name... | keyword[def] identifier[get_id] ( identifier[id] ):
literal[string]
keyword[if] identifier[id] == keyword[None] :
identifier[id] = identifier[wx] . identifier[NewId] ()
identifier[logger] . identifier[debug] ( literal[string] , identifier[id] )
keyword[else] :
identifier[logger] . identifier[debug] (... | def get_id(id):
"""Get a new id if the provided one is None."""
if id == None:
id = wx.NewId()
logger.debug('Generated new ID %s.', id) # depends on [control=['if'], data=['id']]
else:
logger.debug('Using provided id %s.', id)
return id |
def discrete_bottleneck(inputs,
hidden_size,
z_size,
filter_size,
mode=None,
bottleneck_kind="dvq",
num_blocks=2,
num_residuals=1,
... | def function[discrete_bottleneck, parameter[inputs, hidden_size, z_size, filter_size, mode, bottleneck_kind, num_blocks, num_residuals, reshape_method, projection_tensors, beta, ema, means, ema_count, ema_means, epsilon, decay, random_top_k, soft_em, num_samples, softmax_k, temperature_warmup_steps, do_hard_gumbel_soft... | keyword[def] identifier[discrete_bottleneck] ( identifier[inputs] ,
identifier[hidden_size] ,
identifier[z_size] ,
identifier[filter_size] ,
identifier[mode] = keyword[None] ,
identifier[bottleneck_kind] = literal[string] ,
identifier[num_blocks] = literal[int] ,
identifier[num_residuals] = literal[int] ,
ide... | def discrete_bottleneck(inputs, hidden_size, z_size, filter_size, mode=None, bottleneck_kind='dvq', num_blocks=2, num_residuals=1, reshape_method='slice', projection_tensors=None, beta=0.25, ema=True, means=None, ema_count=None, ema_means=None, epsilon=1e-05, decay=0.999, random_top_k=1, soft_em=False, num_samples=1, s... |
def intersection(self, *iterables):
"""
Return a new set with elements common to the set and all *iterables*.
"""
comb = self._set.intersection(*iterables)
return self._fromset(comb, key=self._key) | def function[intersection, parameter[self]]:
constant[
Return a new set with elements common to the set and all *iterables*.
]
variable[comb] assign[=] call[name[self]._set.intersection, parameter[<ast.Starred object at 0x7da1b170f4c0>]]
return[call[name[self]._fromset, parameter[nam... | keyword[def] identifier[intersection] ( identifier[self] ,* identifier[iterables] ):
literal[string]
identifier[comb] = identifier[self] . identifier[_set] . identifier[intersection] (* identifier[iterables] )
keyword[return] identifier[self] . identifier[_fromset] ( identifier[comb] , id... | def intersection(self, *iterables):
"""
Return a new set with elements common to the set and all *iterables*.
"""
comb = self._set.intersection(*iterables)
return self._fromset(comb, key=self._key) |
def documentation(self):
r"""
Configuration documentation in reStructuredText_ syntax (a string).
The purpose of the :attr:`documentation` property is to provide
documentation on the integration of :class:`ConfigLoader` into other
projects without denormalizing the required know... | def function[documentation, parameter[self]]:
constant[
Configuration documentation in reStructuredText_ syntax (a string).
The purpose of the :attr:`documentation` property is to provide
documentation on the integration of :class:`ConfigLoader` into other
projects without denor... | keyword[def] identifier[documentation] ( identifier[self] ):
literal[string]
keyword[from] identifier[humanfriendly] . identifier[tables] keyword[import] identifier[format_rst_table]
identifier[formatted_table] = identifier[format_rst_table] ([
( identifier[directory] ,
... | def documentation(self):
"""
Configuration documentation in reStructuredText_ syntax (a string).
The purpose of the :attr:`documentation` property is to provide
documentation on the integration of :class:`ConfigLoader` into other
projects without denormalizing the required knowledge... |
def predict_cumulative_hazard(self, X, times=None):
"""
Parameters
----------
X: numpy array or DataFrame
a (n,d) covariate numpy array or DataFrame. If a DataFrame, columns
can be in any order. If a numpy array, columns must be in the
same order as t... | def function[predict_cumulative_hazard, parameter[self, X, times]]:
constant[
Parameters
----------
X: numpy array or DataFrame
a (n,d) covariate numpy array or DataFrame. If a DataFrame, columns
can be in any order. If a numpy array, columns must be in the
... | keyword[def] identifier[predict_cumulative_hazard] ( identifier[self] , identifier[X] , identifier[times] = keyword[None] ):
literal[string]
keyword[if] identifier[self] . identifier[strata] :
identifier[cumulative_hazard_] = identifier[pd] . identifier[DataFrame] ()
key... | def predict_cumulative_hazard(self, X, times=None):
"""
Parameters
----------
X: numpy array or DataFrame
a (n,d) covariate numpy array or DataFrame. If a DataFrame, columns
can be in any order. If a numpy array, columns must be in the
same order as the t... |
def ReadFlowRequestsReadyForProcessing(self,
client_id,
flow_id,
next_needed_request=None):
"""Reads all requests for a flow that can be processed by the worker."""
request_dict = self.flow... | def function[ReadFlowRequestsReadyForProcessing, parameter[self, client_id, flow_id, next_needed_request]]:
constant[Reads all requests for a flow that can be processed by the worker.]
variable[request_dict] assign[=] call[name[self].flow_requests.get, parameter[tuple[[<ast.Name object at 0x7da1b1c193f0... | keyword[def] identifier[ReadFlowRequestsReadyForProcessing] ( identifier[self] ,
identifier[client_id] ,
identifier[flow_id] ,
identifier[next_needed_request] = keyword[None] ):
literal[string]
identifier[request_dict] = identifier[self] . identifier[flow_requests] . identifier[get] (( identifier[client... | def ReadFlowRequestsReadyForProcessing(self, client_id, flow_id, next_needed_request=None):
"""Reads all requests for a flow that can be processed by the worker."""
request_dict = self.flow_requests.get((client_id, flow_id), {})
response_dict = self.flow_responses.get((client_id, flow_id), {})
res = {}
... |
def thumb(self, obj):
"""
Generates html and thumbnails for admin site.
"""
format, created = Format.objects.get_or_create(name='newman_thumb',
defaults={
'max_width': 100,
'max_height': 100,
'flex... | def function[thumb, parameter[self, obj]]:
constant[
Generates html and thumbnails for admin site.
]
<ast.Tuple object at 0x7da18f09fd30> assign[=] call[name[Format].objects.get_or_create, parameter[]]
if name[created] begin[:]
name[format].sites assign[=] call[na... | keyword[def] identifier[thumb] ( identifier[self] , identifier[obj] ):
literal[string]
identifier[format] , identifier[created] = identifier[Format] . identifier[objects] . identifier[get_or_create] ( identifier[name] = literal[string] ,
identifier[defaults] ={
literal[string] : l... | def thumb(self, obj):
"""
Generates html and thumbnails for admin site.
"""
(format, created) = Format.objects.get_or_create(name='newman_thumb', defaults={'max_width': 100, 'max_height': 100, 'flexible_height': False, 'stretch': False, 'nocrop': True})
if created:
format.sites = Sit... |
def print_network_spec(mlmodel_spec, interface_only=False):
""" Print the network information summary.
Args:
mlmodel_spec : the mlmodel spec
interface_only : Shows only the input and output of the network
"""
inputs, outputs, layers_info = summarize_neural_network_spec(mlmodel_spec)
print('... | def function[print_network_spec, parameter[mlmodel_spec, interface_only]]:
constant[ Print the network information summary.
Args:
mlmodel_spec : the mlmodel spec
interface_only : Shows only the input and output of the network
]
<ast.Tuple object at 0x7da1b1f774c0> assign[=] call[name[sum... | keyword[def] identifier[print_network_spec] ( identifier[mlmodel_spec] , identifier[interface_only] = keyword[False] ):
literal[string]
identifier[inputs] , identifier[outputs] , identifier[layers_info] = identifier[summarize_neural_network_spec] ( identifier[mlmodel_spec] )
identifier[print] ( liter... | def print_network_spec(mlmodel_spec, interface_only=False):
""" Print the network information summary.
Args:
mlmodel_spec : the mlmodel spec
interface_only : Shows only the input and output of the network
"""
(inputs, outputs, layers_info) = summarize_neural_network_spec(mlmodel_spec)
print(... |
def hyperprior(self):
"""Combined hyperprior for the kernel, noise kernel and (if present) mean function.
"""
hp = self.k.hyperprior * self.noise_k.hyperprior
if self.mu is not None:
hp *= self.mu.hyperprior
return hp | def function[hyperprior, parameter[self]]:
constant[Combined hyperprior for the kernel, noise kernel and (if present) mean function.
]
variable[hp] assign[=] binary_operation[name[self].k.hyperprior * name[self].noise_k.hyperprior]
if compare[name[self].mu is_not constant[None]] begin[:]... | keyword[def] identifier[hyperprior] ( identifier[self] ):
literal[string]
identifier[hp] = identifier[self] . identifier[k] . identifier[hyperprior] * identifier[self] . identifier[noise_k] . identifier[hyperprior]
keyword[if] identifier[self] . identifier[mu] keyword[is] keyword[not] ... | def hyperprior(self):
"""Combined hyperprior for the kernel, noise kernel and (if present) mean function.
"""
hp = self.k.hyperprior * self.noise_k.hyperprior
if self.mu is not None:
hp *= self.mu.hyperprior # depends on [control=['if'], data=[]]
return hp |
def remove_all_gap_columns( self ):
"""
Remove any columns containing only gaps from alignment components,
text of components is modified IN PLACE.
"""
seqs = []
for c in self.components:
try:
seqs.append( list( c.text ) )
except Ty... | def function[remove_all_gap_columns, parameter[self]]:
constant[
Remove any columns containing only gaps from alignment components,
text of components is modified IN PLACE.
]
variable[seqs] assign[=] list[[]]
for taget[name[c]] in starred[name[self].components] begin[:]
... | keyword[def] identifier[remove_all_gap_columns] ( identifier[self] ):
literal[string]
identifier[seqs] =[]
keyword[for] identifier[c] keyword[in] identifier[self] . identifier[components] :
keyword[try] :
identifier[seqs] . identifier[append] ( identifier[l... | def remove_all_gap_columns(self):
"""
Remove any columns containing only gaps from alignment components,
text of components is modified IN PLACE.
"""
seqs = []
for c in self.components:
try:
seqs.append(list(c.text)) # depends on [control=['try'], data=[]]
... |
def copyNodeList(self):
"""Do a recursive copy of the node list. Use
xmlDocCopyNodeList() if possible to ensure string interning. """
ret = libxml2mod.xmlCopyNodeList(self._o)
if ret is None:raise treeError('xmlCopyNodeList() failed')
__tmp = xmlNode(_obj=ret)
return __... | def function[copyNodeList, parameter[self]]:
constant[Do a recursive copy of the node list. Use
xmlDocCopyNodeList() if possible to ensure string interning. ]
variable[ret] assign[=] call[name[libxml2mod].xmlCopyNodeList, parameter[name[self]._o]]
if compare[name[ret] is constant[None]... | keyword[def] identifier[copyNodeList] ( identifier[self] ):
literal[string]
identifier[ret] = identifier[libxml2mod] . identifier[xmlCopyNodeList] ( identifier[self] . identifier[_o] )
keyword[if] identifier[ret] keyword[is] keyword[None] : keyword[raise] identifier[treeError] ( litera... | def copyNodeList(self):
"""Do a recursive copy of the node list. Use
xmlDocCopyNodeList() if possible to ensure string interning. """
ret = libxml2mod.xmlCopyNodeList(self._o)
if ret is None:
raise treeError('xmlCopyNodeList() failed') # depends on [control=['if'], data=[]]
__tmp = xm... |
def _create_sata_controllers(sata_controllers):
'''
Returns a list of vim.vm.device.VirtualDeviceSpec objects representing
SATA controllers
sata_controllers
SATA properties
'''
sata_ctrls = []
keys = range(-15000, -15050, -1)
if sata_controllers:
devs = [sata['adapter'] ... | def function[_create_sata_controllers, parameter[sata_controllers]]:
constant[
Returns a list of vim.vm.device.VirtualDeviceSpec objects representing
SATA controllers
sata_controllers
SATA properties
]
variable[sata_ctrls] assign[=] list[[]]
variable[keys] assign[=] call... | keyword[def] identifier[_create_sata_controllers] ( identifier[sata_controllers] ):
literal[string]
identifier[sata_ctrls] =[]
identifier[keys] = identifier[range] (- literal[int] ,- literal[int] ,- literal[int] )
keyword[if] identifier[sata_controllers] :
identifier[devs] =[ identifier... | def _create_sata_controllers(sata_controllers):
"""
Returns a list of vim.vm.device.VirtualDeviceSpec objects representing
SATA controllers
sata_controllers
SATA properties
"""
sata_ctrls = []
keys = range(-15000, -15050, -1)
if sata_controllers:
devs = [sata['adapter'] ... |
def federated_query(self,
environment_id,
filter=None,
query=None,
natural_language_query=None,
passages=None,
aggregation=None,
count=None,
... | def function[federated_query, parameter[self, environment_id, filter, query, natural_language_query, passages, aggregation, count, return_fields, offset, sort, highlight, passages_fields, passages_count, passages_characters, deduplicate, deduplicate_field, collection_ids, similar, similar_document_ids, similar_fields, ... | keyword[def] identifier[federated_query] ( identifier[self] ,
identifier[environment_id] ,
identifier[filter] = keyword[None] ,
identifier[query] = keyword[None] ,
identifier[natural_language_query] = keyword[None] ,
identifier[passages] = keyword[None] ,
identifier[aggregation] = keyword[None] ,
identifier[co... | def federated_query(self, environment_id, filter=None, query=None, natural_language_query=None, passages=None, aggregation=None, count=None, return_fields=None, offset=None, sort=None, highlight=None, passages_fields=None, passages_count=None, passages_characters=None, deduplicate=None, deduplicate_field=None, collecti... |
def _interpolate(self, colors, n=100):
""" Returns intermediary colors for given list of colors.
"""
gradient = []
for i in _range(n):
l = len(colors) - 1
x = int(1.0 * i / n * l)
x = min(x + 0, l)
y = min(x + 1, l)
base = 1.... | def function[_interpolate, parameter[self, colors, n]]:
constant[ Returns intermediary colors for given list of colors.
]
variable[gradient] assign[=] list[[]]
for taget[name[i]] in starred[call[name[_range], parameter[name[n]]]] begin[:]
variable[l] assign[=] binary_oper... | keyword[def] identifier[_interpolate] ( identifier[self] , identifier[colors] , identifier[n] = literal[int] ):
literal[string]
identifier[gradient] =[]
keyword[for] identifier[i] keyword[in] identifier[_range] ( identifier[n] ):
identifier[l] = identifier[len] ( identifi... | def _interpolate(self, colors, n=100):
""" Returns intermediary colors for given list of colors.
"""
gradient = []
for i in _range(n):
l = len(colors) - 1
x = int(1.0 * i / n * l)
x = min(x + 0, l)
y = min(x + 1, l)
base = 1.0 * n / l * x
d = (i - base... |
def highlight_project_bid(session, bid_id):
"""
Highlight a bid on a project
"""
headers = {
'Content-Type': 'application/x-www-form-urlencoded'
}
bid_data = {
'action': 'highlight'
}
# POST /api/projects/0.1/bids/{bid_id}/?action=revoke
endpoint = 'bids/{}'.format(bi... | def function[highlight_project_bid, parameter[session, bid_id]]:
constant[
Highlight a bid on a project
]
variable[headers] assign[=] dictionary[[<ast.Constant object at 0x7da18dc07d30>], [<ast.Constant object at 0x7da18dc07280>]]
variable[bid_data] assign[=] dictionary[[<ast.Constant ob... | keyword[def] identifier[highlight_project_bid] ( identifier[session] , identifier[bid_id] ):
literal[string]
identifier[headers] ={
literal[string] : literal[string]
}
identifier[bid_data] ={
literal[string] : literal[string]
}
identifier[endpoint] = literal[string] . ide... | def highlight_project_bid(session, bid_id):
"""
Highlight a bid on a project
"""
headers = {'Content-Type': 'application/x-www-form-urlencoded'}
bid_data = {'action': 'highlight'}
# POST /api/projects/0.1/bids/{bid_id}/?action=revoke
endpoint = 'bids/{}'.format(bid_id)
response = make_pu... |
def plot_heatmap(self, kind="final", min_freq=0.01, threshold=2, name=True, max_len=50, aspect=1, **kwargs):
"""Plot clustered heatmap of predicted motif activity.
Parameters
----------
kind : str, optional
Which data type to use for plotting. Default is 'final', whi... | def function[plot_heatmap, parameter[self, kind, min_freq, threshold, name, max_len, aspect]]:
constant[Plot clustered heatmap of predicted motif activity.
Parameters
----------
kind : str, optional
Which data type to use for plotting. Default is 'final', which will ... | keyword[def] identifier[plot_heatmap] ( identifier[self] , identifier[kind] = literal[string] , identifier[min_freq] = literal[int] , identifier[threshold] = literal[int] , identifier[name] = keyword[True] , identifier[max_len] = literal[int] , identifier[aspect] = literal[int] ,** identifier[kwargs] ):
lite... | def plot_heatmap(self, kind='final', min_freq=0.01, threshold=2, name=True, max_len=50, aspect=1, **kwargs):
"""Plot clustered heatmap of predicted motif activity.
Parameters
----------
kind : str, optional
Which data type to use for plotting. Default is 'final', which w... |
def set_direction(self, new_direction):
"""
Set image direction
Arguments
---------
new_direction : numpy.ndarray or tuple or list
updated direction for the image.
should have one value for each dimension
Returns
-------
None
... | def function[set_direction, parameter[self, new_direction]]:
constant[
Set image direction
Arguments
---------
new_direction : numpy.ndarray or tuple or list
updated direction for the image.
should have one value for each dimension
Returns
... | keyword[def] identifier[set_direction] ( identifier[self] , identifier[new_direction] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[new_direction] ,( identifier[tuple] , identifier[list] )):
identifier[new_direction] = identifier[np] . identifier[asarray] ( identi... | def set_direction(self, new_direction):
"""
Set image direction
Arguments
---------
new_direction : numpy.ndarray or tuple or list
updated direction for the image.
should have one value for each dimension
Returns
-------
None
... |
def get_datacenter(conn):
'''
Return the datacenter from the config provider datacenter ID
'''
datacenter_id = get_datacenter_id()
for item in conn.list_datacenters()['items']:
if item['id'] == datacenter_id:
return item
raise SaltCloudNotFound(
'The specified datac... | def function[get_datacenter, parameter[conn]]:
constant[
Return the datacenter from the config provider datacenter ID
]
variable[datacenter_id] assign[=] call[name[get_datacenter_id], parameter[]]
for taget[name[item]] in starred[call[call[name[conn].list_datacenters, parameter[]]][const... | keyword[def] identifier[get_datacenter] ( identifier[conn] ):
literal[string]
identifier[datacenter_id] = identifier[get_datacenter_id] ()
keyword[for] identifier[item] keyword[in] identifier[conn] . identifier[list_datacenters] ()[ literal[string] ]:
keyword[if] identifier[item] [ liter... | def get_datacenter(conn):
"""
Return the datacenter from the config provider datacenter ID
"""
datacenter_id = get_datacenter_id()
for item in conn.list_datacenters()['items']:
if item['id'] == datacenter_id:
return item # depends on [control=['if'], data=[]] # depends on [cont... |
def conv_to_json(obj, fields=None):
"""
return cdx as json dictionary string
if ``fields`` is ``None``, output will include all fields
in order stored, otherwise only specified fields will be
included
:param fields: list of field names to output
"""
if fi... | def function[conv_to_json, parameter[obj, fields]]:
constant[
return cdx as json dictionary string
if ``fields`` is ``None``, output will include all fields
in order stored, otherwise only specified fields will be
included
:param fields: list of field names to output
... | keyword[def] identifier[conv_to_json] ( identifier[obj] , identifier[fields] = keyword[None] ):
literal[string]
keyword[if] identifier[fields] keyword[is] keyword[None] :
keyword[return] identifier[json_encode] ( identifier[OrderedDict] ((( identifier[x] , identifier[obj] [ identif... | def conv_to_json(obj, fields=None):
"""
return cdx as json dictionary string
if ``fields`` is ``None``, output will include all fields
in order stored, otherwise only specified fields will be
included
:param fields: list of field names to output
"""
if fields is ... |
def _special_method_cache(method, cache_wrapper):
"""
Because Python treats special methods differently, it's not
possible to use instance attributes to implement the cached
methods.
Instead, install the wrapper method under a different name
and return a simple proxy to that wrapper.
https://github.com/jaraco/... | def function[_special_method_cache, parameter[method, cache_wrapper]]:
constant[
Because Python treats special methods differently, it's not
possible to use instance attributes to implement the cached
methods.
Instead, install the wrapper method under a different name
and return a simple proxy to that wra... | keyword[def] identifier[_special_method_cache] ( identifier[method] , identifier[cache_wrapper] ):
literal[string]
identifier[name] = identifier[method] . identifier[__name__]
identifier[special_names] = literal[string] , literal[string]
keyword[if] identifier[name] keyword[not] keyword[in] identifier[... | def _special_method_cache(method, cache_wrapper):
"""
Because Python treats special methods differently, it's not
possible to use instance attributes to implement the cached
methods.
Instead, install the wrapper method under a different name
and return a simple proxy to that wrapper.
https://github.com/jara... |
def create_from_request_pdu(pdu):
""" Create instance from request PDU.
This method requires some clarification regarding the unpacking of
the status that are being passed to the callbacks.
A coil status can be 0 or 1. The request PDU contains at least 1 byte,
representing the ... | def function[create_from_request_pdu, parameter[pdu]]:
constant[ Create instance from request PDU.
This method requires some clarification regarding the unpacking of
the status that are being passed to the callbacks.
A coil status can be 0 or 1. The request PDU contains at least 1 byte... | keyword[def] identifier[create_from_request_pdu] ( identifier[pdu] ):
literal[string]
identifier[_] , identifier[starting_address] , identifier[quantity] , identifier[byte_count] = identifier[struct] . identifier[unpack] ( literal[string] , identifier[pdu] [: literal[int] ])
identifier[fm... | def create_from_request_pdu(pdu):
""" Create instance from request PDU.
This method requires some clarification regarding the unpacking of
the status that are being passed to the callbacks.
A coil status can be 0 or 1. The request PDU contains at least 1 byte,
representing the stat... |
def parse_yaml(self, y):
'''Parse a YAML specification of a target port into this object.'''
super(TargetPort, self).parse_yaml(y)
self.port_name = y['portName']
return self | def function[parse_yaml, parameter[self, y]]:
constant[Parse a YAML specification of a target port into this object.]
call[call[name[super], parameter[name[TargetPort], name[self]]].parse_yaml, parameter[name[y]]]
name[self].port_name assign[=] call[name[y]][constant[portName]]
return[name[s... | keyword[def] identifier[parse_yaml] ( identifier[self] , identifier[y] ):
literal[string]
identifier[super] ( identifier[TargetPort] , identifier[self] ). identifier[parse_yaml] ( identifier[y] )
identifier[self] . identifier[port_name] = identifier[y] [ literal[string] ]
keyword[... | def parse_yaml(self, y):
"""Parse a YAML specification of a target port into this object."""
super(TargetPort, self).parse_yaml(y)
self.port_name = y['portName']
return self |
def check_bounds(args, lowerLimit, upperLimit):
"""
checks whether the parameter vector has left its bound, if so, adds a big number
"""
penalty = 0
bound_hit = False
for i in range(0, len(args)):
if args[i] < lowerLimit[i] or args[i] > upperLimit[i]:
... | def function[check_bounds, parameter[args, lowerLimit, upperLimit]]:
constant[
checks whether the parameter vector has left its bound, if so, adds a big number
]
variable[penalty] assign[=] constant[0]
variable[bound_hit] assign[=] constant[False]
for taget[name[i]] in st... | keyword[def] identifier[check_bounds] ( identifier[args] , identifier[lowerLimit] , identifier[upperLimit] ):
literal[string]
identifier[penalty] = literal[int]
identifier[bound_hit] = keyword[False]
keyword[for] identifier[i] keyword[in] identifier[range] ( literal[int] , id... | def check_bounds(args, lowerLimit, upperLimit):
"""
checks whether the parameter vector has left its bound, if so, adds a big number
"""
penalty = 0
bound_hit = False
for i in range(0, len(args)):
if args[i] < lowerLimit[i] or args[i] > upperLimit[i]:
penalty = 10 ** ... |
def applyRule( self ):
"""
Applies the rule from the builder system to this line edit.
"""
widget = self.queryBuilderWidget()
if ( not widget ):
return
rule = widget.findRule(self.uiTermDDL.currentText())
self.setCurrentRule(rule) | def function[applyRule, parameter[self]]:
constant[
Applies the rule from the builder system to this line edit.
]
variable[widget] assign[=] call[name[self].queryBuilderWidget, parameter[]]
if <ast.UnaryOp object at 0x7da1b2469690> begin[:]
return[None]
variable[r... | keyword[def] identifier[applyRule] ( identifier[self] ):
literal[string]
identifier[widget] = identifier[self] . identifier[queryBuilderWidget] ()
keyword[if] ( keyword[not] identifier[widget] ):
keyword[return]
identifier[rule] = identifier[widget] . identifier[fi... | def applyRule(self):
"""
Applies the rule from the builder system to this line edit.
"""
widget = self.queryBuilderWidget()
if not widget:
return # depends on [control=['if'], data=[]]
rule = widget.findRule(self.uiTermDDL.currentText())
self.setCurrentRule(rule) |
def worker(work_unit, max_sample=1000):
'''Expects a coordinate WorkUnit for DragNet and runs the following
steps:
1. scans all dossiers at the *folder* level and assembles feature
vectors for each folder -- see `make_feature`
2. trains a multinomial naive Bayes classifier that treats each
*fo... | def function[worker, parameter[work_unit, max_sample]]:
constant[Expects a coordinate WorkUnit for DragNet and runs the following
steps:
1. scans all dossiers at the *folder* level and assembles feature
vectors for each folder -- see `make_feature`
2. trains a multinomial naive Bayes classifie... | keyword[def] identifier[worker] ( identifier[work_unit] , identifier[max_sample] = literal[int] ):
literal[string]
keyword[if] literal[string] keyword[not] keyword[in] identifier[work_unit] . identifier[spec] :
keyword[raise] identifier[coordinate] . identifier[exceptions] . identifier[Progra... | def worker(work_unit, max_sample=1000):
"""Expects a coordinate WorkUnit for DragNet and runs the following
steps:
1. scans all dossiers at the *folder* level and assembles feature
vectors for each folder -- see `make_feature`
2. trains a multinomial naive Bayes classifier that treats each
*fo... |
def broadcast_variables(*variables):
"""Given any number of variables, return variables with matching dimensions
and broadcast data.
The data on the returned variables will be a view of the data on the
corresponding original arrays, but dimensions will be reordered and
inserted so that both broadca... | def function[broadcast_variables, parameter[]]:
constant[Given any number of variables, return variables with matching dimensions
and broadcast data.
The data on the returned variables will be a view of the data on the
corresponding original arrays, but dimensions will be reordered and
inserted... | keyword[def] identifier[broadcast_variables] (* identifier[variables] ):
literal[string]
identifier[dims_map] = identifier[_unified_dims] ( identifier[variables] )
identifier[dims_tuple] = identifier[tuple] ( identifier[dims_map] )
keyword[return] identifier[tuple] ( identifier[var] . identifier... | def broadcast_variables(*variables):
"""Given any number of variables, return variables with matching dimensions
and broadcast data.
The data on the returned variables will be a view of the data on the
corresponding original arrays, but dimensions will be reordered and
inserted so that both broadca... |
def findProgram(self, builddir, program):
''' Return the builddir-relative path of program, if only a partial
path is specified. Returns None and logs an error message if the
program is ambiguous or not found
'''
# if this is an exact match, do no further checking:
if os... | def function[findProgram, parameter[self, builddir, program]]:
constant[ Return the builddir-relative path of program, if only a partial
path is specified. Returns None and logs an error message if the
program is ambiguous or not found
]
if call[name[os].path.isfile, parameter[c... | keyword[def] identifier[findProgram] ( identifier[self] , identifier[builddir] , identifier[program] ):
literal[string]
keyword[if] identifier[os] . identifier[path] . identifier[isfile] ( identifier[os] . identifier[path] . identifier[join] ( identifier[builddir] , identifier[program] ))... | def findProgram(self, builddir, program):
""" Return the builddir-relative path of program, if only a partial
path is specified. Returns None and logs an error message if the
program is ambiguous or not found
"""
# if this is an exact match, do no further checking:
if os.path.isfile... |
def format_html(format_string, *args, **kwargs):
"""
Similar to str.format, but passes all arguments through conditional_escape,
and calls 'mark_safe' on the result. This function should be used instead
of str.format or % interpolation to build up small HTML fragments.
"""
args_safe = map(condit... | def function[format_html, parameter[format_string]]:
constant[
Similar to str.format, but passes all arguments through conditional_escape,
and calls 'mark_safe' on the result. This function should be used instead
of str.format or % interpolation to build up small HTML fragments.
]
variab... | keyword[def] identifier[format_html] ( identifier[format_string] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
identifier[args_safe] = identifier[map] ( identifier[conditional_escape] , identifier[args] )
identifier[kwargs_safe] = identifier[dict] ([( identifier[k] , identifier[conditi... | def format_html(format_string, *args, **kwargs):
"""
Similar to str.format, but passes all arguments through conditional_escape,
and calls 'mark_safe' on the result. This function should be used instead
of str.format or % interpolation to build up small HTML fragments.
"""
args_safe = map(condit... |
def items(self, folder_id, subfolder_id, ann_id=None):
'''Yields an unodered generator of items in a subfolder.
The generator yields items, which are represented by a tuple
of ``content_id`` and ``subtopic_id``. The format of these
identifiers is unspecified.
By default (with `... | def function[items, parameter[self, folder_id, subfolder_id, ann_id]]:
constant[Yields an unodered generator of items in a subfolder.
The generator yields items, which are represented by a tuple
of ``content_id`` and ``subtopic_id``. The format of these
identifiers is unspecified.
... | keyword[def] identifier[items] ( identifier[self] , identifier[folder_id] , identifier[subfolder_id] , identifier[ann_id] = keyword[None] ):
literal[string]
identifier[self] . identifier[assert_valid_folder_id] ( identifier[folder_id] )
identifier[self] . identifier[assert_valid_folder_id]... | def items(self, folder_id, subfolder_id, ann_id=None):
"""Yields an unodered generator of items in a subfolder.
The generator yields items, which are represented by a tuple
of ``content_id`` and ``subtopic_id``. The format of these
identifiers is unspecified.
By default (with ``ann... |
def op_paths(self, path_base=None):
# type: (Union[str, UrlPath]) -> Generator[Tuple[UrlPath, Operation]]
"""
Return all operations stored in containers.
"""
if path_base:
path_base += self.path_prefix
else:
path_base = self.path_prefix or UrlPath(... | def function[op_paths, parameter[self, path_base]]:
constant[
Return all operations stored in containers.
]
if name[path_base] begin[:]
<ast.AugAssign object at 0x7da1b0a70910>
for taget[name[container]] in starred[name[self].containers] begin[:]
for taget... | keyword[def] identifier[op_paths] ( identifier[self] , identifier[path_base] = keyword[None] ):
literal[string]
keyword[if] identifier[path_base] :
identifier[path_base] += identifier[self] . identifier[path_prefix]
keyword[else] :
identifier[path_base] = ident... | def op_paths(self, path_base=None):
# type: (Union[str, UrlPath]) -> Generator[Tuple[UrlPath, Operation]]
'\n Return all operations stored in containers.\n '
if path_base:
path_base += self.path_prefix # depends on [control=['if'], data=[]]
else:
path_base = self.path_pref... |
def append_headers(f):
"""
Appends all the web headers:
* ZSL version and information,
* default CORS if not already set up,
* cache.
:param f: The decorated function.
:return: The function which appends the web headers.
"""
@wraps(f)
def _response_decorator(*args, **kwarg... | def function[append_headers, parameter[f]]:
constant[
Appends all the web headers:
* ZSL version and information,
* default CORS if not already set up,
* cache.
:param f: The decorated function.
:return: The function which appends the web headers.
]
def function[_respo... | keyword[def] identifier[append_headers] ( identifier[f] ):
literal[string]
@ identifier[wraps] ( identifier[f] )
keyword[def] identifier[_response_decorator] (* identifier[args] ,** identifier[kwargs] ):
identifier[r] = identifier[f] (* identifier[args] ,** identifier[kwargs] )
ident... | def append_headers(f):
"""
Appends all the web headers:
* ZSL version and information,
* default CORS if not already set up,
* cache.
:param f: The decorated function.
:return: The function which appends the web headers.
"""
@wraps(f)
def _response_decorator(*args, **kwar... |
def _set_edge_loop_detection(self, v, load=False):
"""
Setter method for edge_loop_detection, mapped from YANG variable /interface/tengigabitethernet/edge_loop_detection (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_edge_loop_detection is considered as a pr... | def function[_set_edge_loop_detection, parameter[self, v, load]]:
constant[
Setter method for edge_loop_detection, mapped from YANG variable /interface/tengigabitethernet/edge_loop_detection (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_edge_loop_detect... | keyword[def] identifier[_set_edge_loop_detection] ( identifier[self] , identifier[v] , identifier[load] = keyword[False] ):
literal[string]
keyword[if] identifier[hasattr] ( identifier[v] , literal[string] ):
identifier[v] = identifier[v] . identifier[_utype] ( identifier[v] )
keyword[try] :
... | def _set_edge_loop_detection(self, v, load=False):
"""
Setter method for edge_loop_detection, mapped from YANG variable /interface/tengigabitethernet/edge_loop_detection (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_edge_loop_detection is considered as a pr... |
def download_all(self, dst_dir=None):
"""Download all available files.
Arguments:
dst_dir -- Optional destination directory to write files to. If not
specified, then files are downloaded current directory.
Return:
Dictionary of {file_name: file_size, ..}... | def function[download_all, parameter[self, dst_dir]]:
constant[Download all available files.
Arguments:
dst_dir -- Optional destination directory to write files to. If not
specified, then files are downloaded current directory.
Return:
Dictionary of {fil... | keyword[def] identifier[download_all] ( identifier[self] , identifier[dst_dir] = keyword[None] ):
literal[string]
identifier[saved] ={}
identifier[save_as] = keyword[None]
keyword[for] identifier[f] keyword[in] identifier[self] . identifier[files] ():
keyword[if] ... | def download_all(self, dst_dir=None):
"""Download all available files.
Arguments:
dst_dir -- Optional destination directory to write files to. If not
specified, then files are downloaded current directory.
Return:
Dictionary of {file_name: file_size, ..}
... |
def fake_me(cls, source):
"""
fake_me
Class or method decorator
Class decorator: create temporary table for all tests in SimpleTestCase.
Method decorator: create temporary model only for given test method.
:param source: SimpleTestCase or test function
:return:
... | def function[fake_me, parameter[cls, source]]:
constant[
fake_me
Class or method decorator
Class decorator: create temporary table for all tests in SimpleTestCase.
Method decorator: create temporary model only for given test method.
:param source: SimpleTestCase or test... | keyword[def] identifier[fake_me] ( identifier[cls] , identifier[source] ):
literal[string]
keyword[if] identifier[source] keyword[and] identifier[type] ( identifier[source] )== identifier[type] keyword[and] identifier[issubclass] ( identifier[source] , identifier[SimpleTestCase] ):
... | def fake_me(cls, source):
"""
fake_me
Class or method decorator
Class decorator: create temporary table for all tests in SimpleTestCase.
Method decorator: create temporary model only for given test method.
:param source: SimpleTestCase or test function
:return:
... |
def _authorization_headers_valid(self, token_type, token):
"""Verify authorization headers for a request.
Parameters
token_type (str)
Type of token to access resources.
token (str)
Server Token or OAuth 2.0 Access Token.
Returns
... | def function[_authorization_headers_valid, parameter[self, token_type, token]]:
constant[Verify authorization headers for a request.
Parameters
token_type (str)
Type of token to access resources.
token (str)
Server Token or OAuth 2.0 Access Token.
... | keyword[def] identifier[_authorization_headers_valid] ( identifier[self] , identifier[token_type] , identifier[token] ):
literal[string]
keyword[if] identifier[token_type] keyword[not] keyword[in] identifier[http] . identifier[VALID_TOKEN_TYPES] :
keyword[return] keyword[False]
... | def _authorization_headers_valid(self, token_type, token):
"""Verify authorization headers for a request.
Parameters
token_type (str)
Type of token to access resources.
token (str)
Server Token or OAuth 2.0 Access Token.
Returns
(bo... |
def rowcount(self):
"""
This read-only attribute specifies the number of rows that the last
.execute*() produced (for DQL statements like ``SELECT``) or affected
(for DML statements like ``UPDATE`` or ``INSERT``).
"""
if (self._closed or not self._result or "rows" not in ... | def function[rowcount, parameter[self]]:
constant[
This read-only attribute specifies the number of rows that the last
.execute*() produced (for DQL statements like ``SELECT``) or affected
(for DML statements like ``UPDATE`` or ``INSERT``).
]
if <ast.BoolOp object at 0x7d... | keyword[def] identifier[rowcount] ( identifier[self] ):
literal[string]
keyword[if] ( identifier[self] . identifier[_closed] keyword[or] keyword[not] identifier[self] . identifier[_result] keyword[or] literal[string] keyword[not] keyword[in] identifier[self] . identifier[_result] ):
... | def rowcount(self):
"""
This read-only attribute specifies the number of rows that the last
.execute*() produced (for DQL statements like ``SELECT``) or affected
(for DML statements like ``UPDATE`` or ``INSERT``).
"""
if self._closed or not self._result or 'rows' not in self._res... |
def parse_shape(x, pattern: str):
"""
Parse a tensor shape to dictionary mapping axes names to their lengths.
Use underscore to skip the dimension in parsing.
>>> x = np.zeros([2, 3, 5, 7])
>>> parse_shape(x, 'batch _ h w')
{'batch': 2, 'h': 5, 'w': 7}
parse_shape output can be used to spec... | def function[parse_shape, parameter[x, pattern]]:
constant[
Parse a tensor shape to dictionary mapping axes names to their lengths.
Use underscore to skip the dimension in parsing.
>>> x = np.zeros([2, 3, 5, 7])
>>> parse_shape(x, 'batch _ h w')
{'batch': 2, 'h': 5, 'w': 7}
parse_shape ... | keyword[def] identifier[parse_shape] ( identifier[x] , identifier[pattern] : identifier[str] ):
literal[string]
identifier[names] =[ identifier[elementary_axis] keyword[for] identifier[elementary_axis] keyword[in] identifier[pattern] . identifier[split] ( literal[string] ) keyword[if] identifier[len] ... | def parse_shape(x, pattern: str):
"""
Parse a tensor shape to dictionary mapping axes names to their lengths.
Use underscore to skip the dimension in parsing.
>>> x = np.zeros([2, 3, 5, 7])
>>> parse_shape(x, 'batch _ h w')
{'batch': 2, 'h': 5, 'w': 7}
parse_shape output can be used to spec... |
def _run_query(self, query):
"""
Run one query against BigQuery and return the result.
:param query: the query to run
:type query: str
:return: list of per-row response dicts (key => value)
:rtype: ``list``
"""
query_request = self.service.jobs()
... | def function[_run_query, parameter[self, query]]:
constant[
Run one query against BigQuery and return the result.
:param query: the query to run
:type query: str
:return: list of per-row response dicts (key => value)
:rtype: ``list``
]
variable[query_requ... | keyword[def] identifier[_run_query] ( identifier[self] , identifier[query] ):
literal[string]
identifier[query_request] = identifier[self] . identifier[service] . identifier[jobs] ()
identifier[logger] . identifier[debug] ( literal[string] , identifier[query] )
identifier[start] =... | def _run_query(self, query):
"""
Run one query against BigQuery and return the result.
:param query: the query to run
:type query: str
:return: list of per-row response dicts (key => value)
:rtype: ``list``
"""
query_request = self.service.jobs()
logger.debug... |
def potential_from_grid(self, grid):
"""
Calculate the potential at a given set of arc-second gridded coordinates.
Parameters
----------
grid : grids.RegularGrid
The grid of (y,x) arc-second coordinates the deflection angles are computed on.
"""
pote... | def function[potential_from_grid, parameter[self, grid]]:
constant[
Calculate the potential at a given set of arc-second gridded coordinates.
Parameters
----------
grid : grids.RegularGrid
The grid of (y,x) arc-second coordinates the deflection angles are computed on... | keyword[def] identifier[potential_from_grid] ( identifier[self] , identifier[grid] ):
literal[string]
identifier[potential_grid] = identifier[quad_grid] ( identifier[self] . identifier[potential_func] , literal[int] , literal[int] , identifier[grid] ,
identifier[args] =( identifier[self] ... | def potential_from_grid(self, grid):
"""
Calculate the potential at a given set of arc-second gridded coordinates.
Parameters
----------
grid : grids.RegularGrid
The grid of (y,x) arc-second coordinates the deflection angles are computed on.
"""
potential_gri... |
def node_to_elem(root):
"""
Convert (recursively) a Node object into an ElementTree object.
"""
def generate_elem(append, node, level):
var = "e" + str(level)
arg = repr(node.tag)
if node.attrib:
arg += ", **%r" % node.attrib
if level == 1:
append(... | def function[node_to_elem, parameter[root]]:
constant[
Convert (recursively) a Node object into an ElementTree object.
]
def function[generate_elem, parameter[append, node, level]]:
variable[var] assign[=] binary_operation[constant[e] + call[name[str], parameter[name[level]]]]
... | keyword[def] identifier[node_to_elem] ( identifier[root] ):
literal[string]
keyword[def] identifier[generate_elem] ( identifier[append] , identifier[node] , identifier[level] ):
identifier[var] = literal[string] + identifier[str] ( identifier[level] )
identifier[arg] = identifier[repr] (... | def node_to_elem(root):
"""
Convert (recursively) a Node object into an ElementTree object.
"""
def generate_elem(append, node, level):
var = 'e' + str(level)
arg = repr(node.tag)
if node.attrib:
arg += ', **%r' % node.attrib # depends on [control=['if'], data=[]]
... |
def _write_gppu(self, gppu=None):
"""Write the specified byte value to the GPPU registor. If no value
specified the current buffered value will be written.
"""
if gppu is not None:
self.gppu = gppu
self.i2c.write_list(self.GPPU, self.gppu) | def function[_write_gppu, parameter[self, gppu]]:
constant[Write the specified byte value to the GPPU registor. If no value
specified the current buffered value will be written.
]
if compare[name[gppu] is_not constant[None]] begin[:]
name[self].gppu assign[=] name[gppu]
... | keyword[def] identifier[_write_gppu] ( identifier[self] , identifier[gppu] = keyword[None] ):
literal[string]
keyword[if] identifier[gppu] keyword[is] keyword[not] keyword[None] :
identifier[self] . identifier[gppu] = identifier[gppu]
identifier[self] . identifier[i2c] . ... | def _write_gppu(self, gppu=None):
"""Write the specified byte value to the GPPU registor. If no value
specified the current buffered value will be written.
"""
if gppu is not None:
self.gppu = gppu # depends on [control=['if'], data=['gppu']]
self.i2c.write_list(self.GPPU, self.gpp... |
def write_methods(self):
"""
Write all methods in the current module to a byte string.
:return: A bytestring of all current methods in this module
:rtype: bytes
"""
b_array = bytearray()
for key, vm_token in self.all_vm_tokens.items():
b_array.appen... | def function[write_methods, parameter[self]]:
constant[
Write all methods in the current module to a byte string.
:return: A bytestring of all current methods in this module
:rtype: bytes
]
variable[b_array] assign[=] call[name[bytearray], parameter[]]
for taget[... | keyword[def] identifier[write_methods] ( identifier[self] ):
literal[string]
identifier[b_array] = identifier[bytearray] ()
keyword[for] identifier[key] , identifier[vm_token] keyword[in] identifier[self] . identifier[all_vm_tokens] . identifier[items] ():
identifier[b_ar... | def write_methods(self):
"""
Write all methods in the current module to a byte string.
:return: A bytestring of all current methods in this module
:rtype: bytes
"""
b_array = bytearray()
for (key, vm_token) in self.all_vm_tokens.items():
b_array.append(vm_token.out_o... |
def trim_extrema(im, h, mode='maxima'):
r"""
Trims local extrema in greyscale values by a specified amount.
This essentially decapitates peaks and/or floods valleys.
Parameters
----------
im : ND-array
The image whose extrema are to be removed
h : float
The height to remov... | def function[trim_extrema, parameter[im, h, mode]]:
constant[
Trims local extrema in greyscale values by a specified amount.
This essentially decapitates peaks and/or floods valleys.
Parameters
----------
im : ND-array
The image whose extrema are to be removed
h : float
... | keyword[def] identifier[trim_extrema] ( identifier[im] , identifier[h] , identifier[mode] = literal[string] ):
literal[string]
identifier[result] = identifier[im]
keyword[if] identifier[mode] keyword[in] [ literal[string] , literal[string] ]:
identifier[result] = identifier[reconstruction]... | def trim_extrema(im, h, mode='maxima'):
"""
Trims local extrema in greyscale values by a specified amount.
This essentially decapitates peaks and/or floods valleys.
Parameters
----------
im : ND-array
The image whose extrema are to be removed
h : float
The height to remove... |
def run_migrations_online():
"""Run migrations in 'online' mode.
In this scenario we need to create an Engine
and associate a connection with the context.
"""
engine = create_engine(
neutron_config.database.connection,
poolclass=pool.NullPool)
connection = engine.connect()
... | def function[run_migrations_online, parameter[]]:
constant[Run migrations in 'online' mode.
In this scenario we need to create an Engine
and associate a connection with the context.
]
variable[engine] assign[=] call[name[create_engine], parameter[name[neutron_config].database.connection]]
... | keyword[def] identifier[run_migrations_online] ():
literal[string]
identifier[engine] = identifier[create_engine] (
identifier[neutron_config] . identifier[database] . identifier[connection] ,
identifier[poolclass] = identifier[pool] . identifier[NullPool] )
identifier[connection] = identif... | def run_migrations_online():
"""Run migrations in 'online' mode.
In this scenario we need to create an Engine
and associate a connection with the context.
"""
engine = create_engine(neutron_config.database.connection, poolclass=pool.NullPool)
connection = engine.connect()
context.configure... |
def current_day():
"""
Most recent day, if it's during the Advent of Code. Happy Holidays!
Day 1 is assumed, otherwise.
"""
aoc_now = datetime.datetime.now(tz=AOC_TZ)
if aoc_now.month != 12:
log.warning("current_day is only available in December (EST)")
return 1
day = min(aoc... | def function[current_day, parameter[]]:
constant[
Most recent day, if it's during the Advent of Code. Happy Holidays!
Day 1 is assumed, otherwise.
]
variable[aoc_now] assign[=] call[name[datetime].datetime.now, parameter[]]
if compare[name[aoc_now].month not_equal[!=] constant[12]] b... | keyword[def] identifier[current_day] ():
literal[string]
identifier[aoc_now] = identifier[datetime] . identifier[datetime] . identifier[now] ( identifier[tz] = identifier[AOC_TZ] )
keyword[if] identifier[aoc_now] . identifier[month] != literal[int] :
identifier[log] . identifier[warning] ( l... | def current_day():
"""
Most recent day, if it's during the Advent of Code. Happy Holidays!
Day 1 is assumed, otherwise.
"""
aoc_now = datetime.datetime.now(tz=AOC_TZ)
if aoc_now.month != 12:
log.warning('current_day is only available in December (EST)')
return 1 # depends on [co... |
def decode_once(estimator,
problem_name,
hparams,
infer_input_fn,
decode_hp,
decode_to_file,
output_dir,
log_results=True,
checkpoint_path=None):
"""Decodes once.
Args:
estimator: tf.... | def function[decode_once, parameter[estimator, problem_name, hparams, infer_input_fn, decode_hp, decode_to_file, output_dir, log_results, checkpoint_path]]:
constant[Decodes once.
Args:
estimator: tf.estimator.Estimator instance. Used to generate encoded
predictions.
problem_name: str. Name of ... | keyword[def] identifier[decode_once] ( identifier[estimator] ,
identifier[problem_name] ,
identifier[hparams] ,
identifier[infer_input_fn] ,
identifier[decode_hp] ,
identifier[decode_to_file] ,
identifier[output_dir] ,
identifier[log_results] = keyword[True] ,
identifier[checkpoint_path] = keyword[None] ):
... | def decode_once(estimator, problem_name, hparams, infer_input_fn, decode_hp, decode_to_file, output_dir, log_results=True, checkpoint_path=None):
"""Decodes once.
Args:
estimator: tf.estimator.Estimator instance. Used to generate encoded
predictions.
problem_name: str. Name of problem.
hparams:... |
def get_datacenters(service_instance, datacenter_names=None,
get_all_datacenters=False):
'''
Returns all datacenters in a vCenter.
service_instance
The Service Instance Object from which to obtain cluster.
datacenter_names
List of datacenter names to filter by. Defa... | def function[get_datacenters, parameter[service_instance, datacenter_names, get_all_datacenters]]:
constant[
Returns all datacenters in a vCenter.
service_instance
The Service Instance Object from which to obtain cluster.
datacenter_names
List of datacenter names to filter by. Defa... | keyword[def] identifier[get_datacenters] ( identifier[service_instance] , identifier[datacenter_names] = keyword[None] ,
identifier[get_all_datacenters] = keyword[False] ):
literal[string]
identifier[items] =[ identifier[i] [ literal[string] ] keyword[for] identifier[i] keyword[in]
identifier[get_... | def get_datacenters(service_instance, datacenter_names=None, get_all_datacenters=False):
"""
Returns all datacenters in a vCenter.
service_instance
The Service Instance Object from which to obtain cluster.
datacenter_names
List of datacenter names to filter by. Default value is None.
... |
def export_event_based_gateway_info(node_params, output_element):
"""
Adds EventBasedGateway node attributes to exported XML element
:param node_params: dictionary with given event based gateway parameters,
:param output_element: object representing BPMN XML 'eventBasedGateway' element.... | def function[export_event_based_gateway_info, parameter[node_params, output_element]]:
constant[
Adds EventBasedGateway node attributes to exported XML element
:param node_params: dictionary with given event based gateway parameters,
:param output_element: object representing BPMN XML '... | keyword[def] identifier[export_event_based_gateway_info] ( identifier[node_params] , identifier[output_element] ):
literal[string]
identifier[output_element] . identifier[set] ( identifier[consts] . identifier[Consts] . identifier[gateway_direction] , identifier[node_params] [ identifier[consts] . ... | def export_event_based_gateway_info(node_params, output_element):
"""
Adds EventBasedGateway node attributes to exported XML element
:param node_params: dictionary with given event based gateway parameters,
:param output_element: object representing BPMN XML 'eventBasedGateway' element.
... |
def choose_boundary():
"""Generate a multipart boundry.
:returns: A boundary string
"""
global BOUNDARY_PREFIX
if BOUNDARY_PREFIX is None:
BOUNDARY_PREFIX = "urlfetch"
try:
uid = repr(os.getuid())
BOUNDARY_PREFIX += "." + uid
except AttributeError:
... | def function[choose_boundary, parameter[]]:
constant[Generate a multipart boundry.
:returns: A boundary string
]
<ast.Global object at 0x7da1b25e7b80>
if compare[name[BOUNDARY_PREFIX] is constant[None]] begin[:]
variable[BOUNDARY_PREFIX] assign[=] constant[urlfetch]
... | keyword[def] identifier[choose_boundary] ():
literal[string]
keyword[global] identifier[BOUNDARY_PREFIX]
keyword[if] identifier[BOUNDARY_PREFIX] keyword[is] keyword[None] :
identifier[BOUNDARY_PREFIX] = literal[string]
keyword[try] :
identifier[uid] = identifier[re... | def choose_boundary():
"""Generate a multipart boundry.
:returns: A boundary string
"""
global BOUNDARY_PREFIX
if BOUNDARY_PREFIX is None:
BOUNDARY_PREFIX = 'urlfetch'
try:
uid = repr(os.getuid())
BOUNDARY_PREFIX += '.' + uid # depends on [control=['try'], d... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.