code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def deserialize(cls, value):
"""
Creates a new Node instance via a JSON map string.
Note that `port` and `ip` and are required keys for the JSON map,
`peer` and `host` are optional. If `peer` is not present, the new Node
instance will use the current peer. If `host` is not pre... | def function[deserialize, parameter[cls, value]]:
constant[
Creates a new Node instance via a JSON map string.
Note that `port` and `ip` and are required keys for the JSON map,
`peer` and `host` are optional. If `peer` is not present, the new Node
instance will use the current ... | keyword[def] identifier[deserialize] ( identifier[cls] , identifier[value] ):
literal[string]
keyword[if] identifier[getattr] ( identifier[value] , literal[string] , keyword[None] ):
identifier[value] = identifier[value] . identifier[decode] ()
identifier[logger] . identifie... | def deserialize(cls, value):
"""
Creates a new Node instance via a JSON map string.
Note that `port` and `ip` and are required keys for the JSON map,
`peer` and `host` are optional. If `peer` is not present, the new Node
instance will use the current peer. If `host` is not present... |
def camel_to_underscore(name):
"""Convert camel case name to underscore name.
Examples::
>>> camel_to_underscore('HttpRequest')
'http_request'
>>> camel_to_underscore('httpRequest')
'http_request'
>>> camel_to_underscore('HTTPRequest')
'http_request'
>>>... | def function[camel_to_underscore, parameter[name]]:
constant[Convert camel case name to underscore name.
Examples::
>>> camel_to_underscore('HttpRequest')
'http_request'
>>> camel_to_underscore('httpRequest')
'http_request'
>>> camel_to_underscore('HTTPRequest')
... | keyword[def] identifier[camel_to_underscore] ( identifier[name] ):
literal[string]
identifier[name] = identifier[re] . identifier[sub] ( literal[string] , literal[string] , identifier[name] )
identifier[name] = identifier[re] . identifier[sub] ( literal[string] , literal[string] , identifier[name] )
... | def camel_to_underscore(name):
"""Convert camel case name to underscore name.
Examples::
>>> camel_to_underscore('HttpRequest')
'http_request'
>>> camel_to_underscore('httpRequest')
'http_request'
>>> camel_to_underscore('HTTPRequest')
'http_request'
>>>... |
def persist(name, value, config=None):
'''
Assign and persist a simple sysctl parameter for this minion. If ``config``
is not specified, a sensible default will be chosen using
:mod:`sysctl.default_config <salt.modules.linux_sysctl.default_config>`.
CLI Example:
.. code-block:: bash
s... | def function[persist, parameter[name, value, config]]:
constant[
Assign and persist a simple sysctl parameter for this minion. If ``config``
is not specified, a sensible default will be chosen using
:mod:`sysctl.default_config <salt.modules.linux_sysctl.default_config>`.
CLI Example:
.. co... | keyword[def] identifier[persist] ( identifier[name] , identifier[value] , identifier[config] = keyword[None] ):
literal[string]
keyword[if] identifier[config] keyword[is] keyword[None] :
identifier[config] = identifier[default_config] ()
identifier[edited] = keyword[False]
keywo... | def persist(name, value, config=None):
"""
Assign and persist a simple sysctl parameter for this minion. If ``config``
is not specified, a sensible default will be chosen using
:mod:`sysctl.default_config <salt.modules.linux_sysctl.default_config>`.
CLI Example:
.. code-block:: bash
s... |
def autosummary_table_visit_html(self, node):
"""Make the first column of the table non-breaking."""
try:
tbody = node[0][0][-1]
for row in tbody:
col1_entry = row[0]
par = col1_entry[0]
for j, subnode in enumerate(list(par)):
if isinstance(sub... | def function[autosummary_table_visit_html, parameter[self, node]]:
constant[Make the first column of the table non-breaking.]
<ast.Try object at 0x7da20c6abf10> | keyword[def] identifier[autosummary_table_visit_html] ( identifier[self] , identifier[node] ):
literal[string]
keyword[try] :
identifier[tbody] = identifier[node] [ literal[int] ][ literal[int] ][- literal[int] ]
keyword[for] identifier[row] keyword[in] identifier[tbody] :
... | def autosummary_table_visit_html(self, node):
"""Make the first column of the table non-breaking."""
try:
tbody = node[0][0][-1]
for row in tbody:
col1_entry = row[0]
par = col1_entry[0]
for (j, subnode) in enumerate(list(par)):
if isinstance(s... |
def get_filters(self):
""" Coroutine based filters for render pipeline. """
return [
self.compute_style_filter,
self.render_filter,
self.calc_widths_filter,
self.format_row_filter,
self.align_rows_filter,
] | def function[get_filters, parameter[self]]:
constant[ Coroutine based filters for render pipeline. ]
return[list[[<ast.Attribute object at 0x7da207f98790>, <ast.Attribute object at 0x7da207f9ab30>, <ast.Attribute object at 0x7da207f98400>, <ast.Attribute object at 0x7da207f991e0>, <ast.Attribute object at 0... | keyword[def] identifier[get_filters] ( identifier[self] ):
literal[string]
keyword[return] [
identifier[self] . identifier[compute_style_filter] ,
identifier[self] . identifier[render_filter] ,
identifier[self] . identifier[calc_widths_filter] ,
identifier[self] ... | def get_filters(self):
""" Coroutine based filters for render pipeline. """
return [self.compute_style_filter, self.render_filter, self.calc_widths_filter, self.format_row_filter, self.align_rows_filter] |
def constant_pad(X, multiple_of, up_down_rule='even', left_right_rule='even', pad_value=0):
"""Function pads an image of shape (rows, columns, channels) with zeros.
It pads an image so that the shape becomes (rows + padded_rows, columns + padded_columns, channels), where
padded_rows = (int(rows/multipl... | def function[constant_pad, parameter[X, multiple_of, up_down_rule, left_right_rule, pad_value]]:
constant[Function pads an image of shape (rows, columns, channels) with zeros.
It pads an image so that the shape becomes (rows + padded_rows, columns + padded_columns, channels), where
padded_rows = (int(r... | keyword[def] identifier[constant_pad] ( identifier[X] , identifier[multiple_of] , identifier[up_down_rule] = literal[string] , identifier[left_right_rule] = literal[string] , identifier[pad_value] = literal[int] ):
literal[string]
identifier[shape] = identifier[X] . identifier[shape]
ident... | def constant_pad(X, multiple_of, up_down_rule='even', left_right_rule='even', pad_value=0):
"""Function pads an image of shape (rows, columns, channels) with zeros.
It pads an image so that the shape becomes (rows + padded_rows, columns + padded_columns, channels), where
padded_rows = (int(rows/multiple_of... |
def GetBatchJobHelper(self, version=sorted(_SERVICE_MAP.keys())[-1],
server=None):
"""Returns a BatchJobHelper to work with the BatchJobService.
This is a convenience method. It is functionally identical to calling
BatchJobHelper(adwords_client, version).
Args:
[optio... | def function[GetBatchJobHelper, parameter[self, version, server]]:
constant[Returns a BatchJobHelper to work with the BatchJobService.
This is a convenience method. It is functionally identical to calling
BatchJobHelper(adwords_client, version).
Args:
[optional]
version: A string i... | keyword[def] identifier[GetBatchJobHelper] ( identifier[self] , identifier[version] = identifier[sorted] ( identifier[_SERVICE_MAP] . identifier[keys] ())[- literal[int] ],
identifier[server] = keyword[None] ):
literal[string]
keyword[if] keyword[not] identifier[server] :
identifier[server] = ide... | def GetBatchJobHelper(self, version=sorted(_SERVICE_MAP.keys())[-1], server=None):
"""Returns a BatchJobHelper to work with the BatchJobService.
This is a convenience method. It is functionally identical to calling
BatchJobHelper(adwords_client, version).
Args:
[optional]
version: A st... |
def create_cvmfs_persistent_volume_claim(cvmfs_volume):
"""Create CVMFS persistent volume claim."""
from kubernetes.client.rest import ApiException
from reana_commons.k8s.api_client import current_k8s_corev1_api_client
try:
current_k8s_corev1_api_client.\
create_namespaced_persisten... | def function[create_cvmfs_persistent_volume_claim, parameter[cvmfs_volume]]:
constant[Create CVMFS persistent volume claim.]
from relative_module[kubernetes.client.rest] import module[ApiException]
from relative_module[reana_commons.k8s.api_client] import module[current_k8s_corev1_api_client]
<ast.T... | keyword[def] identifier[create_cvmfs_persistent_volume_claim] ( identifier[cvmfs_volume] ):
literal[string]
keyword[from] identifier[kubernetes] . identifier[client] . identifier[rest] keyword[import] identifier[ApiException]
keyword[from] identifier[reana_commons] . identifier[k8s] . identifier[... | def create_cvmfs_persistent_volume_claim(cvmfs_volume):
"""Create CVMFS persistent volume claim."""
from kubernetes.client.rest import ApiException
from reana_commons.k8s.api_client import current_k8s_corev1_api_client
try:
current_k8s_corev1_api_client.create_namespaced_persistent_volume_claim(... |
def is_all_field_none(self):
"""
:rtype: bool
"""
if self._monetary_account_id is not None:
return False
if self._alias is not None:
return False
if self._counterparty_alias is not None:
return False
if self._amount_guarante... | def function[is_all_field_none, parameter[self]]:
constant[
:rtype: bool
]
if compare[name[self]._monetary_account_id is_not constant[None]] begin[:]
return[constant[False]]
if compare[name[self]._alias is_not constant[None]] begin[:]
return[constant[False]]
... | keyword[def] identifier[is_all_field_none] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[_monetary_account_id] keyword[is] keyword[not] keyword[None] :
keyword[return] keyword[False]
keyword[if] identifier[self] . identifier[_alias] ... | def is_all_field_none(self):
"""
:rtype: bool
"""
if self._monetary_account_id is not None:
return False # depends on [control=['if'], data=[]]
if self._alias is not None:
return False # depends on [control=['if'], data=[]]
if self._counterparty_alias is not None:
... |
def listdir(self, name):
"""
TODO collect directories
"""
return [], [obj.filename for obj in cloudstorage.listbucket(self.path(name))] | def function[listdir, parameter[self, name]]:
constant[
TODO collect directories
]
return[tuple[[<ast.List object at 0x7da20e9b1fc0>, <ast.ListComp object at 0x7da20e9b33d0>]]] | keyword[def] identifier[listdir] ( identifier[self] , identifier[name] ):
literal[string]
keyword[return] [],[ identifier[obj] . identifier[filename] keyword[for] identifier[obj] keyword[in] identifier[cloudstorage] . identifier[listbucket] ( identifier[self] . identifier[path] ( identifier[nam... | def listdir(self, name):
"""
TODO collect directories
"""
return ([], [obj.filename for obj in cloudstorage.listbucket(self.path(name))]) |
def roc(args):
""" Calculate ROC_AUC and other metrics and optionally plot ROC curve."""
outputfile = args.outfile
# Default extension for image
if outputfile and not outputfile.endswith(".png"):
outputfile += ".png"
motifs = read_motifs(args.pwmfile, fmt="pwm")
ids = []
if arg... | def function[roc, parameter[args]]:
constant[ Calculate ROC_AUC and other metrics and optionally plot ROC curve.]
variable[outputfile] assign[=] name[args].outfile
if <ast.BoolOp object at 0x7da2044c30d0> begin[:]
<ast.AugAssign object at 0x7da2044c25f0>
variable[motifs] assign[=... | keyword[def] identifier[roc] ( identifier[args] ):
literal[string]
identifier[outputfile] = identifier[args] . identifier[outfile]
keyword[if] identifier[outputfile] keyword[and] keyword[not] identifier[outputfile] . identifier[endswith] ( literal[string] ):
identifier[outputfile] +... | def roc(args):
""" Calculate ROC_AUC and other metrics and optionally plot ROC curve."""
outputfile = args.outfile
# Default extension for image
if outputfile and (not outputfile.endswith('.png')):
outputfile += '.png' # depends on [control=['if'], data=[]]
motifs = read_motifs(args.pwmfile... |
def compile_state_usage(self):
'''
Return all used and unused states for the minion based on the top match data
'''
err = []
top = self.get_top()
err += self.verify_tops(top)
if err:
return err
matches = self.top_matches(top)
state_us... | def function[compile_state_usage, parameter[self]]:
constant[
Return all used and unused states for the minion based on the top match data
]
variable[err] assign[=] list[[]]
variable[top] assign[=] call[name[self].get_top, parameter[]]
<ast.AugAssign object at 0x7da18fe91540>... | keyword[def] identifier[compile_state_usage] ( identifier[self] ):
literal[string]
identifier[err] =[]
identifier[top] = identifier[self] . identifier[get_top] ()
identifier[err] += identifier[self] . identifier[verify_tops] ( identifier[top] )
keyword[if] identifier[er... | def compile_state_usage(self):
"""
Return all used and unused states for the minion based on the top match data
"""
err = []
top = self.get_top()
err += self.verify_tops(top)
if err:
return err # depends on [control=['if'], data=[]]
matches = self.top_matches(top)
st... |
def server(name='proxy-server', headers_middleware=None,
server_software=None, **kwargs):
'''Function to Create a WSGI Proxy Server.'''
if headers_middleware is None:
headers_middleware = [x_forwarded_for]
wsgi_proxy = ProxyServerWsgiHandler(headers_middleware)
kwargs['server_software... | def function[server, parameter[name, headers_middleware, server_software]]:
constant[Function to Create a WSGI Proxy Server.]
if compare[name[headers_middleware] is constant[None]] begin[:]
variable[headers_middleware] assign[=] list[[<ast.Name object at 0x7da18eb55750>]]
variabl... | keyword[def] identifier[server] ( identifier[name] = literal[string] , identifier[headers_middleware] = keyword[None] ,
identifier[server_software] = keyword[None] ,** identifier[kwargs] ):
literal[string]
keyword[if] identifier[headers_middleware] keyword[is] keyword[None] :
identifier[header... | def server(name='proxy-server', headers_middleware=None, server_software=None, **kwargs):
"""Function to Create a WSGI Proxy Server."""
if headers_middleware is None:
headers_middleware = [x_forwarded_for] # depends on [control=['if'], data=['headers_middleware']]
wsgi_proxy = ProxyServerWsgiHandle... |
def gamma(phi1,phi2,theta1,theta2):
"""
calculate third rotation angle
inputs are angles from 2 pulsars
returns the angle.
"""
if phi1 == phi2 and theta1 == theta2:
gamma = 0
else:
gamma = atan( sin(theta2)*sin(phi2-phi1) / \
(cos(theta1)*sin(t... | def function[gamma, parameter[phi1, phi2, theta1, theta2]]:
constant[
calculate third rotation angle
inputs are angles from 2 pulsars
returns the angle.
]
if <ast.BoolOp object at 0x7da1b0549690> begin[:]
variable[gamma] assign[=] constant[0]
variable[dummy_a... | keyword[def] identifier[gamma] ( identifier[phi1] , identifier[phi2] , identifier[theta1] , identifier[theta2] ):
literal[string]
keyword[if] identifier[phi1] == identifier[phi2] keyword[and] identifier[theta1] == identifier[theta2] :
identifier[gamma] = literal[int]
keyword[else] :
... | def gamma(phi1, phi2, theta1, theta2):
"""
calculate third rotation angle
inputs are angles from 2 pulsars
returns the angle.
"""
if phi1 == phi2 and theta1 == theta2:
gamma = 0 # depends on [control=['if'], data=[]]
else:
gamma = atan(sin(theta2) * sin(phi2 - phi1) / (... |
def add_triple(self, subj, pred, obj):
''' Adds an entity property to an existing entity '''
subj_data, pred_data, obj_data = self.are_ilx([subj, pred, obj])
# RELATIONSHIP PROPERTY
if subj_data.get('id') and pred_data.get('id') and obj_data.get('id'):
if pred_data['type'] !=... | def function[add_triple, parameter[self, subj, pred, obj]]:
constant[ Adds an entity property to an existing entity ]
<ast.Tuple object at 0x7da1b1b378e0> assign[=] call[name[self].are_ilx, parameter[list[[<ast.Name object at 0x7da1b1b34040>, <ast.Name object at 0x7da1b1b35900>, <ast.Name object at 0x7d... | keyword[def] identifier[add_triple] ( identifier[self] , identifier[subj] , identifier[pred] , identifier[obj] ):
literal[string]
identifier[subj_data] , identifier[pred_data] , identifier[obj_data] = identifier[self] . identifier[are_ilx] ([ identifier[subj] , identifier[pred] , identifier[obj] ])... | def add_triple(self, subj, pred, obj):
""" Adds an entity property to an existing entity """
(subj_data, pred_data, obj_data) = self.are_ilx([subj, pred, obj])
# RELATIONSHIP PROPERTY
if subj_data.get('id') and pred_data.get('id') and obj_data.get('id'):
if pred_data['type'] != 'relationship':
... |
def sigma(self):
"""
This method returns the sigma value of the gb.
If using 'quick_gen' to generate GB, this value is not valid.
"""
return int(round(self.oriented_unit_cell.volume / self.init_cell.volume)) | def function[sigma, parameter[self]]:
constant[
This method returns the sigma value of the gb.
If using 'quick_gen' to generate GB, this value is not valid.
]
return[call[name[int], parameter[call[name[round], parameter[binary_operation[name[self].oriented_unit_cell.volume / name[sel... | keyword[def] identifier[sigma] ( identifier[self] ):
literal[string]
keyword[return] identifier[int] ( identifier[round] ( identifier[self] . identifier[oriented_unit_cell] . identifier[volume] / identifier[self] . identifier[init_cell] . identifier[volume] )) | def sigma(self):
"""
This method returns the sigma value of the gb.
If using 'quick_gen' to generate GB, this value is not valid.
"""
return int(round(self.oriented_unit_cell.volume / self.init_cell.volume)) |
def generate_trivial_layout(*regs):
"""
Creates a trivial ("one-to-one") Layout with the registers in `regs`.
Args:
*regs (Registers): registers to include in the layout.
Returns:
Layout: A layout with all the `regs` in the given order.
"""
layout ... | def function[generate_trivial_layout, parameter[]]:
constant[
Creates a trivial ("one-to-one") Layout with the registers in `regs`.
Args:
*regs (Registers): registers to include in the layout.
Returns:
Layout: A layout with all the `regs` in the given order.
... | keyword[def] identifier[generate_trivial_layout] (* identifier[regs] ):
literal[string]
identifier[layout] = identifier[Layout] ()
keyword[for] identifier[reg] keyword[in] identifier[regs] :
identifier[layout] . identifier[add_register] ( identifier[reg] )
keyword[... | def generate_trivial_layout(*regs):
"""
Creates a trivial ("one-to-one") Layout with the registers in `regs`.
Args:
*regs (Registers): registers to include in the layout.
Returns:
Layout: A layout with all the `regs` in the given order.
"""
layout = Layout... |
def refresh_stack(self):
"""
Recompute the stack after e.g. show_hidden_frames has been modified
"""
self.stack, _ = self.compute_stack(self.fullstack)
# find the current frame in the new stack
for i, (frame, _) in enumerate(self.stack):
if frame is self.curfr... | def function[refresh_stack, parameter[self]]:
constant[
Recompute the stack after e.g. show_hidden_frames has been modified
]
<ast.Tuple object at 0x7da20e749540> assign[=] call[name[self].compute_stack, parameter[name[self].fullstack]]
for taget[tuple[[<ast.Name object at 0x7da2... | keyword[def] identifier[refresh_stack] ( identifier[self] ):
literal[string]
identifier[self] . identifier[stack] , identifier[_] = identifier[self] . identifier[compute_stack] ( identifier[self] . identifier[fullstack] )
keyword[for] identifier[i] ,( identifier[frame] , identifi... | def refresh_stack(self):
"""
Recompute the stack after e.g. show_hidden_frames has been modified
"""
(self.stack, _) = self.compute_stack(self.fullstack)
# find the current frame in the new stack
for (i, (frame, _)) in enumerate(self.stack):
if frame is self.curframe:
... |
def check_dependencies(self):
"Checks if the test program is available in the python environnement"
if self.test_program == 'nose':
try:
import nose
except ImportError:
sys.exit('Nosetests is not available on your system. Please install it and try ... | def function[check_dependencies, parameter[self]]:
constant[Checks if the test program is available in the python environnement]
if compare[name[self].test_program equal[==] constant[nose]] begin[:]
<ast.Try object at 0x7da1b25d1510>
if compare[name[self].test_program equal[==] constant[... | keyword[def] identifier[check_dependencies] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[test_program] == literal[string] :
keyword[try] :
keyword[import] identifier[nose]
keyword[except] identifier[ImportError] :
... | def check_dependencies(self):
"""Checks if the test program is available in the python environnement"""
if self.test_program == 'nose':
try:
import nose # depends on [control=['try'], data=[]]
except ImportError:
sys.exit('Nosetests is not available on your system. Pleas... |
def setParameter(self, name, index, value):
"""
Overrides :meth:`nupic.bindings.regions.PyRegion.PyRegion.setParameter`.
"""
if name == "learningMode":
self.learningMode = bool(int(value))
elif name == "inferenceMode":
self.inferenceMode = bool(int(value))
else:
return PyRegion... | def function[setParameter, parameter[self, name, index, value]]:
constant[
Overrides :meth:`nupic.bindings.regions.PyRegion.PyRegion.setParameter`.
]
if compare[name[name] equal[==] constant[learningMode]] begin[:]
name[self].learningMode assign[=] call[name[bool], parameter[call... | keyword[def] identifier[setParameter] ( identifier[self] , identifier[name] , identifier[index] , identifier[value] ):
literal[string]
keyword[if] identifier[name] == literal[string] :
identifier[self] . identifier[learningMode] = identifier[bool] ( identifier[int] ( identifier[value] ))
keywo... | def setParameter(self, name, index, value):
"""
Overrides :meth:`nupic.bindings.regions.PyRegion.PyRegion.setParameter`.
"""
if name == 'learningMode':
self.learningMode = bool(int(value)) # depends on [control=['if'], data=[]]
elif name == 'inferenceMode':
self.inferenceMode = bool... |
def allow_client_incoming(self, client_name):
"""
Allow the user of this token to accept incoming connections.
:param str client_name: Client name to accept calls from
"""
self.client_name = client_name
self.capabilities['incoming'] = ScopeURI('client', 'incoming', {'cli... | def function[allow_client_incoming, parameter[self, client_name]]:
constant[
Allow the user of this token to accept incoming connections.
:param str client_name: Client name to accept calls from
]
name[self].client_name assign[=] name[client_name]
call[name[self].capabil... | keyword[def] identifier[allow_client_incoming] ( identifier[self] , identifier[client_name] ):
literal[string]
identifier[self] . identifier[client_name] = identifier[client_name]
identifier[self] . identifier[capabilities] [ literal[string] ]= identifier[ScopeURI] ( literal[string] , lit... | def allow_client_incoming(self, client_name):
"""
Allow the user of this token to accept incoming connections.
:param str client_name: Client name to accept calls from
"""
self.client_name = client_name
self.capabilities['incoming'] = ScopeURI('client', 'incoming', {'clientName': cl... |
def _add_tag_manifest_file(zip_file, dir_name, tag_info_list):
"""Generate the tag manifest file and add it to the zip."""
_add_tag_file(
zip_file, dir_name, tag_info_list, _gen_tag_manifest_file_tup(tag_info_list)
) | def function[_add_tag_manifest_file, parameter[zip_file, dir_name, tag_info_list]]:
constant[Generate the tag manifest file and add it to the zip.]
call[name[_add_tag_file], parameter[name[zip_file], name[dir_name], name[tag_info_list], call[name[_gen_tag_manifest_file_tup], parameter[name[tag_info_list... | keyword[def] identifier[_add_tag_manifest_file] ( identifier[zip_file] , identifier[dir_name] , identifier[tag_info_list] ):
literal[string]
identifier[_add_tag_file] (
identifier[zip_file] , identifier[dir_name] , identifier[tag_info_list] , identifier[_gen_tag_manifest_file_tup] ( identifier[tag_inf... | def _add_tag_manifest_file(zip_file, dir_name, tag_info_list):
"""Generate the tag manifest file and add it to the zip."""
_add_tag_file(zip_file, dir_name, tag_info_list, _gen_tag_manifest_file_tup(tag_info_list)) |
def leave_multicast(self, universe: int) -> None:
"""
Try to leave the multicast group with the specified universe. This does not throw any exception if the group
could not be leaved.
:param universe: the universe to leave the multicast group.
The network hardware has to support ... | def function[leave_multicast, parameter[self, universe]]:
constant[
Try to leave the multicast group with the specified universe. This does not throw any exception if the group
could not be leaved.
:param universe: the universe to leave the multicast group.
The network hardware h... | keyword[def] identifier[leave_multicast] ( identifier[self] , identifier[universe] : identifier[int] )-> keyword[None] :
literal[string]
keyword[try] :
identifier[self] . identifier[sock] . identifier[setsockopt] ( identifier[socket] . identifier[SOL_IP] , identifier[socket] . identifi... | def leave_multicast(self, universe: int) -> None:
"""
Try to leave the multicast group with the specified universe. This does not throw any exception if the group
could not be leaved.
:param universe: the universe to leave the multicast group.
The network hardware has to support the ... |
def _begin_stream(self, command: Command):
'''Start data stream transfer.'''
begin_reply = yield from self._commander.begin_stream(command)
self._response.reply = begin_reply
self.event_dispatcher.notify(self.Event.begin_transfer, self._response) | def function[_begin_stream, parameter[self, command]]:
constant[Start data stream transfer.]
variable[begin_reply] assign[=] <ast.YieldFrom object at 0x7da1b2344b20>
name[self]._response.reply assign[=] name[begin_reply]
call[name[self].event_dispatcher.notify, parameter[name[self].Event... | keyword[def] identifier[_begin_stream] ( identifier[self] , identifier[command] : identifier[Command] ):
literal[string]
identifier[begin_reply] = keyword[yield] keyword[from] identifier[self] . identifier[_commander] . identifier[begin_stream] ( identifier[command] )
identifier[self] .... | def _begin_stream(self, command: Command):
"""Start data stream transfer."""
begin_reply = (yield from self._commander.begin_stream(command))
self._response.reply = begin_reply
self.event_dispatcher.notify(self.Event.begin_transfer, self._response) |
def _send_register_payload(self, websocket):
"""Send the register payload."""
file = os.path.join(os.path.dirname(__file__), HANDSHAKE_FILE_NAME)
data = codecs.open(file, 'r', 'utf-8')
raw_handshake = data.read()
handshake = json.loads(raw_handshake)
handshake['payload'... | def function[_send_register_payload, parameter[self, websocket]]:
constant[Send the register payload.]
variable[file] assign[=] call[name[os].path.join, parameter[call[name[os].path.dirname, parameter[name[__file__]]], name[HANDSHAKE_FILE_NAME]]]
variable[data] assign[=] call[name[codecs].open, ... | keyword[def] identifier[_send_register_payload] ( identifier[self] , identifier[websocket] ):
literal[string]
identifier[file] = identifier[os] . identifier[path] . identifier[join] ( identifier[os] . identifier[path] . identifier[dirname] ( identifier[__file__] ), identifier[HANDSHAKE_FILE_NAME] )... | def _send_register_payload(self, websocket):
"""Send the register payload."""
file = os.path.join(os.path.dirname(__file__), HANDSHAKE_FILE_NAME)
data = codecs.open(file, 'r', 'utf-8')
raw_handshake = data.read()
handshake = json.loads(raw_handshake)
handshake['payload']['client-key'] = self.cli... |
def stop(self):
""" Stops the video stream and resets the clock. """
logger.debug("Stopping playback")
# Stop the clock
self.clock.stop()
# Set plauyer status to ready
self.status = READY | def function[stop, parameter[self]]:
constant[ Stops the video stream and resets the clock. ]
call[name[logger].debug, parameter[constant[Stopping playback]]]
call[name[self].clock.stop, parameter[]]
name[self].status assign[=] name[READY] | keyword[def] identifier[stop] ( identifier[self] ):
literal[string]
identifier[logger] . identifier[debug] ( literal[string] )
identifier[self] . identifier[clock] . identifier[stop] ()
identifier[self] . identifier[status] = identifier[READY] | def stop(self):
""" Stops the video stream and resets the clock. """
logger.debug('Stopping playback') # Stop the clock
self.clock.stop() # Set plauyer status to ready
self.status = READY |
def load(fname: str) -> 'ParallelDataSet':
"""
Loads a dataset from a binary .npy file.
"""
data = mx.nd.load(fname)
n = len(data) // 3
source = data[:n]
target = data[n:2 * n]
label = data[2 * n:]
assert len(source) == len(target) == len(label)
... | def function[load, parameter[fname]]:
constant[
Loads a dataset from a binary .npy file.
]
variable[data] assign[=] call[name[mx].nd.load, parameter[name[fname]]]
variable[n] assign[=] binary_operation[call[name[len], parameter[name[data]]] <ast.FloorDiv object at 0x7da2590d6bc0>... | keyword[def] identifier[load] ( identifier[fname] : identifier[str] )-> literal[string] :
literal[string]
identifier[data] = identifier[mx] . identifier[nd] . identifier[load] ( identifier[fname] )
identifier[n] = identifier[len] ( identifier[data] )// literal[int]
identifier[sou... | def load(fname: str) -> 'ParallelDataSet':
"""
Loads a dataset from a binary .npy file.
"""
data = mx.nd.load(fname)
n = len(data) // 3
source = data[:n]
target = data[n:2 * n]
label = data[2 * n:]
assert len(source) == len(target) == len(label)
return ParallelDataSet(sou... |
def do_fileplaceholder(parser, token):
"""
Method that parse the fileplaceholder template tag.
"""
name, params = parse_placeholder(parser, token)
return FilePlaceholderNode(name, **params) | def function[do_fileplaceholder, parameter[parser, token]]:
constant[
Method that parse the fileplaceholder template tag.
]
<ast.Tuple object at 0x7da18f58c910> assign[=] call[name[parse_placeholder], parameter[name[parser], name[token]]]
return[call[name[FilePlaceholderNode], parameter[name... | keyword[def] identifier[do_fileplaceholder] ( identifier[parser] , identifier[token] ):
literal[string]
identifier[name] , identifier[params] = identifier[parse_placeholder] ( identifier[parser] , identifier[token] )
keyword[return] identifier[FilePlaceholderNode] ( identifier[name] ,** identifier[pa... | def do_fileplaceholder(parser, token):
"""
Method that parse the fileplaceholder template tag.
"""
(name, params) = parse_placeholder(parser, token)
return FilePlaceholderNode(name, **params) |
def extract_parameters(Pressure, PressureErr, A, AErr, Gamma0, Gamma0Err, method="chang"):
"""
Calculates the radius, mass and conversion factor and thier uncertainties.
For values to be correct data must have been taken with feedback off and
at pressures of around 1mbar (this is because the equations a... | def function[extract_parameters, parameter[Pressure, PressureErr, A, AErr, Gamma0, Gamma0Err, method]]:
constant[
Calculates the radius, mass and conversion factor and thier uncertainties.
For values to be correct data must have been taken with feedback off and
at pressures of around 1mbar (this is ... | keyword[def] identifier[extract_parameters] ( identifier[Pressure] , identifier[PressureErr] , identifier[A] , identifier[AErr] , identifier[Gamma0] , identifier[Gamma0Err] , identifier[method] = literal[string] ):
literal[string]
identifier[Pressure] = literal[int] * identifier[Pressure]
identifier... | def extract_parameters(Pressure, PressureErr, A, AErr, Gamma0, Gamma0Err, method='chang'):
"""
Calculates the radius, mass and conversion factor and thier uncertainties.
For values to be correct data must have been taken with feedback off and
at pressures of around 1mbar (this is because the equations a... |
def merge_leaderboards(self, destination, keys, aggregate='SUM'):
'''
Merge leaderboards given by keys with this leaderboard into a named destination leaderboard.
@param destination [String] Destination leaderboard name.
@param keys [Array] Leaderboards to be merged with the current lea... | def function[merge_leaderboards, parameter[self, destination, keys, aggregate]]:
constant[
Merge leaderboards given by keys with this leaderboard into a named destination leaderboard.
@param destination [String] Destination leaderboard name.
@param keys [Array] Leaderboards to be merged... | keyword[def] identifier[merge_leaderboards] ( identifier[self] , identifier[destination] , identifier[keys] , identifier[aggregate] = literal[string] ):
literal[string]
identifier[keys] . identifier[insert] ( literal[int] , identifier[self] . identifier[leaderboard_name] )
identifier[self]... | def merge_leaderboards(self, destination, keys, aggregate='SUM'):
"""
Merge leaderboards given by keys with this leaderboard into a named destination leaderboard.
@param destination [String] Destination leaderboard name.
@param keys [Array] Leaderboards to be merged with the current leaderb... |
def read_packet(self, timeout=3.0):
"""read one packet, timeout if one packet is not available in the timeout period"""
try:
return self.queue.get(timeout=timeout)
except Empty:
raise InternalTimeoutError("Timeout waiting for packet in AsyncPacketBuffer") | def function[read_packet, parameter[self, timeout]]:
constant[read one packet, timeout if one packet is not available in the timeout period]
<ast.Try object at 0x7da204621fc0> | keyword[def] identifier[read_packet] ( identifier[self] , identifier[timeout] = literal[int] ):
literal[string]
keyword[try] :
keyword[return] identifier[self] . identifier[queue] . identifier[get] ( identifier[timeout] = identifier[timeout] )
keyword[except] identifier[Emp... | def read_packet(self, timeout=3.0):
"""read one packet, timeout if one packet is not available in the timeout period"""
try:
return self.queue.get(timeout=timeout) # depends on [control=['try'], data=[]]
except Empty:
raise InternalTimeoutError('Timeout waiting for packet in AsyncPacketBuff... |
def parse_reaction_table_file(path, f, default_compartment):
"""Parse a tab-separated file containing reaction IDs and properties
The reaction properties are parsed according to the header which specifies
which property is contained in each column.
"""
context = FilePathContext(path)
for line... | def function[parse_reaction_table_file, parameter[path, f, default_compartment]]:
constant[Parse a tab-separated file containing reaction IDs and properties
The reaction properties are parsed according to the header which specifies
which property is contained in each column.
]
variable[cont... | keyword[def] identifier[parse_reaction_table_file] ( identifier[path] , identifier[f] , identifier[default_compartment] ):
literal[string]
identifier[context] = identifier[FilePathContext] ( identifier[path] )
keyword[for] identifier[lineno] , identifier[row] keyword[in] identifier[enumerate] ( i... | def parse_reaction_table_file(path, f, default_compartment):
"""Parse a tab-separated file containing reaction IDs and properties
The reaction properties are parsed according to the header which specifies
which property is contained in each column.
"""
context = FilePathContext(path)
for (linen... |
def ipv4_reassembly(packet, *, count=NotImplemented):
"""Make data for IPv4 reassembly."""
ipv4 = getattr(packet, 'ip', None)
if ipv4 is not None:
if ipv4.df: # dismiss not fragmented packet
return False, None
data = dict(
bufid=(
ipaddress.ip_addr... | def function[ipv4_reassembly, parameter[packet]]:
constant[Make data for IPv4 reassembly.]
variable[ipv4] assign[=] call[name[getattr], parameter[name[packet], constant[ip], constant[None]]]
if compare[name[ipv4] is_not constant[None]] begin[:]
if name[ipv4].df begin[:]
... | keyword[def] identifier[ipv4_reassembly] ( identifier[packet] ,*, identifier[count] = identifier[NotImplemented] ):
literal[string]
identifier[ipv4] = identifier[getattr] ( identifier[packet] , literal[string] , keyword[None] )
keyword[if] identifier[ipv4] keyword[is] keyword[not] keyword[None] :
... | def ipv4_reassembly(packet, *, count=NotImplemented):
"""Make data for IPv4 reassembly."""
ipv4 = getattr(packet, 'ip', None)
if ipv4 is not None:
if ipv4.df: # dismiss not fragmented packet
return (False, None) # depends on [control=['if'], data=[]] # source IP address
# dest... |
def read_coils(slave_id, starting_address, quantity):
""" Return ADU for Modbus function code 01: Read Coils.
:param slave_id: Number of slave.
:return: Byte array with ADU.
"""
function = ReadCoils()
function.starting_address = starting_address
function.quantity = quantity
return _cre... | def function[read_coils, parameter[slave_id, starting_address, quantity]]:
constant[ Return ADU for Modbus function code 01: Read Coils.
:param slave_id: Number of slave.
:return: Byte array with ADU.
]
variable[function] assign[=] call[name[ReadCoils], parameter[]]
name[function].s... | keyword[def] identifier[read_coils] ( identifier[slave_id] , identifier[starting_address] , identifier[quantity] ):
literal[string]
identifier[function] = identifier[ReadCoils] ()
identifier[function] . identifier[starting_address] = identifier[starting_address]
identifier[function] . identifier... | def read_coils(slave_id, starting_address, quantity):
""" Return ADU for Modbus function code 01: Read Coils.
:param slave_id: Number of slave.
:return: Byte array with ADU.
"""
function = ReadCoils()
function.starting_address = starting_address
function.quantity = quantity
return _crea... |
def has_content_in(page, language):
"""Fitler that return ``True`` if the page has any content in a
particular language.
:param page: the current page
:param language: the language you want to look at
"""
if page is None:
return False
return Content.objects.filter(page=page, languag... | def function[has_content_in, parameter[page, language]]:
constant[Fitler that return ``True`` if the page has any content in a
particular language.
:param page: the current page
:param language: the language you want to look at
]
if compare[name[page] is constant[None]] begin[:]
... | keyword[def] identifier[has_content_in] ( identifier[page] , identifier[language] ):
literal[string]
keyword[if] identifier[page] keyword[is] keyword[None] :
keyword[return] keyword[False]
keyword[return] identifier[Content] . identifier[objects] . identifier[filter] ( identifier[page] ... | def has_content_in(page, language):
"""Fitler that return ``True`` if the page has any content in a
particular language.
:param page: the current page
:param language: the language you want to look at
"""
if page is None:
return False # depends on [control=['if'], data=[]]
return C... |
def _saturation(color, **kwargs):
""" Get saturation value of HSL color.
"""
s = colorsys.rgb_to_hls(*[x / 255.0 for x in color.value[:3]])[2]
return NumberValue((s * 100, '%')) | def function[_saturation, parameter[color]]:
constant[ Get saturation value of HSL color.
]
variable[s] assign[=] call[call[name[colorsys].rgb_to_hls, parameter[<ast.Starred object at 0x7da1b27ed6c0>]]][constant[2]]
return[call[name[NumberValue], parameter[tuple[[<ast.BinOp object at 0x7da1b27ed... | keyword[def] identifier[_saturation] ( identifier[color] ,** identifier[kwargs] ):
literal[string]
identifier[s] = identifier[colorsys] . identifier[rgb_to_hls] (*[ identifier[x] / literal[int] keyword[for] identifier[x] keyword[in] identifier[color] . identifier[value] [: literal[int] ]])[ literal[int... | def _saturation(color, **kwargs):
""" Get saturation value of HSL color.
"""
s = colorsys.rgb_to_hls(*[x / 255.0 for x in color.value[:3]])[2]
return NumberValue((s * 100, '%')) |
def template_exception_handler(fn, error_context, filename=None):
"""Calls the given function, attempting to catch any template-related errors, and
converts the error to a Statik TemplateError instance. Returns the result returned
by the function itself."""
error_message = None
if filename:
... | def function[template_exception_handler, parameter[fn, error_context, filename]]:
constant[Calls the given function, attempting to catch any template-related errors, and
converts the error to a Statik TemplateError instance. Returns the result returned
by the function itself.]
variable[error_mes... | keyword[def] identifier[template_exception_handler] ( identifier[fn] , identifier[error_context] , identifier[filename] = keyword[None] ):
literal[string]
identifier[error_message] = keyword[None]
keyword[if] identifier[filename] :
identifier[error_context] . identifier[update] ( identifier... | def template_exception_handler(fn, error_context, filename=None):
"""Calls the given function, attempting to catch any template-related errors, and
converts the error to a Statik TemplateError instance. Returns the result returned
by the function itself."""
error_message = None
if filename:
... |
def find_n50(self):
"""
Calculate the N50 for each strain. N50 is defined as the largest contig such that at least half of the total
genome size is contained in contigs equal to or larger than this contig
"""
for sample in self.metadata:
# Initialise the N50 attribute... | def function[find_n50, parameter[self]]:
constant[
Calculate the N50 for each strain. N50 is defined as the largest contig such that at least half of the total
genome size is contained in contigs equal to or larger than this contig
]
for taget[name[sample]] in starred[name[self].... | keyword[def] identifier[find_n50] ( identifier[self] ):
literal[string]
keyword[for] identifier[sample] keyword[in] identifier[self] . identifier[metadata] :
identifier[sample] [ identifier[self] . identifier[analysistype] ]. identifier[n50] = literal[string]
... | def find_n50(self):
"""
Calculate the N50 for each strain. N50 is defined as the largest contig such that at least half of the total
genome size is contained in contigs equal to or larger than this contig
"""
for sample in self.metadata:
# Initialise the N50 attribute in case the... |
def prepend_rez_path(self):
"""Prepend rez path to $PATH."""
if system.rez_bin_path:
self.env.PATH.prepend(system.rez_bin_path) | def function[prepend_rez_path, parameter[self]]:
constant[Prepend rez path to $PATH.]
if name[system].rez_bin_path begin[:]
call[name[self].env.PATH.prepend, parameter[name[system].rez_bin_path]] | keyword[def] identifier[prepend_rez_path] ( identifier[self] ):
literal[string]
keyword[if] identifier[system] . identifier[rez_bin_path] :
identifier[self] . identifier[env] . identifier[PATH] . identifier[prepend] ( identifier[system] . identifier[rez_bin_path] ) | def prepend_rez_path(self):
"""Prepend rez path to $PATH."""
if system.rez_bin_path:
self.env.PATH.prepend(system.rez_bin_path) # depends on [control=['if'], data=[]] |
def update(self, iterable):
"""
Update bag with all elements in iterable.
>>> s = pbag([1])
>>> s.update([1, 2])
pbag([1, 1, 2])
"""
if iterable:
return PBag(reduce(_add_to_counters, iterable, self._counts))
return self | def function[update, parameter[self, iterable]]:
constant[
Update bag with all elements in iterable.
>>> s = pbag([1])
>>> s.update([1, 2])
pbag([1, 1, 2])
]
if name[iterable] begin[:]
return[call[name[PBag], parameter[call[name[reduce], parameter[name[_a... | keyword[def] identifier[update] ( identifier[self] , identifier[iterable] ):
literal[string]
keyword[if] identifier[iterable] :
keyword[return] identifier[PBag] ( identifier[reduce] ( identifier[_add_to_counters] , identifier[iterable] , identifier[self] . identifier[_counts] ))
... | def update(self, iterable):
"""
Update bag with all elements in iterable.
>>> s = pbag([1])
>>> s.update([1, 2])
pbag([1, 1, 2])
"""
if iterable:
return PBag(reduce(_add_to_counters, iterable, self._counts)) # depends on [control=['if'], data=[]]
return self |
def rsa_pkcs1v15_sign(private_key, data, hash_algorithm):
"""
Generates an RSASSA-PKCS-v1.5 signature.
When the hash_algorithm is "raw", the operation is identical to RSA
private key encryption. That is: the data is not hashed and no ASN.1
structure with an algorithm identifier of the hash algorith... | def function[rsa_pkcs1v15_sign, parameter[private_key, data, hash_algorithm]]:
constant[
Generates an RSASSA-PKCS-v1.5 signature.
When the hash_algorithm is "raw", the operation is identical to RSA
private key encryption. That is: the data is not hashed and no ASN.1
structure with an algorithm ... | keyword[def] identifier[rsa_pkcs1v15_sign] ( identifier[private_key] , identifier[data] , identifier[hash_algorithm] ):
literal[string]
keyword[if] identifier[private_key] . identifier[algorithm] != literal[string] :
keyword[raise] identifier[ValueError] ( literal[string] )
keyword[return... | def rsa_pkcs1v15_sign(private_key, data, hash_algorithm):
"""
Generates an RSASSA-PKCS-v1.5 signature.
When the hash_algorithm is "raw", the operation is identical to RSA
private key encryption. That is: the data is not hashed and no ASN.1
structure with an algorithm identifier of the hash algorith... |
def calculate_bottom_margin(self):
"""
Calculate the margin in pixels below the plot area, setting
border_bottom.
"""
bb = 7
if self.key and self.key_position == 'bottom':
bb += len(self.data) * (self.font_size + 5)
bb += 10
if self.show_x_labels:
max_x_label_height_px = self.x_label_font_size
... | def function[calculate_bottom_margin, parameter[self]]:
constant[
Calculate the margin in pixels below the plot area, setting
border_bottom.
]
variable[bb] assign[=] constant[7]
if <ast.BoolOp object at 0x7da1b032b4f0> begin[:]
<ast.AugAssign object at 0x7da1b032b6a0>
<ast.... | keyword[def] identifier[calculate_bottom_margin] ( identifier[self] ):
literal[string]
identifier[bb] = literal[int]
keyword[if] identifier[self] . identifier[key] keyword[and] identifier[self] . identifier[key_position] == literal[string] :
identifier[bb] += identifier[len] ( identifier[self] . ide... | def calculate_bottom_margin(self):
"""
Calculate the margin in pixels below the plot area, setting
border_bottom.
"""
bb = 7
if self.key and self.key_position == 'bottom':
bb += len(self.data) * (self.font_size + 5)
bb += 10 # depends on [control=['if'], data=[]]
if self.show_x_la... |
def properties(self): # type: () -> list
"""
Returns:
(list[str]) List of public properties
"""
_type = type(self)
return [_property for _property in dir(_type) if self._is_property(_property)] | def function[properties, parameter[self]]:
constant[
Returns:
(list[str]) List of public properties
]
variable[_type] assign[=] call[name[type], parameter[name[self]]]
return[<ast.ListComp object at 0x7da1b16475b0>] | keyword[def] identifier[properties] ( identifier[self] ):
literal[string]
identifier[_type] = identifier[type] ( identifier[self] )
keyword[return] [ identifier[_property] keyword[for] identifier[_property] keyword[in] identifier[dir] ( identifier[_type] ) keyword[if] identifier[self... | def properties(self): # type: () -> list
'\n Returns:\n (list[str]) List of public properties\n '
_type = type(self)
return [_property for _property in dir(_type) if self._is_property(_property)] |
def delete_items(self, url, container, container_object=None):
"""Deletes an objects in a container.
:param url:
:param container:
"""
headers, container_uri = self._return_base_data(
url=url,
container=container,
container_object=container_o... | def function[delete_items, parameter[self, url, container, container_object]]:
constant[Deletes an objects in a container.
:param url:
:param container:
]
<ast.Tuple object at 0x7da1b27247c0> assign[=] call[name[self]._return_base_data, parameter[]]
return[call[name[self]._d... | keyword[def] identifier[delete_items] ( identifier[self] , identifier[url] , identifier[container] , identifier[container_object] = keyword[None] ):
literal[string]
identifier[headers] , identifier[container_uri] = identifier[self] . identifier[_return_base_data] (
identifier[url] = ident... | def delete_items(self, url, container, container_object=None):
"""Deletes an objects in a container.
:param url:
:param container:
"""
(headers, container_uri) = self._return_base_data(url=url, container=container, container_object=container_object)
return self._deleter(uri=containe... |
def flow(self)->FlowField:
"Access the flow-field grid after applying queued affine transforms."
if self._flow is None:
self._flow = _affine_grid(self.shape)
if self._affine_mat is not None:
self._flow = _affine_mult(self._flow,self._affine_mat)
self._affine_m... | def function[flow, parameter[self]]:
constant[Access the flow-field grid after applying queued affine transforms.]
if compare[name[self]._flow is constant[None]] begin[:]
name[self]._flow assign[=] call[name[_affine_grid], parameter[name[self].shape]]
if compare[name[self]._affin... | keyword[def] identifier[flow] ( identifier[self] )-> identifier[FlowField] :
literal[string]
keyword[if] identifier[self] . identifier[_flow] keyword[is] keyword[None] :
identifier[self] . identifier[_flow] = identifier[_affine_grid] ( identifier[self] . identifier[shape] )
... | def flow(self) -> FlowField:
"""Access the flow-field grid after applying queued affine transforms."""
if self._flow is None:
self._flow = _affine_grid(self.shape) # depends on [control=['if'], data=[]]
if self._affine_mat is not None:
self._flow = _affine_mult(self._flow, self._affine_mat)... |
def datasets(dataset, node, ll=None, ur=None, start_date=None, end_date=None, api_key=None):
"""
This method is used to find datasets available for searching.
By passing no parameters except node, all available datasets
are returned. Additional parameters such as temporal range
and spatial bounding ... | def function[datasets, parameter[dataset, node, ll, ur, start_date, end_date, api_key]]:
constant[
This method is used to find datasets available for searching.
By passing no parameters except node, all available datasets
are returned. Additional parameters such as temporal range
and spatial bou... | keyword[def] identifier[datasets] ( identifier[dataset] , identifier[node] , identifier[ll] = keyword[None] , identifier[ur] = keyword[None] , identifier[start_date] = keyword[None] , identifier[end_date] = keyword[None] , identifier[api_key] = keyword[None] ):
literal[string]
identifier[payload] ={
... | def datasets(dataset, node, ll=None, ur=None, start_date=None, end_date=None, api_key=None):
"""
This method is used to find datasets available for searching.
By passing no parameters except node, all available datasets
are returned. Additional parameters such as temporal range
and spatial bounding ... |
def convert_instancenorm(node, **kwargs):
"""Map MXNet's InstanceNorm operator attributes to onnx's InstanceNormalization operator
based on the input node's attributes and return the created node.
"""
name, input_nodes, attrs = get_inputs(node, kwargs)
eps = float(attrs.get("eps", 0.001))
node... | def function[convert_instancenorm, parameter[node]]:
constant[Map MXNet's InstanceNorm operator attributes to onnx's InstanceNormalization operator
based on the input node's attributes and return the created node.
]
<ast.Tuple object at 0x7da1b204d0c0> assign[=] call[name[get_inputs], parameter[... | keyword[def] identifier[convert_instancenorm] ( identifier[node] ,** identifier[kwargs] ):
literal[string]
identifier[name] , identifier[input_nodes] , identifier[attrs] = identifier[get_inputs] ( identifier[node] , identifier[kwargs] )
identifier[eps] = identifier[float] ( identifier[attrs] . identi... | def convert_instancenorm(node, **kwargs):
"""Map MXNet's InstanceNorm operator attributes to onnx's InstanceNormalization operator
based on the input node's attributes and return the created node.
"""
(name, input_nodes, attrs) = get_inputs(node, kwargs)
eps = float(attrs.get('eps', 0.001))
node... |
def iteritems(self, pipe=None):
"""Return an iterator over the dictionary's ``(key, value)`` pairs."""
pipe = self.redis if pipe is None else pipe
for k, v in self._data(pipe).items():
yield k, self.cache.get(k, v) | def function[iteritems, parameter[self, pipe]]:
constant[Return an iterator over the dictionary's ``(key, value)`` pairs.]
variable[pipe] assign[=] <ast.IfExp object at 0x7da20c6c5a50>
for taget[tuple[[<ast.Name object at 0x7da20c6c6050>, <ast.Name object at 0x7da20c6c7160>]]] in starred[call[ca... | keyword[def] identifier[iteritems] ( identifier[self] , identifier[pipe] = keyword[None] ):
literal[string]
identifier[pipe] = identifier[self] . identifier[redis] keyword[if] identifier[pipe] keyword[is] keyword[None] keyword[else] identifier[pipe]
keyword[for] identifier[k] , ide... | def iteritems(self, pipe=None):
"""Return an iterator over the dictionary's ``(key, value)`` pairs."""
pipe = self.redis if pipe is None else pipe
for (k, v) in self._data(pipe).items():
yield (k, self.cache.get(k, v)) # depends on [control=['for'], data=[]] |
def as_pandas(self, with_metadata=False):
"""Return this as a pd.DataFrame
Parameters
----------
with_metadata : bool, default False or dict
if True, join data with all meta columns; if a dict, discover
meaningful meta columns from values (in key-value)
"""... | def function[as_pandas, parameter[self, with_metadata]]:
constant[Return this as a pd.DataFrame
Parameters
----------
with_metadata : bool, default False or dict
if True, join data with all meta columns; if a dict, discover
meaningful meta columns from values (in k... | keyword[def] identifier[as_pandas] ( identifier[self] , identifier[with_metadata] = keyword[False] ):
literal[string]
keyword[if] identifier[with_metadata] :
identifier[cols] = identifier[self] . identifier[_discover_meta_cols] (** identifier[with_metadata] ) keyword[if] identifier[i... | def as_pandas(self, with_metadata=False):
"""Return this as a pd.DataFrame
Parameters
----------
with_metadata : bool, default False or dict
if True, join data with all meta columns; if a dict, discover
meaningful meta columns from values (in key-value)
"""
... |
def constant(self, val, ty):
"""
Creates a constant as a VexValue
:param val: The value, as an integer
:param ty: The type of the resulting VexValue
:return: a VexValue
"""
if isinstance(val, VexValue) and not isinstance(val, IRExpr):
raise Exception(... | def function[constant, parameter[self, val, ty]]:
constant[
Creates a constant as a VexValue
:param val: The value, as an integer
:param ty: The type of the resulting VexValue
:return: a VexValue
]
if <ast.BoolOp object at 0x7da1b155f7c0> begin[:]
<ast.Ra... | keyword[def] identifier[constant] ( identifier[self] , identifier[val] , identifier[ty] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[val] , identifier[VexValue] ) keyword[and] keyword[not] identifier[isinstance] ( identifier[val] , identifier[IRExpr] ):
keyword... | def constant(self, val, ty):
"""
Creates a constant as a VexValue
:param val: The value, as an integer
:param ty: The type of the resulting VexValue
:return: a VexValue
"""
if isinstance(val, VexValue) and (not isinstance(val, IRExpr)):
raise Exception('Constant ... |
def merge_from_master(git_action, doc_id, auth_info, parent_sha, doctype_display_name="document"):
"""merge from master into the WIP for this document/author
this is needed to allow a worker's future saves to
be merged seamlessly into master
"""
gh_user = get_user_author(auth_info)[0]
acquire_lo... | def function[merge_from_master, parameter[git_action, doc_id, auth_info, parent_sha, doctype_display_name]]:
constant[merge from master into the WIP for this document/author
this is needed to allow a worker's future saves to
be merged seamlessly into master
]
variable[gh_user] assign[=] call... | keyword[def] identifier[merge_from_master] ( identifier[git_action] , identifier[doc_id] , identifier[auth_info] , identifier[parent_sha] , identifier[doctype_display_name] = literal[string] ):
literal[string]
identifier[gh_user] = identifier[get_user_author] ( identifier[auth_info] )[ literal[int] ]
... | def merge_from_master(git_action, doc_id, auth_info, parent_sha, doctype_display_name='document'):
"""merge from master into the WIP for this document/author
this is needed to allow a worker's future saves to
be merged seamlessly into master
"""
gh_user = get_user_author(auth_info)[0]
acquire_lo... |
def _read_pyMatch(fn, precursors):
"""
read pyMatch file and perform realignment of hits
"""
with open(fn) as handle:
reads = defaultdict(realign)
for line in handle:
query_name, seq, chrom, reference_start, end, mism, add = line.split()
reference_start = int(refe... | def function[_read_pyMatch, parameter[fn, precursors]]:
constant[
read pyMatch file and perform realignment of hits
]
with call[name[open], parameter[name[fn]]] begin[:]
variable[reads] assign[=] call[name[defaultdict], parameter[name[realign]]]
for taget[name[lin... | keyword[def] identifier[_read_pyMatch] ( identifier[fn] , identifier[precursors] ):
literal[string]
keyword[with] identifier[open] ( identifier[fn] ) keyword[as] identifier[handle] :
identifier[reads] = identifier[defaultdict] ( identifier[realign] )
keyword[for] identifier[line] keyw... | def _read_pyMatch(fn, precursors):
"""
read pyMatch file and perform realignment of hits
"""
with open(fn) as handle:
reads = defaultdict(realign)
for line in handle:
(query_name, seq, chrom, reference_start, end, mism, add) = line.split()
reference_start = int(re... |
def set_close_callback(self, callback: Optional[Callable[[], None]]) -> None:
"""Call the given callback when the stream is closed.
This mostly is not necessary for applications that use the
`.Future` interface; all outstanding ``Futures`` will resolve
with a `StreamClosedError` when th... | def function[set_close_callback, parameter[self, callback]]:
constant[Call the given callback when the stream is closed.
This mostly is not necessary for applications that use the
`.Future` interface; all outstanding ``Futures`` will resolve
with a `StreamClosedError` when the stream is... | keyword[def] identifier[set_close_callback] ( identifier[self] , identifier[callback] : identifier[Optional] [ identifier[Callable] [[], keyword[None] ]])-> keyword[None] :
literal[string]
identifier[self] . identifier[_close_callback] = identifier[callback]
identifier[self] . identifier[... | def set_close_callback(self, callback: Optional[Callable[[], None]]) -> None:
"""Call the given callback when the stream is closed.
This mostly is not necessary for applications that use the
`.Future` interface; all outstanding ``Futures`` will resolve
with a `StreamClosedError` when the st... |
def modify_permissions(self, permissions):
"""Modify the user's permissions."""
group = Group.objects.get(name='Admin')
if permissions == 'admin':
self.groups.add(group)
else:
self.groups.remove(group) | def function[modify_permissions, parameter[self, permissions]]:
constant[Modify the user's permissions.]
variable[group] assign[=] call[name[Group].objects.get, parameter[]]
if compare[name[permissions] equal[==] constant[admin]] begin[:]
call[name[self].groups.add, parameter[nam... | keyword[def] identifier[modify_permissions] ( identifier[self] , identifier[permissions] ):
literal[string]
identifier[group] = identifier[Group] . identifier[objects] . identifier[get] ( identifier[name] = literal[string] )
keyword[if] identifier[permissions] == literal[string] :
... | def modify_permissions(self, permissions):
"""Modify the user's permissions."""
group = Group.objects.get(name='Admin')
if permissions == 'admin':
self.groups.add(group) # depends on [control=['if'], data=[]]
else:
self.groups.remove(group) |
def _lats(self):
"""
Return a vector containing the latitudes (in degrees) of each row
of the gridded data.
"""
lats = 90. - _np.arccos(self.zeros) * 180. / _np.pi
return lats | def function[_lats, parameter[self]]:
constant[
Return a vector containing the latitudes (in degrees) of each row
of the gridded data.
]
variable[lats] assign[=] binary_operation[constant[90.0] - binary_operation[binary_operation[call[name[_np].arccos, parameter[name[self].zeros]... | keyword[def] identifier[_lats] ( identifier[self] ):
literal[string]
identifier[lats] = literal[int] - identifier[_np] . identifier[arccos] ( identifier[self] . identifier[zeros] )* literal[int] / identifier[_np] . identifier[pi]
keyword[return] identifier[lats] | def _lats(self):
"""
Return a vector containing the latitudes (in degrees) of each row
of the gridded data.
"""
lats = 90.0 - _np.arccos(self.zeros) * 180.0 / _np.pi
return lats |
def in_(self, value):
"""
Sets the operator type to Query.Op.IsIn and sets the value
to the inputted value.
:param value <variant>
:return <Query>
:usage |>>> from orb import Query as Q
|>>> query = Q('tes... | def function[in_, parameter[self, value]]:
constant[
Sets the operator type to Query.Op.IsIn and sets the value
to the inputted value.
:param value <variant>
:return <Query>
:usage |>>> from orb import Query as Q
... | keyword[def] identifier[in_] ( identifier[self] , identifier[value] ):
literal[string]
identifier[newq] = identifier[self] . identifier[copy] ()
identifier[newq] . identifier[setOp] ( identifier[Query] . identifier[Op] . identifier[IsIn] )
keyword[if] identifier[isinstance] ( id... | def in_(self, value):
"""
Sets the operator type to Query.Op.IsIn and sets the value
to the inputted value.
:param value <variant>
:return <Query>
:usage |>>> from orb import Query as Q
|>>> query = Q('test').... |
def initChild(cls, obj, name, subContext, parent = None):
"""Implementation of initChild."""
addr = statsId(obj)
if addr not in cls.containerMap:
if not parent:
# Find out the parent of the calling object by going back through the call stack until a self != this.
f = inspect.currentfra... | def function[initChild, parameter[cls, obj, name, subContext, parent]]:
constant[Implementation of initChild.]
variable[addr] assign[=] call[name[statsId], parameter[name[obj]]]
if compare[name[addr] <ast.NotIn object at 0x7da2590d7190> name[cls].containerMap] begin[:]
if <ast.Un... | keyword[def] identifier[initChild] ( identifier[cls] , identifier[obj] , identifier[name] , identifier[subContext] , identifier[parent] = keyword[None] ):
literal[string]
identifier[addr] = identifier[statsId] ( identifier[obj] )
keyword[if] identifier[addr] keyword[not] keyword[in] identifier[cls... | def initChild(cls, obj, name, subContext, parent=None):
"""Implementation of initChild."""
addr = statsId(obj)
if addr not in cls.containerMap:
if not parent:
# Find out the parent of the calling object by going back through the call stack until a self != this.
f = inspect.cu... |
def compare_clades(pw):
"""
print min. pident within each clade and then matrix of between-clade max.
"""
names = sorted(set([i for i in pw]))
for i in range(0, 4):
wi, bt = {}, {}
for a in names:
for b in pw[a]:
if ';' not in a or ';' not in b:
... | def function[compare_clades, parameter[pw]]:
constant[
print min. pident within each clade and then matrix of between-clade max.
]
variable[names] assign[=] call[name[sorted], parameter[call[name[set], parameter[<ast.ListComp object at 0x7da1b2440a90>]]]]
for taget[name[i]] in starred[ca... | keyword[def] identifier[compare_clades] ( identifier[pw] ):
literal[string]
identifier[names] = identifier[sorted] ( identifier[set] ([ identifier[i] keyword[for] identifier[i] keyword[in] identifier[pw] ]))
keyword[for] identifier[i] keyword[in] identifier[range] ( literal[int] , literal[int] ... | def compare_clades(pw):
"""
print min. pident within each clade and then matrix of between-clade max.
"""
names = sorted(set([i for i in pw]))
for i in range(0, 4):
(wi, bt) = ({}, {})
for a in names:
for b in pw[a]:
if ';' not in a or ';' not in b:
... |
def put_metric_data(self, namespace, name, value=None, timestamp=None,
unit=None, dimensions=None, statistics=None):
"""
Publishes metric data points to Amazon CloudWatch. Amazon Cloudwatch
associates the data points with the specified metric. If the specified
... | def function[put_metric_data, parameter[self, namespace, name, value, timestamp, unit, dimensions, statistics]]:
constant[
Publishes metric data points to Amazon CloudWatch. Amazon Cloudwatch
associates the data points with the specified metric. If the specified
metric does not exist, ... | keyword[def] identifier[put_metric_data] ( identifier[self] , identifier[namespace] , identifier[name] , identifier[value] = keyword[None] , identifier[timestamp] = keyword[None] ,
identifier[unit] = keyword[None] , identifier[dimensions] = keyword[None] , identifier[statistics] = keyword[None] ):
literal[s... | def put_metric_data(self, namespace, name, value=None, timestamp=None, unit=None, dimensions=None, statistics=None):
"""
Publishes metric data points to Amazon CloudWatch. Amazon Cloudwatch
associates the data points with the specified metric. If the specified
metric does not exist, Amazon... |
def from_array(cls, arr, index=None, name=None, dtype=None, copy=False,
fastpath=False):
"""
Construct Series from array.
.. deprecated :: 0.23.0
Use pd.Series(..) constructor instead.
"""
warnings.warn("'from_array' is deprecated and will be remov... | def function[from_array, parameter[cls, arr, index, name, dtype, copy, fastpath]]:
constant[
Construct Series from array.
.. deprecated :: 0.23.0
Use pd.Series(..) constructor instead.
]
call[name[warnings].warn, parameter[constant['from_array' is deprecated and will... | keyword[def] identifier[from_array] ( identifier[cls] , identifier[arr] , identifier[index] = keyword[None] , identifier[name] = keyword[None] , identifier[dtype] = keyword[None] , identifier[copy] = keyword[False] ,
identifier[fastpath] = keyword[False] ):
literal[string]
identifier[warnings] . i... | def from_array(cls, arr, index=None, name=None, dtype=None, copy=False, fastpath=False):
"""
Construct Series from array.
.. deprecated :: 0.23.0
Use pd.Series(..) constructor instead.
"""
warnings.warn("'from_array' is deprecated and will be removed in a future version. Ple... |
def copy_file(filename):
"""Copy the file and put the correct tag"""
print("Updating file %s" % filename)
out_dir = os.path.abspath(DIRECTORY)
tags = filename[:-4].split("-")
tags[-2] = tags[-2].replace("m", "")
new_name = "-".join(tags) + ".whl"
wheel_flag = "-".join(tags[2:])
with... | def function[copy_file, parameter[filename]]:
constant[Copy the file and put the correct tag]
call[name[print], parameter[binary_operation[constant[Updating file %s] <ast.Mod object at 0x7da2590d6920> name[filename]]]]
variable[out_dir] assign[=] call[name[os].path.abspath, parameter[name[DIRECT... | keyword[def] identifier[copy_file] ( identifier[filename] ):
literal[string]
identifier[print] ( literal[string] % identifier[filename] )
identifier[out_dir] = identifier[os] . identifier[path] . identifier[abspath] ( identifier[DIRECTORY] )
identifier[tags] = identifier[filename] [:- literal[i... | def copy_file(filename):
"""Copy the file and put the correct tag"""
print('Updating file %s' % filename)
out_dir = os.path.abspath(DIRECTORY)
tags = filename[:-4].split('-')
tags[-2] = tags[-2].replace('m', '')
new_name = '-'.join(tags) + '.whl'
wheel_flag = '-'.join(tags[2:])
with InWh... |
def launchDashboardOverlay(self, pchAppKey):
"""
Launches the dashboard overlay application if it is not already running. This call is only valid for
dashboard overlay applications.
"""
fn = self.function_table.launchDashboardOverlay
result = fn(pchAppKey)
retur... | def function[launchDashboardOverlay, parameter[self, pchAppKey]]:
constant[
Launches the dashboard overlay application if it is not already running. This call is only valid for
dashboard overlay applications.
]
variable[fn] assign[=] name[self].function_table.launchDashboardOver... | keyword[def] identifier[launchDashboardOverlay] ( identifier[self] , identifier[pchAppKey] ):
literal[string]
identifier[fn] = identifier[self] . identifier[function_table] . identifier[launchDashboardOverlay]
identifier[result] = identifier[fn] ( identifier[pchAppKey] )
keyword... | def launchDashboardOverlay(self, pchAppKey):
"""
Launches the dashboard overlay application if it is not already running. This call is only valid for
dashboard overlay applications.
"""
fn = self.function_table.launchDashboardOverlay
result = fn(pchAppKey)
return result |
def clear_matplotlib_ticks(ax=None, axis="both"):
"""
Clears the default matplotlib axes, or the one specified by the axis
argument.
Parameters
----------
ax: Matplotlib AxesSubplot, None
The subplot to draw on.
axis: string, "both"
The axis to clear: "x" or "horizontal", "y... | def function[clear_matplotlib_ticks, parameter[ax, axis]]:
constant[
Clears the default matplotlib axes, or the one specified by the axis
argument.
Parameters
----------
ax: Matplotlib AxesSubplot, None
The subplot to draw on.
axis: string, "both"
The axis to clear: "x" ... | keyword[def] identifier[clear_matplotlib_ticks] ( identifier[ax] = keyword[None] , identifier[axis] = literal[string] ):
literal[string]
keyword[if] keyword[not] identifier[ax] :
keyword[return]
keyword[if] identifier[axis] . identifier[lower] () keyword[in] [ literal[string] , literal[st... | def clear_matplotlib_ticks(ax=None, axis='both'):
"""
Clears the default matplotlib axes, or the one specified by the axis
argument.
Parameters
----------
ax: Matplotlib AxesSubplot, None
The subplot to draw on.
axis: string, "both"
The axis to clear: "x" or "horizontal", "y... |
def apply_transformer_types(network):
"""Calculate transformer electrical parameters x, r, b, g from
standard types.
"""
trafos_with_types_b = network.transformers.type != ""
if trafos_with_types_b.zsum() == 0:
return
missing_types = (pd.Index(network.transformers.loc[trafos_with_type... | def function[apply_transformer_types, parameter[network]]:
constant[Calculate transformer electrical parameters x, r, b, g from
standard types.
]
variable[trafos_with_types_b] assign[=] compare[name[network].transformers.type not_equal[!=] constant[]]
if compare[call[name[trafos_with_ty... | keyword[def] identifier[apply_transformer_types] ( identifier[network] ):
literal[string]
identifier[trafos_with_types_b] = identifier[network] . identifier[transformers] . identifier[type] != literal[string]
keyword[if] identifier[trafos_with_types_b] . identifier[zsum] ()== literal[int] :
... | def apply_transformer_types(network):
"""Calculate transformer electrical parameters x, r, b, g from
standard types.
"""
trafos_with_types_b = network.transformers.type != ''
if trafos_with_types_b.zsum() == 0:
return # depends on [control=['if'], data=[]]
missing_types = pd.Index(netw... |
def document(self, document_tree, backend=None):
"""Create a :class:`DocumentTemplate` object based on the given
document tree and this template configuration
Args:
document_tree (DocumentTree): tree of the document's contents
backend: the backend to use when rendering t... | def function[document, parameter[self, document_tree, backend]]:
constant[Create a :class:`DocumentTemplate` object based on the given
document tree and this template configuration
Args:
document_tree (DocumentTree): tree of the document's contents
backend: the backend t... | keyword[def] identifier[document] ( identifier[self] , identifier[document_tree] , identifier[backend] = keyword[None] ):
literal[string]
keyword[return] identifier[self] . identifier[template] ( identifier[document_tree] , identifier[configuration] = identifier[self] ,
identifier[backend... | def document(self, document_tree, backend=None):
"""Create a :class:`DocumentTemplate` object based on the given
document tree and this template configuration
Args:
document_tree (DocumentTree): tree of the document's contents
backend: the backend to use when rendering the d... |
def str2bool(string_, default='raise'):
"""
Convert a string to a bool.
Parameters
----------
string_ : str
default : {'raise', False}
Default behaviour if none of the "true" strings is detected.
Returns
-------
boolean : bool
Examples
--------
>>> str2bool('Tr... | def function[str2bool, parameter[string_, default]]:
constant[
Convert a string to a bool.
Parameters
----------
string_ : str
default : {'raise', False}
Default behaviour if none of the "true" strings is detected.
Returns
-------
boolean : bool
Examples
------... | keyword[def] identifier[str2bool] ( identifier[string_] , identifier[default] = literal[string] ):
literal[string]
identifier[true] =[ literal[string] , literal[string] , literal[string] , literal[string] , literal[string] , literal[string] , literal[string] , literal[string] ]
identifier[false] =[ li... | def str2bool(string_, default='raise'):
"""
Convert a string to a bool.
Parameters
----------
string_ : str
default : {'raise', False}
Default behaviour if none of the "true" strings is detected.
Returns
-------
boolean : bool
Examples
--------
>>> str2bool('Tr... |
def create_jwt(integration_id, private_key_path):
"""Create a JSON Web Token to authenticate a GitHub Integration or
installation.
Parameters
----------
integration_id : `int`
Integration ID. This is available from the GitHub integration's
homepage.
private_key_path : `str`
... | def function[create_jwt, parameter[integration_id, private_key_path]]:
constant[Create a JSON Web Token to authenticate a GitHub Integration or
installation.
Parameters
----------
integration_id : `int`
Integration ID. This is available from the GitHub integration's
homepage.
... | keyword[def] identifier[create_jwt] ( identifier[integration_id] , identifier[private_key_path] ):
literal[string]
identifier[integration_id] = identifier[int] ( identifier[integration_id] )
keyword[with] identifier[open] ( identifier[private_key_path] , literal[string] ) keyword[as] identifier[f] ... | def create_jwt(integration_id, private_key_path):
"""Create a JSON Web Token to authenticate a GitHub Integration or
installation.
Parameters
----------
integration_id : `int`
Integration ID. This is available from the GitHub integration's
homepage.
private_key_path : `str`
... |
def truncate_to_issuer(self, cert):
"""
Remove all certificates in the path after the issuer of the cert
specified, as defined by this path
:param cert:
An asn1crypto.x509.Certificate object to find the issuer of
:raises:
LookupError - when the issuer of... | def function[truncate_to_issuer, parameter[self, cert]]:
constant[
Remove all certificates in the path after the issuer of the cert
specified, as defined by this path
:param cert:
An asn1crypto.x509.Certificate object to find the issuer of
:raises:
Looku... | keyword[def] identifier[truncate_to_issuer] ( identifier[self] , identifier[cert] ):
literal[string]
identifier[issuer_index] = keyword[None]
keyword[for] identifier[index] , identifier[entry] keyword[in] identifier[enumerate] ( identifier[self] ):
keyword[if] identifier... | def truncate_to_issuer(self, cert):
"""
Remove all certificates in the path after the issuer of the cert
specified, as defined by this path
:param cert:
An asn1crypto.x509.Certificate object to find the issuer of
:raises:
LookupError - when the issuer of the... |
def _parse(self, pattern):
"""Parse string of comma-separated x-y/step -like ranges"""
# Comma separated ranges
if pattern.find(',') < 0:
subranges = [pattern]
else:
subranges = pattern.split(',')
for subrange in subranges:
if subrange.find('/... | def function[_parse, parameter[self, pattern]]:
constant[Parse string of comma-separated x-y/step -like ranges]
if compare[call[name[pattern].find, parameter[constant[,]]] less[<] constant[0]] begin[:]
variable[subranges] assign[=] list[[<ast.Name object at 0x7da1b1039180>]]
for ... | keyword[def] identifier[_parse] ( identifier[self] , identifier[pattern] ):
literal[string]
keyword[if] identifier[pattern] . identifier[find] ( literal[string] )< literal[int] :
identifier[subranges] =[ identifier[pattern] ]
keyword[else] :
identifier[s... | def _parse(self, pattern):
"""Parse string of comma-separated x-y/step -like ranges"""
# Comma separated ranges
if pattern.find(',') < 0:
subranges = [pattern] # depends on [control=['if'], data=[]]
else:
subranges = pattern.split(',')
for subrange in subranges:
if subrange.... |
def sell_margin(self):
"""
[float] 卖方向保证金
"""
return sum(position.sell_margin for position in six.itervalues(self._positions)) | def function[sell_margin, parameter[self]]:
constant[
[float] 卖方向保证金
]
return[call[name[sum], parameter[<ast.GeneratorExp object at 0x7da1b212dc90>]]] | keyword[def] identifier[sell_margin] ( identifier[self] ):
literal[string]
keyword[return] identifier[sum] ( identifier[position] . identifier[sell_margin] keyword[for] identifier[position] keyword[in] identifier[six] . identifier[itervalues] ( identifier[self] . identifier[_positions] )) | def sell_margin(self):
"""
[float] 卖方向保证金
"""
return sum((position.sell_margin for position in six.itervalues(self._positions))) |
def finished(tokens, s):
"""Parser(a, None)
Throws an exception if any tokens are left in the input unparsed.
"""
if s.pos >= len(tokens):
return None, s
else:
raise NoParseError(u'should have reached <EOF>', s) | def function[finished, parameter[tokens, s]]:
constant[Parser(a, None)
Throws an exception if any tokens are left in the input unparsed.
]
if compare[name[s].pos greater_or_equal[>=] call[name[len], parameter[name[tokens]]]] begin[:]
return[tuple[[<ast.Constant object at 0x7da18f09f7c0>... | keyword[def] identifier[finished] ( identifier[tokens] , identifier[s] ):
literal[string]
keyword[if] identifier[s] . identifier[pos] >= identifier[len] ( identifier[tokens] ):
keyword[return] keyword[None] , identifier[s]
keyword[else] :
keyword[raise] identifier[NoParseError] (... | def finished(tokens, s):
"""Parser(a, None)
Throws an exception if any tokens are left in the input unparsed.
"""
if s.pos >= len(tokens):
return (None, s) # depends on [control=['if'], data=[]]
else:
raise NoParseError(u'should have reached <EOF>', s) |
def _reorder_csv(d, filename=""):
"""
Preserve the csv column ordering before writing back out to CSV file. Keep column data consistent with JSONLD
column number alignment.
{ "var1" : {"number": 1, "values": [] }, "var2": {"number": 1, "values": [] } }
:param dict d: csv data
:param str filenam... | def function[_reorder_csv, parameter[d, filename]]:
constant[
Preserve the csv column ordering before writing back out to CSV file. Keep column data consistent with JSONLD
column number alignment.
{ "var1" : {"number": 1, "values": [] }, "var2": {"number": 1, "values": [] } }
:param dict d: csv... | keyword[def] identifier[_reorder_csv] ( identifier[d] , identifier[filename] = literal[string] ):
literal[string]
identifier[_ensemble] = identifier[is_ensemble] ( identifier[d] )
identifier[_d2] =[]
keyword[try] :
keyword[if] identifier[_ensemble] :
keyword[if] i... | def _reorder_csv(d, filename=''):
"""
Preserve the csv column ordering before writing back out to CSV file. Keep column data consistent with JSONLD
column number alignment.
{ "var1" : {"number": 1, "values": [] }, "var2": {"number": 1, "values": [] } }
:param dict d: csv data
:param str filenam... |
def HSL_to_RGB(cobj, target_rgb, *args, **kwargs):
"""
HSL to RGB conversion.
"""
H = cobj.hsl_h
S = cobj.hsl_s
L = cobj.hsl_l
if L < 0.5:
var_q = L * (1.0 + S)
else:
var_q = L + S - (L * S)
var_p = 2.0 * L - var_q
# H normalized to range [0,1]
h_sub_k = (H... | def function[HSL_to_RGB, parameter[cobj, target_rgb]]:
constant[
HSL to RGB conversion.
]
variable[H] assign[=] name[cobj].hsl_h
variable[S] assign[=] name[cobj].hsl_s
variable[L] assign[=] name[cobj].hsl_l
if compare[name[L] less[<] constant[0.5]] begin[:]
... | keyword[def] identifier[HSL_to_RGB] ( identifier[cobj] , identifier[target_rgb] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
identifier[H] = identifier[cobj] . identifier[hsl_h]
identifier[S] = identifier[cobj] . identifier[hsl_s]
identifier[L] = identifier[cobj] . identifier[h... | def HSL_to_RGB(cobj, target_rgb, *args, **kwargs):
"""
HSL to RGB conversion.
"""
H = cobj.hsl_h
S = cobj.hsl_s
L = cobj.hsl_l
if L < 0.5:
var_q = L * (1.0 + S) # depends on [control=['if'], data=['L']]
else:
var_q = L + S - L * S
var_p = 2.0 * L - var_q
# H norm... |
def _init_glyph(self, plot, mapping, properties):
"""
Returns a Bokeh glyph object.
"""
properties = mpl_to_bokeh(properties)
properties = dict(properties, **mapping)
if 'xs' in mapping:
renderer = plot.patches(**properties)
else:
renderer ... | def function[_init_glyph, parameter[self, plot, mapping, properties]]:
constant[
Returns a Bokeh glyph object.
]
variable[properties] assign[=] call[name[mpl_to_bokeh], parameter[name[properties]]]
variable[properties] assign[=] call[name[dict], parameter[name[properties]]]
... | keyword[def] identifier[_init_glyph] ( identifier[self] , identifier[plot] , identifier[mapping] , identifier[properties] ):
literal[string]
identifier[properties] = identifier[mpl_to_bokeh] ( identifier[properties] )
identifier[properties] = identifier[dict] ( identifier[properties] ,** i... | def _init_glyph(self, plot, mapping, properties):
"""
Returns a Bokeh glyph object.
"""
properties = mpl_to_bokeh(properties)
properties = dict(properties, **mapping)
if 'xs' in mapping:
renderer = plot.patches(**properties) # depends on [control=['if'], data=[]]
else:
... |
def request(self, content='xml', filter=None, detail=False):
"""Get config from Alu router
*content* Content layer. cli or xml
*filter* specifies the portion of the configuration to retrieve (by default entire configuration is retrieved)
*detail* Show detailed config in CLI -laye... | def function[request, parameter[self, content, filter, detail]]:
constant[Get config from Alu router
*content* Content layer. cli or xml
*filter* specifies the portion of the configuration to retrieve (by default entire configuration is retrieved)
*detail* Show detailed config in... | keyword[def] identifier[request] ( identifier[self] , identifier[content] = literal[string] , identifier[filter] = keyword[None] , identifier[detail] = keyword[False] ):
literal[string]
identifier[node] = identifier[new_ele] ( literal[string] )
identifier[node] . identifier[append] ( iden... | def request(self, content='xml', filter=None, detail=False):
"""Get config from Alu router
*content* Content layer. cli or xml
*filter* specifies the portion of the configuration to retrieve (by default entire configuration is retrieved)
*detail* Show detailed config in CLI -layer"""... |
def diagnostics(self):
"""
Return an iterable (and indexable) object containing the diagnostics.
"""
class DiagIterator:
def __init__(self, tu):
self.tu = tu
def __len__(self):
return int(conf.lib.clang_getNumDiagnostics(self.tu))
... | def function[diagnostics, parameter[self]]:
constant[
Return an iterable (and indexable) object containing the diagnostics.
]
class class[DiagIterator, parameter[]] begin[:]
def function[__init__, parameter[self, tu]]:
name[self].tu assign[=] name[... | keyword[def] identifier[diagnostics] ( identifier[self] ):
literal[string]
keyword[class] identifier[DiagIterator] :
keyword[def] identifier[__init__] ( identifier[self] , identifier[tu] ):
identifier[self] . identifier[tu] = identifier[tu]
keyword[def... | def diagnostics(self):
"""
Return an iterable (and indexable) object containing the diagnostics.
"""
class DiagIterator:
def __init__(self, tu):
self.tu = tu
def __len__(self):
return int(conf.lib.clang_getNumDiagnostics(self.tu))
def __getitem... |
def get_subscriptions(self):
"""Return a list of subscriptions currently active for this WVA device
:raises WVAError: if there is a problem getting the subscription list from the WVA
:returns: A list of :class:`WVASubscription` instances
"""
# Example: {'subscriptions': ['subscr... | def function[get_subscriptions, parameter[self]]:
constant[Return a list of subscriptions currently active for this WVA device
:raises WVAError: if there is a problem getting the subscription list from the WVA
:returns: A list of :class:`WVASubscription` instances
]
variable[sub... | keyword[def] identifier[get_subscriptions] ( identifier[self] ):
literal[string]
identifier[subscriptions] =[]
keyword[for] identifier[uri] keyword[in] identifier[self] . identifier[get_http_client] (). identifier[get] ( literal[string] ). identifier[get] ( literal[string] ):
... | def get_subscriptions(self):
"""Return a list of subscriptions currently active for this WVA device
:raises WVAError: if there is a problem getting the subscription list from the WVA
:returns: A list of :class:`WVASubscription` instances
"""
# Example: {'subscriptions': ['subscriptions/... |
def get_yield_curve(date=None, tenor=None):
"""
获取某个国家市场指定日期的收益率曲线水平。
数据为2002年至今的中债国债收益率曲线,来源于中央国债登记结算有限责任公司。
:param date: 查询日期,默认为策略当前日期前一天
:type date: `str` | `date` | `datetime` | `pandas.Timestamp`
:param str tenor: 标准期限,'0S' - 隔夜,'1M' - 1个月,'1Y' - 1年,默认为全部期限
:return: `pandas.DataFra... | def function[get_yield_curve, parameter[date, tenor]]:
constant[
获取某个国家市场指定日期的收益率曲线水平。
数据为2002年至今的中债国债收益率曲线,来源于中央国债登记结算有限责任公司。
:param date: 查询日期,默认为策略当前日期前一天
:type date: `str` | `date` | `datetime` | `pandas.Timestamp`
:param str tenor: 标准期限,'0S' - 隔夜,'1M' - 1个月,'1Y' - 1年,默认为全部期限
:re... | keyword[def] identifier[get_yield_curve] ( identifier[date] = keyword[None] , identifier[tenor] = keyword[None] ):
literal[string]
identifier[env] = identifier[Environment] . identifier[get_instance] ()
identifier[trading_date] = identifier[env] . identifier[trading_dt] . identifier[date] ()
iden... | def get_yield_curve(date=None, tenor=None):
"""
获取某个国家市场指定日期的收益率曲线水平。
数据为2002年至今的中债国债收益率曲线,来源于中央国债登记结算有限责任公司。
:param date: 查询日期,默认为策略当前日期前一天
:type date: `str` | `date` | `datetime` | `pandas.Timestamp`
:param str tenor: 标准期限,'0S' - 隔夜,'1M' - 1个月,'1Y' - 1年,默认为全部期限
:return: `pandas.DataFra... |
def _set_isns_discovery_domain(self, v, load=False):
"""
Setter method for isns_discovery_domain, mapped from YANG variable /isns/isns_vrf/isns_discovery_domain (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_isns_discovery_domain is considered as a private
me... | def function[_set_isns_discovery_domain, parameter[self, v, load]]:
constant[
Setter method for isns_discovery_domain, mapped from YANG variable /isns/isns_vrf/isns_discovery_domain (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_isns_discovery_domain is consi... | keyword[def] identifier[_set_isns_discovery_domain] ( identifier[self] , identifier[v] , identifier[load] = keyword[False] ):
literal[string]
keyword[if] identifier[hasattr] ( identifier[v] , literal[string] ):
identifier[v] = identifier[v] . identifier[_utype] ( identifier[v] )
keyword[try] :... | def _set_isns_discovery_domain(self, v, load=False):
"""
Setter method for isns_discovery_domain, mapped from YANG variable /isns/isns_vrf/isns_discovery_domain (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_isns_discovery_domain is considered as a private
me... |
def parser_helper(key, val):
'''
Helper for parser function
@param key:
@param val:
'''
start_bracket = key.find("[")
end_bracket = key.find("]")
pdict = {}
if has_variable_name(key): # var['key'][3]
pdict[key[:key.find("[")]] = parser_helper(key[start_bracket:], v... | def function[parser_helper, parameter[key, val]]:
constant[
Helper for parser function
@param key:
@param val:
]
variable[start_bracket] assign[=] call[name[key].find, parameter[constant[[]]]
variable[end_bracket] assign[=] call[name[key].find, parameter[constant[]]]]
var... | keyword[def] identifier[parser_helper] ( identifier[key] , identifier[val] ):
literal[string]
identifier[start_bracket] = identifier[key] . identifier[find] ( literal[string] )
identifier[end_bracket] = identifier[key] . identifier[find] ( literal[string] )
identifier[pdict] ={}
keyword... | def parser_helper(key, val):
"""
Helper for parser function
@param key:
@param val:
"""
start_bracket = key.find('[')
end_bracket = key.find(']')
pdict = {}
if has_variable_name(key): # var['key'][3]
pdict[key[:key.find('[')]] = parser_helper(key[start_bracket:], val) # dep... |
def prior_from_config(cp, variable_params, prior_section,
constraint_section):
"""Gets arguments and keyword arguments from a config file.
Parameters
----------
cp : WorkflowConfigParser
Config file parser to read.
variable_params : list
... | def function[prior_from_config, parameter[cp, variable_params, prior_section, constraint_section]]:
constant[Gets arguments and keyword arguments from a config file.
Parameters
----------
cp : WorkflowConfigParser
Config file parser to read.
variable_params : list
... | keyword[def] identifier[prior_from_config] ( identifier[cp] , identifier[variable_params] , identifier[prior_section] ,
identifier[constraint_section] ):
literal[string]
identifier[logging] . identifier[info] ( literal[string] )
identifier[dists] = identifier[distributions] . ide... | def prior_from_config(cp, variable_params, prior_section, constraint_section):
"""Gets arguments and keyword arguments from a config file.
Parameters
----------
cp : WorkflowConfigParser
Config file parser to read.
variable_params : list
List of of model para... |
def _ip2country(ip):
"""Get user country."""
if ip:
match = geolite2.reader().get(ip)
return match.get('country', {}).get('iso_code') if match else None | def function[_ip2country, parameter[ip]]:
constant[Get user country.]
if name[ip] begin[:]
variable[match] assign[=] call[call[name[geolite2].reader, parameter[]].get, parameter[name[ip]]]
return[<ast.IfExp object at 0x7da2044c1180>] | keyword[def] identifier[_ip2country] ( identifier[ip] ):
literal[string]
keyword[if] identifier[ip] :
identifier[match] = identifier[geolite2] . identifier[reader] (). identifier[get] ( identifier[ip] )
keyword[return] identifier[match] . identifier[get] ( literal[string] ,{}). identifi... | def _ip2country(ip):
"""Get user country."""
if ip:
match = geolite2.reader().get(ip)
return match.get('country', {}).get('iso_code') if match else None # depends on [control=['if'], data=[]] |
def derive_configuration(cls):
"""
Collect the nearest type variables and effective parameters from the type,
its bases, and their origins as necessary.
"""
base_params = cls.base.__parameters__
if hasattr(cls.type, '__args__'):
# typing as of commit abefbe4
... | def function[derive_configuration, parameter[cls]]:
constant[
Collect the nearest type variables and effective parameters from the type,
its bases, and their origins as necessary.
]
variable[base_params] assign[=] name[cls].base.__parameters__
if call[name[hasattr], param... | keyword[def] identifier[derive_configuration] ( identifier[cls] ):
literal[string]
identifier[base_params] = identifier[cls] . identifier[base] . identifier[__parameters__]
keyword[if] identifier[hasattr] ( identifier[cls] . identifier[type] , literal[string] ):
ide... | def derive_configuration(cls):
"""
Collect the nearest type variables and effective parameters from the type,
its bases, and their origins as necessary.
"""
base_params = cls.base.__parameters__
if hasattr(cls.type, '__args__'):
# typing as of commit abefbe4
tvars = {... |
def layer(output_shape=None, new_parameters=None):
"""Create a layer class from a function."""
def layer_decorator(call):
"""Decorating the call function."""
def output_shape_fun(self, input_shape):
if output_shape is None:
return input_shape
kwargs = self._init_kwargs # pylint: disable... | def function[layer, parameter[output_shape, new_parameters]]:
constant[Create a layer class from a function.]
def function[layer_decorator, parameter[call]]:
constant[Decorating the call function.]
def function[output_shape_fun, parameter[self, input_shape]]:
... | keyword[def] identifier[layer] ( identifier[output_shape] = keyword[None] , identifier[new_parameters] = keyword[None] ):
literal[string]
keyword[def] identifier[layer_decorator] ( identifier[call] ):
literal[string]
keyword[def] identifier[output_shape_fun] ( identifier[self] , identifier[input_s... | def layer(output_shape=None, new_parameters=None):
"""Create a layer class from a function."""
def layer_decorator(call):
"""Decorating the call function."""
def output_shape_fun(self, input_shape):
if output_shape is None:
return input_shape # depends on [control=... |
def flatten(in_list):
"""given a list of values in_list, flatten returns the list obtained by
flattening the top-level elements of in_list."""
out_list = []
for val in in_list:
if isinstance(val, list):
out_list.extend(val)
else:
out_list.append(val)
retu... | def function[flatten, parameter[in_list]]:
constant[given a list of values in_list, flatten returns the list obtained by
flattening the top-level elements of in_list.]
variable[out_list] assign[=] list[[]]
for taget[name[val]] in starred[name[in_list]] begin[:]
if call[na... | keyword[def] identifier[flatten] ( identifier[in_list] ):
literal[string]
identifier[out_list] =[]
keyword[for] identifier[val] keyword[in] identifier[in_list] :
keyword[if] identifier[isinstance] ( identifier[val] , identifier[list] ):
identifier[out_list] . identifier[exten... | def flatten(in_list):
"""given a list of values in_list, flatten returns the list obtained by
flattening the top-level elements of in_list."""
out_list = []
for val in in_list:
if isinstance(val, list):
out_list.extend(val) # depends on [control=['if'], data=[]]
else:
... |
async def keepalive_ping(self) -> None:
"""
Send a Ping frame and wait for a Pong frame at regular intervals.
This coroutine exits when the connection terminates and one of the
following happens:
- :meth:`ping` raises :exc:`ConnectionClosed`, or
- :meth:`close_connection... | <ast.AsyncFunctionDef object at 0x7da18eb54280> | keyword[async] keyword[def] identifier[keepalive_ping] ( identifier[self] )-> keyword[None] :
literal[string]
keyword[if] identifier[self] . identifier[ping_interval] keyword[is] keyword[None] :
keyword[return]
keyword[try] :
keyword[while] keyword[True] :
... | async def keepalive_ping(self) -> None:
"""
Send a Ping frame and wait for a Pong frame at regular intervals.
This coroutine exits when the connection terminates and one of the
following happens:
- :meth:`ping` raises :exc:`ConnectionClosed`, or
- :meth:`close_connection` ca... |
def deploy_branch_exists(deploy_branch):
"""
Check if there is a remote branch with name specified in ``deploy_branch``.
Note that default ``deploy_branch`` is ``gh-pages`` for regular repos and
``master`` for ``github.io`` repos.
This isn't completely robust. If there are multiple remotes and you... | def function[deploy_branch_exists, parameter[deploy_branch]]:
constant[
Check if there is a remote branch with name specified in ``deploy_branch``.
Note that default ``deploy_branch`` is ``gh-pages`` for regular repos and
``master`` for ``github.io`` repos.
This isn't completely robust. If the... | keyword[def] identifier[deploy_branch_exists] ( identifier[deploy_branch] ):
literal[string]
identifier[remote_name] = literal[string]
identifier[branch_names] = identifier[subprocess] . identifier[check_output] ([ literal[string] , literal[string] , literal[string] ]). identifier[decode] ( literal[s... | def deploy_branch_exists(deploy_branch):
"""
Check if there is a remote branch with name specified in ``deploy_branch``.
Note that default ``deploy_branch`` is ``gh-pages`` for regular repos and
``master`` for ``github.io`` repos.
This isn't completely robust. If there are multiple remotes and you... |
def set_attribute(attribute, attribute_value, instance_name=None, instance_id=None, region=None, key=None, keyid=None,
profile=None, filters=None):
'''
Set an EC2 instance attribute.
Returns whether the operation succeeded or not.
CLI Example:
.. code-block:: bash
salt m... | def function[set_attribute, parameter[attribute, attribute_value, instance_name, instance_id, region, key, keyid, profile, filters]]:
constant[
Set an EC2 instance attribute.
Returns whether the operation succeeded or not.
CLI Example:
.. code-block:: bash
salt myminion boto_ec2.set_a... | keyword[def] identifier[set_attribute] ( identifier[attribute] , identifier[attribute_value] , identifier[instance_name] = keyword[None] , identifier[instance_id] = keyword[None] , identifier[region] = keyword[None] , identifier[key] = keyword[None] , identifier[keyid] = keyword[None] ,
identifier[profile] = keyword... | def set_attribute(attribute, attribute_value, instance_name=None, instance_id=None, region=None, key=None, keyid=None, profile=None, filters=None):
"""
Set an EC2 instance attribute.
Returns whether the operation succeeded or not.
CLI Example:
.. code-block:: bash
salt myminion boto_ec2.s... |
def barycenter_graph(distance_matrix, X, reg=1e-3):
"""
Computes the barycenter weighted graph for points in X
Parameters
----------
distance_matrix: sparse Ndarray, (N_obs, N_obs) pairwise distance matrix.
X : Ndarray (N_obs, N_dim) observed data matrix.
reg : float, optional
Amoun... | def function[barycenter_graph, parameter[distance_matrix, X, reg]]:
constant[
Computes the barycenter weighted graph for points in X
Parameters
----------
distance_matrix: sparse Ndarray, (N_obs, N_obs) pairwise distance matrix.
X : Ndarray (N_obs, N_dim) observed data matrix.
reg : flo... | keyword[def] identifier[barycenter_graph] ( identifier[distance_matrix] , identifier[X] , identifier[reg] = literal[int] ):
literal[string]
( identifier[N] , identifier[d_in] )= identifier[X] . identifier[shape]
( identifier[rows] , identifier[cols] )= identifier[distance_matrix] . identifier[nonzero] ... | def barycenter_graph(distance_matrix, X, reg=0.001):
"""
Computes the barycenter weighted graph for points in X
Parameters
----------
distance_matrix: sparse Ndarray, (N_obs, N_obs) pairwise distance matrix.
X : Ndarray (N_obs, N_dim) observed data matrix.
reg : float, optional
Amou... |
def configure(self, argv=None):
'''
Configures this engine based on the options array passed into
`argv`. If `argv` is ``None``, then ``sys.argv`` is used instead.
During configuration, the command line options are merged with
previously stored values. Then the logging subsystem and the
database... | def function[configure, parameter[self, argv]]:
constant[
Configures this engine based on the options array passed into
`argv`. If `argv` is ``None``, then ``sys.argv`` is used instead.
During configuration, the command line options are merged with
previously stored values. Then the logging subs... | keyword[def] identifier[configure] ( identifier[self] , identifier[argv] = keyword[None] ):
literal[string]
identifier[self] . identifier[_setupOptions] ()
identifier[self] . identifier[_parseOptions] ( identifier[argv] )
identifier[self] . identifier[_setupLogging] ()
identifier[self] . ide... | def configure(self, argv=None):
"""
Configures this engine based on the options array passed into
`argv`. If `argv` is ``None``, then ``sys.argv`` is used instead.
During configuration, the command line options are merged with
previously stored values. Then the logging subsystem and the
database... |
def parse_cadd(variant, transcripts):
"""Check if the cadd phred score is annotated"""
cadd = 0
cadd_keys = ['CADD', 'CADD_PHRED']
for key in cadd_keys:
cadd = variant.INFO.get(key, 0)
if cadd:
return float(cadd)
for transcript in transcripts:
cadd_entry = tr... | def function[parse_cadd, parameter[variant, transcripts]]:
constant[Check if the cadd phred score is annotated]
variable[cadd] assign[=] constant[0]
variable[cadd_keys] assign[=] list[[<ast.Constant object at 0x7da18f58ca00>, <ast.Constant object at 0x7da18f58dc60>]]
for taget[name[key]]... | keyword[def] identifier[parse_cadd] ( identifier[variant] , identifier[transcripts] ):
literal[string]
identifier[cadd] = literal[int]
identifier[cadd_keys] =[ literal[string] , literal[string] ]
keyword[for] identifier[key] keyword[in] identifier[cadd_keys] :
identifier[cadd] = iden... | def parse_cadd(variant, transcripts):
"""Check if the cadd phred score is annotated"""
cadd = 0
cadd_keys = ['CADD', 'CADD_PHRED']
for key in cadd_keys:
cadd = variant.INFO.get(key, 0)
if cadd:
return float(cadd) # depends on [control=['if'], data=[]] # depends on [control=... |
def check( state_engine, nameop, block_id, checked_ops ):
"""
Given a NAME_IMPORT nameop, see if we can import it.
* the name must be well-formed
* the namespace must be revealed, but not ready
* the name cannot have been imported yet
* the sender must be the same as the namespace's sender
... | def function[check, parameter[state_engine, nameop, block_id, checked_ops]]:
constant[
Given a NAME_IMPORT nameop, see if we can import it.
* the name must be well-formed
* the namespace must be revealed, but not ready
* the name cannot have been imported yet
* the sender must be the same as... | keyword[def] identifier[check] ( identifier[state_engine] , identifier[nameop] , identifier[block_id] , identifier[checked_ops] ):
literal[string]
keyword[from] .. identifier[nameset] keyword[import] identifier[BlockstackDB]
identifier[name] = identifier[str] ( identifier[nameop] [ literal[string... | def check(state_engine, nameop, block_id, checked_ops):
"""
Given a NAME_IMPORT nameop, see if we can import it.
* the name must be well-formed
* the namespace must be revealed, but not ready
* the name cannot have been imported yet
* the sender must be the same as the namespace's sender
Se... |
def _get_veths(net_data):
'''
Parse the nic setup inside lxc conf tuples back to a dictionary indexed by
network interface
'''
if isinstance(net_data, dict):
net_data = list(net_data.items())
nics = salt.utils.odict.OrderedDict()
current_nic = salt.utils.odict.OrderedDict()
no_na... | def function[_get_veths, parameter[net_data]]:
constant[
Parse the nic setup inside lxc conf tuples back to a dictionary indexed by
network interface
]
if call[name[isinstance], parameter[name[net_data], name[dict]]] begin[:]
variable[net_data] assign[=] call[name[list], para... | keyword[def] identifier[_get_veths] ( identifier[net_data] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[net_data] , identifier[dict] ):
identifier[net_data] = identifier[list] ( identifier[net_data] . identifier[items] ())
identifier[nics] = identifier[salt] . identifie... | def _get_veths(net_data):
"""
Parse the nic setup inside lxc conf tuples back to a dictionary indexed by
network interface
"""
if isinstance(net_data, dict):
net_data = list(net_data.items()) # depends on [control=['if'], data=[]]
nics = salt.utils.odict.OrderedDict()
current_nic = ... |
def vendor_runtime(chroot, dest_basedir, label, root_module_names):
"""Includes portions of vendored distributions in a chroot.
The portion to include is selected by root module name. If the module is a file, just it is
included. If the module represents a package, the package and all its sub-packages are added
... | def function[vendor_runtime, parameter[chroot, dest_basedir, label, root_module_names]]:
constant[Includes portions of vendored distributions in a chroot.
The portion to include is selected by root module name. If the module is a file, just it is
included. If the module represents a package, the package an... | keyword[def] identifier[vendor_runtime] ( identifier[chroot] , identifier[dest_basedir] , identifier[label] , identifier[root_module_names] ):
literal[string]
identifier[vendor_module_names] ={ identifier[root_module_name] : keyword[False] keyword[for] identifier[root_module_name] keyword[in] identifier[ro... | def vendor_runtime(chroot, dest_basedir, label, root_module_names):
"""Includes portions of vendored distributions in a chroot.
The portion to include is selected by root module name. If the module is a file, just it is
included. If the module represents a package, the package and all its sub-packages are adde... |
def get_task_filelist(cls, task_factory, courseid, taskid):
""" Returns a flattened version of all the files inside the task directory, excluding the files task.* and hidden files.
It returns a list of tuples, of the type (Integer Level, Boolean IsDirectory, String Name, String CompleteName)
... | def function[get_task_filelist, parameter[cls, task_factory, courseid, taskid]]:
constant[ Returns a flattened version of all the files inside the task directory, excluding the files task.* and hidden files.
It returns a list of tuples, of the type (Integer Level, Boolean IsDirectory, String Name, S... | keyword[def] identifier[get_task_filelist] ( identifier[cls] , identifier[task_factory] , identifier[courseid] , identifier[taskid] ):
literal[string]
identifier[task_fs] = identifier[task_factory] . identifier[get_task_fs] ( identifier[courseid] , identifier[taskid] )
keyword[if] keyword... | def get_task_filelist(cls, task_factory, courseid, taskid):
""" Returns a flattened version of all the files inside the task directory, excluding the files task.* and hidden files.
It returns a list of tuples, of the type (Integer Level, Boolean IsDirectory, String Name, String CompleteName)
"""... |
def object_deserializer(obj):
"""Helper to deserialize a raw result dict into a proper dict.
:param obj: The dict.
"""
for key, val in obj.items():
if isinstance(val, six.string_types) and DATETIME_REGEX.search(val):
try:
obj[key] = dates.localize_datetime(parser.par... | def function[object_deserializer, parameter[obj]]:
constant[Helper to deserialize a raw result dict into a proper dict.
:param obj: The dict.
]
for taget[tuple[[<ast.Name object at 0x7da1b0ca6c80>, <ast.Name object at 0x7da1b0ca63e0>]]] in starred[call[name[obj].items, parameter[]]] begin[:]
... | keyword[def] identifier[object_deserializer] ( identifier[obj] ):
literal[string]
keyword[for] identifier[key] , identifier[val] keyword[in] identifier[obj] . identifier[items] ():
keyword[if] identifier[isinstance] ( identifier[val] , identifier[six] . identifier[string_types] ) keyword[and] ... | def object_deserializer(obj):
"""Helper to deserialize a raw result dict into a proper dict.
:param obj: The dict.
"""
for (key, val) in obj.items():
if isinstance(val, six.string_types) and DATETIME_REGEX.search(val):
try:
obj[key] = dates.localize_datetime(parser.p... |
async def kick(self, user_id: base.Integer,
until_date: typing.Union[base.Integer, None] = None):
"""
Use this method to kick a user from a group, a supergroup or a channel.
In the case of supergroups and channels, the user will not be able to return to the group
on th... | <ast.AsyncFunctionDef object at 0x7da1b1782bc0> | keyword[async] keyword[def] identifier[kick] ( identifier[self] , identifier[user_id] : identifier[base] . identifier[Integer] ,
identifier[until_date] : identifier[typing] . identifier[Union] [ identifier[base] . identifier[Integer] , keyword[None] ]= keyword[None] ):
literal[string]
keyword[ret... | async def kick(self, user_id: base.Integer, until_date: typing.Union[base.Integer, None]=None):
"""
Use this method to kick a user from a group, a supergroup or a channel.
In the case of supergroups and channels, the user will not be able to return to the group
on their own using invite link... |
def set_row_gap(self, value):
"""Sets the gap value between rows
Args:
value (int or str): gap value (i.e. 10 or "10px")
"""
value = str(value) + 'px'
value = value.replace('pxpx', 'px')
self.style['grid-row-gap'] = value | def function[set_row_gap, parameter[self, value]]:
constant[Sets the gap value between rows
Args:
value (int or str): gap value (i.e. 10 or "10px")
]
variable[value] assign[=] binary_operation[call[name[str], parameter[name[value]]] + constant[px]]
variable[value] as... | keyword[def] identifier[set_row_gap] ( identifier[self] , identifier[value] ):
literal[string]
identifier[value] = identifier[str] ( identifier[value] )+ literal[string]
identifier[value] = identifier[value] . identifier[replace] ( literal[string] , literal[string] )
identifier[s... | def set_row_gap(self, value):
"""Sets the gap value between rows
Args:
value (int or str): gap value (i.e. 10 or "10px")
"""
value = str(value) + 'px'
value = value.replace('pxpx', 'px')
self.style['grid-row-gap'] = value |
def export(self, out_filename):
"""Export desired threads as a zipfile to out_filename.
"""
with zipfile.ZipFile(out_filename, 'w', zipfile.ZIP_DEFLATED) as arc:
id_list = list(self.get_thread_info())
for num, my_info in enumerate(id_list):
logging.info('W... | def function[export, parameter[self, out_filename]]:
constant[Export desired threads as a zipfile to out_filename.
]
with call[name[zipfile].ZipFile, parameter[name[out_filename], constant[w], name[zipfile].ZIP_DEFLATED]] begin[:]
variable[id_list] assign[=] call[name[list], para... | keyword[def] identifier[export] ( identifier[self] , identifier[out_filename] ):
literal[string]
keyword[with] identifier[zipfile] . identifier[ZipFile] ( identifier[out_filename] , literal[string] , identifier[zipfile] . identifier[ZIP_DEFLATED] ) keyword[as] identifier[arc] :
ident... | def export(self, out_filename):
"""Export desired threads as a zipfile to out_filename.
"""
with zipfile.ZipFile(out_filename, 'w', zipfile.ZIP_DEFLATED) as arc:
id_list = list(self.get_thread_info())
for (num, my_info) in enumerate(id_list):
logging.info('Working on item %i ... |
def _encode(self, value, path_from_root):
"""Normalize, compress, and encode sub-objects for backend storage.
value: Object to encode.
path_from_root: `tuple` of key strings from the top-level summary to the
current `value`.
Returns:
A new tree of dict's with la... | def function[_encode, parameter[self, value, path_from_root]]:
constant[Normalize, compress, and encode sub-objects for backend storage.
value: Object to encode.
path_from_root: `tuple` of key strings from the top-level summary to the
current `value`.
Returns:
A... | keyword[def] identifier[_encode] ( identifier[self] , identifier[value] , identifier[path_from_root] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[value] , identifier[dict] ):
identifier[json_value] ={}
keyword[for] identifier[key... | def _encode(self, value, path_from_root):
"""Normalize, compress, and encode sub-objects for backend storage.
value: Object to encode.
path_from_root: `tuple` of key strings from the top-level summary to the
current `value`.
Returns:
A new tree of dict's with large ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.