code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def tgv_phantom(space, edge_smoothing=0.2):
"""Piecewise affine phantom.
This phantom is taken from [Bre+2010] and includes both linearly varying
regions and sharp discontinuities. It is designed to work well with
Total Generalized Variation (TGV) type regularization.
Parameters
----------
... | def function[tgv_phantom, parameter[space, edge_smoothing]]:
constant[Piecewise affine phantom.
This phantom is taken from [Bre+2010] and includes both linearly varying
regions and sharp discontinuities. It is designed to work well with
Total Generalized Variation (TGV) type regularization.
Pa... | keyword[def] identifier[tgv_phantom] ( identifier[space] , identifier[edge_smoothing] = literal[int] ):
literal[string]
keyword[if] identifier[space] . identifier[ndim] != literal[int] :
keyword[raise] identifier[ValueError] ( literal[string]
literal[string] . identifier[format] ( iden... | def tgv_phantom(space, edge_smoothing=0.2):
"""Piecewise affine phantom.
This phantom is taken from [Bre+2010] and includes both linearly varying
regions and sharp discontinuities. It is designed to work well with
Total Generalized Variation (TGV) type regularization.
Parameters
----------
... |
def jobInsert(self, client, cmdLine, clientInfo='', clientKey='', params='',
alreadyRunning=False, minimumWorkers=0, maximumWorkers=0,
jobType='', priority=DEFAULT_JOB_PRIORITY):
""" Add an entry to the jobs table for a new job request. This is called by
clients that wish to star... | def function[jobInsert, parameter[self, client, cmdLine, clientInfo, clientKey, params, alreadyRunning, minimumWorkers, maximumWorkers, jobType, priority]]:
constant[ Add an entry to the jobs table for a new job request. This is called by
clients that wish to startup a new job, like a Hypersearch, stream jo... | keyword[def] identifier[jobInsert] ( identifier[self] , identifier[client] , identifier[cmdLine] , identifier[clientInfo] = literal[string] , identifier[clientKey] = literal[string] , identifier[params] = literal[string] ,
identifier[alreadyRunning] = keyword[False] , identifier[minimumWorkers] = literal[int] , iden... | def jobInsert(self, client, cmdLine, clientInfo='', clientKey='', params='', alreadyRunning=False, minimumWorkers=0, maximumWorkers=0, jobType='', priority=DEFAULT_JOB_PRIORITY):
""" Add an entry to the jobs table for a new job request. This is called by
clients that wish to startup a new job, like a Hypersearc... |
def config(self, show_row_hdrs=True, show_col_hdrs=True,
show_col_hdr_in_cell=False, auto_resize=True):
"""
Override the in-class params:
@param show_row_hdrs : show row headers
@param show_col_hdrs : show column headers
@param show_col_hdr_in_cell : embed column... | def function[config, parameter[self, show_row_hdrs, show_col_hdrs, show_col_hdr_in_cell, auto_resize]]:
constant[
Override the in-class params:
@param show_row_hdrs : show row headers
@param show_col_hdrs : show column headers
@param show_col_hdr_in_cell : embed column header in... | keyword[def] identifier[config] ( identifier[self] , identifier[show_row_hdrs] = keyword[True] , identifier[show_col_hdrs] = keyword[True] ,
identifier[show_col_hdr_in_cell] = keyword[False] , identifier[auto_resize] = keyword[True] ):
literal[string]
identifier[self] . identifier[show_row_hdrs] =... | def config(self, show_row_hdrs=True, show_col_hdrs=True, show_col_hdr_in_cell=False, auto_resize=True):
"""
Override the in-class params:
@param show_row_hdrs : show row headers
@param show_col_hdrs : show column headers
@param show_col_hdr_in_cell : embed column header in each cell... |
def send_text(self, user_id, content, account=None):
"""
发送文本消息
详情请参考
http://mp.weixin.qq.com/wiki/7/12a5a320ae96fecdf0e15cb06123de9f.html
:param user_id: 用户 ID 。 就是你收到的 `Message` 的 source
:param content: 消息正文
:param account: 可选,客服账号
:return: 返回的 JSON 数据... | def function[send_text, parameter[self, user_id, content, account]]:
constant[
发送文本消息
详情请参考
http://mp.weixin.qq.com/wiki/7/12a5a320ae96fecdf0e15cb06123de9f.html
:param user_id: 用户 ID 。 就是你收到的 `Message` 的 source
:param content: 消息正文
:param account: 可选,客服账号
... | keyword[def] identifier[send_text] ( identifier[self] , identifier[user_id] , identifier[content] , identifier[account] = keyword[None] ):
literal[string]
identifier[data] ={
literal[string] : identifier[user_id] ,
literal[string] : literal[string] ,
literal[string] :{ li... | def send_text(self, user_id, content, account=None):
"""
发送文本消息
详情请参考
http://mp.weixin.qq.com/wiki/7/12a5a320ae96fecdf0e15cb06123de9f.html
:param user_id: 用户 ID 。 就是你收到的 `Message` 的 source
:param content: 消息正文
:param account: 可选,客服账号
:return: 返回的 JSON 数据包
... |
def _get_battery_status(self, battery):
"""
Get the battery status
"""
if battery["charge"] == -1:
return (UNKNOWN_SYMBOL, UNKNOWN, "#FFFFFF")
if battery["isCharging"]:
status = self.status_chr
color = self.py3.COLOR_GOOD
else:
... | def function[_get_battery_status, parameter[self, battery]]:
constant[
Get the battery status
]
if compare[call[name[battery]][constant[charge]] equal[==] <ast.UnaryOp object at 0x7da1b2089750>] begin[:]
return[tuple[[<ast.Name object at 0x7da1b208ae00>, <ast.Name object at 0x7da... | keyword[def] identifier[_get_battery_status] ( identifier[self] , identifier[battery] ):
literal[string]
keyword[if] identifier[battery] [ literal[string] ]==- literal[int] :
keyword[return] ( identifier[UNKNOWN_SYMBOL] , identifier[UNKNOWN] , literal[string] )
keyword[if] ... | def _get_battery_status(self, battery):
"""
Get the battery status
"""
if battery['charge'] == -1:
return (UNKNOWN_SYMBOL, UNKNOWN, '#FFFFFF') # depends on [control=['if'], data=[]]
if battery['isCharging']:
status = self.status_chr
color = self.py3.COLOR_GOOD # dep... |
def _create_dataset(self, *data):
"""Converts input data to the appropriate Dataset"""
# Make sure data is a tuple of dense tensors
data = [self._to_torch(x, dtype=torch.FloatTensor) for x in data]
return TensorDataset(*data) | def function[_create_dataset, parameter[self]]:
constant[Converts input data to the appropriate Dataset]
variable[data] assign[=] <ast.ListComp object at 0x7da1b1b64280>
return[call[name[TensorDataset], parameter[<ast.Starred object at 0x7da1b1cbb040>]]] | keyword[def] identifier[_create_dataset] ( identifier[self] ,* identifier[data] ):
literal[string]
identifier[data] =[ identifier[self] . identifier[_to_torch] ( identifier[x] , identifier[dtype] = identifier[torch] . identifier[FloatTensor] ) keyword[for] identifier[x] keyword[in] iden... | def _create_dataset(self, *data):
"""Converts input data to the appropriate Dataset"""
# Make sure data is a tuple of dense tensors
data = [self._to_torch(x, dtype=torch.FloatTensor) for x in data]
return TensorDataset(*data) |
def histogram(sa, xlabel=LABEL_DEFAULT, ylabel=LABEL_DEFAULT, title=LABEL_DEFAULT):
"""
Plots a histogram of the sarray provided as input, and returns the
resulting Plot object.
The function supports numeric SArrays with dtypes int or float.
Parameters
----------
sa : SArray
The... | def function[histogram, parameter[sa, xlabel, ylabel, title]]:
constant[
Plots a histogram of the sarray provided as input, and returns the
resulting Plot object.
The function supports numeric SArrays with dtypes int or float.
Parameters
----------
sa : SArray
The data to ge... | keyword[def] identifier[histogram] ( identifier[sa] , identifier[xlabel] = identifier[LABEL_DEFAULT] , identifier[ylabel] = identifier[LABEL_DEFAULT] , identifier[title] = identifier[LABEL_DEFAULT] ):
literal[string]
keyword[if] ( keyword[not] identifier[isinstance] ( identifier[sa] , identifier[tc] . ide... | def histogram(sa, xlabel=LABEL_DEFAULT, ylabel=LABEL_DEFAULT, title=LABEL_DEFAULT):
"""
Plots a histogram of the sarray provided as input, and returns the
resulting Plot object.
The function supports numeric SArrays with dtypes int or float.
Parameters
----------
sa : SArray
The... |
def send(self):
""" Post fields and files to an HTTP server as multipart/form-data.
Return the server's response.
"""
scheme, location, path, query, _ = urlparse.urlsplit(self.url)
assert scheme in ("http", "https"), "Unsupported scheme %r" % scheme
content_type, bod... | def function[send, parameter[self]]:
constant[ Post fields and files to an HTTP server as multipart/form-data.
Return the server's response.
]
<ast.Tuple object at 0x7da18f58e530> assign[=] call[name[urlparse].urlsplit, parameter[name[self].url]]
assert[compare[name[scheme] in tu... | keyword[def] identifier[send] ( identifier[self] ):
literal[string]
identifier[scheme] , identifier[location] , identifier[path] , identifier[query] , identifier[_] = identifier[urlparse] . identifier[urlsplit] ( identifier[self] . identifier[url] )
keyword[assert] identifier[scheme] key... | def send(self):
""" Post fields and files to an HTTP server as multipart/form-data.
Return the server's response.
"""
(scheme, location, path, query, _) = urlparse.urlsplit(self.url)
assert scheme in ('http', 'https'), 'Unsupported scheme %r' % scheme
(content_type, body) = self._enc... |
def print_doc1(*args, **kwargs):
'''Print the first paragraph of the docstring of the decorated function.
The paragraph will be printed as a oneliner.
May be invoked as a simple, argument-less decorator (i.e. ``@print_doc1``)
or with named arguments ``color``, ``bold``, ``prefix`` of ``tail``
(eg.... | def function[print_doc1, parameter[]]:
constant[Print the first paragraph of the docstring of the decorated function.
The paragraph will be printed as a oneliner.
May be invoked as a simple, argument-less decorator (i.e. ``@print_doc1``)
or with named arguments ``color``, ``bold``, ``prefix`` of `... | keyword[def] identifier[print_doc1] (* identifier[args] ,** identifier[kwargs] ):
literal[string]
identifier[color] = identifier[kwargs] . identifier[get] ( literal[string] , identifier[blue] )
identifier[bold] = identifier[kwargs] . identifier[get] ( literal[string] , keyword[False] )
ident... | def print_doc1(*args, **kwargs):
'''Print the first paragraph of the docstring of the decorated function.
The paragraph will be printed as a oneliner.
May be invoked as a simple, argument-less decorator (i.e. ``@print_doc1``)
or with named arguments ``color``, ``bold``, ``prefix`` of ``tail``
(eg.... |
def _add_months(self, date, months):
"""
Add ``months`` months to ``date``.
Unfortunately we can't use timedeltas to add months because timedelta counts in days
and there's no foolproof way to add N months in days without counting the number of
days per month.
"""
... | def function[_add_months, parameter[self, date, months]]:
constant[
Add ``months`` months to ``date``.
Unfortunately we can't use timedeltas to add months because timedelta counts in days
and there's no foolproof way to add N months in days without counting the number of
days pe... | keyword[def] identifier[_add_months] ( identifier[self] , identifier[date] , identifier[months] ):
literal[string]
identifier[year] = identifier[date] . identifier[year] +( identifier[date] . identifier[month] + identifier[months] - literal[int] )// literal[int]
identifier[month] =( ident... | def _add_months(self, date, months):
"""
Add ``months`` months to ``date``.
Unfortunately we can't use timedeltas to add months because timedelta counts in days
and there's no foolproof way to add N months in days without counting the number of
days per month.
"""
year =... |
def p_moduleComplianceClause(self, p):
"""moduleComplianceClause : LOWERCASE_IDENTIFIER MODULE_COMPLIANCE STATUS Status DESCRIPTION Text ReferPart ComplianceModulePart COLON_COLON_EQUAL '{' objectIdentifier '}'"""
p[0] = ('moduleComplianceClause',
p[1], # id
# p[2], # M... | def function[p_moduleComplianceClause, parameter[self, p]]:
constant[moduleComplianceClause : LOWERCASE_IDENTIFIER MODULE_COMPLIANCE STATUS Status DESCRIPTION Text ReferPart ComplianceModulePart COLON_COLON_EQUAL '{' objectIdentifier '}']
call[name[p]][constant[0]] assign[=] tuple[[<ast.Constant object ... | keyword[def] identifier[p_moduleComplianceClause] ( identifier[self] , identifier[p] ):
literal[string]
identifier[p] [ literal[int] ]=( literal[string] ,
identifier[p] [ literal[int] ],
identifier[p] [ literal[int] ],
( identifier[p] [ literal[int] ], identifier[... | def p_moduleComplianceClause(self, p):
"""moduleComplianceClause : LOWERCASE_IDENTIFIER MODULE_COMPLIANCE STATUS Status DESCRIPTION Text ReferPart ComplianceModulePart COLON_COLON_EQUAL '{' objectIdentifier '}'""" # id
# p[2], # MODULE_COMPLIANCE
# status
# description
# reference
# Compliance... |
def detect(self, sampfrom=0, sampto='end', learn=True, verbose=True):
"""
Detect qrs locations between two samples.
Parameters
----------
sampfrom : int, optional
The starting sample number to run the detection on.
sampto : int, optional
The final... | def function[detect, parameter[self, sampfrom, sampto, learn, verbose]]:
constant[
Detect qrs locations between two samples.
Parameters
----------
sampfrom : int, optional
The starting sample number to run the detection on.
sampto : int, optional
... | keyword[def] identifier[detect] ( identifier[self] , identifier[sampfrom] = literal[int] , identifier[sampto] = literal[string] , identifier[learn] = keyword[True] , identifier[verbose] = keyword[True] ):
literal[string]
keyword[if] identifier[sampfrom] < literal[int] :
keyword[raise]... | def detect(self, sampfrom=0, sampto='end', learn=True, verbose=True):
"""
Detect qrs locations between two samples.
Parameters
----------
sampfrom : int, optional
The starting sample number to run the detection on.
sampto : int, optional
The final sam... |
def rrandom():
"""Get the next random number in the range [0.0, 1.0].
Returns a float."""
import urllib.request
import urllib.error
import urllib.parse
if checkquota() < 1:
raise Exception("Your www.random.org quota has already run out.")
request = urllib.request.Request(
'ht... | def function[rrandom, parameter[]]:
constant[Get the next random number in the range [0.0, 1.0].
Returns a float.]
import module[urllib.request]
import module[urllib.error]
import module[urllib.parse]
if compare[call[name[checkquota], parameter[]] less[<] constant[1]] begin[:]
<a... | keyword[def] identifier[rrandom] ():
literal[string]
keyword[import] identifier[urllib] . identifier[request]
keyword[import] identifier[urllib] . identifier[error]
keyword[import] identifier[urllib] . identifier[parse]
keyword[if] identifier[checkquota] ()< literal[int] :
ke... | def rrandom():
"""Get the next random number in the range [0.0, 1.0].
Returns a float."""
import urllib.request
import urllib.error
import urllib.parse
if checkquota() < 1:
raise Exception('Your www.random.org quota has already run out.') # depends on [control=['if'], data=[]]
reque... |
def explain_prediction_lightning(estimator, doc, vec=None, top=None,
target_names=None, targets=None,
feature_names=None, vectorized=False,
coef_scale=None):
""" Return an explanation of a lightning estimator predicti... | def function[explain_prediction_lightning, parameter[estimator, doc, vec, top, target_names, targets, feature_names, vectorized, coef_scale]]:
constant[ Return an explanation of a lightning estimator predictions ]
return[call[name[explain_weights_lightning_not_supported], parameter[name[estimator], name[doc... | keyword[def] identifier[explain_prediction_lightning] ( identifier[estimator] , identifier[doc] , identifier[vec] = keyword[None] , identifier[top] = keyword[None] ,
identifier[target_names] = keyword[None] , identifier[targets] = keyword[None] ,
identifier[feature_names] = keyword[None] , identifier[vectorized] = ... | def explain_prediction_lightning(estimator, doc, vec=None, top=None, target_names=None, targets=None, feature_names=None, vectorized=False, coef_scale=None):
""" Return an explanation of a lightning estimator predictions """
return explain_weights_lightning_not_supported(estimator, doc) |
def AND(queryArr,
exclude = None):
"""
create a combined query with multiple items on which to perform an AND operation
@param queryArr: a list of items on which to perform an AND operation. Items can be either a CombinedQuery or BaseQuery instances.
@param exclude: a instanc... | def function[AND, parameter[queryArr, exclude]]:
constant[
create a combined query with multiple items on which to perform an AND operation
@param queryArr: a list of items on which to perform an AND operation. Items can be either a CombinedQuery or BaseQuery instances.
@param exclude: a... | keyword[def] identifier[AND] ( identifier[queryArr] ,
identifier[exclude] = keyword[None] ):
literal[string]
keyword[assert] identifier[isinstance] ( identifier[queryArr] , identifier[list] ), literal[string]
keyword[assert] identifier[len] ( identifier[queryArr] )> literal[int] , lite... | def AND(queryArr, exclude=None):
"""
create a combined query with multiple items on which to perform an AND operation
@param queryArr: a list of items on which to perform an AND operation. Items can be either a CombinedQuery or BaseQuery instances.
@param exclude: a instance of BaseQuery, Co... |
def validate_data_dir(data_dir):
"""
Validates all files in a data_dir
"""
all_meta, all_table, all_element, all_component = fileio.get_all_filelist(data_dir)
for f in all_meta:
full_path = os.path.join(data_dir, f)
validate_file('metadata', full_path)
for f in all_table:
... | def function[validate_data_dir, parameter[data_dir]]:
constant[
Validates all files in a data_dir
]
<ast.Tuple object at 0x7da2041d8550> assign[=] call[name[fileio].get_all_filelist, parameter[name[data_dir]]]
for taget[name[f]] in starred[name[all_meta]] begin[:]
variabl... | keyword[def] identifier[validate_data_dir] ( identifier[data_dir] ):
literal[string]
identifier[all_meta] , identifier[all_table] , identifier[all_element] , identifier[all_component] = identifier[fileio] . identifier[get_all_filelist] ( identifier[data_dir] )
keyword[for] identifier[f] keyword[in... | def validate_data_dir(data_dir):
"""
Validates all files in a data_dir
"""
(all_meta, all_table, all_element, all_component) = fileio.get_all_filelist(data_dir)
for f in all_meta:
full_path = os.path.join(data_dir, f)
validate_file('metadata', full_path) # depends on [control=['for'... |
def list(self, **params):
"""
Retrieve all deals
Returns all deals available to the user according to the parameters provided
:calls: ``get /deals``
:param dict params: (optional) Search options.
:return: List of dictionaries that support attriubte-style access, which r... | def function[list, parameter[self]]:
constant[
Retrieve all deals
Returns all deals available to the user according to the parameters provided
:calls: ``get /deals``
:param dict params: (optional) Search options.
:return: List of dictionaries that support attriubte-styl... | keyword[def] identifier[list] ( identifier[self] ,** identifier[params] ):
literal[string]
identifier[_] , identifier[_] , identifier[deals] = identifier[self] . identifier[http_client] . identifier[get] ( literal[string] , identifier[params] = identifier[params] )
keyword[for] identifie... | def list(self, **params):
"""
Retrieve all deals
Returns all deals available to the user according to the parameters provided
:calls: ``get /deals``
:param dict params: (optional) Search options.
:return: List of dictionaries that support attriubte-style access, which repre... |
def parser(key = "default"):
"""Returns the parser for the given key, (e.g. 'ssh')"""
#Make sure we have a parser for that key. If we don't, then set
#one up if we know what parameters to use; otherwise return the
#default parser.
if key not in _parsers:
if key == "ssh":
_parsers... | def function[parser, parameter[key]]:
constant[Returns the parser for the given key, (e.g. 'ssh')]
if compare[name[key] <ast.NotIn object at 0x7da2590d7190> name[_parsers]] begin[:]
if compare[name[key] equal[==] constant[ssh]] begin[:]
call[name[_parsers]][consta... | keyword[def] identifier[parser] ( identifier[key] = literal[string] ):
literal[string]
keyword[if] identifier[key] keyword[not] keyword[in] identifier[_parsers] :
keyword[if] identifier[key] == literal[string] :
identifier[_parsers] [ literal[string] ]= identifier[... | def parser(key='default'):
"""Returns the parser for the given key, (e.g. 'ssh')"""
#Make sure we have a parser for that key. If we don't, then set
#one up if we know what parameters to use; otherwise return the
#default parser.
if key not in _parsers:
if key == 'ssh':
_parsers['... |
def __check_file_status(self, index):
"""Check if file has been changed in any way outside Spyder:
1. removed, moved or renamed outside Spyder
2. modified outside Spyder"""
if self.__file_status_flag:
# Avoid infinite loop: when the QMessageBox.question pops, it
... | def function[__check_file_status, parameter[self, index]]:
constant[Check if file has been changed in any way outside Spyder:
1. removed, moved or renamed outside Spyder
2. modified outside Spyder]
if name[self].__file_status_flag begin[:]
return[None]
name[self].__file_s... | keyword[def] identifier[__check_file_status] ( identifier[self] , identifier[index] ):
literal[string]
keyword[if] identifier[self] . identifier[__file_status_flag] :
keyword[return]
identifier[self] . identifier[__file_status_flag] = keywor... | def __check_file_status(self, index):
"""Check if file has been changed in any way outside Spyder:
1. removed, moved or renamed outside Spyder
2. modified outside Spyder"""
if self.__file_status_flag: # Avoid infinite loop: when the QMessageBox.question pops, it
# gets focus and then gi... |
def close(self, code=None):
'''return a `close` :class:`Frame`.
'''
code = code or 1000
body = pack('!H', code)
body += self._close_codes.get(code, '').encode('utf-8')
return self.encode(body, opcode=0x8) | def function[close, parameter[self, code]]:
constant[return a `close` :class:`Frame`.
]
variable[code] assign[=] <ast.BoolOp object at 0x7da18f58e860>
variable[body] assign[=] call[name[pack], parameter[constant[!H], name[code]]]
<ast.AugAssign object at 0x7da18f58f7f0>
return[ca... | keyword[def] identifier[close] ( identifier[self] , identifier[code] = keyword[None] ):
literal[string]
identifier[code] = identifier[code] keyword[or] literal[int]
identifier[body] = identifier[pack] ( literal[string] , identifier[code] )
identifier[body] += identifier[self] .... | def close(self, code=None):
"""return a `close` :class:`Frame`.
"""
code = code or 1000
body = pack('!H', code)
body += self._close_codes.get(code, '').encode('utf-8')
return self.encode(body, opcode=8) |
def actualize (self, scanner = None):
""" Generates all the actual targets and sets up build actions for
this target.
If 'scanner' is specified, creates an additional target
with the same location as actual target, which will depend on the
actual target and be as... | def function[actualize, parameter[self, scanner]]:
constant[ Generates all the actual targets and sets up build actions for
this target.
If 'scanner' is specified, creates an additional target
with the same location as actual target, which will depend on the
actu... | keyword[def] identifier[actualize] ( identifier[self] , identifier[scanner] = keyword[None] ):
literal[string]
keyword[if] identifier[__debug__] :
keyword[from] . identifier[scanner] keyword[import] identifier[Scanner]
keyword[assert] identifier[scanner] keyword[is] ... | def actualize(self, scanner=None):
""" Generates all the actual targets and sets up build actions for
this target.
If 'scanner' is specified, creates an additional target
with the same location as actual target, which will depend on the
actual target and be associate... |
def parse_number_from_substring(substring) -> Optional[float]:
'''
Returns the number in the expected string "N:12.3", where "N" is the
key, and "12.3" is a floating point value
For the temp-deck or thermocycler's temperature response, one expected
input is something like "T:none", where "none" sho... | def function[parse_number_from_substring, parameter[substring]]:
constant[
Returns the number in the expected string "N:12.3", where "N" is the
key, and "12.3" is a floating point value
For the temp-deck or thermocycler's temperature response, one expected
input is something like "T:none", wher... | keyword[def] identifier[parse_number_from_substring] ( identifier[substring] )-> identifier[Optional] [ identifier[float] ]:
literal[string]
keyword[try] :
identifier[value] = identifier[substring] . identifier[split] ( literal[string] )[ literal[int] ]
keyword[if] identifier[value] . id... | def parse_number_from_substring(substring) -> Optional[float]:
"""
Returns the number in the expected string "N:12.3", where "N" is the
key, and "12.3" is a floating point value
For the temp-deck or thermocycler's temperature response, one expected
input is something like "T:none", where "none" sho... |
def slaves(self, name):
"""Returns a list of slaves for ``name``."""
fut = self.execute(b'SLAVES', name, encoding='utf-8')
return wait_convert(fut, parse_sentinel_slaves_and_sentinels) | def function[slaves, parameter[self, name]]:
constant[Returns a list of slaves for ``name``.]
variable[fut] assign[=] call[name[self].execute, parameter[constant[b'SLAVES'], name[name]]]
return[call[name[wait_convert], parameter[name[fut], name[parse_sentinel_slaves_and_sentinels]]]] | keyword[def] identifier[slaves] ( identifier[self] , identifier[name] ):
literal[string]
identifier[fut] = identifier[self] . identifier[execute] ( literal[string] , identifier[name] , identifier[encoding] = literal[string] )
keyword[return] identifier[wait_convert] ( identifier[fut] , id... | def slaves(self, name):
"""Returns a list of slaves for ``name``."""
fut = self.execute(b'SLAVES', name, encoding='utf-8')
return wait_convert(fut, parse_sentinel_slaves_and_sentinels) |
def connect_async(self, connection_id, connection_string, callback, retries=4, context=None):
"""Connect to a device by its connection_string
This function asynchronously connects to a device by its BLE address + address type passed in the
connection_string parameter and calls callback when fin... | def function[connect_async, parameter[self, connection_id, connection_string, callback, retries, context]]:
constant[Connect to a device by its connection_string
This function asynchronously connects to a device by its BLE address + address type passed in the
connection_string parameter and cal... | keyword[def] identifier[connect_async] ( identifier[self] , identifier[connection_id] , identifier[connection_string] , identifier[callback] , identifier[retries] = literal[int] , identifier[context] = keyword[None] ):
literal[string]
keyword[if] identifier[context] keyword[is] keyword[None] :
... | def connect_async(self, connection_id, connection_string, callback, retries=4, context=None):
"""Connect to a device by its connection_string
This function asynchronously connects to a device by its BLE address + address type passed in the
connection_string parameter and calls callback when finishe... |
def TENSES(self):
""" Yields a list of tenses for this language, excluding negations.
Each tense is a (tense, person, number, mood, aspect)-tuple.
"""
a = set(TENSES[id] for id in self._format)
a = a.union(set(TENSES[id] for id in self._default.keys()))
a = a.union(se... | def function[TENSES, parameter[self]]:
constant[ Yields a list of tenses for this language, excluding negations.
Each tense is a (tense, person, number, mood, aspect)-tuple.
]
variable[a] assign[=] call[name[set], parameter[<ast.GeneratorExp object at 0x7da20c6e5000>]]
variab... | keyword[def] identifier[TENSES] ( identifier[self] ):
literal[string]
identifier[a] = identifier[set] ( identifier[TENSES] [ identifier[id] ] keyword[for] identifier[id] keyword[in] identifier[self] . identifier[_format] )
identifier[a] = identifier[a] . identifier[union] ( identifier[s... | def TENSES(self):
""" Yields a list of tenses for this language, excluding negations.
Each tense is a (tense, person, number, mood, aspect)-tuple.
"""
a = set((TENSES[id] for id in self._format))
a = a.union(set((TENSES[id] for id in self._default.keys())))
a = a.union(set((TENSES[id... |
def fix(csvfile):
'''Apply a fix (ie. remove plain names)'''
header('Apply fixes from {}', csvfile.name)
bads = []
reader = csv.reader(csvfile)
reader.next() # Skip header
for id, _, sources, dests in reader:
advice = Advice.objects.get(id=id)
sources = [s.strip() for s in sourc... | def function[fix, parameter[csvfile]]:
constant[Apply a fix (ie. remove plain names)]
call[name[header], parameter[constant[Apply fixes from {}], name[csvfile].name]]
variable[bads] assign[=] list[[]]
variable[reader] assign[=] call[name[csv].reader, parameter[name[csvfile]]]
cal... | keyword[def] identifier[fix] ( identifier[csvfile] ):
literal[string]
identifier[header] ( literal[string] , identifier[csvfile] . identifier[name] )
identifier[bads] =[]
identifier[reader] = identifier[csv] . identifier[reader] ( identifier[csvfile] )
identifier[reader] . identifier[next] (... | def fix(csvfile):
"""Apply a fix (ie. remove plain names)"""
header('Apply fixes from {}', csvfile.name)
bads = []
reader = csv.reader(csvfile)
reader.next() # Skip header
for (id, _, sources, dests) in reader:
advice = Advice.objects.get(id=id)
sources = [s.strip() for s in sou... |
def configure_plugin(app): # noqa: C901
"""
This is a factory function that configures all the routes for
flask given a particular library.
"""
@app.route(
"/v1/api/client_has_addon/<hashed_client_id>/<addon_id>/", methods=["GET"]
)
def client_has_addon(hashed_client_id, addon_id):... | def function[configure_plugin, parameter[app]]:
constant[
This is a factory function that configures all the routes for
flask given a particular library.
]
def function[client_has_addon, parameter[hashed_client_id, addon_id]]:
<ast.Global object at 0x7da1b0ea0340>
var... | keyword[def] identifier[configure_plugin] ( identifier[app] ):
literal[string]
@ identifier[app] . identifier[route] (
literal[string] , identifier[methods] =[ literal[string] ]
)
keyword[def] identifier[client_has_addon] ( identifier[hashed_client_id] , identifier[addon_id] ):
... | def configure_plugin(app): # noqa: C901
'\n This is a factory function that configures all the routes for\n flask given a particular library.\n '
@app.route('/v1/api/client_has_addon/<hashed_client_id>/<addon_id>/', methods=['GET'])
def client_has_addon(hashed_client_id, addon_id):
# Use ... |
def api_get(uri, key=None):
"""
Simple API endpoint get, return only the keys we care about
"""
response = get_json(uri)
if response:
if type(response) == list:
r = response[0]
elif type(response) == dict:
r = response
if type(r) == dict:
... | def function[api_get, parameter[uri, key]]:
constant[
Simple API endpoint get, return only the keys we care about
]
variable[response] assign[=] call[name[get_json], parameter[name[uri]]]
if name[response] begin[:]
if compare[call[name[type], parameter[name[response]]] eq... | keyword[def] identifier[api_get] ( identifier[uri] , identifier[key] = keyword[None] ):
literal[string]
identifier[response] = identifier[get_json] ( identifier[uri] )
keyword[if] identifier[response] :
keyword[if] identifier[type] ( identifier[response] )== identifier[list] :
... | def api_get(uri, key=None):
"""
Simple API endpoint get, return only the keys we care about
"""
response = get_json(uri)
if response:
if type(response) == list:
r = response[0] # depends on [control=['if'], data=[]]
elif type(response) == dict:
r = response ... |
def crypto_box_beforenm(pk, sk):
"""
Computes and returns the shared key for the public key ``pk`` and the
secret key ``sk``. This can be used to speed up operations where the same
set of keys is going to be used multiple times.
:param pk: bytes
:param sk: bytes
:rtype: bytes
"""
if... | def function[crypto_box_beforenm, parameter[pk, sk]]:
constant[
Computes and returns the shared key for the public key ``pk`` and the
secret key ``sk``. This can be used to speed up operations where the same
set of keys is going to be used multiple times.
:param pk: bytes
:param sk: bytes
... | keyword[def] identifier[crypto_box_beforenm] ( identifier[pk] , identifier[sk] ):
literal[string]
keyword[if] identifier[len] ( identifier[pk] )!= identifier[crypto_box_PUBLICKEYBYTES] :
keyword[raise] identifier[exc] . identifier[ValueError] ( literal[string] )
keyword[if] identifier[len... | def crypto_box_beforenm(pk, sk):
"""
Computes and returns the shared key for the public key ``pk`` and the
secret key ``sk``. This can be used to speed up operations where the same
set of keys is going to be used multiple times.
:param pk: bytes
:param sk: bytes
:rtype: bytes
"""
if... |
def compile_geometry(lat, lon, elev):
"""
Take in lists of lat and lon coordinates, and determine what geometry to create
:param list lat: Latitude values
:param list lon: Longitude values
:param float elev: Elevation value
:return dict:
"""
logger_excel.info("enter compile_geometry")
... | def function[compile_geometry, parameter[lat, lon, elev]]:
constant[
Take in lists of lat and lon coordinates, and determine what geometry to create
:param list lat: Latitude values
:param list lon: Longitude values
:param float elev: Elevation value
:return dict:
]
call[name[log... | keyword[def] identifier[compile_geometry] ( identifier[lat] , identifier[lon] , identifier[elev] ):
literal[string]
identifier[logger_excel] . identifier[info] ( literal[string] )
identifier[lat] = identifier[_remove_geo_placeholders] ( identifier[lat] )
identifier[lon] = identifier[_remove_geo_p... | def compile_geometry(lat, lon, elev):
"""
Take in lists of lat and lon coordinates, and determine what geometry to create
:param list lat: Latitude values
:param list lon: Longitude values
:param float elev: Elevation value
:return dict:
"""
logger_excel.info('enter compile_geometry')
... |
def save_sequence_rule(self, sequence_rule_form, *args, **kwargs):
"""Pass through to provider SequenceRuleAdminSession.update_sequence_rule"""
# Implemented from kitosid template for -
# osid.resource.ResourceAdminSession.update_resource
if sequence_rule_form.is_for_update():
... | def function[save_sequence_rule, parameter[self, sequence_rule_form]]:
constant[Pass through to provider SequenceRuleAdminSession.update_sequence_rule]
if call[name[sequence_rule_form].is_for_update, parameter[]] begin[:]
return[call[name[self].update_sequence_rule, parameter[name[sequence_rule_... | keyword[def] identifier[save_sequence_rule] ( identifier[self] , identifier[sequence_rule_form] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
keyword[if] identifier[sequence_rule_form] . identifier[is_for_update] ():
keyword[return] identifier[self] ... | def save_sequence_rule(self, sequence_rule_form, *args, **kwargs):
"""Pass through to provider SequenceRuleAdminSession.update_sequence_rule"""
# Implemented from kitosid template for -
# osid.resource.ResourceAdminSession.update_resource
if sequence_rule_form.is_for_update():
return self.update... |
def local_expert_attention(x,
k,
loss_coef,
attention_num_experts,
train=True,
batch_coordinate=None,
**kwargs):
"""Attention using a mixture of experts.
... | def function[local_expert_attention, parameter[x, k, loss_coef, attention_num_experts, train, batch_coordinate]]:
constant[Attention using a mixture of experts.
Positions sent to the same expert can attend to each other.
The mixture of experts is "local" in that it is replicated on each
datashard.
... | keyword[def] identifier[local_expert_attention] ( identifier[x] ,
identifier[k] ,
identifier[loss_coef] ,
identifier[attention_num_experts] ,
identifier[train] = keyword[True] ,
identifier[batch_coordinate] = keyword[None] ,
** identifier[kwargs] ):
literal[string]
keyword[if] identifier[batch_coordinate... | def local_expert_attention(x, k, loss_coef, attention_num_experts, train=True, batch_coordinate=None, **kwargs):
"""Attention using a mixture of experts.
Positions sent to the same expert can attend to each other.
The mixture of experts is "local" in that it is replicated on each
datashard.
local_... |
def hash(file):
"""
Hashes file using SHA-256.
:param file: name of file to be hashed
:type file: str
:rtype: str
:raises check50.Failure: if ``file`` does not exist
"""
exists(file)
log(_("hashing {}...").format(file))
# https://stackoverflow.com/a/22058673
with open(fil... | def function[hash, parameter[file]]:
constant[
Hashes file using SHA-256.
:param file: name of file to be hashed
:type file: str
:rtype: str
:raises check50.Failure: if ``file`` does not exist
]
call[name[exists], parameter[name[file]]]
call[name[log], parameter[call[ca... | keyword[def] identifier[hash] ( identifier[file] ):
literal[string]
identifier[exists] ( identifier[file] )
identifier[log] ( identifier[_] ( literal[string] ). identifier[format] ( identifier[file] ))
keyword[with] identifier[open] ( identifier[file] , literal[string] ) keyword[as] iden... | def hash(file):
"""
Hashes file using SHA-256.
:param file: name of file to be hashed
:type file: str
:rtype: str
:raises check50.Failure: if ``file`` does not exist
"""
exists(file)
log(_('hashing {}...').format(file))
# https://stackoverflow.com/a/22058673
with open(file,... |
def clear(self):
"""
Cleans up the handler. The handler can't be used after this method has
been called
"""
self._logger.debug("Component handlers are cleared")
# Clean up everything to avoid stale references, ...
self._field = None
self._name = None
... | def function[clear, parameter[self]]:
constant[
Cleans up the handler. The handler can't be used after this method has
been called
]
call[name[self]._logger.debug, parameter[constant[Component handlers are cleared]]]
name[self]._field assign[=] constant[None]
name... | keyword[def] identifier[clear] ( identifier[self] ):
literal[string]
identifier[self] . identifier[_logger] . identifier[debug] ( literal[string] )
identifier[self] . identifier[_field] = keyword[None]
identifier[self] . identifier[_name] = keyword[None]
ident... | def clear(self):
"""
Cleans up the handler. The handler can't be used after this method has
been called
"""
self._logger.debug('Component handlers are cleared')
# Clean up everything to avoid stale references, ...
self._field = None
self._name = None
self._logger = None |
def handle(self, request, buffer_size):
"""
Handle a message
:param request: the request socket.
:param buffer_size: the buffer size.
:return: True if success, False otherwise
"""
if self.component_type == StreamComponent.SOURCE:
msg = self.handler_fu... | def function[handle, parameter[self, request, buffer_size]]:
constant[
Handle a message
:param request: the request socket.
:param buffer_size: the buffer size.
:return: True if success, False otherwise
]
if compare[name[self].component_type equal[==] name[StreamC... | keyword[def] identifier[handle] ( identifier[self] , identifier[request] , identifier[buffer_size] ):
literal[string]
keyword[if] identifier[self] . identifier[component_type] == identifier[StreamComponent] . identifier[SOURCE] :
identifier[msg] = identifier[self] . identifier[handle... | def handle(self, request, buffer_size):
"""
Handle a message
:param request: the request socket.
:param buffer_size: the buffer size.
:return: True if success, False otherwise
"""
if self.component_type == StreamComponent.SOURCE:
msg = self.handler_function()
... |
def corethreads(self):
"""
Create a .cds file consisting of fasta records of CDS features for each strain
"""
printtime('Creating CDS files and finding core genes', self.start)
# Create and start threads
for i in range(self.cpus):
# Send the threads to the app... | def function[corethreads, parameter[self]]:
constant[
Create a .cds file consisting of fasta records of CDS features for each strain
]
call[name[printtime], parameter[constant[Creating CDS files and finding core genes], name[self].start]]
for taget[name[i]] in starred[call[name[r... | keyword[def] identifier[corethreads] ( identifier[self] ):
literal[string]
identifier[printtime] ( literal[string] , identifier[self] . identifier[start] )
keyword[for] identifier[i] keyword[in] identifier[range] ( identifier[self] . identifier[cpus] ):
id... | def corethreads(self):
"""
Create a .cds file consisting of fasta records of CDS features for each strain
"""
printtime('Creating CDS files and finding core genes', self.start)
# Create and start threads
for i in range(self.cpus):
# Send the threads to the appropriate destination... |
def enrich(self, column1, column2):
""" This method calculates the difference in seconds between
the 2 columns (column2 - column1)
The final result may provided negative values depending on the values
from column1 and column2.
:param column1: first column. Values in column1... | def function[enrich, parameter[self, column1, column2]]:
constant[ This method calculates the difference in seconds between
the 2 columns (column2 - column1)
The final result may provided negative values depending on the values
from column1 and column2.
:param column1: firs... | keyword[def] identifier[enrich] ( identifier[self] , identifier[column1] , identifier[column2] ):
literal[string]
keyword[if] identifier[column1] keyword[not] keyword[in] identifier[self] . identifier[data] . identifier[columns] keyword[or] identifier[column2] keyword[not] keyword[in] ide... | def enrich(self, column1, column2):
""" This method calculates the difference in seconds between
the 2 columns (column2 - column1)
The final result may provided negative values depending on the values
from column1 and column2.
:param column1: first column. Values in column1 mus... |
def mean_with_attention(x, name, num_heads=4):
"""Mean and attention to reduce spatial dimensions."""
with tf.variable_scope(name):
shape = shape_list(x)
m = tf.reduce_mean(x, [1, 2])
a = layers().Dense(num_heads, name="mean_attn")(x)
s = tf.reshape(a, [shape[0], -1, num_heads])
s = tf.nn.softma... | def function[mean_with_attention, parameter[x, name, num_heads]]:
constant[Mean and attention to reduce spatial dimensions.]
with call[name[tf].variable_scope, parameter[name[name]]] begin[:]
variable[shape] assign[=] call[name[shape_list], parameter[name[x]]]
variable[m]... | keyword[def] identifier[mean_with_attention] ( identifier[x] , identifier[name] , identifier[num_heads] = literal[int] ):
literal[string]
keyword[with] identifier[tf] . identifier[variable_scope] ( identifier[name] ):
identifier[shape] = identifier[shape_list] ( identifier[x] )
identifier[m] = ident... | def mean_with_attention(x, name, num_heads=4):
"""Mean and attention to reduce spatial dimensions."""
with tf.variable_scope(name):
shape = shape_list(x)
m = tf.reduce_mean(x, [1, 2])
a = layers().Dense(num_heads, name='mean_attn')(x)
s = tf.reshape(a, [shape[0], -1, num_heads])
... |
def on(self, event: str) -> Callable:
""" Decorator for subscribing a function to a specific event.
:param event: Name of the event to subscribe to.
:type event: str
:return: The outer function.
:rtype: Callable
"""
def outer(func):
self.add_event(f... | def function[on, parameter[self, event]]:
constant[ Decorator for subscribing a function to a specific event.
:param event: Name of the event to subscribe to.
:type event: str
:return: The outer function.
:rtype: Callable
]
def function[outer, parameter[func]]:
... | keyword[def] identifier[on] ( identifier[self] , identifier[event] : identifier[str] )-> identifier[Callable] :
literal[string]
keyword[def] identifier[outer] ( identifier[func] ):
identifier[self] . identifier[add_event] ( identifier[func] , identifier[event] )
@ identi... | def on(self, event: str) -> Callable:
""" Decorator for subscribing a function to a specific event.
:param event: Name of the event to subscribe to.
:type event: str
:return: The outer function.
:rtype: Callable
"""
def outer(func):
self.add_event(func, event)
... |
def make_patch_request(url, data, params, headers, connection):
"""
Helper function that makes an HTTP PATCH request to the given firebase
endpoint. Timeout is 60 seconds.
`url`: The full URL of the firebase endpoint (DSN appended.)
`data`: JSON serializable dict that will be stored in the remote st... | def function[make_patch_request, parameter[url, data, params, headers, connection]]:
constant[
Helper function that makes an HTTP PATCH request to the given firebase
endpoint. Timeout is 60 seconds.
`url`: The full URL of the firebase endpoint (DSN appended.)
`data`: JSON serializable dict that ... | keyword[def] identifier[make_patch_request] ( identifier[url] , identifier[data] , identifier[params] , identifier[headers] , identifier[connection] ):
literal[string]
identifier[timeout] = identifier[getattr] ( identifier[connection] , literal[string] )
identifier[response] = identifier[connection] .... | def make_patch_request(url, data, params, headers, connection):
"""
Helper function that makes an HTTP PATCH request to the given firebase
endpoint. Timeout is 60 seconds.
`url`: The full URL of the firebase endpoint (DSN appended.)
`data`: JSON serializable dict that will be stored in the remote st... |
def _link_variables_on_expr(self, variable_manager, block, stmt_idx, stmt, expr):
"""
Link atoms (AIL expressions) in the given expression to corresponding variables identified previously.
:param variable_manager: Variable manager of the function.
:param ailment.Block block: AIL bloc... | def function[_link_variables_on_expr, parameter[self, variable_manager, block, stmt_idx, stmt, expr]]:
constant[
Link atoms (AIL expressions) in the given expression to corresponding variables identified previously.
:param variable_manager: Variable manager of the function.
:param ai... | keyword[def] identifier[_link_variables_on_expr] ( identifier[self] , identifier[variable_manager] , identifier[block] , identifier[stmt_idx] , identifier[stmt] , identifier[expr] ):
literal[string]
keyword[if] identifier[type] ( identifier[expr] ) keyword[is] identifier[ailment] . identifier[Ex... | def _link_variables_on_expr(self, variable_manager, block, stmt_idx, stmt, expr):
"""
Link atoms (AIL expressions) in the given expression to corresponding variables identified previously.
:param variable_manager: Variable manager of the function.
:param ailment.Block block: AIL block.
... |
def gradient(self, ts):
"""
Find the gradient of the log likelihood with respect to the given time series.
Based on http://www.unc.edu/~jbhill/Bollerslev_GARCH_1986.pdf
Returns an 3-element array containing the gradient for the alpha, beta, and omega parameters.
... | def function[gradient, parameter[self, ts]]:
constant[
Find the gradient of the log likelihood with respect to the given time series.
Based on http://www.unc.edu/~jbhill/Bollerslev_GARCH_1986.pdf
Returns an 3-element array containing the gradient for the alpha, beta, an... | keyword[def] identifier[gradient] ( identifier[self] , identifier[ts] ):
literal[string]
identifier[gradient] = identifier[self] . identifier[_jmodel] . identifier[gradient] ( identifier[_py2java] ( identifier[self] . identifier[_ctx] , identifier[Vectors] . identifier[dense] ( identifier[ts] )))
... | def gradient(self, ts):
"""
Find the gradient of the log likelihood with respect to the given time series.
Based on http://www.unc.edu/~jbhill/Bollerslev_GARCH_1986.pdf
Returns an 3-element array containing the gradient for the alpha, beta, and omega parameters.
"""... |
def code_constants(self):
"""
All of the constants that are used by this functions's code.
"""
# TODO: remove link register values
return [const.value for block in self.blocks for const in block.vex.constants] | def function[code_constants, parameter[self]]:
constant[
All of the constants that are used by this functions's code.
]
return[<ast.ListComp object at 0x7da18dc05a50>] | keyword[def] identifier[code_constants] ( identifier[self] ):
literal[string]
keyword[return] [ identifier[const] . identifier[value] keyword[for] identifier[block] keyword[in] identifier[self] . identifier[blocks] keyword[for] identifier[const] keyword[in] identifier[block] . iden... | def code_constants(self):
"""
All of the constants that are used by this functions's code.
"""
# TODO: remove link register values
return [const.value for block in self.blocks for const in block.vex.constants] |
def unshell_list(s):
"""Turn a command-line argument into a list."""
if not s:
return None
if sys.platform == 'win32':
# When running coverage as coverage.exe, some of the behavior
# of the shell is emulated: wildcards are expanded into a list of
# filenames. So you have to ... | def function[unshell_list, parameter[s]]:
constant[Turn a command-line argument into a list.]
if <ast.UnaryOp object at 0x7da20e962830> begin[:]
return[constant[None]]
if compare[name[sys].platform equal[==] constant[win32]] begin[:]
variable[s] assign[=] call[name[s].str... | keyword[def] identifier[unshell_list] ( identifier[s] ):
literal[string]
keyword[if] keyword[not] identifier[s] :
keyword[return] keyword[None]
keyword[if] identifier[sys] . identifier[platform] == literal[string] :
identifier[s] = identifier[s] . identi... | def unshell_list(s):
"""Turn a command-line argument into a list."""
if not s:
return None # depends on [control=['if'], data=[]]
if sys.platform == 'win32':
# When running coverage as coverage.exe, some of the behavior
# of the shell is emulated: wildcards are expanded into a list ... |
def load_new_checkpoint_when_available(
self, sess, current_checkpoint, sleep_seconds=10):
"""Waits for a new checkpoint to be available and then loads it.
Args:
sess: The current session.
current_checkpoint: The current checkpoint or None to just load the next
one.
sleep_second... | def function[load_new_checkpoint_when_available, parameter[self, sess, current_checkpoint, sleep_seconds]]:
constant[Waits for a new checkpoint to be available and then loads it.
Args:
sess: The current session.
current_checkpoint: The current checkpoint or None to just load the next
on... | keyword[def] identifier[load_new_checkpoint_when_available] (
identifier[self] , identifier[sess] , identifier[current_checkpoint] , identifier[sleep_seconds] = literal[int] ):
literal[string]
keyword[while] keyword[True] :
identifier[next_checkpoint] = identifier[self] . identifier[load_from... | def load_new_checkpoint_when_available(self, sess, current_checkpoint, sleep_seconds=10):
"""Waits for a new checkpoint to be available and then loads it.
Args:
sess: The current session.
current_checkpoint: The current checkpoint or None to just load the next
one.
sleep_seconds: How ... |
def _create_session(team, auth):
"""
Creates a session object to be used for `push`, `install`, etc.
"""
session = requests.Session()
session.hooks.update(dict(
response=partial(_handle_response, team)
))
session.headers.update({
"Content-Type": "application/json",
"A... | def function[_create_session, parameter[team, auth]]:
constant[
Creates a session object to be used for `push`, `install`, etc.
]
variable[session] assign[=] call[name[requests].Session, parameter[]]
call[name[session].hooks.update, parameter[call[name[dict], parameter[]]]]
call[... | keyword[def] identifier[_create_session] ( identifier[team] , identifier[auth] ):
literal[string]
identifier[session] = identifier[requests] . identifier[Session] ()
identifier[session] . identifier[hooks] . identifier[update] ( identifier[dict] (
identifier[response] = identifier[partial] ( iden... | def _create_session(team, auth):
"""
Creates a session object to be used for `push`, `install`, etc.
"""
session = requests.Session()
session.hooks.update(dict(response=partial(_handle_response, team)))
session.headers.update({'Content-Type': 'application/json', 'Accept': 'application/json', 'Us... |
def _digi_bounds(fmt):
"""
Return min and max digital values for each format type.
Accepts lists.
Parmeters
---------
fmt : str, or list
The wfdb dat format, or a list of them.
"""
if isinstance(fmt, list):
return [_digi_bounds(f) for f in fmt]
if fmt == '80':
... | def function[_digi_bounds, parameter[fmt]]:
constant[
Return min and max digital values for each format type.
Accepts lists.
Parmeters
---------
fmt : str, or list
The wfdb dat format, or a list of them.
]
if call[name[isinstance], parameter[name[fmt], name[list]]] begi... | keyword[def] identifier[_digi_bounds] ( identifier[fmt] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[fmt] , identifier[list] ):
keyword[return] [ identifier[_digi_bounds] ( identifier[f] ) keyword[for] identifier[f] keyword[in] identifier[fmt] ]
keyword[if] identif... | def _digi_bounds(fmt):
"""
Return min and max digital values for each format type.
Accepts lists.
Parmeters
---------
fmt : str, or list
The wfdb dat format, or a list of them.
"""
if isinstance(fmt, list):
return [_digi_bounds(f) for f in fmt] # depends on [control=['... |
def com_google_fonts_check_aat(ttFont):
"""Are there unwanted Apple tables?"""
UNWANTED_TABLES = {
'EBSC', 'Zaph', 'acnt', 'ankr', 'bdat', 'bhed', 'bloc',
'bmap', 'bsln', 'fdsc', 'feat', 'fond', 'gcid', 'just',
'kerx', 'lcar', 'ltag', 'mort', 'morx', 'opbd', 'prop',
'trak', 'xref'
}
unwanted_tab... | def function[com_google_fonts_check_aat, parameter[ttFont]]:
constant[Are there unwanted Apple tables?]
variable[UNWANTED_TABLES] assign[=] <ast.Set object at 0x7da1b12531c0>
variable[unwanted_tables_found] assign[=] list[[]]
for taget[name[table]] in starred[call[name[ttFont].keys, para... | keyword[def] identifier[com_google_fonts_check_aat] ( identifier[ttFont] ):
literal[string]
identifier[UNWANTED_TABLES] ={
literal[string] , literal[string] , literal[string] , literal[string] , literal[string] , literal[string] , literal[string] ,
literal[string] , literal[string] , literal[string] , li... | def com_google_fonts_check_aat(ttFont):
"""Are there unwanted Apple tables?"""
UNWANTED_TABLES = {'EBSC', 'Zaph', 'acnt', 'ankr', 'bdat', 'bhed', 'bloc', 'bmap', 'bsln', 'fdsc', 'feat', 'fond', 'gcid', 'just', 'kerx', 'lcar', 'ltag', 'mort', 'morx', 'opbd', 'prop', 'trak', 'xref'}
unwanted_tables_found = []... |
def _cast_to_type(self, value):
""" Raise error if the value is not a dict """
if not isinstance(value, dict):
self.fail('invalid', value=value)
return value | def function[_cast_to_type, parameter[self, value]]:
constant[ Raise error if the value is not a dict ]
if <ast.UnaryOp object at 0x7da1b1bb9ae0> begin[:]
call[name[self].fail, parameter[constant[invalid]]]
return[name[value]] | keyword[def] identifier[_cast_to_type] ( identifier[self] , identifier[value] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[value] , identifier[dict] ):
identifier[self] . identifier[fail] ( literal[string] , identifier[value] = identifier[value] )
... | def _cast_to_type(self, value):
""" Raise error if the value is not a dict """
if not isinstance(value, dict):
self.fail('invalid', value=value) # depends on [control=['if'], data=[]]
return value |
def locate(iterable, pred=bool, window_size=None):
"""Yield the index of each item in *iterable* for which *pred* returns
``True``.
*pred* defaults to :func:`bool`, which will select truthy items:
>>> list(locate([0, 1, 1, 0, 1, 0, 0]))
[1, 2, 4]
Set *pred* to a custom function to, e.... | def function[locate, parameter[iterable, pred, window_size]]:
constant[Yield the index of each item in *iterable* for which *pred* returns
``True``.
*pred* defaults to :func:`bool`, which will select truthy items:
>>> list(locate([0, 1, 1, 0, 1, 0, 0]))
[1, 2, 4]
Set *pred* to a c... | keyword[def] identifier[locate] ( identifier[iterable] , identifier[pred] = identifier[bool] , identifier[window_size] = keyword[None] ):
literal[string]
keyword[if] identifier[window_size] keyword[is] keyword[None] :
keyword[return] identifier[compress] ( identifier[count] (), identifier[map]... | def locate(iterable, pred=bool, window_size=None):
"""Yield the index of each item in *iterable* for which *pred* returns
``True``.
*pred* defaults to :func:`bool`, which will select truthy items:
>>> list(locate([0, 1, 1, 0, 1, 0, 0]))
[1, 2, 4]
Set *pred* to a custom function to, e.... |
def solve(self, value, attribute, args=None, kwargs=None):
"""Try to get the given attribute/function result for the given value.
If ``args`` or ``kwargs`` are passed, the attribute got from ``value`` must be callable.
They will be passed anyway (using ``[]`` and ``{}`` as default values) if th... | def function[solve, parameter[self, value, attribute, args, kwargs]]:
constant[Try to get the given attribute/function result for the given value.
If ``args`` or ``kwargs`` are passed, the attribute got from ``value`` must be callable.
They will be passed anyway (using ``[]`` and ``{}`` as defa... | keyword[def] identifier[solve] ( identifier[self] , identifier[value] , identifier[attribute] , identifier[args] = keyword[None] , identifier[kwargs] = keyword[None] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[value] , identifier[self] . identifier[source] ) k... | def solve(self, value, attribute, args=None, kwargs=None):
"""Try to get the given attribute/function result for the given value.
If ``args`` or ``kwargs`` are passed, the attribute got from ``value`` must be callable.
They will be passed anyway (using ``[]`` and ``{}`` as default values) if the at... |
def ascii_printable(self, keysym):
"""
If the keysym corresponds to a non-printable ascii character this will
return False. If it is printable, then True will be returned.
ascii 11 (vertical tab) and ascii 12 are printable, chr(11) and chr(12)
will return '\x0b' and '\x0c' respe... | def function[ascii_printable, parameter[self, keysym]]:
constant[
If the keysym corresponds to a non-printable ascii character this will
return False. If it is printable, then True will be returned.
ascii 11 (vertical tab) and ascii 12 are printable, chr(11) and chr(12)
will ret... | keyword[def] identifier[ascii_printable] ( identifier[self] , identifier[keysym] ):
literal[string]
keyword[if] literal[int] <= identifier[keysym] < literal[int] :
keyword[return] keyword[False]
keyword[elif] literal[int] < identifier[keysym] < literal[int] :
... | def ascii_printable(self, keysym):
"""
If the keysym corresponds to a non-printable ascii character this will
return False. If it is printable, then True will be returned.
ascii 11 (vertical tab) and ascii 12 are printable, chr(11) and chr(12)
will return '\x0b' and '\x0c' respectiv... |
def get_external_files(self):
"""
An external file manages file paths.
"""
external_files = []
for table in self._tables.values():
for r in table:
external_files.extend([ef for ef in r.get_external_files()])
return external_files | def function[get_external_files, parameter[self]]:
constant[
An external file manages file paths.
]
variable[external_files] assign[=] list[[]]
for taget[name[table]] in starred[call[name[self]._tables.values, parameter[]]] begin[:]
for taget[name[r]] in starred[n... | keyword[def] identifier[get_external_files] ( identifier[self] ):
literal[string]
identifier[external_files] =[]
keyword[for] identifier[table] keyword[in] identifier[self] . identifier[_tables] . identifier[values] ():
keyword[for] identifier[r] keyword[in] identifier[t... | def get_external_files(self):
"""
An external file manages file paths.
"""
external_files = []
for table in self._tables.values():
for r in table:
external_files.extend([ef for ef in r.get_external_files()]) # depends on [control=['for'], data=['r']] # depends on [contr... |
async def store_their_did(wallet_handle: int,
identity_json: str) -> None:
"""
Saves their DID for a pairwise connection in a secured Wallet,
so that it can be used to verify transaction.
:param wallet_handle: wallet handler (created by open_wallet).
:param identity_json: ... | <ast.AsyncFunctionDef object at 0x7da20e957460> | keyword[async] keyword[def] identifier[store_their_did] ( identifier[wallet_handle] : identifier[int] ,
identifier[identity_json] : identifier[str] )-> keyword[None] :
literal[string]
identifier[logger] = identifier[logging] . identifier[getLogger] ( identifier[__name__] )
identifier[logger] . iden... | async def store_their_did(wallet_handle: int, identity_json: str) -> None:
"""
Saves their DID for a pairwise connection in a secured Wallet,
so that it can be used to verify transaction.
:param wallet_handle: wallet handler (created by open_wallet).
:param identity_json: Identity information as js... |
def df(self, keys=None, basis=None, uwi=False):
"""
Return current curve data as a ``pandas.DataFrame`` object.
Everything has to have the same basis, because the depth
is going to become the index of the DataFrame. If you don't
provide one, ``welly`` will make one using... | def function[df, parameter[self, keys, basis, uwi]]:
constant[
Return current curve data as a ``pandas.DataFrame`` object.
Everything has to have the same basis, because the depth
is going to become the index of the DataFrame. If you don't
provide one, ``welly`` will mak... | keyword[def] identifier[df] ( identifier[self] , identifier[keys] = keyword[None] , identifier[basis] = keyword[None] , identifier[uwi] = keyword[False] ):
literal[string]
keyword[try] :
keyword[import] identifier[pandas] keyword[as] identifier[pd]
keyword[except] :
... | def df(self, keys=None, basis=None, uwi=False):
"""
Return current curve data as a ``pandas.DataFrame`` object.
Everything has to have the same basis, because the depth
is going to become the index of the DataFrame. If you don't
provide one, ``welly`` will make one using ``s... |
def get_response_data(self, response, parse_json=True):
"""
Get response data or throw an appropiate exception
:param response: requests response object
:param parse_json: if True, response will be parsed as JSON
:return: response data, either as json or as a regular response.con... | def function[get_response_data, parameter[self, response, parse_json]]:
constant[
Get response data or throw an appropiate exception
:param response: requests response object
:param parse_json: if True, response will be parsed as JSON
:return: response data, either as json or as ... | keyword[def] identifier[get_response_data] ( identifier[self] , identifier[response] , identifier[parse_json] = keyword[True] ):
literal[string]
keyword[if] identifier[response] . identifier[status_code] keyword[in] ( identifier[requests] . identifier[codes] . identifier[ok] , identifier[requests... | def get_response_data(self, response, parse_json=True):
"""
Get response data or throw an appropiate exception
:param response: requests response object
:param parse_json: if True, response will be parsed as JSON
:return: response data, either as json or as a regular response.content... |
def resize_image_folder(bucket, key_prefix, pil_size):
""" This function resizes all the images in a folder """
con = boto.connect_s3()
b = con.get_bucket(bucket)
for key in b.list(key_prefix):
key = b.get_key(key.name)
if 'image' not in key.content_type:
continue
siz... | def function[resize_image_folder, parameter[bucket, key_prefix, pil_size]]:
constant[ This function resizes all the images in a folder ]
variable[con] assign[=] call[name[boto].connect_s3, parameter[]]
variable[b] assign[=] call[name[con].get_bucket, parameter[name[bucket]]]
for taget[na... | keyword[def] identifier[resize_image_folder] ( identifier[bucket] , identifier[key_prefix] , identifier[pil_size] ):
literal[string]
identifier[con] = identifier[boto] . identifier[connect_s3] ()
identifier[b] = identifier[con] . identifier[get_bucket] ( identifier[bucket] )
keyword[for] identif... | def resize_image_folder(bucket, key_prefix, pil_size):
""" This function resizes all the images in a folder """
con = boto.connect_s3()
b = con.get_bucket(bucket)
for key in b.list(key_prefix):
key = b.get_key(key.name)
if 'image' not in key.content_type:
continue # depends ... |
def _get_virtual_variable(variables, key, level_vars=None, dim_sizes=None):
"""Get a virtual variable (e.g., 'time.year' or a MultiIndex level)
from a dict of xarray.Variable objects (if possible)
"""
if level_vars is None:
level_vars = {}
if dim_sizes is None:
dim_sizes = {}
if... | def function[_get_virtual_variable, parameter[variables, key, level_vars, dim_sizes]]:
constant[Get a virtual variable (e.g., 'time.year' or a MultiIndex level)
from a dict of xarray.Variable objects (if possible)
]
if compare[name[level_vars] is constant[None]] begin[:]
variable... | keyword[def] identifier[_get_virtual_variable] ( identifier[variables] , identifier[key] , identifier[level_vars] = keyword[None] , identifier[dim_sizes] = keyword[None] ):
literal[string]
keyword[if] identifier[level_vars] keyword[is] keyword[None] :
identifier[level_vars] ={}
keyword[if]... | def _get_virtual_variable(variables, key, level_vars=None, dim_sizes=None):
"""Get a virtual variable (e.g., 'time.year' or a MultiIndex level)
from a dict of xarray.Variable objects (if possible)
"""
if level_vars is None:
level_vars = {} # depends on [control=['if'], data=['level_vars']]
... |
def set_grade_system(self, grade_system_id):
"""Sets the grading system.
arg: grade_system_id (osid.id.Id): the grade system
raise: InvalidArgument - ``grade_system_id`` is invalid
raise: NoAccess - ``Metadata.isReadOnly()`` is ``true``
*compliance: mandatory -- This method... | def function[set_grade_system, parameter[self, grade_system_id]]:
constant[Sets the grading system.
arg: grade_system_id (osid.id.Id): the grade system
raise: InvalidArgument - ``grade_system_id`` is invalid
raise: NoAccess - ``Metadata.isReadOnly()`` is ``true``
*complianc... | keyword[def] identifier[set_grade_system] ( identifier[self] , identifier[grade_system_id] ):
literal[string]
keyword[if] identifier[self] . identifier[get_grade_system_metadata] (). identifier[is_read_only] ():
keyword[raise] identifier[errors] . identifier[NoAccess] ()
... | def set_grade_system(self, grade_system_id):
"""Sets the grading system.
arg: grade_system_id (osid.id.Id): the grade system
raise: InvalidArgument - ``grade_system_id`` is invalid
raise: NoAccess - ``Metadata.isReadOnly()`` is ``true``
*compliance: mandatory -- This method mus... |
def main():
"""Run Chronophore based on the command line arguments."""
args = get_args()
# Make Chronophore's directories and files in $HOME
DATA_DIR = pathlib.Path(appdirs.user_data_dir(__title__))
LOG_FILE = pathlib.Path(appdirs.user_log_dir(__title__), 'debug.log')
os.makedirs(str(DATA_DIR),... | def function[main, parameter[]]:
constant[Run Chronophore based on the command line arguments.]
variable[args] assign[=] call[name[get_args], parameter[]]
variable[DATA_DIR] assign[=] call[name[pathlib].Path, parameter[call[name[appdirs].user_data_dir, parameter[name[__title__]]]]]
varia... | keyword[def] identifier[main] ():
literal[string]
identifier[args] = identifier[get_args] ()
identifier[DATA_DIR] = identifier[pathlib] . identifier[Path] ( identifier[appdirs] . identifier[user_data_dir] ( identifier[__title__] ))
identifier[LOG_FILE] = identifier[pathlib] . identifier[Pat... | def main():
"""Run Chronophore based on the command line arguments."""
args = get_args()
# Make Chronophore's directories and files in $HOME
DATA_DIR = pathlib.Path(appdirs.user_data_dir(__title__))
LOG_FILE = pathlib.Path(appdirs.user_log_dir(__title__), 'debug.log')
os.makedirs(str(DATA_DIR), ... |
def get_tier(self, name_num):
"""Gives a tier, when multiple tiers exist with that name only the
first is returned.
:param name_num: Name or number of the tier to return.
:type name_num: int or str
:returns: The tier.
:raises IndexError: If the tier doesn't exist.
... | def function[get_tier, parameter[self, name_num]]:
constant[Gives a tier, when multiple tiers exist with that name only the
first is returned.
:param name_num: Name or number of the tier to return.
:type name_num: int or str
:returns: The tier.
:raises IndexError: If the... | keyword[def] identifier[get_tier] ( identifier[self] , identifier[name_num] ):
literal[string]
keyword[return] identifier[self] . identifier[tiers] [ identifier[name_num] - literal[int] ] keyword[if] identifier[isinstance] ( identifier[name_num] , identifier[int] ) keyword[else] [ identifier[i] ... | def get_tier(self, name_num):
"""Gives a tier, when multiple tiers exist with that name only the
first is returned.
:param name_num: Name or number of the tier to return.
:type name_num: int or str
:returns: The tier.
:raises IndexError: If the tier doesn't exist.
""... |
def getPk(self):
'''
getPk - Resolve any absent pk's off the obj's (like if an obj has been saved), and return the pk.
'''
if not self.pk and self.obj:
if self.obj._id:
self.pk = self.obj._id
return self.pk | def function[getPk, parameter[self]]:
constant[
getPk - Resolve any absent pk's off the obj's (like if an obj has been saved), and return the pk.
]
if <ast.BoolOp object at 0x7da1b0022c50> begin[:]
if name[self].obj._id begin[:]
name[self].pk assign[=] name[s... | keyword[def] identifier[getPk] ( identifier[self] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[pk] keyword[and] identifier[self] . identifier[obj] :
keyword[if] identifier[self] . identifier[obj] . identifier[_id] :
identifier[self] . identifier[pk] = identifier[self]... | def getPk(self):
"""
getPk - Resolve any absent pk's off the obj's (like if an obj has been saved), and return the pk.
"""
if not self.pk and self.obj:
if self.obj._id:
self.pk = self.obj._id # depends on [control=['if'], data=[]] # depends on [control=['if'], data=[]]
return self... |
def process(self, session: AppSession):
'''Populate the visits from the CDX into the URL table.'''
if not session.args.warc_dedup:
return
iterable = wpull.warc.format.read_cdx(
session.args.warc_dedup,
encoding=session.args.local_encoding or 'utf-8'
)... | def function[process, parameter[self, session]]:
constant[Populate the visits from the CDX into the URL table.]
if <ast.UnaryOp object at 0x7da2043459c0> begin[:]
return[None]
variable[iterable] assign[=] call[name[wpull].warc.format.read_cdx, parameter[name[session].args.warc_dedup]]
... | keyword[def] identifier[process] ( identifier[self] , identifier[session] : identifier[AppSession] ):
literal[string]
keyword[if] keyword[not] identifier[session] . identifier[args] . identifier[warc_dedup] :
keyword[return]
identifier[iterable] = identifier[wpull] . ident... | def process(self, session: AppSession):
"""Populate the visits from the CDX into the URL table."""
if not session.args.warc_dedup:
return # depends on [control=['if'], data=[]]
iterable = wpull.warc.format.read_cdx(session.args.warc_dedup, encoding=session.args.local_encoding or 'utf-8')
missin... |
def get_threadline_theming(self, thread, colourmode):
"""
look up how to display a Threadline wiidget in search mode
for a given thread.
:param thread: Thread to theme Threadline for
:type thread: alot.db.thread.Thread
:param colourmode: colourmode to use, one of 1,16,25... | def function[get_threadline_theming, parameter[self, thread, colourmode]]:
constant[
look up how to display a Threadline wiidget in search mode
for a given thread.
:param thread: Thread to theme Threadline for
:type thread: alot.db.thread.Thread
:param colourmode: colour... | keyword[def] identifier[get_threadline_theming] ( identifier[self] , identifier[thread] , identifier[colourmode] ):
literal[string]
keyword[def] identifier[pickcolour] ( identifier[triple] ):
keyword[return] identifier[triple] [ identifier[self] . identifier[_colours] . identifier[in... | def get_threadline_theming(self, thread, colourmode):
"""
look up how to display a Threadline wiidget in search mode
for a given thread.
:param thread: Thread to theme Threadline for
:type thread: alot.db.thread.Thread
:param colourmode: colourmode to use, one of 1,16,256.
... |
def depth(self, *args):
"""
Get/set the depth
"""
if len(args):
self._depth = args[0]
else:
return self._depth | def function[depth, parameter[self]]:
constant[
Get/set the depth
]
if call[name[len], parameter[name[args]]] begin[:]
name[self]._depth assign[=] call[name[args]][constant[0]] | keyword[def] identifier[depth] ( identifier[self] ,* identifier[args] ):
literal[string]
keyword[if] identifier[len] ( identifier[args] ):
identifier[self] . identifier[_depth] = identifier[args] [ literal[int] ]
keyword[else] :
keyword[return... | def depth(self, *args):
"""
Get/set the depth
"""
if len(args):
self._depth = args[0] # depends on [control=['if'], data=[]]
else:
return self._depth |
def convert_datetime_array(array):
''' Convert NumPy datetime arrays to arrays to milliseconds since epoch.
Args:
array : (obj)
A NumPy array of datetime to convert
If the value passed in is not a NumPy array, it will be returned as-is.
Returns:
array
'''
... | def function[convert_datetime_array, parameter[array]]:
constant[ Convert NumPy datetime arrays to arrays to milliseconds since epoch.
Args:
array : (obj)
A NumPy array of datetime to convert
If the value passed in is not a NumPy array, it will be returned as-is.
Retur... | keyword[def] identifier[convert_datetime_array] ( identifier[array] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[array] , identifier[np] . identifier[ndarray] ):
keyword[return] identifier[array]
keyword[try] :
identifier[dt2001] = identifier[... | def convert_datetime_array(array):
""" Convert NumPy datetime arrays to arrays to milliseconds since epoch.
Args:
array : (obj)
A NumPy array of datetime to convert
If the value passed in is not a NumPy array, it will be returned as-is.
Returns:
array
"""
... |
def _order_by_is_valid_or_none(self, params):
"""
Validates that a given order_by has proper syntax.
:param params: Query params.
:return: Returns True if either no order_by is present, or if the order_by is well-formed.
"""
if not "order_by" in params or not params["ord... | def function[_order_by_is_valid_or_none, parameter[self, params]]:
constant[
Validates that a given order_by has proper syntax.
:param params: Query params.
:return: Returns True if either no order_by is present, or if the order_by is well-formed.
]
if <ast.BoolOp object... | keyword[def] identifier[_order_by_is_valid_or_none] ( identifier[self] , identifier[params] ):
literal[string]
keyword[if] keyword[not] literal[string] keyword[in] identifier[params] keyword[or] keyword[not] identifier[params] [ literal[string] ]:
keyword[return] keyword[True] ... | def _order_by_is_valid_or_none(self, params):
"""
Validates that a given order_by has proper syntax.
:param params: Query params.
:return: Returns True if either no order_by is present, or if the order_by is well-formed.
"""
if not 'order_by' in params or not params['order_by']:... |
def expected_bar_values_2d(dates,
assets,
asset_info,
colname,
holes=None):
"""
Return an 2D array containing cls.expected_value(asset_id, date,
colname) for each date/asset pair in the inputs.
M... | def function[expected_bar_values_2d, parameter[dates, assets, asset_info, colname, holes]]:
constant[
Return an 2D array containing cls.expected_value(asset_id, date,
colname) for each date/asset pair in the inputs.
Missing locs are filled with 0 for volume and NaN for price columns:
- Val... | keyword[def] identifier[expected_bar_values_2d] ( identifier[dates] ,
identifier[assets] ,
identifier[asset_info] ,
identifier[colname] ,
identifier[holes] = keyword[None] ):
literal[string]
keyword[if] identifier[colname] == literal[string] :
identifier[dtype] = identifier[uint32]
... | def expected_bar_values_2d(dates, assets, asset_info, colname, holes=None):
"""
Return an 2D array containing cls.expected_value(asset_id, date,
colname) for each date/asset pair in the inputs.
Missing locs are filled with 0 for volume and NaN for price columns:
- Values before/after an asset'... |
def sign(self, byts):
'''
Compute the ECC signature for the given bytestream.
Args:
byts (bytes): The bytes to sign.
Returns:
bytes: The RSA Signature bytes.
'''
chosen_hash = c_hashes.SHA256()
hasher = c_hashes.Hash(chosen_hash, default_... | def function[sign, parameter[self, byts]]:
constant[
Compute the ECC signature for the given bytestream.
Args:
byts (bytes): The bytes to sign.
Returns:
bytes: The RSA Signature bytes.
]
variable[chosen_hash] assign[=] call[name[c_hashes].SHA256,... | keyword[def] identifier[sign] ( identifier[self] , identifier[byts] ):
literal[string]
identifier[chosen_hash] = identifier[c_hashes] . identifier[SHA256] ()
identifier[hasher] = identifier[c_hashes] . identifier[Hash] ( identifier[chosen_hash] , identifier[default_backend] ())
id... | def sign(self, byts):
"""
Compute the ECC signature for the given bytestream.
Args:
byts (bytes): The bytes to sign.
Returns:
bytes: The RSA Signature bytes.
"""
chosen_hash = c_hashes.SHA256()
hasher = c_hashes.Hash(chosen_hash, default_backend())
... |
def get(self, name):
"""
Get the resource URI for a specified resource name.
If an entry for the specified resource name does not exist in the
Name-URI cache, the cache is refreshed from the HMC with all resources
of the manager holding this cache.
If an entry for the s... | def function[get, parameter[self, name]]:
constant[
Get the resource URI for a specified resource name.
If an entry for the specified resource name does not exist in the
Name-URI cache, the cache is refreshed from the HMC with all resources
of the manager holding this cache.
... | keyword[def] identifier[get] ( identifier[self] , identifier[name] ):
literal[string]
identifier[self] . identifier[auto_invalidate] ()
keyword[try] :
keyword[return] identifier[self] . identifier[_uris] [ identifier[name] ]
keyword[except] identifier[KeyError] :
... | def get(self, name):
"""
Get the resource URI for a specified resource name.
If an entry for the specified resource name does not exist in the
Name-URI cache, the cache is refreshed from the HMC with all resources
of the manager holding this cache.
If an entry for the speci... |
def clear_list_value(self, value):
"""
Clean the argument value to eliminate None or Falsy values if needed.
"""
# Don't go any further: this value is empty.
if not value:
return self.empty_value
# Clean empty items if wanted
if self.clean_empty:
... | def function[clear_list_value, parameter[self, value]]:
constant[
Clean the argument value to eliminate None or Falsy values if needed.
]
if <ast.UnaryOp object at 0x7da18c4ce4d0> begin[:]
return[name[self].empty_value]
if name[self].clean_empty begin[:]
v... | keyword[def] identifier[clear_list_value] ( identifier[self] , identifier[value] ):
literal[string]
keyword[if] keyword[not] identifier[value] :
keyword[return] identifier[self] . identifier[empty_value]
keyword[if] identifier[self] . identifier[clea... | def clear_list_value(self, value):
"""
Clean the argument value to eliminate None or Falsy values if needed.
"""
# Don't go any further: this value is empty.
if not value:
return self.empty_value # depends on [control=['if'], data=[]]
# Clean empty items if wanted
if self.cl... |
def process_musicbed(vargs):
"""
Main MusicBed path.
"""
# let's validate given MusicBed url
validated = False
if vargs['artist_url'].startswith( 'https://www.musicbed.com/' ):
splitted = vargs['artist_url'][len('https://www.musicbed.com/'):].split( '/' )
if len( splitted ) == 3... | def function[process_musicbed, parameter[vargs]]:
constant[
Main MusicBed path.
]
variable[validated] assign[=] constant[False]
if call[call[name[vargs]][constant[artist_url]].startswith, parameter[constant[https://www.musicbed.com/]]] begin[:]
variable[splitted] assign[=... | keyword[def] identifier[process_musicbed] ( identifier[vargs] ):
literal[string]
identifier[validated] = keyword[False]
keyword[if] identifier[vargs] [ literal[string] ]. identifier[startswith] ( literal[string] ):
identifier[splitted] = identifier[vargs] [ literal[string] ][ identifi... | def process_musicbed(vargs):
"""
Main MusicBed path.
"""
# let's validate given MusicBed url
validated = False
if vargs['artist_url'].startswith('https://www.musicbed.com/'):
splitted = vargs['artist_url'][len('https://www.musicbed.com/'):].split('/')
if len(splitted) == 3:
... |
def export_maxloss_ruptures(ekey, dstore):
"""
:param ekey: export key, i.e. a pair (datastore key, fmt)
:param dstore: datastore object
"""
oq = dstore['oqparam']
mesh = get_mesh(dstore['sitecol'])
rlzs_by_gsim = dstore['csm_info'].get_rlzs_by_gsim_grp()
num_ses = oq.ses_per_logic_tree_... | def function[export_maxloss_ruptures, parameter[ekey, dstore]]:
constant[
:param ekey: export key, i.e. a pair (datastore key, fmt)
:param dstore: datastore object
]
variable[oq] assign[=] call[name[dstore]][constant[oqparam]]
variable[mesh] assign[=] call[name[get_mesh], parameter[c... | keyword[def] identifier[export_maxloss_ruptures] ( identifier[ekey] , identifier[dstore] ):
literal[string]
identifier[oq] = identifier[dstore] [ literal[string] ]
identifier[mesh] = identifier[get_mesh] ( identifier[dstore] [ literal[string] ])
identifier[rlzs_by_gsim] = identifier[dstore] [ lit... | def export_maxloss_ruptures(ekey, dstore):
"""
:param ekey: export key, i.e. a pair (datastore key, fmt)
:param dstore: datastore object
"""
oq = dstore['oqparam']
mesh = get_mesh(dstore['sitecol'])
rlzs_by_gsim = dstore['csm_info'].get_rlzs_by_gsim_grp()
num_ses = oq.ses_per_logic_tree_... |
def split_dmap_overlay(obj, depth=0):
"""
Splits a DynamicMap into the original component layers it was
constructed from by traversing the graph to search for dynamically
overlaid components (i.e. constructed by using * on a DynamicMap).
Useful for assigning subplots of an OverlayPlot the streams th... | def function[split_dmap_overlay, parameter[obj, depth]]:
constant[
Splits a DynamicMap into the original component layers it was
constructed from by traversing the graph to search for dynamically
overlaid components (i.e. constructed by using * on a DynamicMap).
Useful for assigning subplots of ... | keyword[def] identifier[split_dmap_overlay] ( identifier[obj] , identifier[depth] = literal[int] ):
literal[string]
identifier[layers] =[]
keyword[if] identifier[isinstance] ( identifier[obj] , identifier[DynamicMap] ):
keyword[if] identifier[issubclass] ( identifier[obj] . identifier[type]... | def split_dmap_overlay(obj, depth=0):
"""
Splits a DynamicMap into the original component layers it was
constructed from by traversing the graph to search for dynamically
overlaid components (i.e. constructed by using * on a DynamicMap).
Useful for assigning subplots of an OverlayPlot the streams th... |
def get_sport(sport):
"""
Get live scores for all matches in a particular sport
:param sport: the sport being played
:type sport: string
:return: List containing Match objects
:rtype: list
"""
sport = sport.lower()
data = _request_xml(sport)
matches = []
for match in data:
... | def function[get_sport, parameter[sport]]:
constant[
Get live scores for all matches in a particular sport
:param sport: the sport being played
:type sport: string
:return: List containing Match objects
:rtype: list
]
variable[sport] assign[=] call[name[sport].lower, parameter[]... | keyword[def] identifier[get_sport] ( identifier[sport] ):
literal[string]
identifier[sport] = identifier[sport] . identifier[lower] ()
identifier[data] = identifier[_request_xml] ( identifier[sport] )
identifier[matches] =[]
keyword[for] identifier[match] keyword[in] identifier[data] :
... | def get_sport(sport):
"""
Get live scores for all matches in a particular sport
:param sport: the sport being played
:type sport: string
:return: List containing Match objects
:rtype: list
"""
sport = sport.lower()
data = _request_xml(sport)
matches = []
for match in data:
... |
def __step4(self):
"""
Find a noncovered zero and prime it. If there is no starred zero
in the row containing this primed zero, Go to Step 5. Otherwise,
cover this row and uncover the column containing the starred
zero. Continue in this manner until there are no uncovered zeros
... | def function[__step4, parameter[self]]:
constant[
Find a noncovered zero and prime it. If there is no starred zero
in the row containing this primed zero, Go to Step 5. Otherwise,
cover this row and uncover the column containing the starred
zero. Continue in this manner until the... | keyword[def] identifier[__step4] ( identifier[self] ):
literal[string]
identifier[step] = literal[int]
identifier[done] = keyword[False]
identifier[row] =- literal[int]
identifier[col] =- literal[int]
identifier[star_col] =- literal[int]
keyword[whi... | def __step4(self):
"""
Find a noncovered zero and prime it. If there is no starred zero
in the row containing this primed zero, Go to Step 5. Otherwise,
cover this row and uncover the column containing the starred
zero. Continue in this manner until there are no uncovered zeros
... |
def _from_dict(cls, _dict):
"""Initialize a DialogNodeOutput object from a json dictionary."""
args = {}
xtra = _dict.copy()
if 'generic' in _dict:
args['generic'] = [
DialogNodeOutputGeneric._from_dict(x)
for x in (_dict.get('generic'))
... | def function[_from_dict, parameter[cls, _dict]]:
constant[Initialize a DialogNodeOutput object from a json dictionary.]
variable[args] assign[=] dictionary[[], []]
variable[xtra] assign[=] call[name[_dict].copy, parameter[]]
if compare[constant[generic] in name[_dict]] begin[:]
... | keyword[def] identifier[_from_dict] ( identifier[cls] , identifier[_dict] ):
literal[string]
identifier[args] ={}
identifier[xtra] = identifier[_dict] . identifier[copy] ()
keyword[if] literal[string] keyword[in] identifier[_dict] :
identifier[args] [ literal[strin... | def _from_dict(cls, _dict):
"""Initialize a DialogNodeOutput object from a json dictionary."""
args = {}
xtra = _dict.copy()
if 'generic' in _dict:
args['generic'] = [DialogNodeOutputGeneric._from_dict(x) for x in _dict.get('generic')]
del xtra['generic'] # depends on [control=['if'], d... |
def patterson_d(aca, acb, acc, acd):
"""Unbiased estimator for D(A, B; C, D), the normalised four-population
test for admixture between (A or B) and (C or D), also known as the
"ABBA BABA" test.
Parameters
----------
aca : array_like, int, shape (n_variants, 2),
Allele counts for popula... | def function[patterson_d, parameter[aca, acb, acc, acd]]:
constant[Unbiased estimator for D(A, B; C, D), the normalised four-population
test for admixture between (A or B) and (C or D), also known as the
"ABBA BABA" test.
Parameters
----------
aca : array_like, int, shape (n_variants, 2),
... | keyword[def] identifier[patterson_d] ( identifier[aca] , identifier[acb] , identifier[acc] , identifier[acd] ):
literal[string]
identifier[aca] = identifier[AlleleCountsArray] ( identifier[aca] , identifier[copy] = keyword[False] )
keyword[assert] identifier[aca] . identifier[shape] [ literal[i... | def patterson_d(aca, acb, acc, acd):
"""Unbiased estimator for D(A, B; C, D), the normalised four-population
test for admixture between (A or B) and (C or D), also known as the
"ABBA BABA" test.
Parameters
----------
aca : array_like, int, shape (n_variants, 2),
Allele counts for popula... |
def _is_interactive(self):
''' Prevent middlewares and orders to work outside live mode '''
return not (
self.realworld and (dt.date.today() > self.datetime.date())) | def function[_is_interactive, parameter[self]]:
constant[ Prevent middlewares and orders to work outside live mode ]
return[<ast.UnaryOp object at 0x7da1b0ef8520>] | keyword[def] identifier[_is_interactive] ( identifier[self] ):
literal[string]
keyword[return] keyword[not] (
identifier[self] . identifier[realworld] keyword[and] ( identifier[dt] . identifier[date] . identifier[today] ()> identifier[self] . identifier[datetime] . identifier[date] ())) | def _is_interactive(self):
""" Prevent middlewares and orders to work outside live mode """
return not (self.realworld and dt.date.today() > self.datetime.date()) |
def check_response(self, resp):
"""raise a descriptive exception on a "bad request" response"""
if resp.status_code == 400:
raise ApiException(json.loads(resp.content).get('message'))
return resp | def function[check_response, parameter[self, resp]]:
constant[raise a descriptive exception on a "bad request" response]
if compare[name[resp].status_code equal[==] constant[400]] begin[:]
<ast.Raise object at 0x7da1b2380370>
return[name[resp]] | keyword[def] identifier[check_response] ( identifier[self] , identifier[resp] ):
literal[string]
keyword[if] identifier[resp] . identifier[status_code] == literal[int] :
keyword[raise] identifier[ApiException] ( identifier[json] . identifier[loads] ( identifier[resp] . identifier[con... | def check_response(self, resp):
"""raise a descriptive exception on a "bad request" response"""
if resp.status_code == 400:
raise ApiException(json.loads(resp.content).get('message')) # depends on [control=['if'], data=[]]
return resp |
async def reply_video_note(self, video_note: typing.Union[base.InputFile, base.String],
duration: typing.Union[base.Integer, None] = None,
length: typing.Union[base.Integer, None] = None,
disable_notification: typing.Union[base... | <ast.AsyncFunctionDef object at 0x7da1b17ba920> | keyword[async] keyword[def] identifier[reply_video_note] ( identifier[self] , identifier[video_note] : identifier[typing] . identifier[Union] [ identifier[base] . identifier[InputFile] , identifier[base] . identifier[String] ],
identifier[duration] : identifier[typing] . identifier[Union] [ identifier[base] . ident... | async def reply_video_note(self, video_note: typing.Union[base.InputFile, base.String], duration: typing.Union[base.Integer, None]=None, length: typing.Union[base.Integer, None]=None, disable_notification: typing.Union[base.Boolean, None]=None, reply_markup=None, reply=True) -> Message:
"""
As of v.4.0, Tel... |
def should_generate_summaries():
"""Is this an appropriate context to generate summaries.
Returns:
a boolean
"""
name_scope = tf.contrib.framework.get_name_scope()
if name_scope and "while/" in name_scope:
# Summaries don't work well within tf.while_loop()
return False
if tf.get_variable_scope(... | def function[should_generate_summaries, parameter[]]:
constant[Is this an appropriate context to generate summaries.
Returns:
a boolean
]
variable[name_scope] assign[=] call[name[tf].contrib.framework.get_name_scope, parameter[]]
if <ast.BoolOp object at 0x7da1b205bd60> begin[:]
... | keyword[def] identifier[should_generate_summaries] ():
literal[string]
identifier[name_scope] = identifier[tf] . identifier[contrib] . identifier[framework] . identifier[get_name_scope] ()
keyword[if] identifier[name_scope] keyword[and] literal[string] keyword[in] identifier[name_scope] :
keywo... | def should_generate_summaries():
"""Is this an appropriate context to generate summaries.
Returns:
a boolean
"""
name_scope = tf.contrib.framework.get_name_scope()
if name_scope and 'while/' in name_scope:
# Summaries don't work well within tf.while_loop()
return False # depends on... |
def frame_to_yaml_safe(frame, ordered=False):
"""
Convert a pandas DataFrame to a dictionary that will survive
YAML serialization and re-conversion back to a DataFrame.
Parameters
----------
frame : pandas.DataFrame
ordered: bool, optional, default False
If True, an OrderedDict is r... | def function[frame_to_yaml_safe, parameter[frame, ordered]]:
constant[
Convert a pandas DataFrame to a dictionary that will survive
YAML serialization and re-conversion back to a DataFrame.
Parameters
----------
frame : pandas.DataFrame
ordered: bool, optional, default False
If ... | keyword[def] identifier[frame_to_yaml_safe] ( identifier[frame] , identifier[ordered] = keyword[False] ):
literal[string]
keyword[if] identifier[ordered] :
keyword[return] identifier[OrderedDict] ( identifier[tuple] (( identifier[col] , identifier[series_to_yaml_safe] ( identifier[series] , keyw... | def frame_to_yaml_safe(frame, ordered=False):
"""
Convert a pandas DataFrame to a dictionary that will survive
YAML serialization and re-conversion back to a DataFrame.
Parameters
----------
frame : pandas.DataFrame
ordered: bool, optional, default False
If True, an OrderedDict is r... |
def _build_index(self):
"""Build an index for indexing the sorted list.
Indexes are represented as binary trees in a dense array notation
similar to a binary heap.
For example, given a _lists representation storing integers:
[0]: 1 2 3
[1]: 4 5
[2]: 6 7 8 9
... | def function[_build_index, parameter[self]]:
constant[Build an index for indexing the sorted list.
Indexes are represented as binary trees in a dense array notation
similar to a binary heap.
For example, given a _lists representation storing integers:
[0]: 1 2 3
[1]: 4... | keyword[def] identifier[_build_index] ( identifier[self] ):
literal[string]
identifier[row0] = identifier[list] ( identifier[map] ( identifier[len] , identifier[self] . identifier[_lists] ))
keyword[if] identifier[len] ( identifier[row0] )== literal[int] :
identifier[self] .... | def _build_index(self):
"""Build an index for indexing the sorted list.
Indexes are represented as binary trees in a dense array notation
similar to a binary heap.
For example, given a _lists representation storing integers:
[0]: 1 2 3
[1]: 4 5
[2]: 6 7 8 9
... |
def manager_view(request, managerTitle):
''' View the details of a manager position.
Parameters:
request is an HTTP request
managerTitle is the URL title of the manager.
'''
targetManager = get_object_or_404(Manager, url_title=managerTitle)
if not targetManager.active:
messa... | def function[manager_view, parameter[request, managerTitle]]:
constant[ View the details of a manager position.
Parameters:
request is an HTTP request
managerTitle is the URL title of the manager.
]
variable[targetManager] assign[=] call[name[get_object_or_404], parameter[name[Ma... | keyword[def] identifier[manager_view] ( identifier[request] , identifier[managerTitle] ):
literal[string]
identifier[targetManager] = identifier[get_object_or_404] ( identifier[Manager] , identifier[url_title] = identifier[managerTitle] )
keyword[if] keyword[not] identifier[targetManager] . identif... | def manager_view(request, managerTitle):
""" View the details of a manager position.
Parameters:
request is an HTTP request
managerTitle is the URL title of the manager.
"""
targetManager = get_object_or_404(Manager, url_title=managerTitle)
if not targetManager.active:
messag... |
def serve(config):
"Serve the app with Gevent"
from gevent.pywsgi import WSGIServer
app = make_app(config=config)
host = app.config.get("HOST", '127.0.0.1')
port = app.config.get("PORT", 5000)
http_server = WSGIServer((host, port), app)
http_server.serve_forever() | def function[serve, parameter[config]]:
constant[Serve the app with Gevent]
from relative_module[gevent.pywsgi] import module[WSGIServer]
variable[app] assign[=] call[name[make_app], parameter[]]
variable[host] assign[=] call[name[app].config.get, parameter[constant[HOST], constant[127.0.0.1... | keyword[def] identifier[serve] ( identifier[config] ):
literal[string]
keyword[from] identifier[gevent] . identifier[pywsgi] keyword[import] identifier[WSGIServer]
identifier[app] = identifier[make_app] ( identifier[config] = identifier[config] )
identifier[host] = identifier[app] . identif... | def serve(config):
"""Serve the app with Gevent"""
from gevent.pywsgi import WSGIServer
app = make_app(config=config)
host = app.config.get('HOST', '127.0.0.1')
port = app.config.get('PORT', 5000)
http_server = WSGIServer((host, port), app)
http_server.serve_forever() |
def getVoIPchanStats(self, chantype,
codec_list=('ulaw', 'alaw', 'gsm', 'g729')):
"""Query Asterisk Manager Interface for SIP / IAX2 Channel / Codec Stats.
CLI Commands - sip show channels
iax2 show channnels
@param chantype: M... | def function[getVoIPchanStats, parameter[self, chantype, codec_list]]:
constant[Query Asterisk Manager Interface for SIP / IAX2 Channel / Codec Stats.
CLI Commands - sip show channels
iax2 show channnels
@param chantype: Must be 'sip' or 'iax2'.
... | keyword[def] identifier[getVoIPchanStats] ( identifier[self] , identifier[chantype] ,
identifier[codec_list] =( literal[string] , literal[string] , literal[string] , literal[string] )):
literal[string]
identifier[chan] = identifier[chantype] . identifier[lower] ()
keyword[if] keyword[not... | def getVoIPchanStats(self, chantype, codec_list=('ulaw', 'alaw', 'gsm', 'g729')):
"""Query Asterisk Manager Interface for SIP / IAX2 Channel / Codec Stats.
CLI Commands - sip show channels
iax2 show channnels
@param chantype: Must be 'sip' or 'iax2'.
... |
def _unbind_topics(self, topics):
"""Unsubscribe to all of the topics we needed for communication with device
Args:
topics (MQTTTopicValidator): The topic validator for this device that
we have connected to.
"""
self.client.unsubscribe(topics.status)
... | def function[_unbind_topics, parameter[self, topics]]:
constant[Unsubscribe to all of the topics we needed for communication with device
Args:
topics (MQTTTopicValidator): The topic validator for this device that
we have connected to.
]
call[name[self].client... | keyword[def] identifier[_unbind_topics] ( identifier[self] , identifier[topics] ):
literal[string]
identifier[self] . identifier[client] . identifier[unsubscribe] ( identifier[topics] . identifier[status] )
identifier[self] . identifier[client] . identifier[unsubscribe] ( identifier[topic... | def _unbind_topics(self, topics):
"""Unsubscribe to all of the topics we needed for communication with device
Args:
topics (MQTTTopicValidator): The topic validator for this device that
we have connected to.
"""
self.client.unsubscribe(topics.status)
self.client.... |
def insert(self, index, value):
'''Insert a node in-place. It is highly suggested that you do not
use this method. Use assoc instead'''
newnode = LookupTreeNode(index, value)
level = 0
node = self.root
while True:
ind = _getbits(newnode.index, level)
... | def function[insert, parameter[self, index, value]]:
constant[Insert a node in-place. It is highly suggested that you do not
use this method. Use assoc instead]
variable[newnode] assign[=] call[name[LookupTreeNode], parameter[name[index], name[value]]]
variable[level] assign[=] constant[... | keyword[def] identifier[insert] ( identifier[self] , identifier[index] , identifier[value] ):
literal[string]
identifier[newnode] = identifier[LookupTreeNode] ( identifier[index] , identifier[value] )
identifier[level] = literal[int]
identifier[node] = identifier[self] . identifi... | def insert(self, index, value):
"""Insert a node in-place. It is highly suggested that you do not
use this method. Use assoc instead"""
newnode = LookupTreeNode(index, value)
level = 0
node = self.root
while True:
ind = _getbits(newnode.index, level)
level += 1
child ... |
def before_update(self, context, current, resource):
"""
If the resource has changed we try to generate a budget data
package, but if it hasn't then we don't do anything
"""
# Return if the budget data package fields have not been filled in
if not self.are_budget_data_pa... | def function[before_update, parameter[self, context, current, resource]]:
constant[
If the resource has changed we try to generate a budget data
package, but if it hasn't then we don't do anything
]
if <ast.UnaryOp object at 0x7da20cabc550> begin[:]
return[None]
i... | keyword[def] identifier[before_update] ( identifier[self] , identifier[context] , identifier[current] , identifier[resource] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[are_budget_data_package_fields_filled_in] ( identifier[resource] ):
keyword... | def before_update(self, context, current, resource):
"""
If the resource has changed we try to generate a budget data
package, but if it hasn't then we don't do anything
"""
# Return if the budget data package fields have not been filled in
if not self.are_budget_data_package_fields_... |
def build(self):
"""
The decoder computational graph consists of three components:
(1) the input node `decoder_input`
(2) the embedding node `decoder_embed`
(3) the recurrent (RNN) part `decoder_rnn`
(4) the output of th... | def function[build, parameter[self]]:
constant[
The decoder computational graph consists of three components:
(1) the input node `decoder_input`
(2) the embedding node `decoder_embed`
(3) the recurrent (RNN) part `decoder_rnn`
... | keyword[def] identifier[build] ( identifier[self] ):
literal[string]
identifier[hidden_dim] = identifier[self] . identifier[config] [ literal[string] ]
identifier[recurrent_unit] = identifier[self] . identifier[config] [ literal[string] ]
identifier[bidirectional] = keyw... | def build(self):
"""
The decoder computational graph consists of three components:
(1) the input node `decoder_input`
(2) the embedding node `decoder_embed`
(3) the recurrent (RNN) part `decoder_rnn`
(4) the output of the de... |
def pos(self, element = None):
''' Tries to decide about the part of speech. '''
tags = []
if element:
if element.startswith(('der', 'die', 'das')):
tags.append('NN')
if ' VERB' in element:
tags.append('VB')
if ' ADJ' in element:
tags.append('JJ')
else:
for element in self.elements:
... | def function[pos, parameter[self, element]]:
constant[ Tries to decide about the part of speech. ]
variable[tags] assign[=] list[[]]
if name[element] begin[:]
if call[name[element].startswith, parameter[tuple[[<ast.Constant object at 0x7da1b10e44c0>, <ast.Constant object at 0x7da... | keyword[def] identifier[pos] ( identifier[self] , identifier[element] = keyword[None] ):
literal[string]
identifier[tags] =[]
keyword[if] identifier[element] :
keyword[if] identifier[element] . identifier[startswith] (( literal[string] , literal[string] , literal[string] )):
identifier[tags] . i... | def pos(self, element=None):
""" Tries to decide about the part of speech. """
tags = []
if element:
if element.startswith(('der', 'die', 'das')):
tags.append('NN') # depends on [control=['if'], data=[]]
if ' VERB' in element:
tags.append('VB') # depends on [control... |
def create_generic_instances(self, instances):
"""
Generalize each (single) Istio instance into two OpenMetricsBaseCheck instances
"""
generic_instances = []
for instance in instances:
istio_mesh_instance = self._create_istio_mesh_instance(instance)
proce... | def function[create_generic_instances, parameter[self, instances]]:
constant[
Generalize each (single) Istio instance into two OpenMetricsBaseCheck instances
]
variable[generic_instances] assign[=] list[[]]
for taget[name[instance]] in starred[name[instances]] begin[:]
... | keyword[def] identifier[create_generic_instances] ( identifier[self] , identifier[instances] ):
literal[string]
identifier[generic_instances] =[]
keyword[for] identifier[instance] keyword[in] identifier[instances] :
identifier[istio_mesh_instance] = identifier[self] . iden... | def create_generic_instances(self, instances):
"""
Generalize each (single) Istio instance into two OpenMetricsBaseCheck instances
"""
generic_instances = []
for instance in instances:
istio_mesh_instance = self._create_istio_mesh_instance(instance)
process_mixer_instance = s... |
def downgrade():
"""Downgrade database."""
# table ObjectVersionTag
op.drop_table('files_objecttags')
# table ObjectVersion: modify primary_key
if op.get_context().dialect.name == 'mysql':
op.execute(
'ALTER TABLE files_object '
'DROP INDEX uq_files_object_bucket_id, ... | def function[downgrade, parameter[]]:
constant[Downgrade database.]
call[name[op].drop_table, parameter[constant[files_objecttags]]]
if compare[call[name[op].get_context, parameter[]].dialect.name equal[==] constant[mysql]] begin[:]
call[name[op].execute, parameter[constant[ALTER... | keyword[def] identifier[downgrade] ():
literal[string]
identifier[op] . identifier[drop_table] ( literal[string] )
keyword[if] identifier[op] . identifier[get_context] (). identifier[dialect] . identifier[name] == literal[string] :
identifier[op] . identifier[execute] (
li... | def downgrade():
"""Downgrade database."""
# table ObjectVersionTag
op.drop_table('files_objecttags')
# table ObjectVersion: modify primary_key
if op.get_context().dialect.name == 'mysql':
op.execute('ALTER TABLE files_object DROP INDEX uq_files_object_bucket_id, DROP PRIMARY KEY, ADD PRIMAR... |
def pixels(self):
# type: () -> Pixels
"""
:return list: RGB tuples.
"""
if not self.__pixels:
rgb_tuples = zip(
self.raw[2::4], self.raw[1::4], self.raw[0::4]
) # type: Iterator[Pixel]
self.__pixels = list(zip(*[iter(rgb_tupl... | def function[pixels, parameter[self]]:
constant[
:return list: RGB tuples.
]
if <ast.UnaryOp object at 0x7da1b07e2800> begin[:]
variable[rgb_tuples] assign[=] call[name[zip], parameter[call[name[self].raw][<ast.Slice object at 0x7da1b07e15d0>], call[name[self].raw][<ast.S... | keyword[def] identifier[pixels] ( identifier[self] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[__pixels] :
identifier[rgb_tuples] = identifier[zip] (
identifier[self] . identifier[raw] [ literal[int] :: literal[int] ], identifier[self] . i... | def pixels(self):
# type: () -> Pixels
'\n :return list: RGB tuples.\n '
if not self.__pixels:
rgb_tuples = zip(self.raw[2::4], self.raw[1::4], self.raw[0::4]) # type: Iterator[Pixel]
self.__pixels = list(zip(*[iter(rgb_tuples)] * self.width)) # type: ignore # depends on [co... |
def response_json(self, status, response, content_type='application/json', encoding='utf-8', headers=None, jsonp=None):
"""
Send a JSON response
"""
encoder = JSONEncoder(
check_circular=self.app.validate_output,
allow_nan=False,
sort_keys=True,
... | def function[response_json, parameter[self, status, response, content_type, encoding, headers, jsonp]]:
constant[
Send a JSON response
]
variable[encoder] assign[=] call[name[JSONEncoder], parameter[]]
variable[content] assign[=] call[name[encoder].encode, parameter[name[response... | keyword[def] identifier[response_json] ( identifier[self] , identifier[status] , identifier[response] , identifier[content_type] = literal[string] , identifier[encoding] = literal[string] , identifier[headers] = keyword[None] , identifier[jsonp] = keyword[None] ):
literal[string]
identifier[encode... | def response_json(self, status, response, content_type='application/json', encoding='utf-8', headers=None, jsonp=None):
"""
Send a JSON response
"""
encoder = JSONEncoder(check_circular=self.app.validate_output, allow_nan=False, sort_keys=True, indent=2 if self.app.pretty_output else None, separ... |
def EnumerateFilesystemsFromClient(args):
"""List all local filesystems mounted on this system."""
del args # Unused.
for fs_struct in client_utils_osx.GetFileSystems():
yield rdf_client_fs.Filesystem(
device=fs_struct.f_mntfromname,
mount_point=fs_struct.f_mntonname,
type=fs_struct.f... | def function[EnumerateFilesystemsFromClient, parameter[args]]:
constant[List all local filesystems mounted on this system.]
<ast.Delete object at 0x7da1b1c24df0>
for taget[name[fs_struct]] in starred[call[name[client_utils_osx].GetFileSystems, parameter[]]] begin[:]
<ast.Yield object... | keyword[def] identifier[EnumerateFilesystemsFromClient] ( identifier[args] ):
literal[string]
keyword[del] identifier[args]
keyword[for] identifier[fs_struct] keyword[in] identifier[client_utils_osx] . identifier[GetFileSystems] ():
keyword[yield] identifier[rdf_client_fs] . identifier[Filesystem... | def EnumerateFilesystemsFromClient(args):
"""List all local filesystems mounted on this system."""
del args # Unused.
for fs_struct in client_utils_osx.GetFileSystems():
yield rdf_client_fs.Filesystem(device=fs_struct.f_mntfromname, mount_point=fs_struct.f_mntonname, type=fs_struct.f_fstypename) #... |
def save(self, obj, usePipeline=True, forceID=False, cascadeSave=True, conn=None):
'''
save - Save an object / objects associated with this model.
You probably want to just do object.save() instead of this, but to save multiple objects at once in a single transaction,
you can use:
MyModel.s... | def function[save, parameter[self, obj, usePipeline, forceID, cascadeSave, conn]]:
constant[
save - Save an object / objects associated with this model.
You probably want to just do object.save() instead of this, but to save multiple objects at once in a single transaction,
you can use:
... | keyword[def] identifier[save] ( identifier[self] , identifier[obj] , identifier[usePipeline] = keyword[True] , identifier[forceID] = keyword[False] , identifier[cascadeSave] = keyword[True] , identifier[conn] = keyword[None] ):
literal[string]
keyword[if] identifier[conn] keyword[is] keyword[None] :
ide... | def save(self, obj, usePipeline=True, forceID=False, cascadeSave=True, conn=None):
"""
save - Save an object / objects associated with this model.
You probably want to just do object.save() instead of this, but to save multiple objects at once in a single transaction,
you can use:
MyModel... |
def replace(self, old_patch, new_patch):
""" Replace old_patch with new_patch
The method only replaces the patch and doesn't change any comments.
"""
self._check_patch(old_patch)
old_patchline = self.patch2line[old_patch]
index = self.patchlines.index(old_patchline)
... | def function[replace, parameter[self, old_patch, new_patch]]:
constant[ Replace old_patch with new_patch
The method only replaces the patch and doesn't change any comments.
]
call[name[self]._check_patch, parameter[name[old_patch]]]
variable[old_patchline] assign[=] call[name[sel... | keyword[def] identifier[replace] ( identifier[self] , identifier[old_patch] , identifier[new_patch] ):
literal[string]
identifier[self] . identifier[_check_patch] ( identifier[old_patch] )
identifier[old_patchline] = identifier[self] . identifier[patch2line] [ identifier[old_patch] ]
... | def replace(self, old_patch, new_patch):
""" Replace old_patch with new_patch
The method only replaces the patch and doesn't change any comments.
"""
self._check_patch(old_patch)
old_patchline = self.patch2line[old_patch]
index = self.patchlines.index(old_patchline)
self.patchlines.p... |
def delete(self, filename, storage_type=None, bucket_name=None):
"""Deletes the specified file, either locally or from S3, depending on the file's storage type."""
if not (storage_type and bucket_name):
self._delete_local(filename)
else:
if storage_type != 's3':
... | def function[delete, parameter[self, filename, storage_type, bucket_name]]:
constant[Deletes the specified file, either locally or from S3, depending on the file's storage type.]
if <ast.UnaryOp object at 0x7da1b01feb60> begin[:]
call[name[self]._delete_local, parameter[name[filename]]] | keyword[def] identifier[delete] ( identifier[self] , identifier[filename] , identifier[storage_type] = keyword[None] , identifier[bucket_name] = keyword[None] ):
literal[string]
keyword[if] keyword[not] ( identifier[storage_type] keyword[and] identifier[bucket_name] ):
identifier[s... | def delete(self, filename, storage_type=None, bucket_name=None):
"""Deletes the specified file, either locally or from S3, depending on the file's storage type."""
if not (storage_type and bucket_name):
self._delete_local(filename) # depends on [control=['if'], data=[]]
else:
if storage_typ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.