code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def autodiff_tree(func, wrt, motion, mode, preserve_result, check_dims,
verbose):
"""Perform AD on all functions in a call tree.
This function walks the call tree and differentiates each function in it. It
also ensures that the global namespaces that each function in the call tree
was in are ... | def function[autodiff_tree, parameter[func, wrt, motion, mode, preserve_result, check_dims, verbose]]:
constant[Perform AD on all functions in a call tree.
This function walks the call tree and differentiates each function in it. It
also ensures that the global namespaces that each function in the call tre... | keyword[def] identifier[autodiff_tree] ( identifier[func] , identifier[wrt] , identifier[motion] , identifier[mode] , identifier[preserve_result] , identifier[check_dims] ,
identifier[verbose] ):
literal[string]
keyword[import] identifier[tangent]
identifier[namespace] ={ literal[string] : identifier[... | def autodiff_tree(func, wrt, motion, mode, preserve_result, check_dims, verbose):
"""Perform AD on all functions in a call tree.
This function walks the call tree and differentiates each function in it. It
also ensures that the global namespaces that each function in the call tree
was in are merged.
The `... |
def pyprf(strCsvCnfg, lgcTest=False, varRat=None, strPathHrf=None):
"""
Main function for pRF mapping.
Parameters
----------
strCsvCnfg : str
Absolute file path of config file.
lgcTest : Boolean
Whether this is a test (pytest). If yes, absolute path of pyprf libary
will ... | def function[pyprf, parameter[strCsvCnfg, lgcTest, varRat, strPathHrf]]:
constant[
Main function for pRF mapping.
Parameters
----------
strCsvCnfg : str
Absolute file path of config file.
lgcTest : Boolean
Whether this is a test (pytest). If yes, absolute path of pyprf libar... | keyword[def] identifier[pyprf] ( identifier[strCsvCnfg] , identifier[lgcTest] = keyword[False] , identifier[varRat] = keyword[None] , identifier[strPathHrf] = keyword[None] ):
literal[string]
identifier[print] ( literal[string] )
identifier[varTme01] = identifier[time] . identifier[time] ()
... | def pyprf(strCsvCnfg, lgcTest=False, varRat=None, strPathHrf=None):
"""
Main function for pRF mapping.
Parameters
----------
strCsvCnfg : str
Absolute file path of config file.
lgcTest : Boolean
Whether this is a test (pytest). If yes, absolute path of pyprf libary
will ... |
def parse_from_import_statement(self):
"""Parse a 'from x import y' statement.
The purpose is to find __future__ statements.
"""
self.log.debug("parsing from/import statement.")
is_future_import = self._parse_from_import_source()
self._parse_from_import_names(is_future_i... | def function[parse_from_import_statement, parameter[self]]:
constant[Parse a 'from x import y' statement.
The purpose is to find __future__ statements.
]
call[name[self].log.debug, parameter[constant[parsing from/import statement.]]]
variable[is_future_import] assign[=] call[nam... | keyword[def] identifier[parse_from_import_statement] ( identifier[self] ):
literal[string]
identifier[self] . identifier[log] . identifier[debug] ( literal[string] )
identifier[is_future_import] = identifier[self] . identifier[_parse_from_import_source] ()
identifier[self] . ident... | def parse_from_import_statement(self):
"""Parse a 'from x import y' statement.
The purpose is to find __future__ statements.
"""
self.log.debug('parsing from/import statement.')
is_future_import = self._parse_from_import_source()
self._parse_from_import_names(is_future_import) |
def export_public_key(device_type, args):
"""Generate a new pubkey for a new/existing GPG identity."""
log.warning('NOTE: in order to re-generate the exact same GPG key later, '
'run this command with "--time=%d" commandline flag (to set '
'the timestamp of the GPG key manually).... | def function[export_public_key, parameter[device_type, args]]:
constant[Generate a new pubkey for a new/existing GPG identity.]
call[name[log].warning, parameter[constant[NOTE: in order to re-generate the exact same GPG key later, run this command with "--time=%d" commandline flag (to set the timestamp ... | keyword[def] identifier[export_public_key] ( identifier[device_type] , identifier[args] ):
literal[string]
identifier[log] . identifier[warning] ( literal[string]
literal[string]
literal[string] , identifier[args] . identifier[time] )
identifier[c] = identifier[client] . identifier[Client]... | def export_public_key(device_type, args):
"""Generate a new pubkey for a new/existing GPG identity."""
log.warning('NOTE: in order to re-generate the exact same GPG key later, run this command with "--time=%d" commandline flag (to set the timestamp of the GPG key manually).', args.time)
c = client.Client(de... |
def ExtractBarcodes(read, match,
extract_umi=False,
extract_cell=False,
discard=False,
retain_umi=False):
'''Extract the cell and umi barcodes using a regex.match object
inputs:
- read 1 and read2 = Record objects
- match ... | def function[ExtractBarcodes, parameter[read, match, extract_umi, extract_cell, discard, retain_umi]]:
constant[Extract the cell and umi barcodes using a regex.match object
inputs:
- read 1 and read2 = Record objects
- match = regex.match object
- extract_umi and extract_cell = switches to det... | keyword[def] identifier[ExtractBarcodes] ( identifier[read] , identifier[match] ,
identifier[extract_umi] = keyword[False] ,
identifier[extract_cell] = keyword[False] ,
identifier[discard] = keyword[False] ,
identifier[retain_umi] = keyword[False] ):
literal[string]
identifier[cell_barcode] , identifie... | def ExtractBarcodes(read, match, extract_umi=False, extract_cell=False, discard=False, retain_umi=False):
"""Extract the cell and umi barcodes using a regex.match object
inputs:
- read 1 and read2 = Record objects
- match = regex.match object
- extract_umi and extract_cell = switches to determine ... |
def walkdirs(self, *args, **kwargs):
""" D.walkdirs() -> iterator over subdirs, recursively.
"""
return (
item
for item in self.walk(*args, **kwargs)
if item.isdir()
) | def function[walkdirs, parameter[self]]:
constant[ D.walkdirs() -> iterator over subdirs, recursively.
]
return[<ast.GeneratorExp object at 0x7da20cabc0a0>] | keyword[def] identifier[walkdirs] ( identifier[self] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
keyword[return] (
identifier[item]
keyword[for] identifier[item] keyword[in] identifier[self] . identifier[walk] (* identifier[args] ,** identifier[kwargs] )
... | def walkdirs(self, *args, **kwargs):
""" D.walkdirs() -> iterator over subdirs, recursively.
"""
return (item for item in self.walk(*args, **kwargs) if item.isdir()) |
def canonical_url(app, pagename, templatename, context, doctree):
"""Build the canonical URL for a page. Appends the path for the
page to the base URL specified by the
``html_context["canonical_url"]`` config and stores it in
``html_context["page_canonical_url"]``.
"""
base = context.get("canoni... | def function[canonical_url, parameter[app, pagename, templatename, context, doctree]]:
constant[Build the canonical URL for a page. Appends the path for the
page to the base URL specified by the
``html_context["canonical_url"]`` config and stores it in
``html_context["page_canonical_url"]``.
]
... | keyword[def] identifier[canonical_url] ( identifier[app] , identifier[pagename] , identifier[templatename] , identifier[context] , identifier[doctree] ):
literal[string]
identifier[base] = identifier[context] . identifier[get] ( literal[string] )
keyword[if] keyword[not] identifier[base] :
... | def canonical_url(app, pagename, templatename, context, doctree):
"""Build the canonical URL for a page. Appends the path for the
page to the base URL specified by the
``html_context["canonical_url"]`` config and stores it in
``html_context["page_canonical_url"]``.
"""
base = context.get('canoni... |
def move_column(column=1, file=sys.stdout):
""" Move the cursor to the specified column, default 1.
Esc[<column>G
"""
move.column(column).write(file=file) | def function[move_column, parameter[column, file]]:
constant[ Move the cursor to the specified column, default 1.
Esc[<column>G
]
call[call[name[move].column, parameter[name[column]]].write, parameter[]] | keyword[def] identifier[move_column] ( identifier[column] = literal[int] , identifier[file] = identifier[sys] . identifier[stdout] ):
literal[string]
identifier[move] . identifier[column] ( identifier[column] ). identifier[write] ( identifier[file] = identifier[file] ) | def move_column(column=1, file=sys.stdout):
""" Move the cursor to the specified column, default 1.
Esc[<column>G
"""
move.column(column).write(file=file) |
def time2isoz(t=None):
"""Return a string representing time in seconds since epoch, t.
If the function is called without an argument, it will use the current
time.
The format of the returned string is like "YYYY-MM-DD hh:mm:ssZ",
representing Universal Time (UTC, aka GMT). An example of this form... | def function[time2isoz, parameter[t]]:
constant[Return a string representing time in seconds since epoch, t.
If the function is called without an argument, it will use the current
time.
The format of the returned string is like "YYYY-MM-DD hh:mm:ssZ",
representing Universal Time (UTC, aka GMT)... | keyword[def] identifier[time2isoz] ( identifier[t] = keyword[None] ):
literal[string]
keyword[if] identifier[t] keyword[is] keyword[None] :
identifier[dt] = identifier[datetime] . identifier[datetime] . identifier[utcnow] ()
keyword[else] :
identifier[dt] = identifier[datetime] . ... | def time2isoz(t=None):
"""Return a string representing time in seconds since epoch, t.
If the function is called without an argument, it will use the current
time.
The format of the returned string is like "YYYY-MM-DD hh:mm:ssZ",
representing Universal Time (UTC, aka GMT). An example of this form... |
def CreateTaskStorage(self, task):
"""Creates a task storage.
Args:
task (Task): task.
Returns:
FakeStorageWriter: storage writer.
Raises:
IOError: if the task storage already exists.
OSError: if the task storage already exists.
"""
if task.identifier in self._task_sto... | def function[CreateTaskStorage, parameter[self, task]]:
constant[Creates a task storage.
Args:
task (Task): task.
Returns:
FakeStorageWriter: storage writer.
Raises:
IOError: if the task storage already exists.
OSError: if the task storage already exists.
]
if ... | keyword[def] identifier[CreateTaskStorage] ( identifier[self] , identifier[task] ):
literal[string]
keyword[if] identifier[task] . identifier[identifier] keyword[in] identifier[self] . identifier[_task_storage_writers] :
keyword[raise] identifier[IOError] ( literal[string] . identifier[format] (... | def CreateTaskStorage(self, task):
"""Creates a task storage.
Args:
task (Task): task.
Returns:
FakeStorageWriter: storage writer.
Raises:
IOError: if the task storage already exists.
OSError: if the task storage already exists.
"""
if task.identifier in self._task_sto... |
def _set_standard(self, v, load=False):
"""
Setter method for standard, mapped from YANG variable /ipv6_acl/ipv6/access_list/standard (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_standard is considered as a private
method. Backends looking to populate this ... | def function[_set_standard, parameter[self, v, load]]:
constant[
Setter method for standard, mapped from YANG variable /ipv6_acl/ipv6/access_list/standard (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_standard is considered as a private
method. Backends ... | keyword[def] identifier[_set_standard] ( 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] :
ident... | def _set_standard(self, v, load=False):
"""
Setter method for standard, mapped from YANG variable /ipv6_acl/ipv6/access_list/standard (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_standard is considered as a private
method. Backends looking to populate this ... |
def invoice_access(request, access_code):
''' Redirects to an invoice for the attendee that matches the given access
code, if any.
If the attendee has multiple invoices, we use the following tie-break:
- If there's an unpaid invoice, show that, otherwise
- If there's a paid invoice, show the most ... | def function[invoice_access, parameter[request, access_code]]:
constant[ Redirects to an invoice for the attendee that matches the given access
code, if any.
If the attendee has multiple invoices, we use the following tie-break:
- If there's an unpaid invoice, show that, otherwise
- If there's... | keyword[def] identifier[invoice_access] ( identifier[request] , identifier[access_code] ):
literal[string]
identifier[invoices] = identifier[commerce] . identifier[Invoice] . identifier[objects] . identifier[filter] (
identifier[user__attendee__access_code] = identifier[access_code] ,
). identifi... | def invoice_access(request, access_code):
""" Redirects to an invoice for the attendee that matches the given access
code, if any.
If the attendee has multiple invoices, we use the following tie-break:
- If there's an unpaid invoice, show that, otherwise
- If there's a paid invoice, show the most ... |
def convolve_filter(signal, impulse_response):
"""
Convovle the two input signals, if impulse_response is None,
returns the unaltered signal
"""
if impulse_response is not None:
# print 'interpolated calibration'#, self.calibration_frequencies
adjusted_signal = fftconvolve(signal, im... | def function[convolve_filter, parameter[signal, impulse_response]]:
constant[
Convovle the two input signals, if impulse_response is None,
returns the unaltered signal
]
if compare[name[impulse_response] is_not constant[None]] begin[:]
variable[adjusted_signal] assign[=] call... | keyword[def] identifier[convolve_filter] ( identifier[signal] , identifier[impulse_response] ):
literal[string]
keyword[if] identifier[impulse_response] keyword[is] keyword[not] keyword[None] :
identifier[adjusted_signal] = identifier[fftconvolve] ( identifier[signal] , identifier[impulse... | def convolve_filter(signal, impulse_response):
"""
Convovle the two input signals, if impulse_response is None,
returns the unaltered signal
"""
if impulse_response is not None:
# print 'interpolated calibration'#, self.calibration_frequencies
adjusted_signal = fftconvolve(signal, im... |
def effective_len(self):
"""
Get the length of the sequence if N's are disregarded.
"""
if self._effective_len is None:
self._effective_len = len([nuc for nuc in self.sequenceData
if nuc != "N" and nuc != "n"])
return self._effective_len | def function[effective_len, parameter[self]]:
constant[
Get the length of the sequence if N's are disregarded.
]
if compare[name[self]._effective_len is constant[None]] begin[:]
name[self]._effective_len assign[=] call[name[len], parameter[<ast.ListComp object at 0x7da1b1461540>]... | keyword[def] identifier[effective_len] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[_effective_len] keyword[is] keyword[None] :
identifier[self] . identifier[_effective_len] = identifier[len] ([ identifier[nuc] keyword[for] identifier[nuc] keyword[in] identi... | def effective_len(self):
"""
Get the length of the sequence if N's are disregarded.
"""
if self._effective_len is None:
self._effective_len = len([nuc for nuc in self.sequenceData if nuc != 'N' and nuc != 'n']) # depends on [control=['if'], data=[]]
return self._effective_len |
def imagetransformer_base_10l_16h_big_uncond_dr01_imgnet():
"""big 1d model for conditional image generation."""
hparams = imagetransformer_base_14l_8h_big_dr01()
# num_hidden_layers
hparams.num_decoder_layers = 10
hparams.num_heads = 16
hparams.hidden_size = 1024
hparams.filter_size = 4096
hparams.batc... | def function[imagetransformer_base_10l_16h_big_uncond_dr01_imgnet, parameter[]]:
constant[big 1d model for conditional image generation.]
variable[hparams] assign[=] call[name[imagetransformer_base_14l_8h_big_dr01], parameter[]]
name[hparams].num_decoder_layers assign[=] constant[10]
nam... | keyword[def] identifier[imagetransformer_base_10l_16h_big_uncond_dr01_imgnet] ():
literal[string]
identifier[hparams] = identifier[imagetransformer_base_14l_8h_big_dr01] ()
identifier[hparams] . identifier[num_decoder_layers] = literal[int]
identifier[hparams] . identifier[num_heads] = literal[int]
... | def imagetransformer_base_10l_16h_big_uncond_dr01_imgnet():
"""big 1d model for conditional image generation."""
hparams = imagetransformer_base_14l_8h_big_dr01()
# num_hidden_layers
hparams.num_decoder_layers = 10
hparams.num_heads = 16
hparams.hidden_size = 1024
hparams.filter_size = 4096
... |
def updateVocalAuto(self, component, files):
"""Updates the auto-parameter with selected *component* to have
*files*. Adds auto-parameter if not already present. The auto-parameter is expected to have only one selected
component (the one given). If length of files < 1, removes the
auto-p... | def function[updateVocalAuto, parameter[self, component, files]]:
constant[Updates the auto-parameter with selected *component* to have
*files*. Adds auto-parameter if not already present. The auto-parameter is expected to have only one selected
component (the one given). If length of files < 1,... | keyword[def] identifier[updateVocalAuto] ( identifier[self] , identifier[component] , identifier[files] ):
literal[string]
identifier[auto_model] = identifier[self] . identifier[model] (). identifier[autoParams] ()
identifier[row] = identifier[auto_model] . identifier[fileParameter] ( iden... | def updateVocalAuto(self, component, files):
"""Updates the auto-parameter with selected *component* to have
*files*. Adds auto-parameter if not already present. The auto-parameter is expected to have only one selected
component (the one given). If length of files < 1, removes the
auto-param... |
def get_location(vm_=None):
'''
Return the joyent data center to use, in this order:
- CLI parameter
- VM parameter
- Cloud profile setting
'''
return __opts__.get(
'location',
config.get_cloud_config_value(
'location',
vm_ or get_configure... | def function[get_location, parameter[vm_]]:
constant[
Return the joyent data center to use, in this order:
- CLI parameter
- VM parameter
- Cloud profile setting
]
return[call[name[__opts__].get, parameter[constant[location], call[name[config].get_cloud_config_value, paramete... | keyword[def] identifier[get_location] ( identifier[vm_] = keyword[None] ):
literal[string]
keyword[return] identifier[__opts__] . identifier[get] (
literal[string] ,
identifier[config] . identifier[get_cloud_config_value] (
literal[string] ,
identifier[vm_] keyword[or] identifier[get... | def get_location(vm_=None):
"""
Return the joyent data center to use, in this order:
- CLI parameter
- VM parameter
- Cloud profile setting
"""
return __opts__.get('location', config.get_cloud_config_value('location', vm_ or get_configured_provider(), __opts__, default=DEFAULT_LO... |
def get_route53_client(agent, region, cooperator=None):
"""
Get a non-registration Route53 client.
"""
if cooperator is None:
cooperator = task
return region.get_client(
_Route53Client,
agent=agent,
creds=region.creds,
region=REGION_US_EAST_1,
endpoint... | def function[get_route53_client, parameter[agent, region, cooperator]]:
constant[
Get a non-registration Route53 client.
]
if compare[name[cooperator] is constant[None]] begin[:]
variable[cooperator] assign[=] name[task]
return[call[name[region].get_client, parameter[name[_Ro... | keyword[def] identifier[get_route53_client] ( identifier[agent] , identifier[region] , identifier[cooperator] = keyword[None] ):
literal[string]
keyword[if] identifier[cooperator] keyword[is] keyword[None] :
identifier[cooperator] = identifier[task]
keyword[return] identifier[region] . i... | def get_route53_client(agent, region, cooperator=None):
"""
Get a non-registration Route53 client.
"""
if cooperator is None:
cooperator = task # depends on [control=['if'], data=['cooperator']]
return region.get_client(_Route53Client, agent=agent, creds=region.creds, region=REGION_US_EAST_... |
def download(self, songs, template=None):
"""Download Google Music songs.
Parameters:
songs (list or dict): Google Music song dict(s).
template (str): A filepath which can include template patterns.
Returns:
A list of result dictionaries.
::
[
{'result': 'downloaded', 'id': song_id, 'file... | def function[download, parameter[self, songs, template]]:
constant[Download Google Music songs.
Parameters:
songs (list or dict): Google Music song dict(s).
template (str): A filepath which can include template patterns.
Returns:
A list of result dictionaries.
::
[
{'result': 'downl... | keyword[def] identifier[download] ( identifier[self] , identifier[songs] , identifier[template] = keyword[None] ):
literal[string]
keyword[if] keyword[not] identifier[template] :
identifier[template] = identifier[os] . identifier[getcwd] ()
identifier[songnum] = literal[int]
identifier[total] = ... | def download(self, songs, template=None):
"""Download Google Music songs.
Parameters:
songs (list or dict): Google Music song dict(s).
template (str): A filepath which can include template patterns.
Returns:
A list of result dictionaries.
::
[
{'result': 'downloaded', 'id': song_id, 'fi... |
def list_packages(conn=None):
'''
List files for an installed package
'''
close = False
if conn is None:
close = True
conn = init()
ret = []
data = conn.execute('SELECT package FROM packages')
for pkg in data.fetchall():
ret.append(pkg)
if close:
con... | def function[list_packages, parameter[conn]]:
constant[
List files for an installed package
]
variable[close] assign[=] constant[False]
if compare[name[conn] is constant[None]] begin[:]
variable[close] assign[=] constant[True]
variable[conn] assign[=] call... | keyword[def] identifier[list_packages] ( identifier[conn] = keyword[None] ):
literal[string]
identifier[close] = keyword[False]
keyword[if] identifier[conn] keyword[is] keyword[None] :
identifier[close] = keyword[True]
identifier[conn] = identifier[init] ()
identifier[ret]... | def list_packages(conn=None):
"""
List files for an installed package
"""
close = False
if conn is None:
close = True
conn = init() # depends on [control=['if'], data=['conn']]
ret = []
data = conn.execute('SELECT package FROM packages')
for pkg in data.fetchall():
... |
def is_newer_than(pth1, pth2):
"""
Return true if either file pth1 or file pth2 don't exist, or if
pth1 has been modified more recently than pth2
"""
return not os.path.exists(pth1) or not os.path.exists(pth2) or \
os.stat(pth1).st_mtime > os.stat(pth2).st_mtime | def function[is_newer_than, parameter[pth1, pth2]]:
constant[
Return true if either file pth1 or file pth2 don't exist, or if
pth1 has been modified more recently than pth2
]
return[<ast.BoolOp object at 0x7da1b07fb5e0>] | keyword[def] identifier[is_newer_than] ( identifier[pth1] , identifier[pth2] ):
literal[string]
keyword[return] keyword[not] identifier[os] . identifier[path] . identifier[exists] ( identifier[pth1] ) keyword[or] keyword[not] identifier[os] . identifier[path] . identifier[exists] ( identifier[pth2] ) ... | def is_newer_than(pth1, pth2):
"""
Return true if either file pth1 or file pth2 don't exist, or if
pth1 has been modified more recently than pth2
"""
return not os.path.exists(pth1) or not os.path.exists(pth2) or os.stat(pth1).st_mtime > os.stat(pth2).st_mtime |
def _to_dict(self):
"""Return a json dictionary representing this model."""
_dict = {}
if hasattr(self, 'label') and self.label is not None:
_dict['label'] = self.label
if hasattr(self, 'provenance_ids') and self.provenance_ids is not None:
_dict['provenance_ids']... | def function[_to_dict, parameter[self]]:
constant[Return a json dictionary representing this model.]
variable[_dict] assign[=] dictionary[[], []]
if <ast.BoolOp object at 0x7da1b23450c0> begin[:]
call[name[_dict]][constant[label]] assign[=] name[self].label
if <ast.BoolOp... | keyword[def] identifier[_to_dict] ( identifier[self] ):
literal[string]
identifier[_dict] ={}
keyword[if] identifier[hasattr] ( identifier[self] , literal[string] ) keyword[and] identifier[self] . identifier[label] keyword[is] keyword[not] keyword[None] :
identifier[_dict... | def _to_dict(self):
"""Return a json dictionary representing this model."""
_dict = {}
if hasattr(self, 'label') and self.label is not None:
_dict['label'] = self.label # depends on [control=['if'], data=[]]
if hasattr(self, 'provenance_ids') and self.provenance_ids is not None:
_dict['... |
def add_swagger(app, json_route, html_route):
"""
a convenience method for both adding a swagger.json route,
as well as adding a page showing the html documentation
"""
app.router.add_route('GET', json_route, create_swagger_json_handler(app))
add_swagger_api_route(app, html_route, json_route) | def function[add_swagger, parameter[app, json_route, html_route]]:
constant[
a convenience method for both adding a swagger.json route,
as well as adding a page showing the html documentation
]
call[name[app].router.add_route, parameter[constant[GET], name[json_route], call[name[create_swagg... | keyword[def] identifier[add_swagger] ( identifier[app] , identifier[json_route] , identifier[html_route] ):
literal[string]
identifier[app] . identifier[router] . identifier[add_route] ( literal[string] , identifier[json_route] , identifier[create_swagger_json_handler] ( identifier[app] ))
identifier[... | def add_swagger(app, json_route, html_route):
"""
a convenience method for both adding a swagger.json route,
as well as adding a page showing the html documentation
"""
app.router.add_route('GET', json_route, create_swagger_json_handler(app))
add_swagger_api_route(app, html_route, json_route) |
def convert_timestamp(timestamp):
"""
Converts bokehJS timestamp to datetime64.
"""
datetime = dt.datetime.utcfromtimestamp(timestamp/1000.)
return np.datetime64(datetime.replace(tzinfo=None)) | def function[convert_timestamp, parameter[timestamp]]:
constant[
Converts bokehJS timestamp to datetime64.
]
variable[datetime] assign[=] call[name[dt].datetime.utcfromtimestamp, parameter[binary_operation[name[timestamp] / constant[1000.0]]]]
return[call[name[np].datetime64, parameter[call[... | keyword[def] identifier[convert_timestamp] ( identifier[timestamp] ):
literal[string]
identifier[datetime] = identifier[dt] . identifier[datetime] . identifier[utcfromtimestamp] ( identifier[timestamp] / literal[int] )
keyword[return] identifier[np] . identifier[datetime64] ( identifier[datetime] . i... | def convert_timestamp(timestamp):
"""
Converts bokehJS timestamp to datetime64.
"""
datetime = dt.datetime.utcfromtimestamp(timestamp / 1000.0)
return np.datetime64(datetime.replace(tzinfo=None)) |
def check_required(self):
""" Check all required settings have been provided
"""
die = False
for key, value in self.spec.items():
if not getattr(self, key.upper()) and value['required']:
print(f"{key} is a required setting. "
"Set via com... | def function[check_required, parameter[self]]:
constant[ Check all required settings have been provided
]
variable[die] assign[=] constant[False]
for taget[tuple[[<ast.Name object at 0x7da207f01a80>, <ast.Name object at 0x7da207f002e0>]]] in starred[call[name[self].spec.items, parameter[... | keyword[def] identifier[check_required] ( identifier[self] ):
literal[string]
identifier[die] = keyword[False]
keyword[for] identifier[key] , identifier[value] keyword[in] identifier[self] . identifier[spec] . identifier[items] ():
keyword[if] keyword[not] identifier[get... | def check_required(self):
""" Check all required settings have been provided
"""
die = False
for (key, value) in self.spec.items():
if not getattr(self, key.upper()) and value['required']:
print(f"{key} is a required setting. Set via command-line params, env or file. For examples... |
def option_group_exists(name, tags=None, region=None, key=None, keyid=None,
profile=None):
'''
Check to see if an RDS option group exists.
CLI example::
salt myminion boto_rds.option_group_exists myoptiongr region=us-east-1
'''
conn = _get_conn(region=region, key=ke... | def function[option_group_exists, parameter[name, tags, region, key, keyid, profile]]:
constant[
Check to see if an RDS option group exists.
CLI example::
salt myminion boto_rds.option_group_exists myoptiongr region=us-east-1
]
variable[conn] assign[=] call[name[_get_conn], paramet... | keyword[def] identifier[option_group_exists] ( identifier[name] , identifier[tags] = keyword[None] , identifier[region] = keyword[None] , identifier[key] = keyword[None] , identifier[keyid] = keyword[None] ,
identifier[profile] = keyword[None] ):
literal[string]
identifier[conn] = identifier[_get_conn] ( ... | def option_group_exists(name, tags=None, region=None, key=None, keyid=None, profile=None):
"""
Check to see if an RDS option group exists.
CLI example::
salt myminion boto_rds.option_group_exists myoptiongr region=us-east-1
"""
conn = _get_conn(region=region, key=key, keyid=keyid, profile=... |
def session_preparation(self):
"""Prepare the session after the connection has been established."""
# 0 will defer to the global delay factor
delay_factor = self.select_delay_factor(delay_factor=0)
self._test_channel_read()
self.set_base_prompt()
cmd = "{}set cli mode -pa... | def function[session_preparation, parameter[self]]:
constant[Prepare the session after the connection has been established.]
variable[delay_factor] assign[=] call[name[self].select_delay_factor, parameter[]]
call[name[self]._test_channel_read, parameter[]]
call[name[self].set_base_prompt... | keyword[def] identifier[session_preparation] ( identifier[self] ):
literal[string]
identifier[delay_factor] = identifier[self] . identifier[select_delay_factor] ( identifier[delay_factor] = literal[int] )
identifier[self] . identifier[_test_channel_read] ()
identifier[sel... | def session_preparation(self):
"""Prepare the session after the connection has been established."""
# 0 will defer to the global delay factor
delay_factor = self.select_delay_factor(delay_factor=0)
self._test_channel_read()
self.set_base_prompt()
cmd = '{}set cli mode -page OFF{}'.format(self.RE... |
def gff3_parse_attributes(attributes_string):
"""
Parse a string of GFF3 attributes ('key=value' pairs delimited by ';')
and return a dictionary.
"""
attributes = dict()
fields = attributes_string.split(';')
for f in fields:
if '=' in f:
key, value = f.split('=')... | def function[gff3_parse_attributes, parameter[attributes_string]]:
constant[
Parse a string of GFF3 attributes ('key=value' pairs delimited by ';')
and return a dictionary.
]
variable[attributes] assign[=] call[name[dict], parameter[]]
variable[fields] assign[=] call[name[attribu... | keyword[def] identifier[gff3_parse_attributes] ( identifier[attributes_string] ):
literal[string]
identifier[attributes] = identifier[dict] ()
identifier[fields] = identifier[attributes_string] . identifier[split] ( literal[string] )
keyword[for] identifier[f] keyword[in] identifier[fields] :... | def gff3_parse_attributes(attributes_string):
"""
Parse a string of GFF3 attributes ('key=value' pairs delimited by ';')
and return a dictionary.
"""
attributes = dict()
fields = attributes_string.split(';')
for f in fields:
if '=' in f:
(key, value) = f.split('=')
... |
def get_info(self):
'''
Get information about the counter
.. note::
GetCounterInfo sometimes crashes in the wrapper code. Fewer crashes
if this is called after sampling data.
'''
if not self.info:
ci = win32pdh.GetCounterInfo(self.handle, 0)
... | def function[get_info, parameter[self]]:
constant[
Get information about the counter
.. note::
GetCounterInfo sometimes crashes in the wrapper code. Fewer crashes
if this is called after sampling data.
]
if <ast.UnaryOp object at 0x7da18f00cac0> begin[:]
... | keyword[def] identifier[get_info] ( identifier[self] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[info] :
identifier[ci] = identifier[win32pdh] . identifier[GetCounterInfo] ( identifier[self] . identifier[handle] , literal[int] )
identifier[s... | def get_info(self):
"""
Get information about the counter
.. note::
GetCounterInfo sometimes crashes in the wrapper code. Fewer crashes
if this is called after sampling data.
"""
if not self.info:
ci = win32pdh.GetCounterInfo(self.handle, 0)
self.... |
def wrap(value):
"""
Wraps the given value in a Document or DocumentList as applicable.
"""
if isinstance(value, Document) or isinstance(value, DocumentList):
return value
elif isinstance(value, dict):
return Document(value)
elif isinstance(value, list):
return DocumentLi... | def function[wrap, parameter[value]]:
constant[
Wraps the given value in a Document or DocumentList as applicable.
]
if <ast.BoolOp object at 0x7da1b12904f0> begin[:]
return[name[value]] | keyword[def] identifier[wrap] ( identifier[value] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[value] , identifier[Document] ) keyword[or] identifier[isinstance] ( identifier[value] , identifier[DocumentList] ):
keyword[return] identifier[value]
keyword[elif] identi... | def wrap(value):
"""
Wraps the given value in a Document or DocumentList as applicable.
"""
if isinstance(value, Document) or isinstance(value, DocumentList):
return value # depends on [control=['if'], data=[]]
elif isinstance(value, dict):
return Document(value) # depends on [cont... |
def AmericanDateToEpoch(self, date_str):
"""Take a US format date and return epoch."""
try:
epoch = time.strptime(date_str, "%m/%d/%Y")
return int(calendar.timegm(epoch)) * 1000000
except ValueError:
return 0 | def function[AmericanDateToEpoch, parameter[self, date_str]]:
constant[Take a US format date and return epoch.]
<ast.Try object at 0x7da1b1b6afe0> | keyword[def] identifier[AmericanDateToEpoch] ( identifier[self] , identifier[date_str] ):
literal[string]
keyword[try] :
identifier[epoch] = identifier[time] . identifier[strptime] ( identifier[date_str] , literal[string] )
keyword[return] identifier[int] ( identifier[calendar] . identifier[... | def AmericanDateToEpoch(self, date_str):
"""Take a US format date and return epoch."""
try:
epoch = time.strptime(date_str, '%m/%d/%Y')
return int(calendar.timegm(epoch)) * 1000000 # depends on [control=['try'], data=[]]
except ValueError:
return 0 # depends on [control=['except'],... |
def open(self, fname, mode='rb'):
"""
(Re-)opens a backup file
"""
self.close()
self.fp = open(fname, mode)
self.fname = fname | def function[open, parameter[self, fname, mode]]:
constant[
(Re-)opens a backup file
]
call[name[self].close, parameter[]]
name[self].fp assign[=] call[name[open], parameter[name[fname], name[mode]]]
name[self].fname assign[=] name[fname] | keyword[def] identifier[open] ( identifier[self] , identifier[fname] , identifier[mode] = literal[string] ):
literal[string]
identifier[self] . identifier[close] ()
identifier[self] . identifier[fp] = identifier[open] ( identifier[fname] , identifier[mode] )
identifier[self] . ide... | def open(self, fname, mode='rb'):
"""
(Re-)opens a backup file
"""
self.close()
self.fp = open(fname, mode)
self.fname = fname |
def node_is_upstream_leaf(graph: BELGraph, node: BaseEntity) -> bool:
"""Return if the node is an upstream leaf.
An upstream leaf is defined as a node that has no in-edges, and exactly 1 out-edge.
"""
return 0 == len(graph.predecessors(node)) and 1 == len(graph.successors(node)) | def function[node_is_upstream_leaf, parameter[graph, node]]:
constant[Return if the node is an upstream leaf.
An upstream leaf is defined as a node that has no in-edges, and exactly 1 out-edge.
]
return[<ast.BoolOp object at 0x7da20c796a70>] | keyword[def] identifier[node_is_upstream_leaf] ( identifier[graph] : identifier[BELGraph] , identifier[node] : identifier[BaseEntity] )-> identifier[bool] :
literal[string]
keyword[return] literal[int] == identifier[len] ( identifier[graph] . identifier[predecessors] ( identifier[node] )) keyword[and] li... | def node_is_upstream_leaf(graph: BELGraph, node: BaseEntity) -> bool:
"""Return if the node is an upstream leaf.
An upstream leaf is defined as a node that has no in-edges, and exactly 1 out-edge.
"""
return 0 == len(graph.predecessors(node)) and 1 == len(graph.successors(node)) |
def do_blot(source, source_wcs, blot_wcs, exptime, coeffs = True,
interp='poly5', sinscl=1.0, stepsize=10, wcsmap=None):
""" Core functionality of performing the 'blot' operation to create a single
blotted image from a single source image.
All distortion information is assumed to be incl... | def function[do_blot, parameter[source, source_wcs, blot_wcs, exptime, coeffs, interp, sinscl, stepsize, wcsmap]]:
constant[ Core functionality of performing the 'blot' operation to create a single
blotted image from a single source image.
All distortion information is assumed to be included in ... | keyword[def] identifier[do_blot] ( identifier[source] , identifier[source_wcs] , identifier[blot_wcs] , identifier[exptime] , identifier[coeffs] = keyword[True] ,
identifier[interp] = literal[string] , identifier[sinscl] = literal[int] , identifier[stepsize] = literal[int] , identifier[wcsmap] = keyword[None] ):
... | def do_blot(source, source_wcs, blot_wcs, exptime, coeffs=True, interp='poly5', sinscl=1.0, stepsize=10, wcsmap=None):
""" Core functionality of performing the 'blot' operation to create a single
blotted image from a single source image.
All distortion information is assumed to be included in the WC... |
def print_setting(self):
"""
prints the setting of the parameter class
:return:
"""
num, param_list = self.num_param()
num_linear = self.num_param_linear()
print("The following model options are chosen:")
print("Lens models:", self._lens_model_list)
... | def function[print_setting, parameter[self]]:
constant[
prints the setting of the parameter class
:return:
]
<ast.Tuple object at 0x7da1b26adc60> assign[=] call[name[self].num_param, parameter[]]
variable[num_linear] assign[=] call[name[self].num_param_linear, parameter[... | keyword[def] identifier[print_setting] ( identifier[self] ):
literal[string]
identifier[num] , identifier[param_list] = identifier[self] . identifier[num_param] ()
identifier[num_linear] = identifier[self] . identifier[num_param_linear] ()
identifier[print] ( literal[string] )
... | def print_setting(self):
"""
prints the setting of the parameter class
:return:
"""
(num, param_list) = self.num_param()
num_linear = self.num_param_linear()
print('The following model options are chosen:')
print('Lens models:', self._lens_model_list)
print('Source model... |
def configure(self, options, conf):
"""Configure which kinds of exceptions trigger plugin.
"""
self.conf = conf
self.enabled = options.epdb_debugErrors or options.epdb_debugFailures
self.enabled_for_errors = options.epdb_debugErrors
self.enabled_for_failures = options.epd... | def function[configure, parameter[self, options, conf]]:
constant[Configure which kinds of exceptions trigger plugin.
]
name[self].conf assign[=] name[conf]
name[self].enabled assign[=] <ast.BoolOp object at 0x7da18dc98ca0>
name[self].enabled_for_errors assign[=] name[options].ep... | keyword[def] identifier[configure] ( identifier[self] , identifier[options] , identifier[conf] ):
literal[string]
identifier[self] . identifier[conf] = identifier[conf]
identifier[self] . identifier[enabled] = identifier[options] . identifier[epdb_debugErrors] keyword[or] identifier[opt... | def configure(self, options, conf):
"""Configure which kinds of exceptions trigger plugin.
"""
self.conf = conf
self.enabled = options.epdb_debugErrors or options.epdb_debugFailures
self.enabled_for_errors = options.epdb_debugErrors
self.enabled_for_failures = options.epdb_debugFailures |
def collection_to_included_trees(collection):
"""Takes a collection object (or a filepath to collection object), returns
each element of the `decisions` list that has the decision set to included.
"""
if is_str_type(collection):
collection = read_as_json(collection)
inc = []
for d in col... | def function[collection_to_included_trees, parameter[collection]]:
constant[Takes a collection object (or a filepath to collection object), returns
each element of the `decisions` list that has the decision set to included.
]
if call[name[is_str_type], parameter[name[collection]]] begin[:]
... | keyword[def] identifier[collection_to_included_trees] ( identifier[collection] ):
literal[string]
keyword[if] identifier[is_str_type] ( identifier[collection] ):
identifier[collection] = identifier[read_as_json] ( identifier[collection] )
identifier[inc] =[]
keyword[for] identifier[d] ... | def collection_to_included_trees(collection):
"""Takes a collection object (or a filepath to collection object), returns
each element of the `decisions` list that has the decision set to included.
"""
if is_str_type(collection):
collection = read_as_json(collection) # depends on [control=['if']... |
def _read_value(self, file):
"""Read a single value from the given file"""
if self.data_type.nptype is not None:
dtype = (np.dtype(self.data_type.nptype).newbyteorder(
self.endianness))
return fromfile(file, dtype=dtype, count=1)
return self.data_type.rea... | def function[_read_value, parameter[self, file]]:
constant[Read a single value from the given file]
if compare[name[self].data_type.nptype is_not constant[None]] begin[:]
variable[dtype] assign[=] call[call[name[np].dtype, parameter[name[self].data_type.nptype]].newbyteorder, parameter[n... | keyword[def] identifier[_read_value] ( identifier[self] , identifier[file] ):
literal[string]
keyword[if] identifier[self] . identifier[data_type] . identifier[nptype] keyword[is] keyword[not] keyword[None] :
identifier[dtype] =( identifier[np] . identifier[dtype] ( identifier[sel... | def _read_value(self, file):
"""Read a single value from the given file"""
if self.data_type.nptype is not None:
dtype = np.dtype(self.data_type.nptype).newbyteorder(self.endianness)
return fromfile(file, dtype=dtype, count=1) # depends on [control=['if'], data=[]]
return self.data_type.rea... |
def get_mirror(self, target_root, source_root=None):
"""
Returns a File or Folder object that reperesents if the entire
fragment of this directory starting with `source_root` were copied
to `target_root`.
>>> Folder('/usr/local/hyde/stuff').get_mirror('/usr/tmp',
... | def function[get_mirror, parameter[self, target_root, source_root]]:
constant[
Returns a File or Folder object that reperesents if the entire
fragment of this directory starting with `source_root` were copied
to `target_root`.
>>> Folder('/usr/local/hyde/stuff').get_mirror('/usr... | keyword[def] identifier[get_mirror] ( identifier[self] , identifier[target_root] , identifier[source_root] = keyword[None] ):
literal[string]
identifier[fragment] = identifier[self] . identifier[get_relative_path] (
identifier[source_root] keyword[if] identifier[source_root] keyword[els... | def get_mirror(self, target_root, source_root=None):
"""
Returns a File or Folder object that reperesents if the entire
fragment of this directory starting with `source_root` were copied
to `target_root`.
>>> Folder('/usr/local/hyde/stuff').get_mirror('/usr/tmp',
... |
def get_unique_families(hkls):
"""
Returns unique families of Miller indices. Families must be permutations
of each other.
Args:
hkls ([h, k, l]): List of Miller indices.
Returns:
{hkl: multiplicity}: A dict with unique hkl and multiplicity.
"""
# TODO: Definitely can be sp... | def function[get_unique_families, parameter[hkls]]:
constant[
Returns unique families of Miller indices. Families must be permutations
of each other.
Args:
hkls ([h, k, l]): List of Miller indices.
Returns:
{hkl: multiplicity}: A dict with unique hkl and multiplicity.
]
... | keyword[def] identifier[get_unique_families] ( identifier[hkls] ):
literal[string]
keyword[def] identifier[is_perm] ( identifier[hkl1] , identifier[hkl2] ):
identifier[h1] = identifier[np] . identifier[abs] ( identifier[hkl1] )
identifier[h2] = identifier[np] . identifier[abs] ( ide... | def get_unique_families(hkls):
"""
Returns unique families of Miller indices. Families must be permutations
of each other.
Args:
hkls ([h, k, l]): List of Miller indices.
Returns:
{hkl: multiplicity}: A dict with unique hkl and multiplicity.
"""
# TODO: Definitely can be sp... |
def type_and_times(type_: str, start: Timestamp, end: Timestamp, probability: Number = None) -> str:
"""
Format line type and times into the beginning of a spoken line string
"""
if not type_:
return ''
if type_ == 'BECMG':
return f"At {start.dt.hour or 'midnight'} zulu becoming"
... | def function[type_and_times, parameter[type_, start, end, probability]]:
constant[
Format line type and times into the beginning of a spoken line string
]
if <ast.UnaryOp object at 0x7da20c6e5570> begin[:]
return[constant[]]
if compare[name[type_] equal[==] constant[BECMG]] begin... | keyword[def] identifier[type_and_times] ( identifier[type_] : identifier[str] , identifier[start] : identifier[Timestamp] , identifier[end] : identifier[Timestamp] , identifier[probability] : identifier[Number] = keyword[None] )-> identifier[str] :
literal[string]
keyword[if] keyword[not] identifier[type... | def type_and_times(type_: str, start: Timestamp, end: Timestamp, probability: Number=None) -> str:
"""
Format line type and times into the beginning of a spoken line string
"""
if not type_:
return '' # depends on [control=['if'], data=[]]
if type_ == 'BECMG':
return f"At {start.dt.... |
def init_app(self, app):
'''Initalizes the application with the extension.
:param app: The Flask application object.
'''
self.app = app
self._session_conf = app.config.get('BEAKER_SESSION', {
'session.type': 'file',
'session.data_dir': '/tmp/sessi... | def function[init_app, parameter[self, app]]:
constant[Initalizes the application with the extension.
:param app: The Flask application object.
]
name[self].app assign[=] name[app]
name[self]._session_conf assign[=] call[name[app].config.get, parameter[constant[BEAKER_SE... | keyword[def] identifier[init_app] ( identifier[self] , identifier[app] ):
literal[string]
identifier[self] . identifier[app] = identifier[app]
identifier[self] . identifier[_session_conf] = identifier[app] . identifier[config] . identifier[get] ( literal[string] ,{
literal[string... | def init_app(self, app):
"""Initalizes the application with the extension.
:param app: The Flask application object.
"""
self.app = app
self._session_conf = app.config.get('BEAKER_SESSION', {'session.type': 'file', 'session.data_dir': '/tmp/session/data', 'session.lock_dir': '/tmp/s... |
def transition_issue(self, issue, transition, fields=None, comment=None, worklog=None, **fieldargs):
"""Perform a transition on an issue.
Each keyword argument (other than the predefined ones) is treated as a field name and the argument's value
is treated as the intended value for that field --... | def function[transition_issue, parameter[self, issue, transition, fields, comment, worklog]]:
constant[Perform a transition on an issue.
Each keyword argument (other than the predefined ones) is treated as a field name and the argument's value
is treated as the intended value for that field -- ... | keyword[def] identifier[transition_issue] ( identifier[self] , identifier[issue] , identifier[transition] , identifier[fields] = keyword[None] , identifier[comment] = keyword[None] , identifier[worklog] = keyword[None] ,** identifier[fieldargs] ):
literal[string]
identifier[transitionId] = keyword[... | def transition_issue(self, issue, transition, fields=None, comment=None, worklog=None, **fieldargs):
"""Perform a transition on an issue.
Each keyword argument (other than the predefined ones) is treated as a field name and the argument's value
is treated as the intended value for that field -- if ... |
def intensity_at_radius(self, radius):
""" Compute the intensity of the profile at a given radius.
Parameters
----------
radius : float
The distance from the centre of the profile.
"""
return self.intensity * np.exp(
-self.sersic_constant * (((rad... | def function[intensity_at_radius, parameter[self, radius]]:
constant[ Compute the intensity of the profile at a given radius.
Parameters
----------
radius : float
The distance from the centre of the profile.
]
return[binary_operation[name[self].intensity * call[n... | keyword[def] identifier[intensity_at_radius] ( identifier[self] , identifier[radius] ):
literal[string]
keyword[return] identifier[self] . identifier[intensity] * identifier[np] . identifier[exp] (
- identifier[self] . identifier[sersic_constant] *((( identifier[radius] / identifier[self] ... | def intensity_at_radius(self, radius):
""" Compute the intensity of the profile at a given radius.
Parameters
----------
radius : float
The distance from the centre of the profile.
"""
return self.intensity * np.exp(-self.sersic_constant * ((radius / self.effective_r... |
def _issubclass_Tuple(subclass, superclass, bound_Generic, bound_typevars,
bound_typevars_readonly, follow_fwd_refs, _recursion_check):
"""Helper for _issubclass, a.k.a pytypes.issubtype.
"""
# this function is partly based on code from typing module 3.5.2.2
if subclass in _extra_dict:
... | def function[_issubclass_Tuple, parameter[subclass, superclass, bound_Generic, bound_typevars, bound_typevars_readonly, follow_fwd_refs, _recursion_check]]:
constant[Helper for _issubclass, a.k.a pytypes.issubtype.
]
if compare[name[subclass] in name[_extra_dict]] begin[:]
variable[s... | keyword[def] identifier[_issubclass_Tuple] ( identifier[subclass] , identifier[superclass] , identifier[bound_Generic] , identifier[bound_typevars] ,
identifier[bound_typevars_readonly] , identifier[follow_fwd_refs] , identifier[_recursion_check] ):
literal[string]
keyword[if] identifier[subclass] ... | def _issubclass_Tuple(subclass, superclass, bound_Generic, bound_typevars, bound_typevars_readonly, follow_fwd_refs, _recursion_check):
"""Helper for _issubclass, a.k.a pytypes.issubtype.
"""
# this function is partly based on code from typing module 3.5.2.2
if subclass in _extra_dict:
subclass ... |
def _build_path(self, path, metric_type):
"""Return a normalized path.
:param list path: elements of the metric path to record
:param str metric_type: The metric type
:rtype: str
"""
path = self._get_prefixes(metric_type) + list(path)
return '{}.{}'.format(self.... | def function[_build_path, parameter[self, path, metric_type]]:
constant[Return a normalized path.
:param list path: elements of the metric path to record
:param str metric_type: The metric type
:rtype: str
]
variable[path] assign[=] binary_operation[call[name[self]._get... | keyword[def] identifier[_build_path] ( identifier[self] , identifier[path] , identifier[metric_type] ):
literal[string]
identifier[path] = identifier[self] . identifier[_get_prefixes] ( identifier[metric_type] )+ identifier[list] ( identifier[path] )
keyword[return] literal[string] . iden... | def _build_path(self, path, metric_type):
"""Return a normalized path.
:param list path: elements of the metric path to record
:param str metric_type: The metric type
:rtype: str
"""
path = self._get_prefixes(metric_type) + list(path)
return '{}.{}'.format(self._namespace, ... |
def _massage_metakeys(dct, prfx):
"""
Returns a copy of the supplied dictionary, prefixing any keys that do
not begin with the specified prefix accordingly.
"""
lowprefix = prfx.lower()
ret = {}
for k, v in list(dct.items()):
if not k.lower().startswith(lowprefix):
k = "%... | def function[_massage_metakeys, parameter[dct, prfx]]:
constant[
Returns a copy of the supplied dictionary, prefixing any keys that do
not begin with the specified prefix accordingly.
]
variable[lowprefix] assign[=] call[name[prfx].lower, parameter[]]
variable[ret] assign[=] dictiona... | keyword[def] identifier[_massage_metakeys] ( identifier[dct] , identifier[prfx] ):
literal[string]
identifier[lowprefix] = identifier[prfx] . identifier[lower] ()
identifier[ret] ={}
keyword[for] identifier[k] , identifier[v] keyword[in] identifier[list] ( identifier[dct] . identifier[items] (... | def _massage_metakeys(dct, prfx):
"""
Returns a copy of the supplied dictionary, prefixing any keys that do
not begin with the specified prefix accordingly.
"""
lowprefix = prfx.lower()
ret = {}
for (k, v) in list(dct.items()):
if not k.lower().startswith(lowprefix):
k = ... |
def pre_approval_cancel(self, code):
""" cancel a subscribe """
response = self.get(url=self.config.PRE_APPROVAL_CANCEL_URL % code)
return PagSeguroPreApprovalCancel(response.content, self.config) | def function[pre_approval_cancel, parameter[self, code]]:
constant[ cancel a subscribe ]
variable[response] assign[=] call[name[self].get, parameter[]]
return[call[name[PagSeguroPreApprovalCancel], parameter[name[response].content, name[self].config]]] | keyword[def] identifier[pre_approval_cancel] ( identifier[self] , identifier[code] ):
literal[string]
identifier[response] = identifier[self] . identifier[get] ( identifier[url] = identifier[self] . identifier[config] . identifier[PRE_APPROVAL_CANCEL_URL] % identifier[code] )
keyword[retur... | def pre_approval_cancel(self, code):
""" cancel a subscribe """
response = self.get(url=self.config.PRE_APPROVAL_CANCEL_URL % code)
return PagSeguroPreApprovalCancel(response.content, self.config) |
def slice_index(self, *slice_dims, **kwargs):
"""
Returns a tuple of slices, each slice equal to the
slice(lower_extent, upper_extent, 1) of the dimensions
supplied in slice_dims. If the dimension is integer d,
slice(0, d, 1) will be used instead of the lower and upper extents
... | def function[slice_index, parameter[self]]:
constant[
Returns a tuple of slices, each slice equal to the
slice(lower_extent, upper_extent, 1) of the dimensions
supplied in slice_dims. If the dimension is integer d,
slice(0, d, 1) will be used instead of the lower and upper extent... | keyword[def] identifier[slice_index] ( identifier[self] ,* identifier[slice_dims] ,** identifier[kwargs] ):
literal[string]
keyword[return] identifier[tuple] ( identifier[slice] ( identifier[l] , identifier[u] , literal[int] ) keyword[for] identifier[l] , identifier[u] keyword[in] identifier[zi... | def slice_index(self, *slice_dims, **kwargs):
"""
Returns a tuple of slices, each slice equal to the
slice(lower_extent, upper_extent, 1) of the dimensions
supplied in slice_dims. If the dimension is integer d,
slice(0, d, 1) will be used instead of the lower and upper extents
... |
def _get_desired_pkg(name, desired):
'''
Helper function that retrieves and nicely formats the desired pkg (and
version if specified) so that helpful information can be printed in the
comment for the state.
'''
if not desired[name] or desired[name].startswith(('<', '>', '=')):
oper = ''
... | def function[_get_desired_pkg, parameter[name, desired]]:
constant[
Helper function that retrieves and nicely formats the desired pkg (and
version if specified) so that helpful information can be printed in the
comment for the state.
]
if <ast.BoolOp object at 0x7da1b212d900> begin[:]
... | keyword[def] identifier[_get_desired_pkg] ( identifier[name] , identifier[desired] ):
literal[string]
keyword[if] keyword[not] identifier[desired] [ identifier[name] ] keyword[or] identifier[desired] [ identifier[name] ]. identifier[startswith] (( literal[string] , literal[string] , literal[string] )):
... | def _get_desired_pkg(name, desired):
"""
Helper function that retrieves and nicely formats the desired pkg (and
version if specified) so that helpful information can be printed in the
comment for the state.
"""
if not desired[name] or desired[name].startswith(('<', '>', '=')):
oper = '' ... |
def run(self):
"""
This method continually runs. If an incoming character is available on the serial port
it is read and placed on the _command_deque
@return: Never Returns
"""
while not self.is_stopped():
# we can get an OSError: [Errno9] Bad file descriptor ... | def function[run, parameter[self]]:
constant[
This method continually runs. If an incoming character is available on the serial port
it is read and placed on the _command_deque
@return: Never Returns
]
while <ast.UnaryOp object at 0x7da1b021c7c0> begin[:]
<ast.Try... | keyword[def] identifier[run] ( identifier[self] ):
literal[string]
keyword[while] keyword[not] identifier[self] . identifier[is_stopped] ():
keyword[try] :
keyword[if] identifier[self] . identifier[arduino] . identifier[inWaiting] ():
... | def run(self):
"""
This method continually runs. If an incoming character is available on the serial port
it is read and placed on the _command_deque
@return: Never Returns
"""
while not self.is_stopped():
# we can get an OSError: [Errno9] Bad file descriptor when shuttin... |
def build_arg_parser2():
"""
Build an argument parser using optparse. Use it when python version is 2.5 or 2.6.
"""
usage_str = "Smatch table calculator -- arguments"
parser = optparse.OptionParser(usage=usage_str)
parser.add_option("--fl", dest="fl", type="string", help='AMR ID list file')
... | def function[build_arg_parser2, parameter[]]:
constant[
Build an argument parser using optparse. Use it when python version is 2.5 or 2.6.
]
variable[usage_str] assign[=] constant[Smatch table calculator -- arguments]
variable[parser] assign[=] call[name[optparse].OptionParser, paramete... | keyword[def] identifier[build_arg_parser2] ():
literal[string]
identifier[usage_str] = literal[string]
identifier[parser] = identifier[optparse] . identifier[OptionParser] ( identifier[usage] = identifier[usage_str] )
identifier[parser] . identifier[add_option] ( literal[string] , identifier[des... | def build_arg_parser2():
"""
Build an argument parser using optparse. Use it when python version is 2.5 or 2.6.
"""
usage_str = 'Smatch table calculator -- arguments'
parser = optparse.OptionParser(usage=usage_str)
parser.add_option('--fl', dest='fl', type='string', help='AMR ID list file')
... |
def check_pdb_status(pdbid):
"""Returns the status and up-to-date entry in the PDB for a given PDB ID"""
url = 'http://www.rcsb.org/pdb/rest/idStatus?structureId=%s' % pdbid
xmlf = urlopen(url)
xml = et.parse(xmlf)
xmlf.close()
status = None
current_pdbid = pdbid
for df in xml.xpath('//r... | def function[check_pdb_status, parameter[pdbid]]:
constant[Returns the status and up-to-date entry in the PDB for a given PDB ID]
variable[url] assign[=] binary_operation[constant[http://www.rcsb.org/pdb/rest/idStatus?structureId=%s] <ast.Mod object at 0x7da2590d6920> name[pdbid]]
variable[xmlf]... | keyword[def] identifier[check_pdb_status] ( identifier[pdbid] ):
literal[string]
identifier[url] = literal[string] % identifier[pdbid]
identifier[xmlf] = identifier[urlopen] ( identifier[url] )
identifier[xml] = identifier[et] . identifier[parse] ( identifier[xmlf] )
identifier[xmlf] . iden... | def check_pdb_status(pdbid):
"""Returns the status and up-to-date entry in the PDB for a given PDB ID"""
url = 'http://www.rcsb.org/pdb/rest/idStatus?structureId=%s' % pdbid
xmlf = urlopen(url)
xml = et.parse(xmlf)
xmlf.close()
status = None
current_pdbid = pdbid
for df in xml.xpath('//r... |
def Name(self, number):
"""Returns a string containing the name of an enum value."""
if number in self._enum_type.values_by_number:
return self._enum_type.values_by_number[number].name
raise ValueError('Enum %s has no name defined for value %d' % (
self._enum_type.name, number)) | def function[Name, parameter[self, number]]:
constant[Returns a string containing the name of an enum value.]
if compare[name[number] in name[self]._enum_type.values_by_number] begin[:]
return[call[name[self]._enum_type.values_by_number][name[number]].name]
<ast.Raise object at 0x7da1b21c5c0... | keyword[def] identifier[Name] ( identifier[self] , identifier[number] ):
literal[string]
keyword[if] identifier[number] keyword[in] identifier[self] . identifier[_enum_type] . identifier[values_by_number] :
keyword[return] identifier[self] . identifier[_enum_type] . identifier[values_by_number] ... | def Name(self, number):
"""Returns a string containing the name of an enum value."""
if number in self._enum_type.values_by_number:
return self._enum_type.values_by_number[number].name # depends on [control=['if'], data=['number']]
raise ValueError('Enum %s has no name defined for value %d' % (self... |
def evolve(self, profile, t, return_log=False):
"""
Compute the probability of the sequence state of the child
at time t later, given the parent profile.
Parameters
----------
profile : numpy.array
Sequence profile. Shape = (L, a),
where L - seq... | def function[evolve, parameter[self, profile, t, return_log]]:
constant[
Compute the probability of the sequence state of the child
at time t later, given the parent profile.
Parameters
----------
profile : numpy.array
Sequence profile. Shape = (L, a),
... | keyword[def] identifier[evolve] ( identifier[self] , identifier[profile] , identifier[t] , identifier[return_log] = keyword[False] ):
literal[string]
identifier[Qt] = identifier[self] . identifier[expQt] ( identifier[t] ). identifier[T]
identifier[res] = identifier[profile] . identifier[d... | def evolve(self, profile, t, return_log=False):
"""
Compute the probability of the sequence state of the child
at time t later, given the parent profile.
Parameters
----------
profile : numpy.array
Sequence profile. Shape = (L, a),
where L - sequenc... |
def get_policies_from_aws(client, scope='Local'):
"""Returns a list of all the policies currently applied to an AWS Account. Returns a list containing all the
policies for the specified scope
Args:
client (:obj:`boto3.session.Session`): A boto3 Session object
scope (`str... | def function[get_policies_from_aws, parameter[client, scope]]:
constant[Returns a list of all the policies currently applied to an AWS Account. Returns a list containing all the
policies for the specified scope
Args:
client (:obj:`boto3.session.Session`): A boto3 Session object
... | keyword[def] identifier[get_policies_from_aws] ( identifier[client] , identifier[scope] = literal[string] ):
literal[string]
identifier[done] = keyword[False]
identifier[marker] = keyword[None]
identifier[policies] =[]
keyword[while] keyword[not] identifier[done] :
... | def get_policies_from_aws(client, scope='Local'):
"""Returns a list of all the policies currently applied to an AWS Account. Returns a list containing all the
policies for the specified scope
Args:
client (:obj:`boto3.session.Session`): A boto3 Session object
scope (`str`): ... |
def wantMethod(self, method):
"""Is the method a test method?
"""
try:
method_name = method.__name__
except AttributeError:
# not a method
return False
if method_name.startswith('_'):
# never collect 'private' methods
re... | def function[wantMethod, parameter[self, method]]:
constant[Is the method a test method?
]
<ast.Try object at 0x7da1b021c0d0>
if call[name[method_name].startswith, parameter[constant[_]]] begin[:]
return[constant[False]]
variable[declared] assign[=] call[name[getattr], parame... | keyword[def] identifier[wantMethod] ( identifier[self] , identifier[method] ):
literal[string]
keyword[try] :
identifier[method_name] = identifier[method] . identifier[__name__]
keyword[except] identifier[AttributeError] :
keyword[return] keyword[False... | def wantMethod(self, method):
"""Is the method a test method?
"""
try:
method_name = method.__name__ # depends on [control=['try'], data=[]]
except AttributeError:
# not a method
return False # depends on [control=['except'], data=[]]
if method_name.startswith('_'):
... |
def log_indexing_error(cls, indexing_errors):
""" Logs indexing errors and raises a general ElasticSearch Exception"""
indexing_errors_log = []
for indexing_error in indexing_errors:
indexing_errors_log.append(str(indexing_error))
raise exceptions.ElasticsearchException(', '.... | def function[log_indexing_error, parameter[cls, indexing_errors]]:
constant[ Logs indexing errors and raises a general ElasticSearch Exception]
variable[indexing_errors_log] assign[=] list[[]]
for taget[name[indexing_error]] in starred[name[indexing_errors]] begin[:]
call[name[in... | keyword[def] identifier[log_indexing_error] ( identifier[cls] , identifier[indexing_errors] ):
literal[string]
identifier[indexing_errors_log] =[]
keyword[for] identifier[indexing_error] keyword[in] identifier[indexing_errors] :
identifier[indexing_errors_log] . identifier[... | def log_indexing_error(cls, indexing_errors):
""" Logs indexing errors and raises a general ElasticSearch Exception"""
indexing_errors_log = []
for indexing_error in indexing_errors:
indexing_errors_log.append(str(indexing_error)) # depends on [control=['for'], data=['indexing_error']]
raise ex... |
def compile_and_process(self, in_path):
"""compile a file, save it to the ouput file if the inline flag true"""
out_path = self.path_mapping[in_path]
if not self.embed:
pdebug("[%s::%s] %s -> %s" % (
self.compiler_name,
self.name,
os.p... | def function[compile_and_process, parameter[self, in_path]]:
constant[compile a file, save it to the ouput file if the inline flag true]
variable[out_path] assign[=] call[name[self].path_mapping][name[in_path]]
if <ast.UnaryOp object at 0x7da20e955c90> begin[:]
call[name[pdebug],... | keyword[def] identifier[compile_and_process] ( identifier[self] , identifier[in_path] ):
literal[string]
identifier[out_path] = identifier[self] . identifier[path_mapping] [ identifier[in_path] ]
keyword[if] keyword[not] identifier[self] . identifier[embed] :
identifier[pde... | def compile_and_process(self, in_path):
"""compile a file, save it to the ouput file if the inline flag true"""
out_path = self.path_mapping[in_path]
if not self.embed:
pdebug('[%s::%s] %s -> %s' % (self.compiler_name, self.name, os.path.relpath(in_path), os.path.relpath(out_path)), groups=['build_t... |
def cmd_balance():
"""
Посмотреть баланс основного счёта.
"""
r = rocket.operations.cool_feed.get(params={"per_page": 1})
r = handle_error(r)
j = r.json()
template = "".join([
click.style("{rur} {code}, ", fg="green", bold=True),
"{miles} рокетрублей"])
click.echo(templa... | def function[cmd_balance, parameter[]]:
constant[
Посмотреть баланс основного счёта.
]
variable[r] assign[=] call[name[rocket].operations.cool_feed.get, parameter[]]
variable[r] assign[=] call[name[handle_error], parameter[name[r]]]
variable[j] assign[=] call[name[r].json, parame... | keyword[def] identifier[cmd_balance] ():
literal[string]
identifier[r] = identifier[rocket] . identifier[operations] . identifier[cool_feed] . identifier[get] ( identifier[params] ={ literal[string] : literal[int] })
identifier[r] = identifier[handle_error] ( identifier[r] )
identifier[j] = ident... | def cmd_balance():
"""
Посмотреть баланс основного счёта.
"""
r = rocket.operations.cool_feed.get(params={'per_page': 1})
r = handle_error(r)
j = r.json()
template = ''.join([click.style('{rur} {code}, ', fg='green', bold=True), '{miles} рокетрублей'])
click.echo(template.format(rur=j['b... |
def enumerated_list(self, nth, text):
"""Example::
1. item
"""
if not isinstance(nth, int):
raise Exception("'nth' argument has to be an integer!")
return "{nth}. {text}".format(nth=nth, text=text) | def function[enumerated_list, parameter[self, nth, text]]:
constant[Example::
1. item
]
if <ast.UnaryOp object at 0x7da1b1628c10> begin[:]
<ast.Raise object at 0x7da1b162ad40>
return[call[constant[{nth}. {text}].format, parameter[]]] | keyword[def] identifier[enumerated_list] ( identifier[self] , identifier[nth] , identifier[text] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[nth] , identifier[int] ):
keyword[raise] identifier[Exception] ( literal[string] )
keyword[return... | def enumerated_list(self, nth, text):
"""Example::
1. item
"""
if not isinstance(nth, int):
raise Exception("'nth' argument has to be an integer!") # depends on [control=['if'], data=[]]
return '{nth}. {text}'.format(nth=nth, text=text) |
def clicks(times=None, frames=None, sr=22050, hop_length=512,
click_freq=1000.0, click_duration=0.1, click=None, length=None):
"""Returns a signal with the signal `click` placed at each specified time
Parameters
----------
times : np.ndarray or None
times to place clicks, in seconds
... | def function[clicks, parameter[times, frames, sr, hop_length, click_freq, click_duration, click, length]]:
constant[Returns a signal with the signal `click` placed at each specified time
Parameters
----------
times : np.ndarray or None
times to place clicks, in seconds
frames : np.ndar... | keyword[def] identifier[clicks] ( identifier[times] = keyword[None] , identifier[frames] = keyword[None] , identifier[sr] = literal[int] , identifier[hop_length] = literal[int] ,
identifier[click_freq] = literal[int] , identifier[click_duration] = literal[int] , identifier[click] = keyword[None] , identifier[length]... | def clicks(times=None, frames=None, sr=22050, hop_length=512, click_freq=1000.0, click_duration=0.1, click=None, length=None):
"""Returns a signal with the signal `click` placed at each specified time
Parameters
----------
times : np.ndarray or None
times to place clicks, in seconds
frames... |
def new_gp_object(typename):
""" Create an indirect pointer to a GPhoto2 type, call its matching
constructor function and return the pointer to it.
:param typename: Name of the type to create.
:return: A pointer to the specified data type.
"""
obj_p = backend.ffi.new("{0}**".f... | def function[new_gp_object, parameter[typename]]:
constant[ Create an indirect pointer to a GPhoto2 type, call its matching
constructor function and return the pointer to it.
:param typename: Name of the type to create.
:return: A pointer to the specified data type.
]
... | keyword[def] identifier[new_gp_object] ( identifier[typename] ):
literal[string]
identifier[obj_p] = identifier[backend] . identifier[ffi] . identifier[new] ( literal[string] . identifier[format] ( identifier[typename] ))
identifier[backend] . identifier[CONSTRUCTORS] [ identifier[typename] ]( identif... | def new_gp_object(typename):
""" Create an indirect pointer to a GPhoto2 type, call its matching
constructor function and return the pointer to it.
:param typename: Name of the type to create.
:return: A pointer to the specified data type.
"""
obj_p = backend.ffi.new('{0}**'.f... |
def read_text(self, file_handle):
"""Parse the TEXT segment of the FCS file.
The TEXT segment contains meta data associated with the FCS file.
Converting all meta keywords to lower case.
"""
header = self.annotation['__header__'] # For convenience
#####
# Read ... | def function[read_text, parameter[self, file_handle]]:
constant[Parse the TEXT segment of the FCS file.
The TEXT segment contains meta data associated with the FCS file.
Converting all meta keywords to lower case.
]
variable[header] assign[=] call[name[self].annotation][constant... | keyword[def] identifier[read_text] ( identifier[self] , identifier[file_handle] ):
literal[string]
identifier[header] = identifier[self] . identifier[annotation] [ literal[string] ]
identifier[file_handle] . identifier[seek] ( identifier[header] [ literal[string... | def read_text(self, file_handle):
"""Parse the TEXT segment of the FCS file.
The TEXT segment contains meta data associated with the FCS file.
Converting all meta keywords to lower case.
"""
header = self.annotation['__header__'] # For convenience
#####
# Read in the TEXT segme... |
def get_optimal_variant(self, variants, start_words, **kwargs):
"""
Возвращает оптимальный вариант, из выборки.
"""
if not start_words:
return (choice(variants), {})
_variants = []
_weights = []
for tok in frozenset(variants):
if not self... | def function[get_optimal_variant, parameter[self, variants, start_words]]:
constant[
Возвращает оптимальный вариант, из выборки.
]
if <ast.UnaryOp object at 0x7da207f03a00> begin[:]
return[tuple[[<ast.Call object at 0x7da207f032b0>, <ast.Dict object at 0x7da207f01000>]]]
... | keyword[def] identifier[get_optimal_variant] ( identifier[self] , identifier[variants] , identifier[start_words] ,** identifier[kwargs] ):
literal[string]
keyword[if] keyword[not] identifier[start_words] :
keyword[return] ( identifier[choice] ( identifier[variants] ),{})
i... | def get_optimal_variant(self, variants, start_words, **kwargs):
"""
Возвращает оптимальный вариант, из выборки.
"""
if not start_words:
return (choice(variants), {}) # depends on [control=['if'], data=[]]
_variants = []
_weights = []
for tok in frozenset(variants):
i... |
def custom(self, ref, context=None):
"""
Get whether the specified reference is B{not} an (xs) builtin.
@param ref: A str or qref.
@type ref: (str|qref)
@return: True if B{not} a builtin, else False.
@rtype: bool
"""
if ref is None:
return True... | def function[custom, parameter[self, ref, context]]:
constant[
Get whether the specified reference is B{not} an (xs) builtin.
@param ref: A str or qref.
@type ref: (str|qref)
@return: True if B{not} a builtin, else False.
@rtype: bool
]
if compare[name[ref... | keyword[def] identifier[custom] ( identifier[self] , identifier[ref] , identifier[context] = keyword[None] ):
literal[string]
keyword[if] identifier[ref] keyword[is] keyword[None] :
keyword[return] keyword[True]
keyword[else] :
keyword[return] keyword[not] ... | def custom(self, ref, context=None):
"""
Get whether the specified reference is B{not} an (xs) builtin.
@param ref: A str or qref.
@type ref: (str|qref)
@return: True if B{not} a builtin, else False.
@rtype: bool
"""
if ref is None:
return True # depends ... |
def _create_messages(self, metrics):
"""Create a list of zabbix messages from a list of ZabbixMetrics.
:type metrics_array: list
:param metrics_array: List of :class:`zabbix.sender.ZabbixMetric`.
:rtype: list
:return: List of zabbix messages.
"""
messages = []
... | def function[_create_messages, parameter[self, metrics]]:
constant[Create a list of zabbix messages from a list of ZabbixMetrics.
:type metrics_array: list
:param metrics_array: List of :class:`zabbix.sender.ZabbixMetric`.
:rtype: list
:return: List of zabbix messages.
... | keyword[def] identifier[_create_messages] ( identifier[self] , identifier[metrics] ):
literal[string]
identifier[messages] =[]
keyword[for] identifier[m] keyword[in] identifier[metrics] :
identifier[messages] . identifier[append] ( identifier[str] ( identifier[m]... | def _create_messages(self, metrics):
"""Create a list of zabbix messages from a list of ZabbixMetrics.
:type metrics_array: list
:param metrics_array: List of :class:`zabbix.sender.ZabbixMetric`.
:rtype: list
:return: List of zabbix messages.
"""
messages = []
# Fil... |
def _fetch_issues(self, from_date):
"""Fetch the issues from a project (distribution/package)"""
issues_groups = self.client.issues(start=from_date)
for raw_issues in issues_groups:
issues = json.loads(raw_issues)['entries']
for issue in issues:
issue =... | def function[_fetch_issues, parameter[self, from_date]]:
constant[Fetch the issues from a project (distribution/package)]
variable[issues_groups] assign[=] call[name[self].client.issues, parameter[]]
for taget[name[raw_issues]] in starred[name[issues_groups]] begin[:]
variable[is... | keyword[def] identifier[_fetch_issues] ( identifier[self] , identifier[from_date] ):
literal[string]
identifier[issues_groups] = identifier[self] . identifier[client] . identifier[issues] ( identifier[start] = identifier[from_date] )
keyword[for] identifier[raw_issues] keyword[in] ide... | def _fetch_issues(self, from_date):
"""Fetch the issues from a project (distribution/package)"""
issues_groups = self.client.issues(start=from_date)
for raw_issues in issues_groups:
issues = json.loads(raw_issues)['entries']
for issue in issues:
issue = self.__init_extra_issue_fi... |
def jx_expression_to_function(expr):
"""
RETURN FUNCTION THAT REQUIRES PARAMETERS (row, rownum=None, rows=None):
"""
if is_expression(expr):
if is_op(expr, ScriptOp) and not is_text(expr.script):
return expr.script
else:
return compile_expression(Python[expr].to_p... | def function[jx_expression_to_function, parameter[expr]]:
constant[
RETURN FUNCTION THAT REQUIRES PARAMETERS (row, rownum=None, rows=None):
]
if call[name[is_expression], parameter[name[expr]]] begin[:]
if <ast.BoolOp object at 0x7da20c992830> begin[:]
return[name[exp... | keyword[def] identifier[jx_expression_to_function] ( identifier[expr] ):
literal[string]
keyword[if] identifier[is_expression] ( identifier[expr] ):
keyword[if] identifier[is_op] ( identifier[expr] , identifier[ScriptOp] ) keyword[and] keyword[not] identifier[is_text] ( identifier[expr] . iden... | def jx_expression_to_function(expr):
"""
RETURN FUNCTION THAT REQUIRES PARAMETERS (row, rownum=None, rows=None):
"""
if is_expression(expr):
if is_op(expr, ScriptOp) and (not is_text(expr.script)):
return expr.script # depends on [control=['if'], data=[]]
else:
r... |
def read_form_data(self):
"""Attempt to read the form data from the request"""
if self.processed_data:
raise exceptions.AlreadyProcessed('The data has already been processed for this form')
if self.readonly:
return
if request.method == self.method:
... | def function[read_form_data, parameter[self]]:
constant[Attempt to read the form data from the request]
if name[self].processed_data begin[:]
<ast.Raise object at 0x7da20c796560>
if name[self].readonly begin[:]
return[None]
if compare[name[request].method equal[==] name[s... | keyword[def] identifier[read_form_data] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[processed_data] :
keyword[raise] identifier[exceptions] . identifier[AlreadyProcessed] ( literal[string] )
keyword[if] identifier[self] . identifier[read... | def read_form_data(self):
"""Attempt to read the form data from the request"""
if self.processed_data:
raise exceptions.AlreadyProcessed('The data has already been processed for this form') # depends on [control=['if'], data=[]]
if self.readonly:
return # depends on [control=['if'], data=[... |
def CreateUnit(self, parent=None, value=None, bid_amount=None):
"""Creates a unit node.
Args:
parent: The node that should be this node's parent.
value: The value being partitioned on.
bid_amount: The amount to bid for matching products, in micros.
Returns:
A new unit node.
"""
... | def function[CreateUnit, parameter[self, parent, value, bid_amount]]:
constant[Creates a unit node.
Args:
parent: The node that should be this node's parent.
value: The value being partitioned on.
bid_amount: The amount to bid for matching products, in micros.
Returns:
A new uni... | keyword[def] identifier[CreateUnit] ( identifier[self] , identifier[parent] = keyword[None] , identifier[value] = keyword[None] , identifier[bid_amount] = keyword[None] ):
literal[string]
identifier[unit] ={
literal[string] : literal[string] ,
literal[string] : literal[string]
}
k... | def CreateUnit(self, parent=None, value=None, bid_amount=None):
"""Creates a unit node.
Args:
parent: The node that should be this node's parent.
value: The value being partitioned on.
bid_amount: The amount to bid for matching products, in micros.
Returns:
A new unit node.
"""
... |
def _compute_distance_matrix(self):
"""Compute the full distance matrix on pairs of nodes.
The distance map self._dist_matrix is computed from the graph using
all_pairs_shortest_path_length.
"""
if not self.is_connected():
raise CouplingError("coupling graph not conn... | def function[_compute_distance_matrix, parameter[self]]:
constant[Compute the full distance matrix on pairs of nodes.
The distance map self._dist_matrix is computed from the graph using
all_pairs_shortest_path_length.
]
if <ast.UnaryOp object at 0x7da18f00e440> begin[:]
... | keyword[def] identifier[_compute_distance_matrix] ( identifier[self] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[is_connected] ():
keyword[raise] identifier[CouplingError] ( literal[string] )
identifier[lengths] = identifier[nx] . identifier[al... | def _compute_distance_matrix(self):
"""Compute the full distance matrix on pairs of nodes.
The distance map self._dist_matrix is computed from the graph using
all_pairs_shortest_path_length.
"""
if not self.is_connected():
raise CouplingError('coupling graph not connected') # d... |
def dict_query(dic, query):
""" Query a dict with 'dotted notation'. Returns an OrderedDict.
A query of "foo.bar.baz" would retrieve 'wat' from this::
dic = {
'foo': {
'bar': {
'baz': 'wat',
}
}
}
Multiple querie... | def function[dict_query, parameter[dic, query]]:
constant[ Query a dict with 'dotted notation'. Returns an OrderedDict.
A query of "foo.bar.baz" would retrieve 'wat' from this::
dic = {
'foo': {
'bar': {
'baz': 'wat',
}
}... | keyword[def] identifier[dict_query] ( identifier[dic] , identifier[query] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[query] , identifier[six] . identifier[string_types] ):
keyword[raise] identifier[ValueError] ( literal[string] % identifier[type] ( identifi... | def dict_query(dic, query):
""" Query a dict with 'dotted notation'. Returns an OrderedDict.
A query of "foo.bar.baz" would retrieve 'wat' from this::
dic = {
'foo': {
'bar': {
'baz': 'wat',
}
}
}
Multiple querie... |
def below(self, ref):
"""
Move this object below the referenced object.
"""
if not self._valid_ordering_reference(ref):
raise ValueError(
"%r can only be moved below instances of %r which %s equals %r." % (
self, self.__class__, self.order_... | def function[below, parameter[self, ref]]:
constant[
Move this object below the referenced object.
]
if <ast.UnaryOp object at 0x7da1b00e76d0> begin[:]
<ast.Raise object at 0x7da1b00e66e0>
if compare[name[self].order equal[==] name[ref].order] begin[:]
return[None... | keyword[def] identifier[below] ( identifier[self] , identifier[ref] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[_valid_ordering_reference] ( identifier[ref] ):
keyword[raise] identifier[ValueError] (
literal[string] %(
identifi... | def below(self, ref):
"""
Move this object below the referenced object.
"""
if not self._valid_ordering_reference(ref):
raise ValueError('%r can only be moved below instances of %r which %s equals %r.' % (self, self.__class__, self.order_with_respect_to, self._get_order_with_respect_to()... |
def _place_secondary_files(inp_tool, inp_binding=None):
"""Put secondaryFiles at the level of the File item to ensure indexes get passed.
"""
def _is_file(val):
return (val == "File" or (isinstance(val, (list, tuple)) and
("File" in val or any(isinstance(x, dict) an... | def function[_place_secondary_files, parameter[inp_tool, inp_binding]]:
constant[Put secondaryFiles at the level of the File item to ensure indexes get passed.
]
def function[_is_file, parameter[val]]:
return[<ast.BoolOp object at 0x7da1b18bcd30>]
variable[secondary_files] assign[=] ... | keyword[def] identifier[_place_secondary_files] ( identifier[inp_tool] , identifier[inp_binding] = keyword[None] ):
literal[string]
keyword[def] identifier[_is_file] ( identifier[val] ):
keyword[return] ( identifier[val] == literal[string] keyword[or] ( identifier[isinstance] ( identifier[val] ,... | def _place_secondary_files(inp_tool, inp_binding=None):
"""Put secondaryFiles at the level of the File item to ensure indexes get passed.
"""
def _is_file(val):
return val == 'File' or (isinstance(val, (list, tuple)) and ('File' in val or any(isinstance(x, dict) and _is_file(val)) for x in val))
... |
def __run_py_file(self, filepath, module_name):
"""Execute the python file at the passed path
Parameters
----------
filepath: str
the path of the file to execute
module_name: str
the name of the python module
"""
# Import the module
... | def function[__run_py_file, parameter[self, filepath, module_name]]:
constant[Execute the python file at the passed path
Parameters
----------
filepath: str
the path of the file to execute
module_name: str
the name of the python module
]
... | keyword[def] identifier[__run_py_file] ( identifier[self] , identifier[filepath] , identifier[module_name] ):
literal[string]
identifier[spec] = identifier[importlib] . identifier[util] . identifier[spec_from_file_location] ( identifier[module_name] , identifier[filepath] )
ident... | def __run_py_file(self, filepath, module_name):
"""Execute the python file at the passed path
Parameters
----------
filepath: str
the path of the file to execute
module_name: str
the name of the python module
"""
# Import the module
spec =... |
def from_spacegroup(cls, sg, lattice, species, coords, site_properties=None,
coords_are_cartesian=False, tol=1e-5):
"""
Generate a structure using a spacegroup. Note that only symmetrically
distinct species and coords should be provided. All equivalent sites
are g... | def function[from_spacegroup, parameter[cls, sg, lattice, species, coords, site_properties, coords_are_cartesian, tol]]:
constant[
Generate a structure using a spacegroup. Note that only symmetrically
distinct species and coords should be provided. All equivalent sites
are generated from... | keyword[def] identifier[from_spacegroup] ( identifier[cls] , identifier[sg] , identifier[lattice] , identifier[species] , identifier[coords] , identifier[site_properties] = keyword[None] ,
identifier[coords_are_cartesian] = keyword[False] , identifier[tol] = literal[int] ):
literal[string]
keyword... | def from_spacegroup(cls, sg, lattice, species, coords, site_properties=None, coords_are_cartesian=False, tol=1e-05):
"""
Generate a structure using a spacegroup. Note that only symmetrically
distinct species and coords should be provided. All equivalent sites
are generated from the spacegrou... |
def build_input_pipeline(x, y, batch_size):
"""Build a Dataset iterator for supervised classification.
Args:
x: Numpy `array` of features, indexed by the first dimension.
y: Numpy `array` of labels, with the same first dimension as `x`.
batch_size: Number of elements in each training batch.
Returns:... | def function[build_input_pipeline, parameter[x, y, batch_size]]:
constant[Build a Dataset iterator for supervised classification.
Args:
x: Numpy `array` of features, indexed by the first dimension.
y: Numpy `array` of labels, with the same first dimension as `x`.
batch_size: Number of elements in... | keyword[def] identifier[build_input_pipeline] ( identifier[x] , identifier[y] , identifier[batch_size] ):
literal[string]
identifier[training_dataset] = identifier[tf] . identifier[data] . identifier[Dataset] . identifier[from_tensor_slices] (( identifier[x] , identifier[y] ))
identifier[training_batches] =... | def build_input_pipeline(x, y, batch_size):
"""Build a Dataset iterator for supervised classification.
Args:
x: Numpy `array` of features, indexed by the first dimension.
y: Numpy `array` of labels, with the same first dimension as `x`.
batch_size: Number of elements in each training batch.
Return... |
def get_versioned_references_for(self, instance):
"""Returns the versioned references for the given instance
"""
vrefs = []
# Retrieve the referenced objects
refs = instance.getRefs(relationship=self.relationship)
ref_versions = getattr(instance, REFERENCE_VERSIONS, Non... | def function[get_versioned_references_for, parameter[self, instance]]:
constant[Returns the versioned references for the given instance
]
variable[vrefs] assign[=] list[[]]
variable[refs] assign[=] call[name[instance].getRefs, parameter[]]
variable[ref_versions] assign[=] call[na... | keyword[def] identifier[get_versioned_references_for] ( identifier[self] , identifier[instance] ):
literal[string]
identifier[vrefs] =[]
identifier[refs] = identifier[instance] . identifier[getRefs] ( identifier[relationship] = identifier[self] . identifier[relationship] )
... | def get_versioned_references_for(self, instance):
"""Returns the versioned references for the given instance
"""
vrefs = []
# Retrieve the referenced objects
refs = instance.getRefs(relationship=self.relationship)
ref_versions = getattr(instance, REFERENCE_VERSIONS, None)
# No versions s... |
def sync_mptt_tree_fields_from_draft_to_published(
draft_copy, dry_run=False, force_update_cached_urls=False):
"""
Sync tree structure changes from a draft publishable object to its
published copy, and updates the published copy's Fluent cached URLs when
necessary. Or simulates doing this if ``d... | def function[sync_mptt_tree_fields_from_draft_to_published, parameter[draft_copy, dry_run, force_update_cached_urls]]:
constant[
Sync tree structure changes from a draft publishable object to its
published copy, and updates the published copy's Fluent cached URLs when
necessary. Or simulates doing t... | keyword[def] identifier[sync_mptt_tree_fields_from_draft_to_published] (
identifier[draft_copy] , identifier[dry_run] = keyword[False] , identifier[force_update_cached_urls] = keyword[False] ):
literal[string]
identifier[mptt_opts] = identifier[getattr] ( identifier[draft_copy] , literal[string] , keyword... | def sync_mptt_tree_fields_from_draft_to_published(draft_copy, dry_run=False, force_update_cached_urls=False):
"""
Sync tree structure changes from a draft publishable object to its
published copy, and updates the published copy's Fluent cached URLs when
necessary. Or simulates doing this if ``dry_run`` ... |
def assemble_oligos(dna_list, reference=None):
'''Given a list of DNA sequences, assemble into a single construct.
:param dna_list: List of DNA sequences - they must be single-stranded.
:type dna_list: coral.DNA list
:param reference: Expected sequence - once assembly completed, this will
be used to... | def function[assemble_oligos, parameter[dna_list, reference]]:
constant[Given a list of DNA sequences, assemble into a single construct.
:param dna_list: List of DNA sequences - they must be single-stranded.
:type dna_list: coral.DNA list
:param reference: Expected sequence - once assembly completed... | keyword[def] identifier[assemble_oligos] ( identifier[dna_list] , identifier[reference] = keyword[None] ):
literal[string]
identifier[match_3] =[ identifier[bind_unique] ( identifier[seq] , identifier[dna_list] , identifier[right] = keyword[True] ) keyword[for] identifier[i] , identifi... | def assemble_oligos(dna_list, reference=None):
"""Given a list of DNA sequences, assemble into a single construct.
:param dna_list: List of DNA sequences - they must be single-stranded.
:type dna_list: coral.DNA list
:param reference: Expected sequence - once assembly completed, this will
be used to... |
def check_migrations_applied(app_configs, **kwargs):
"""
A Django check to see if all migrations have been applied correctly.
"""
from django.db.migrations.loader import MigrationLoader
errors = []
# Load migrations from disk/DB
try:
loader = MigrationLoader(connection, ignore_no_mi... | def function[check_migrations_applied, parameter[app_configs]]:
constant[
A Django check to see if all migrations have been applied correctly.
]
from relative_module[django.db.migrations.loader] import module[MigrationLoader]
variable[errors] assign[=] list[[]]
<ast.Try object at 0x7da18... | keyword[def] identifier[check_migrations_applied] ( identifier[app_configs] ,** identifier[kwargs] ):
literal[string]
keyword[from] identifier[django] . identifier[db] . identifier[migrations] . identifier[loader] keyword[import] identifier[MigrationLoader]
identifier[errors] =[]
keywor... | def check_migrations_applied(app_configs, **kwargs):
"""
A Django check to see if all migrations have been applied correctly.
"""
from django.db.migrations.loader import MigrationLoader
errors = []
# Load migrations from disk/DB
try:
loader = MigrationLoader(connection, ignore_no_mig... |
def single_from_classes(path:Union[Path, str], classes:Collection[str], ds_tfms:TfmList=None, **kwargs):
"Create an empty `ImageDataBunch` in `path` with `classes`. Typically used for inference."
warn("""This method is deprecated and will be removed in a future version, use `load_learner` after
... | def function[single_from_classes, parameter[path, classes, ds_tfms]]:
constant[Create an empty `ImageDataBunch` in `path` with `classes`. Typically used for inference.]
call[name[warn], parameter[constant[This method is deprecated and will be removed in a future version, use `load_learner` after
... | keyword[def] identifier[single_from_classes] ( identifier[path] : identifier[Union] [ identifier[Path] , identifier[str] ], identifier[classes] : identifier[Collection] [ identifier[str] ], identifier[ds_tfms] : identifier[TfmList] = keyword[None] ,** identifier[kwargs] ):
literal[string]
identifie... | def single_from_classes(path: Union[Path, str], classes: Collection[str], ds_tfms: TfmList=None, **kwargs):
"""Create an empty `ImageDataBunch` in `path` with `classes`. Typically used for inference."""
warn('This method is deprecated and will be removed in a future version, use `load_learner` after\n ... |
def _basename(fname):
"""Return file name without path."""
if not isinstance(fname, Path):
fname = Path(fname)
path, name, ext = fname.parent, fname.stem, fname.suffix
return path, name, ext | def function[_basename, parameter[fname]]:
constant[Return file name without path.]
if <ast.UnaryOp object at 0x7da1b0465c00> begin[:]
variable[fname] assign[=] call[name[Path], parameter[name[fname]]]
<ast.Tuple object at 0x7da18eb544c0> assign[=] tuple[[<ast.Attribute object at... | keyword[def] identifier[_basename] ( identifier[fname] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[fname] , identifier[Path] ):
identifier[fname] = identifier[Path] ( identifier[fname] )
identifier[path] , identifier[name] , identifier[ext] = identifier[f... | def _basename(fname):
"""Return file name without path."""
if not isinstance(fname, Path):
fname = Path(fname) # depends on [control=['if'], data=[]]
(path, name, ext) = (fname.parent, fname.stem, fname.suffix)
return (path, name, ext) |
def toEncoding(self, s, encoding=None):
"""Encodes an object to a string in some encoding, or to Unicode.
."""
if isinstance(s, unicode):
if encoding:
s = s.encode(encoding)
elif isinstance(s, str):
if encoding:
s = s.encode(encodin... | def function[toEncoding, parameter[self, s, encoding]]:
constant[Encodes an object to a string in some encoding, or to Unicode.
.]
if call[name[isinstance], parameter[name[s], name[unicode]]] begin[:]
if name[encoding] begin[:]
variable[s] assign[=] call[n... | keyword[def] identifier[toEncoding] ( identifier[self] , identifier[s] , identifier[encoding] = keyword[None] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[s] , identifier[unicode] ):
keyword[if] identifier[encoding] :
identifier[s] = identifier[... | def toEncoding(self, s, encoding=None):
"""Encodes an object to a string in some encoding, or to Unicode.
."""
if isinstance(s, unicode):
if encoding:
s = s.encode(encoding) # depends on [control=['if'], data=[]] # depends on [control=['if'], data=[]]
elif isinstance(s, str):
... |
def st_mtime(self):
"""Return the modification time in seconds."""
mtime = self._st_mtime_ns / 1e9
return mtime if self.use_float else int(mtime) | def function[st_mtime, parameter[self]]:
constant[Return the modification time in seconds.]
variable[mtime] assign[=] binary_operation[name[self]._st_mtime_ns / constant[1000000000.0]]
return[<ast.IfExp object at 0x7da20c6e6aa0>] | keyword[def] identifier[st_mtime] ( identifier[self] ):
literal[string]
identifier[mtime] = identifier[self] . identifier[_st_mtime_ns] / literal[int]
keyword[return] identifier[mtime] keyword[if] identifier[self] . identifier[use_float] keyword[else] identifier[int] ( identifier[mti... | def st_mtime(self):
"""Return the modification time in seconds."""
mtime = self._st_mtime_ns / 1000000000.0
return mtime if self.use_float else int(mtime) |
def add_asset(self, asset_type, asset_name):
"""
Add an asset to the adversary
Args:
asset_type: (str) Either PHONE, HANDLER, or URL
asset_name: (str) the value for the asset
Returns:
"""
if not self.can_update():
self._tcex.handle_er... | def function[add_asset, parameter[self, asset_type, asset_name]]:
constant[
Add an asset to the adversary
Args:
asset_type: (str) Either PHONE, HANDLER, or URL
asset_name: (str) the value for the asset
Returns:
]
if <ast.UnaryOp object at 0x7da18... | keyword[def] identifier[add_asset] ( identifier[self] , identifier[asset_type] , identifier[asset_name] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[can_update] ():
identifier[self] . identifier[_tcex] . identifier[handle_error] ( literal[int] ,[ identifi... | def add_asset(self, asset_type, asset_name):
"""
Add an asset to the adversary
Args:
asset_type: (str) Either PHONE, HANDLER, or URL
asset_name: (str) the value for the asset
Returns:
"""
if not self.can_update():
self._tcex.handle_error(910, [se... |
def eval_simple_cor_pattern(self, pattern, hosts, services,
hostgroups, servicegroups, running=False):
"""Parse and build recursively a tree of DependencyNode from a simple pattern
:param pattern: pattern to parse
:type pattern: str
:param hosts: hosts li... | def function[eval_simple_cor_pattern, parameter[self, pattern, hosts, services, hostgroups, servicegroups, running]]:
constant[Parse and build recursively a tree of DependencyNode from a simple pattern
:param pattern: pattern to parse
:type pattern: str
:param hosts: hosts list, used to... | keyword[def] identifier[eval_simple_cor_pattern] ( identifier[self] , identifier[pattern] , identifier[hosts] , identifier[services] ,
identifier[hostgroups] , identifier[servicegroups] , identifier[running] = keyword[False] ):
literal[string]
identifier[node] = identifier[DependencyNode] ()
... | def eval_simple_cor_pattern(self, pattern, hosts, services, hostgroups, servicegroups, running=False):
"""Parse and build recursively a tree of DependencyNode from a simple pattern
:param pattern: pattern to parse
:type pattern: str
:param hosts: hosts list, used to find a specific host
... |
def generate_encoded_user_data(
env='dev',
region='us-east-1',
generated=None,
group_name='',
pipeline_type='',
canary=False,
):
r"""Generate base64 encoded User Data.
Args:
env (str): Deployment environment, e.g. dev, stage.
region (str): AWS Reg... | def function[generate_encoded_user_data, parameter[env, region, generated, group_name, pipeline_type, canary]]:
constant[Generate base64 encoded User Data.
Args:
env (str): Deployment environment, e.g. dev, stage.
region (str): AWS Region, e.g. us-east-1.
generated (gogoutils.Genera... | keyword[def] identifier[generate_encoded_user_data] (
identifier[env] = literal[string] ,
identifier[region] = literal[string] ,
identifier[generated] = keyword[None] ,
identifier[group_name] = literal[string] ,
identifier[pipeline_type] = literal[string] ,
identifier[canary] = keyword[False] ,
):
literal[... | def generate_encoded_user_data(env='dev', region='us-east-1', generated=None, group_name='', pipeline_type='', canary=False):
"""Generate base64 encoded User Data.
Args:
env (str): Deployment environment, e.g. dev, stage.
region (str): AWS Region, e.g. us-east-1.
generated (gogoutils.Ge... |
def formatter(self):
"""
Creates and returns a Formatter capable of nicely formatting Lambda function logs
Returns
-------
LogsFormatter
"""
formatter_chain = [
LambdaLogMsgFormatters.colorize_errors,
# Format JSON "before" highlighting t... | def function[formatter, parameter[self]]:
constant[
Creates and returns a Formatter capable of nicely formatting Lambda function logs
Returns
-------
LogsFormatter
]
variable[formatter_chain] assign[=] list[[<ast.Attribute object at 0x7da1b1f71240>, <ast.Attribut... | keyword[def] identifier[formatter] ( identifier[self] ):
literal[string]
identifier[formatter_chain] =[
identifier[LambdaLogMsgFormatters] . identifier[colorize_errors] ,
identifier[JSONMsgFormatter] . identifier[format_json] ,
identifier[KeywordHighli... | def formatter(self):
"""
Creates and returns a Formatter capable of nicely formatting Lambda function logs
Returns
-------
LogsFormatter
"""
# Format JSON "before" highlighting the keywords. Otherwise, JSON will be invalid from all the
# ANSI color codes and fail to ... |
def _get_default(self, obj):
''' Internal implementation of instance attribute access for default
values.
Handles bookeeping around |PropertyContainer| value, etc.
'''
if self.name in obj._property_values:
# this shouldn't happen because we should have checked befor... | def function[_get_default, parameter[self, obj]]:
constant[ Internal implementation of instance attribute access for default
values.
Handles bookeeping around |PropertyContainer| value, etc.
]
if compare[name[self].name in name[obj]._property_values] begin[:]
<ast.Raise... | keyword[def] identifier[_get_default] ( identifier[self] , identifier[obj] ):
literal[string]
keyword[if] identifier[self] . identifier[name] keyword[in] identifier[obj] . identifier[_property_values] :
keyword[raise] identifier[RuntimeError] ( literal[string] )
... | def _get_default(self, obj):
""" Internal implementation of instance attribute access for default
values.
Handles bookeeping around |PropertyContainer| value, etc.
"""
if self.name in obj._property_values:
# this shouldn't happen because we should have checked before _get_defau... |
def fire_freerun_worker(self, thread_handler_header):
""" fires free-run worker with no dependencies to track """
try:
assert isinstance(thread_handler_header, ThreadHandlerHeader)
self.logger.info('{0} {{'.format(thread_handler_header.key))
state_machine = self.time... | def function[fire_freerun_worker, parameter[self, thread_handler_header]]:
constant[ fires free-run worker with no dependencies to track ]
<ast.Try object at 0x7da1b2424280> | keyword[def] identifier[fire_freerun_worker] ( identifier[self] , identifier[thread_handler_header] ):
literal[string]
keyword[try] :
keyword[assert] identifier[isinstance] ( identifier[thread_handler_header] , identifier[ThreadHandlerHeader] )
identifier[self] . identifi... | def fire_freerun_worker(self, thread_handler_header):
""" fires free-run worker with no dependencies to track """
try:
assert isinstance(thread_handler_header, ThreadHandlerHeader)
self.logger.info('{0} {{'.format(thread_handler_header.key))
state_machine = self.timetable.state_machines[... |
def Overlay_setSuspended(self, suspended):
"""
Function path: Overlay.setSuspended
Domain: Overlay
Method name: setSuspended
Parameters:
Required arguments:
'suspended' (type: boolean) -> Whether overlay should be suspended and not consume any resources until resumed.
No return value.
"... | def function[Overlay_setSuspended, parameter[self, suspended]]:
constant[
Function path: Overlay.setSuspended
Domain: Overlay
Method name: setSuspended
Parameters:
Required arguments:
'suspended' (type: boolean) -> Whether overlay should be suspended and not consume any resources until re... | keyword[def] identifier[Overlay_setSuspended] ( identifier[self] , identifier[suspended] ):
literal[string]
keyword[assert] identifier[isinstance] ( identifier[suspended] ,( identifier[bool] ,)
), literal[string] % identifier[type] (
identifier[suspended] )
identifier[subdom_funcs] = identifier[self] ... | def Overlay_setSuspended(self, suspended):
"""
Function path: Overlay.setSuspended
Domain: Overlay
Method name: setSuspended
Parameters:
Required arguments:
'suspended' (type: boolean) -> Whether overlay should be suspended and not consume any resources until resumed.
No return value.
... |
def WriteClientSnapshot(self, snapshot):
"""Writes new client snapshot."""
client_id = snapshot.client_id
if client_id not in self.metadatas:
raise db.UnknownClientError(client_id)
startup_info = snapshot.startup_info
snapshot.startup_info = None
ts = rdfvalue.RDFDatetime.Now()
hist... | def function[WriteClientSnapshot, parameter[self, snapshot]]:
constant[Writes new client snapshot.]
variable[client_id] assign[=] name[snapshot].client_id
if compare[name[client_id] <ast.NotIn object at 0x7da2590d7190> name[self].metadatas] begin[:]
<ast.Raise object at 0x7da1b1b47940>
... | keyword[def] identifier[WriteClientSnapshot] ( identifier[self] , identifier[snapshot] ):
literal[string]
identifier[client_id] = identifier[snapshot] . identifier[client_id]
keyword[if] identifier[client_id] keyword[not] keyword[in] identifier[self] . identifier[metadatas] :
keyword[rais... | def WriteClientSnapshot(self, snapshot):
"""Writes new client snapshot."""
client_id = snapshot.client_id
if client_id not in self.metadatas:
raise db.UnknownClientError(client_id) # depends on [control=['if'], data=['client_id']]
startup_info = snapshot.startup_info
snapshot.startup_info =... |
def _get_goids(gostr):
"""Return GO IDs from a GO str (e.g., GO:0043473,GO:0009987) or a file."""
if 'GO:' in gostr:
return gostr.split(',')
elif os.path.exists(gostr):
return GetGOs().get_goids(None, gostr, sys.stdout) | def function[_get_goids, parameter[gostr]]:
constant[Return GO IDs from a GO str (e.g., GO:0043473,GO:0009987) or a file.]
if compare[constant[GO:] in name[gostr]] begin[:]
return[call[name[gostr].split, parameter[constant[,]]]] | keyword[def] identifier[_get_goids] ( identifier[gostr] ):
literal[string]
keyword[if] literal[string] keyword[in] identifier[gostr] :
keyword[return] identifier[gostr] . identifier[split] ( literal[string] )
keyword[elif] identifier[os] . identifier[path] . identifier[ex... | def _get_goids(gostr):
"""Return GO IDs from a GO str (e.g., GO:0043473,GO:0009987) or a file."""
if 'GO:' in gostr:
return gostr.split(',') # depends on [control=['if'], data=['gostr']]
elif os.path.exists(gostr):
return GetGOs().get_goids(None, gostr, sys.stdout) # depends on [control=['... |
def notify(self, msgtype, method, params):
"""Handle an incoming notify request."""
self.dispatch.call(method, params) | def function[notify, parameter[self, msgtype, method, params]]:
constant[Handle an incoming notify request.]
call[name[self].dispatch.call, parameter[name[method], name[params]]] | keyword[def] identifier[notify] ( identifier[self] , identifier[msgtype] , identifier[method] , identifier[params] ):
literal[string]
identifier[self] . identifier[dispatch] . identifier[call] ( identifier[method] , identifier[params] ) | def notify(self, msgtype, method, params):
"""Handle an incoming notify request."""
self.dispatch.call(method, params) |
def wherenot(self, fieldname, value):
"""
Logical opposite of `where`.
"""
return self.where(fieldname, value, negate=True) | def function[wherenot, parameter[self, fieldname, value]]:
constant[
Logical opposite of `where`.
]
return[call[name[self].where, parameter[name[fieldname], name[value]]]] | keyword[def] identifier[wherenot] ( identifier[self] , identifier[fieldname] , identifier[value] ):
literal[string]
keyword[return] identifier[self] . identifier[where] ( identifier[fieldname] , identifier[value] , identifier[negate] = keyword[True] ) | def wherenot(self, fieldname, value):
"""
Logical opposite of `where`.
"""
return self.where(fieldname, value, negate=True) |
def read_rec(table_name, objid):
"""Generator that yields keyed recs from store."""
req = datastore.LookupRequest()
req.key.extend([make_key(table_name, objid)])
for found in datastore.lookup(req).found:
yield extract_entity(found) | def function[read_rec, parameter[table_name, objid]]:
constant[Generator that yields keyed recs from store.]
variable[req] assign[=] call[name[datastore].LookupRequest, parameter[]]
call[name[req].key.extend, parameter[list[[<ast.Call object at 0x7da20c76fb20>]]]]
for taget[name[found]] ... | keyword[def] identifier[read_rec] ( identifier[table_name] , identifier[objid] ):
literal[string]
identifier[req] = identifier[datastore] . identifier[LookupRequest] ()
identifier[req] . identifier[key] . identifier[extend] ([ identifier[make_key] ( identifier[table_name] , identifier[objid] )])
... | def read_rec(table_name, objid):
"""Generator that yields keyed recs from store."""
req = datastore.LookupRequest()
req.key.extend([make_key(table_name, objid)])
for found in datastore.lookup(req).found:
yield extract_entity(found) # depends on [control=['for'], data=['found']] |
def calc_individual_chi_squares(residuals,
long_probabilities,
rows_to_obs):
"""
Calculates individual chi-squared values for each choice situation in the
dataset.
Parameters
----------
residuals : 1D ndarray.
The choice ve... | def function[calc_individual_chi_squares, parameter[residuals, long_probabilities, rows_to_obs]]:
constant[
Calculates individual chi-squared values for each choice situation in the
dataset.
Parameters
----------
residuals : 1D ndarray.
The choice vector minus the predicted probabil... | keyword[def] identifier[calc_individual_chi_squares] ( identifier[residuals] ,
identifier[long_probabilities] ,
identifier[rows_to_obs] ):
literal[string]
identifier[chi_squared_terms] = identifier[np] . identifier[square] ( identifier[residuals] )/ identifier[long_probabilities]
keyword[return] i... | def calc_individual_chi_squares(residuals, long_probabilities, rows_to_obs):
"""
Calculates individual chi-squared values for each choice situation in the
dataset.
Parameters
----------
residuals : 1D ndarray.
The choice vector minus the predicted probability of each alternative
... |
def get_attached_volume(self, datacenter_id, server_id, volume_id):
"""
Retrieves volume information.
:param datacenter_id: The unique ID of the data center.
:type datacenter_id: ``str``
:param server_id: The unique ID of the server.
:type server_i... | def function[get_attached_volume, parameter[self, datacenter_id, server_id, volume_id]]:
constant[
Retrieves volume information.
:param datacenter_id: The unique ID of the data center.
:type datacenter_id: ``str``
:param server_id: The unique ID of the server.
... | keyword[def] identifier[get_attached_volume] ( identifier[self] , identifier[datacenter_id] , identifier[server_id] , identifier[volume_id] ):
literal[string]
identifier[response] = identifier[self] . identifier[_perform_request] (
literal[string] %(
identifier[datacenter_id] ,
... | def get_attached_volume(self, datacenter_id, server_id, volume_id):
"""
Retrieves volume information.
:param datacenter_id: The unique ID of the data center.
:type datacenter_id: ``str``
:param server_id: The unique ID of the server.
:type server_id: `... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.