code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def _create_kvstore(kvstore, num_device, arg_params):
"""Create kvstore
This function select and create a proper kvstore if given the kvstore type.
Parameters
----------
kvstore : KVStore or str
The kvstore.
num_device : int
The number of devices
arg_params : dict of str to ... | def function[_create_kvstore, parameter[kvstore, num_device, arg_params]]:
constant[Create kvstore
This function select and create a proper kvstore if given the kvstore type.
Parameters
----------
kvstore : KVStore or str
The kvstore.
num_device : int
The number of devices
... | keyword[def] identifier[_create_kvstore] ( identifier[kvstore] , identifier[num_device] , identifier[arg_params] ):
literal[string]
identifier[update_on_kvstore] = identifier[bool] ( identifier[int] ( identifier[os] . identifier[getenv] ( literal[string] , literal[string] )))
keyword[if] identifier[k... | def _create_kvstore(kvstore, num_device, arg_params):
"""Create kvstore
This function select and create a proper kvstore if given the kvstore type.
Parameters
----------
kvstore : KVStore or str
The kvstore.
num_device : int
The number of devices
arg_params : dict of str to ... |
def get_user_lists(self, course, aggregationid=''):
""" Get the available student and tutor lists for aggregation edition"""
tutor_list = course.get_staff()
# Determine student list and if they are grouped
student_list = list(self.database.aggregations.aggregate([
{"$match":... | def function[get_user_lists, parameter[self, course, aggregationid]]:
constant[ Get the available student and tutor lists for aggregation edition]
variable[tutor_list] assign[=] call[name[course].get_staff, parameter[]]
variable[student_list] assign[=] call[name[list], parameter[call[name[self].... | keyword[def] identifier[get_user_lists] ( identifier[self] , identifier[course] , identifier[aggregationid] = literal[string] ):
literal[string]
identifier[tutor_list] = identifier[course] . identifier[get_staff] ()
identifier[student_list] = identifier[list] ( identifier[self] .... | def get_user_lists(self, course, aggregationid=''):
""" Get the available student and tutor lists for aggregation edition"""
tutor_list = course.get_staff()
# Determine student list and if they are grouped
student_list = list(self.database.aggregations.aggregate([{'$match': {'courseid': course.get_id()}... |
def create(cls, name, min_dst_port, max_dst_port=None, min_src_port=None,
max_src_port=None, protocol_agent=None, comment=None):
"""
Create the TCP service
:param str name: name of tcp service
:param int min_dst_port: minimum destination port value
:param int max_... | def function[create, parameter[cls, name, min_dst_port, max_dst_port, min_src_port, max_src_port, protocol_agent, comment]]:
constant[
Create the TCP service
:param str name: name of tcp service
:param int min_dst_port: minimum destination port value
:param int max_dst_port: max... | keyword[def] identifier[create] ( identifier[cls] , identifier[name] , identifier[min_dst_port] , identifier[max_dst_port] = keyword[None] , identifier[min_src_port] = keyword[None] ,
identifier[max_src_port] = keyword[None] , identifier[protocol_agent] = keyword[None] , identifier[comment] = keyword[None] ):
... | def create(cls, name, min_dst_port, max_dst_port=None, min_src_port=None, max_src_port=None, protocol_agent=None, comment=None):
"""
Create the TCP service
:param str name: name of tcp service
:param int min_dst_port: minimum destination port value
:param int max_dst_port: maximum d... |
def on_data(self, data):
"""
The function called when new data has arrived.
:param data: The list of data records received.
"""
for d in data:
self._populate_sub_entity(d, 'Device')
self._populate_sub_entity(d, 'Rule')
date = dates.localize_da... | def function[on_data, parameter[self, data]]:
constant[
The function called when new data has arrived.
:param data: The list of data records received.
]
for taget[name[d]] in starred[name[data]] begin[:]
call[name[self]._populate_sub_entity, parameter[name[d], co... | keyword[def] identifier[on_data] ( identifier[self] , identifier[data] ):
literal[string]
keyword[for] identifier[d] keyword[in] identifier[data] :
identifier[self] . identifier[_populate_sub_entity] ( identifier[d] , literal[string] )
identifier[self] . identifier[_pop... | def on_data(self, data):
"""
The function called when new data has arrived.
:param data: The list of data records received.
"""
for d in data:
self._populate_sub_entity(d, 'Device')
self._populate_sub_entity(d, 'Rule')
date = dates.localize_datetime(d['activeFrom... |
def _get_decision_trees_bulk(self, payload, valid_indices, invalid_indices, invalid_dts):
"""Tool for the function get_decision_trees_bulk.
:param list payload: contains the informations necessary for getting
the trees. Its form is the same than for the function.
get_decision_trees_bulk.
:param lis... | def function[_get_decision_trees_bulk, parameter[self, payload, valid_indices, invalid_indices, invalid_dts]]:
constant[Tool for the function get_decision_trees_bulk.
:param list payload: contains the informations necessary for getting
the trees. Its form is the same than for the function.
get_deci... | keyword[def] identifier[_get_decision_trees_bulk] ( identifier[self] , identifier[payload] , identifier[valid_indices] , identifier[invalid_indices] , identifier[invalid_dts] ):
literal[string]
identifier[valid_dts] = identifier[self] . identifier[_create_and_send_json_bulk] ([ identifier[payload] [ identi... | def _get_decision_trees_bulk(self, payload, valid_indices, invalid_indices, invalid_dts):
"""Tool for the function get_decision_trees_bulk.
:param list payload: contains the informations necessary for getting
the trees. Its form is the same than for the function.
get_decision_trees_bulk.
:param lis... |
def connect_to_wifi(self, ssid, password=None):
"""
[Test Agent]
Connect to *ssid* with *password*
"""
cmd = 'am broadcast -a testagent -e action CONNECT_TO_WIFI -e ssid %s -e password %s' % (ssid, password)
self.adb.shell_cmd(cmd) | def function[connect_to_wifi, parameter[self, ssid, password]]:
constant[
[Test Agent]
Connect to *ssid* with *password*
]
variable[cmd] assign[=] binary_operation[constant[am broadcast -a testagent -e action CONNECT_TO_WIFI -e ssid %s -e password %s] <ast.Mod object at 0x7da259... | keyword[def] identifier[connect_to_wifi] ( identifier[self] , identifier[ssid] , identifier[password] = keyword[None] ):
literal[string]
identifier[cmd] = literal[string] %( identifier[ssid] , identifier[password] )
identifier[self] . identifier[adb] . identifier[shell_cmd] ( identifier[cm... | def connect_to_wifi(self, ssid, password=None):
"""
[Test Agent]
Connect to *ssid* with *password*
"""
cmd = 'am broadcast -a testagent -e action CONNECT_TO_WIFI -e ssid %s -e password %s' % (ssid, password)
self.adb.shell_cmd(cmd) |
def transform(self, path):
"""
Transform a path into an actual Python object.
The path can be arbitrary long. You can pass the path to a package,
a module, a class, a function or a global variable, as deep as you
want, as long as the deepest module is importable through
... | def function[transform, parameter[self, path]]:
constant[
Transform a path into an actual Python object.
The path can be arbitrary long. You can pass the path to a package,
a module, a class, a function or a global variable, as deep as you
want, as long as the deepest module is ... | keyword[def] identifier[transform] ( identifier[self] , identifier[path] ):
literal[string]
keyword[if] identifier[path] keyword[is] keyword[None] keyword[or] keyword[not] identifier[path] :
keyword[return] keyword[None]
identifier[obj_parent_modules] = identifier[pat... | def transform(self, path):
"""
Transform a path into an actual Python object.
The path can be arbitrary long. You can pass the path to a package,
a module, a class, a function or a global variable, as deep as you
want, as long as the deepest module is importable through
``im... |
def _set_rpc(self, rpc_type: str) -> None:
"""
Sets rpc based on the type
:param rpc_type: The type of connection: like infura, ganache, localhost
:return:
"""
if rpc_type == "infura":
self.set_api_rpc_infura()
elif rpc_type == "localhost":
... | def function[_set_rpc, parameter[self, rpc_type]]:
constant[
Sets rpc based on the type
:param rpc_type: The type of connection: like infura, ganache, localhost
:return:
]
if compare[name[rpc_type] equal[==] constant[infura]] begin[:]
call[name[self].set_a... | keyword[def] identifier[_set_rpc] ( identifier[self] , identifier[rpc_type] : identifier[str] )-> keyword[None] :
literal[string]
keyword[if] identifier[rpc_type] == literal[string] :
identifier[self] . identifier[set_api_rpc_infura] ()
keyword[elif] identifier[rpc_type] == ... | def _set_rpc(self, rpc_type: str) -> None:
"""
Sets rpc based on the type
:param rpc_type: The type of connection: like infura, ganache, localhost
:return:
"""
if rpc_type == 'infura':
self.set_api_rpc_infura() # depends on [control=['if'], data=[]]
elif rpc_type == ... |
def _compute_schoenfeld_within_strata(self, X, T, E, weights):
"""
A positive value of the residual shows an X value that is higher than expected at that death time.
"""
# TODO: the diff_against is gross
# This uses Efron ties.
n, d = X.shape
if not np.any(E):
... | def function[_compute_schoenfeld_within_strata, parameter[self, X, T, E, weights]]:
constant[
A positive value of the residual shows an X value that is higher than expected at that death time.
]
<ast.Tuple object at 0x7da20c992c50> assign[=] name[X].shape
if <ast.UnaryOp object a... | keyword[def] identifier[_compute_schoenfeld_within_strata] ( identifier[self] , identifier[X] , identifier[T] , identifier[E] , identifier[weights] ):
literal[string]
identifier[n] , identifier[d] = identifier[X] . identifier[shape]
keyword[if] keyword[not] identifie... | def _compute_schoenfeld_within_strata(self, X, T, E, weights):
"""
A positive value of the residual shows an X value that is higher than expected at that death time.
"""
# TODO: the diff_against is gross
# This uses Efron ties.
(n, d) = X.shape
if not np.any(E):
# sometimes s... |
def open(cls, filename, band_names=None, lazy_load=True, mutable=False, **kwargs):
"""
Read a georaster from a file.
:param filename: url
:param band_names: list of strings, or string.
if None - will try to read from image, otherwise - these will be ['0', ..]... | def function[open, parameter[cls, filename, band_names, lazy_load, mutable]]:
constant[
Read a georaster from a file.
:param filename: url
:param band_names: list of strings, or string.
if None - will try to read from image, otherwise - these will be ['0', ..... | keyword[def] identifier[open] ( identifier[cls] , identifier[filename] , identifier[band_names] = keyword[None] , identifier[lazy_load] = keyword[True] , identifier[mutable] = keyword[False] ,** identifier[kwargs] ):
literal[string]
keyword[if] identifier[mutable] :
identifier[geo_ras... | def open(cls, filename, band_names=None, lazy_load=True, mutable=False, **kwargs):
"""
Read a georaster from a file.
:param filename: url
:param band_names: list of strings, or string.
if None - will try to read from image, otherwise - these will be ['0', ..]
... |
def get_sort_indicator(self, field):
"""
Returns a sort class for the active sort only. That is, if field is not
sort_field, then nothing will be returned becaues the sort is not
active.
"""
indicator = ''
if field == self.sort_field:
indicator = 'sort... | def function[get_sort_indicator, parameter[self, field]]:
constant[
Returns a sort class for the active sort only. That is, if field is not
sort_field, then nothing will be returned becaues the sort is not
active.
]
variable[indicator] assign[=] constant[]
if comp... | keyword[def] identifier[get_sort_indicator] ( identifier[self] , identifier[field] ):
literal[string]
identifier[indicator] = literal[string]
keyword[if] identifier[field] == identifier[self] . identifier[sort_field] :
identifier[indicator] = literal[string]
ke... | def get_sort_indicator(self, field):
"""
Returns a sort class for the active sort only. That is, if field is not
sort_field, then nothing will be returned becaues the sort is not
active.
"""
indicator = ''
if field == self.sort_field:
indicator = 'sort-asc'
if... |
def p_initial(self, p):
'initial : INITIAL initial_statement'
p[0] = Initial(p[2], lineno=p.lineno(1))
p.set_lineno(0, p.lineno(1)) | def function[p_initial, parameter[self, p]]:
constant[initial : INITIAL initial_statement]
call[name[p]][constant[0]] assign[=] call[name[Initial], parameter[call[name[p]][constant[2]]]]
call[name[p].set_lineno, parameter[constant[0], call[name[p].lineno, parameter[constant[1]]]]] | keyword[def] identifier[p_initial] ( identifier[self] , identifier[p] ):
literal[string]
identifier[p] [ literal[int] ]= identifier[Initial] ( identifier[p] [ literal[int] ], identifier[lineno] = identifier[p] . identifier[lineno] ( literal[int] ))
identifier[p] . identifier[set_lineno] ( ... | def p_initial(self, p):
"""initial : INITIAL initial_statement"""
p[0] = Initial(p[2], lineno=p.lineno(1))
p.set_lineno(0, p.lineno(1)) |
def makeWritePacket(ID, reg, values=None):
"""
Creates a packet that writes a value(s) to servo ID at location reg. Make
sure the values are in little endian (use Packet.le() if necessary) for 16 b
(word size) values.
"""
pkt = makePacket(ID, xl320.XL320_WRITE, reg, values)
return pkt | def function[makeWritePacket, parameter[ID, reg, values]]:
constant[
Creates a packet that writes a value(s) to servo ID at location reg. Make
sure the values are in little endian (use Packet.le() if necessary) for 16 b
(word size) values.
]
variable[pkt] assign[=] call[name[makePacket], parameter[n... | keyword[def] identifier[makeWritePacket] ( identifier[ID] , identifier[reg] , identifier[values] = keyword[None] ):
literal[string]
identifier[pkt] = identifier[makePacket] ( identifier[ID] , identifier[xl320] . identifier[XL320_WRITE] , identifier[reg] , identifier[values] )
keyword[return] identifier[pkt] | def makeWritePacket(ID, reg, values=None):
"""
Creates a packet that writes a value(s) to servo ID at location reg. Make
sure the values are in little endian (use Packet.le() if necessary) for 16 b
(word size) values.
"""
pkt = makePacket(ID, xl320.XL320_WRITE, reg, values)
return pkt |
def cuts_connections(self, a, b):
"""Check if this cut severs any connections from ``a`` to ``b``.
Args:
a (tuple[int]): A set of nodes.
b (tuple[int]): A set of nodes.
"""
n = max(self.indices) + 1
return self.cut_matrix(n)[np.ix_(a, b)].any() | def function[cuts_connections, parameter[self, a, b]]:
constant[Check if this cut severs any connections from ``a`` to ``b``.
Args:
a (tuple[int]): A set of nodes.
b (tuple[int]): A set of nodes.
]
variable[n] assign[=] binary_operation[call[name[max], parameter[... | keyword[def] identifier[cuts_connections] ( identifier[self] , identifier[a] , identifier[b] ):
literal[string]
identifier[n] = identifier[max] ( identifier[self] . identifier[indices] )+ literal[int]
keyword[return] identifier[self] . identifier[cut_matrix] ( identifier[n] )[ identifier... | def cuts_connections(self, a, b):
"""Check if this cut severs any connections from ``a`` to ``b``.
Args:
a (tuple[int]): A set of nodes.
b (tuple[int]): A set of nodes.
"""
n = max(self.indices) + 1
return self.cut_matrix(n)[np.ix_(a, b)].any() |
def single_conv_dist(name, x, output_channels=None):
"""A 3x3 convolution mapping x to a standard normal distribution at init.
Args:
name: variable scope.
x: 4-D Tensor.
output_channels: number of channels of the mean and std.
"""
with tf.variable_scope(name, reuse=tf.AUTO_REUSE):
x_shape = com... | def function[single_conv_dist, parameter[name, x, output_channels]]:
constant[A 3x3 convolution mapping x to a standard normal distribution at init.
Args:
name: variable scope.
x: 4-D Tensor.
output_channels: number of channels of the mean and std.
]
with call[name[tf].variable_scope, p... | keyword[def] identifier[single_conv_dist] ( identifier[name] , identifier[x] , identifier[output_channels] = keyword[None] ):
literal[string]
keyword[with] identifier[tf] . identifier[variable_scope] ( identifier[name] , identifier[reuse] = identifier[tf] . identifier[AUTO_REUSE] ):
identifier[x_shape] =... | def single_conv_dist(name, x, output_channels=None):
"""A 3x3 convolution mapping x to a standard normal distribution at init.
Args:
name: variable scope.
x: 4-D Tensor.
output_channels: number of channels of the mean and std.
"""
with tf.variable_scope(name, reuse=tf.AUTO_REUSE):
x_sha... |
def remove(self, dist):
"""Remove `dist` from the distribution map"""
while dist.location in self.paths:
self.paths.remove(dist.location)
self.dirty = True
Environment.remove(self, dist) | def function[remove, parameter[self, dist]]:
constant[Remove `dist` from the distribution map]
while compare[name[dist].location in name[self].paths] begin[:]
call[name[self].paths.remove, parameter[name[dist].location]]
name[self].dirty assign[=] constant[True]
c... | keyword[def] identifier[remove] ( identifier[self] , identifier[dist] ):
literal[string]
keyword[while] identifier[dist] . identifier[location] keyword[in] identifier[self] . identifier[paths] :
identifier[self] . identifier[paths] . identifier[remove] ( identifier[dist] . identifie... | def remove(self, dist):
"""Remove `dist` from the distribution map"""
while dist.location in self.paths:
self.paths.remove(dist.location)
self.dirty = True # depends on [control=['while'], data=[]]
Environment.remove(self, dist) |
def _execute(self, endpoint, database, query, default_timeout, properties=None):
"""Executes given query against this client"""
request_payload = {"db": database, "csl": query}
if properties:
request_payload["properties"] = properties.to_json()
request_headers = {
... | def function[_execute, parameter[self, endpoint, database, query, default_timeout, properties]]:
constant[Executes given query against this client]
variable[request_payload] assign[=] dictionary[[<ast.Constant object at 0x7da1b23447f0>, <ast.Constant object at 0x7da1b23477f0>], [<ast.Name object at 0x7d... | keyword[def] identifier[_execute] ( identifier[self] , identifier[endpoint] , identifier[database] , identifier[query] , identifier[default_timeout] , identifier[properties] = keyword[None] ):
literal[string]
identifier[request_payload] ={ literal[string] : identifier[database] , literal[string... | def _execute(self, endpoint, database, query, default_timeout, properties=None):
"""Executes given query against this client"""
request_payload = {'db': database, 'csl': query}
if properties:
request_payload['properties'] = properties.to_json() # depends on [control=['if'], data=[]]
request_hea... |
def return_tip(self, home_after=True):
"""
Drop the pipette's current tip to it's originating tip rack
Notes
-----
This method requires one or more tip-rack :any:`Container`
to be in this Pipette's `tip_racks` list (see :any:`Pipette`)
Returns
-------
... | def function[return_tip, parameter[self, home_after]]:
constant[
Drop the pipette's current tip to it's originating tip rack
Notes
-----
This method requires one or more tip-rack :any:`Container`
to be in this Pipette's `tip_racks` list (see :any:`Pipette`)
Retu... | keyword[def] identifier[return_tip] ( identifier[self] , identifier[home_after] = keyword[True] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[tip_attached] :
identifier[log] . identifier[warning] ( literal[string] )
keyword[if] keyword[not] ide... | def return_tip(self, home_after=True):
"""
Drop the pipette's current tip to it's originating tip rack
Notes
-----
This method requires one or more tip-rack :any:`Container`
to be in this Pipette's `tip_racks` list (see :any:`Pipette`)
Returns
-------
... |
def dragEnterEvent(self, event):
"""
Listens for query's being dragged and dropped onto this tree.
:param event | <QDragEnterEvent>
"""
data = event.mimeData()
if data.hasFormat('application/x-orb-table') and \
data.hasFormat('application/... | def function[dragEnterEvent, parameter[self, event]]:
constant[
Listens for query's being dragged and dropped onto this tree.
:param event | <QDragEnterEvent>
]
variable[data] assign[=] call[name[event].mimeData, parameter[]]
if <ast.BoolOp object at 0x7da18... | keyword[def] identifier[dragEnterEvent] ( identifier[self] , identifier[event] ):
literal[string]
identifier[data] = identifier[event] . identifier[mimeData] ()
keyword[if] identifier[data] . identifier[hasFormat] ( literal[string] ) keyword[and] identifier[data] . identifier[hasForma... | def dragEnterEvent(self, event):
"""
Listens for query's being dragged and dropped onto this tree.
:param event | <QDragEnterEvent>
"""
data = event.mimeData()
if data.hasFormat('application/x-orb-table') and data.hasFormat('application/x-orb-query'):
tableName ... |
def remove_entry_listener(self, registration_id):
"""
Removes the specified entry listener. Returns silently if there is no such listener added before.
:param registration_id: (str), id of registered listener.
:return: (bool), ``true`` if registration is removed, ``false`` otherwise.
... | def function[remove_entry_listener, parameter[self, registration_id]]:
constant[
Removes the specified entry listener. Returns silently if there is no such listener added before.
:param registration_id: (str), id of registered listener.
:return: (bool), ``true`` if registration is remov... | keyword[def] identifier[remove_entry_listener] ( identifier[self] , identifier[registration_id] ):
literal[string]
keyword[return] identifier[self] . identifier[_stop_listening] ( identifier[registration_id] ,
keyword[lambda] identifier[i] : identifier[multi_map_remove_entry_listener_cod... | def remove_entry_listener(self, registration_id):
"""
Removes the specified entry listener. Returns silently if there is no such listener added before.
:param registration_id: (str), id of registered listener.
:return: (bool), ``true`` if registration is removed, ``false`` otherwise.
... |
def get_agg(self):
"""
Returns the aggregated value for the metric
:return: the value of the metric
"""
""" Returns an aggregated value """
query = self.get_query(False)
res = self.get_metrics_data(query)
# We need to extract the data from the JSON res
... | def function[get_agg, parameter[self]]:
constant[
Returns the aggregated value for the metric
:return: the value of the metric
]
constant[ Returns an aggregated value ]
variable[query] assign[=] call[name[self].get_query, parameter[constant[False]]]
variable[res]... | keyword[def] identifier[get_agg] ( identifier[self] ):
literal[string]
literal[string]
identifier[query] = identifier[self] . identifier[get_query] ( keyword[False] )
identifier[res] = identifier[self] . identifier[get_metrics_data] ( identifier[query] )
... | def get_agg(self):
"""
Returns the aggregated value for the metric
:return: the value of the metric
"""
' Returns an aggregated value '
query = self.get_query(False)
res = self.get_metrics_data(query)
# We need to extract the data from the JSON res
# If we have agg data ... |
def on_hook(self, hook):
# type: (Hook) -> None
"""Takes a hook, and optionally calls hook.run on a function"""
try:
func, args_gen = self.hooked[type(hook)]
except (KeyError, TypeError):
return
else:
hook(func, args_gen()) | def function[on_hook, parameter[self, hook]]:
constant[Takes a hook, and optionally calls hook.run on a function]
<ast.Try object at 0x7da18ede57e0> | keyword[def] identifier[on_hook] ( identifier[self] , identifier[hook] ):
literal[string]
keyword[try] :
identifier[func] , identifier[args_gen] = identifier[self] . identifier[hooked] [ identifier[type] ( identifier[hook] )]
keyword[except] ( identifier[KeyError] , identifie... | def on_hook(self, hook):
# type: (Hook) -> None
'Takes a hook, and optionally calls hook.run on a function'
try:
(func, args_gen) = self.hooked[type(hook)] # depends on [control=['try'], data=[]]
except (KeyError, TypeError):
return # depends on [control=['except'], data=[]]
else:
... |
def get(self, key, default=None):
"""
Returns the value of the key or the default value if the key is
not yet in gconf
"""
#function arguments override defaults
if default is None:
default = self.DEFAULTS.get(key, None)
vtype = type(default)
... | def function[get, parameter[self, key, default]]:
constant[
Returns the value of the key or the default value if the key is
not yet in gconf
]
if compare[name[default] is constant[None]] begin[:]
variable[default] assign[=] call[name[self].DEFAULTS.get, parameter[... | keyword[def] identifier[get] ( identifier[self] , identifier[key] , identifier[default] = keyword[None] ):
literal[string]
keyword[if] identifier[default] keyword[is] keyword[None] :
identifier[default] = identifier[self] . identifier[DEFAULTS] . identifier[get] ( identifi... | def get(self, key, default=None):
"""
Returns the value of the key or the default value if the key is
not yet in gconf
"""
#function arguments override defaults
if default is None:
default = self.DEFAULTS.get(key, None) # depends on [control=['if'], data=['default']]
vty... |
def _install_from_scratch(python_cmd, use_sudo):
"""
Install setuptools from scratch using installer
"""
with cd("/tmp"):
download(EZ_SETUP_URL)
command = '%(python_cmd)s ez_setup.py' % locals()
if use_sudo:
run_as_root(command)
else:
run(command... | def function[_install_from_scratch, parameter[python_cmd, use_sudo]]:
constant[
Install setuptools from scratch using installer
]
with call[name[cd], parameter[constant[/tmp]]] begin[:]
call[name[download], parameter[name[EZ_SETUP_URL]]]
variable[command] assign[=... | keyword[def] identifier[_install_from_scratch] ( identifier[python_cmd] , identifier[use_sudo] ):
literal[string]
keyword[with] identifier[cd] ( literal[string] ):
identifier[download] ( identifier[EZ_SETUP_URL] )
identifier[command] = literal[string] % identifier[locals] ()
k... | def _install_from_scratch(python_cmd, use_sudo):
"""
Install setuptools from scratch using installer
"""
with cd('/tmp'):
download(EZ_SETUP_URL)
command = '%(python_cmd)s ez_setup.py' % locals()
if use_sudo:
run_as_root(command) # depends on [control=['if'], data=[]]... |
def __clearRepositoryCache(self, duplicate=None):
"""Called when we change the repository(ies) for a directory.
This clears any cached information that is invalidated by changing
the repository."""
for node in list(self.entries.values()):
if node != self.dir:
... | def function[__clearRepositoryCache, parameter[self, duplicate]]:
constant[Called when we change the repository(ies) for a directory.
This clears any cached information that is invalidated by changing
the repository.]
for taget[name[node]] in starred[call[name[list], parameter[call[name[... | keyword[def] identifier[__clearRepositoryCache] ( identifier[self] , identifier[duplicate] = keyword[None] ):
literal[string]
keyword[for] identifier[node] keyword[in] identifier[list] ( identifier[self] . identifier[entries] . identifier[values] ()):
keyword[if] identifier[node] ... | def __clearRepositoryCache(self, duplicate=None):
"""Called when we change the repository(ies) for a directory.
This clears any cached information that is invalidated by changing
the repository."""
for node in list(self.entries.values()):
if node != self.dir:
if node != self ... |
def _serialize_object(self, response_data, request):
""" Override to not serialize doc responses. """
if self._is_doc_request(request):
return response_data
else:
return super(DocumentedResource, self)._serialize_object(
response_data, request) | def function[_serialize_object, parameter[self, response_data, request]]:
constant[ Override to not serialize doc responses. ]
if call[name[self]._is_doc_request, parameter[name[request]]] begin[:]
return[name[response_data]] | keyword[def] identifier[_serialize_object] ( identifier[self] , identifier[response_data] , identifier[request] ):
literal[string]
keyword[if] identifier[self] . identifier[_is_doc_request] ( identifier[request] ):
keyword[return] identifier[response_data]
keyword[else] :
... | def _serialize_object(self, response_data, request):
""" Override to not serialize doc responses. """
if self._is_doc_request(request):
return response_data # depends on [control=['if'], data=[]]
else:
return super(DocumentedResource, self)._serialize_object(response_data, request) |
def extension_preselection(network, args, method, days = 3):
"""
Function that preselects lines which are extendend in snapshots leading to
overloading to reduce nubmer of extension variables.
Parameters
----------
network : :class:`pypsa.Network
Overall container of PyPSA
... | def function[extension_preselection, parameter[network, args, method, days]]:
constant[
Function that preselects lines which are extendend in snapshots leading to
overloading to reduce nubmer of extension variables.
Parameters
----------
network : :class:`pypsa.Network
Overall... | keyword[def] identifier[extension_preselection] ( identifier[network] , identifier[args] , identifier[method] , identifier[days] = literal[int] ):
literal[string]
identifier[weighting] = identifier[network] . identifier[snapshot_weightings]
keyword[if] identifier[method] == literal[string] :
... | def extension_preselection(network, args, method, days=3):
"""
Function that preselects lines which are extendend in snapshots leading to
overloading to reduce nubmer of extension variables.
Parameters
----------
network : :class:`pypsa.Network
Overall container of PyPSA
args ... |
def tag(iterable, tags=None, key='@tags'):
"""
Add tags to each dict or dict-like object in ``iterable``. Tags are added
to each dict with a key set by ``key``. If a key already exists under the
key given by ``key``, this function will attempt to ``.extend()``` it, but
will fall back to replacing it... | def function[tag, parameter[iterable, tags, key]]:
constant[
Add tags to each dict or dict-like object in ``iterable``. Tags are added
to each dict with a key set by ``key``. If a key already exists under the
key given by ``key``, this function will attempt to ``.extend()``` it, but
will fall ba... | keyword[def] identifier[tag] ( identifier[iterable] , identifier[tags] = keyword[None] , identifier[key] = literal[string] ):
literal[string]
keyword[if] keyword[not] identifier[tags] :
keyword[for] identifier[item] keyword[in] identifier[iterable] :
keyword[yield] identifier[it... | def tag(iterable, tags=None, key='@tags'):
"""
Add tags to each dict or dict-like object in ``iterable``. Tags are added
to each dict with a key set by ``key``. If a key already exists under the
key given by ``key``, this function will attempt to ``.extend()``` it, but
will fall back to replacing it... |
def shift_annotations(self, time):
"""Shift all annotations in time. Annotations that are in the beginning
and a left shift is applied can be squashed or discarded.
:param int time: Time shift width, negative numbers make a left shift.
:returns: Tuple of a list of squashed annotations a... | def function[shift_annotations, parameter[self, time]]:
constant[Shift all annotations in time. Annotations that are in the beginning
and a left shift is applied can be squashed or discarded.
:param int time: Time shift width, negative numbers make a left shift.
:returns: Tuple of a lis... | keyword[def] identifier[shift_annotations] ( identifier[self] , identifier[time] ):
literal[string]
identifier[total_re] =[]
identifier[total_sq] =[]
keyword[for] identifier[name] , identifier[tier] keyword[in] identifier[self] . identifier[tiers] . identifier[items] ():
... | def shift_annotations(self, time):
"""Shift all annotations in time. Annotations that are in the beginning
and a left shift is applied can be squashed or discarded.
:param int time: Time shift width, negative numbers make a left shift.
:returns: Tuple of a list of squashed annotations and a... |
def convConn (self, preCellsTags, postCellsTags, connParam):
from .. import sim
''' Generates connections between all pre and post-syn cells based on probability values'''
if sim.cfg.verbose: print('Generating set of convergent connections (rule: %s) ...' % (connParam['label']))
# get list ... | def function[convConn, parameter[self, preCellsTags, postCellsTags, connParam]]:
from relative_module[None] import module[sim]
constant[ Generates connections between all pre and post-syn cells based on probability values]
if name[sim].cfg.verbose begin[:]
call[name[print], parameter... | keyword[def] identifier[convConn] ( identifier[self] , identifier[preCellsTags] , identifier[postCellsTags] , identifier[connParam] ):
keyword[from] .. keyword[import] identifier[sim]
literal[string]
keyword[if] identifier[sim] . identifier[cfg] . identifier[verbose] : identifier[print] ( literal[... | def convConn(self, preCellsTags, postCellsTags, connParam):
from .. import sim
' Generates connections between all pre and post-syn cells based on probability values'
if sim.cfg.verbose:
print('Generating set of convergent connections (rule: %s) ...' % connParam['label']) # depends on [control=['if... |
def get_neuroml_from_sonata(sonata_filename, id, generate_lems = True, format='xml'):
"""
Return a NeuroMLDocument with (most of) the contents of the Sonata model
"""
from neuroml.hdf5.NetworkBuilder import NetworkBuilder
neuroml_handler = NetworkBuilder()
sr = SonataReader(filename=s... | def function[get_neuroml_from_sonata, parameter[sonata_filename, id, generate_lems, format]]:
constant[
Return a NeuroMLDocument with (most of) the contents of the Sonata model
]
from relative_module[neuroml.hdf5.NetworkBuilder] import module[NetworkBuilder]
variable[neuroml_handler] assign... | keyword[def] identifier[get_neuroml_from_sonata] ( identifier[sonata_filename] , identifier[id] , identifier[generate_lems] = keyword[True] , identifier[format] = literal[string] ):
literal[string]
keyword[from] identifier[neuroml] . identifier[hdf5] . identifier[NetworkBuilder] keyword[import] identif... | def get_neuroml_from_sonata(sonata_filename, id, generate_lems=True, format='xml'):
"""
Return a NeuroMLDocument with (most of) the contents of the Sonata model
"""
from neuroml.hdf5.NetworkBuilder import NetworkBuilder
neuroml_handler = NetworkBuilder()
sr = SonataReader(filename=sonata_filena... |
def broken_chains(samples, chains):
"""Find the broken chains.
Args:
samples (array_like):
Samples as a nS x nV array_like object where nS is the number of samples and nV is the
number of variables. The values should all be 0/1 or -1/+1.
chains (list[array_like]):
... | def function[broken_chains, parameter[samples, chains]]:
constant[Find the broken chains.
Args:
samples (array_like):
Samples as a nS x nV array_like object where nS is the number of samples and nV is the
number of variables. The values should all be 0/1 or -1/+1.
c... | keyword[def] identifier[broken_chains] ( identifier[samples] , identifier[chains] ):
literal[string]
identifier[samples] = identifier[np] . identifier[asarray] ( identifier[samples] )
keyword[if] identifier[samples] . identifier[ndim] != literal[int] :
keyword[raise] identifier[ValueError] ... | def broken_chains(samples, chains):
"""Find the broken chains.
Args:
samples (array_like):
Samples as a nS x nV array_like object where nS is the number of samples and nV is the
number of variables. The values should all be 0/1 or -1/+1.
chains (list[array_like]):
... |
def print_data(data_sources):
"""
Print dataset information in tabular form
"""
if not data_sources:
return
headers = ["DATA NAME", "CREATED", "STATUS", "DISK USAGE"]
data_list = []
for data_source in data_sources:
data_list.append([data_source.name,
... | def function[print_data, parameter[data_sources]]:
constant[
Print dataset information in tabular form
]
if <ast.UnaryOp object at 0x7da1b0d0f550> begin[:]
return[None]
variable[headers] assign[=] list[[<ast.Constant object at 0x7da1b0d0dea0>, <ast.Constant object at 0x7da1b0d0cf... | keyword[def] identifier[print_data] ( identifier[data_sources] ):
literal[string]
keyword[if] keyword[not] identifier[data_sources] :
keyword[return]
identifier[headers] =[ literal[string] , literal[string] , literal[string] , literal[string] ]
identifier[data_list] =[]
keyword[... | def print_data(data_sources):
"""
Print dataset information in tabular form
"""
if not data_sources:
return # depends on [control=['if'], data=[]]
headers = ['DATA NAME', 'CREATED', 'STATUS', 'DISK USAGE']
data_list = []
for data_source in data_sources:
data_list.append([dat... |
def iter_rows(self, start=None, end=None):
"""Iterate each of the Region rows in this region"""
start = start or 0
end = end or self.nrows
for i in range(start, end):
yield self.iloc[i, :] | def function[iter_rows, parameter[self, start, end]]:
constant[Iterate each of the Region rows in this region]
variable[start] assign[=] <ast.BoolOp object at 0x7da1b1d39b70>
variable[end] assign[=] <ast.BoolOp object at 0x7da1b1d3b9a0>
for taget[name[i]] in starred[call[name[range], par... | keyword[def] identifier[iter_rows] ( identifier[self] , identifier[start] = keyword[None] , identifier[end] = keyword[None] ):
literal[string]
identifier[start] = identifier[start] keyword[or] literal[int]
identifier[end] = identifier[end] keyword[or] identifier[self] . identifier[nro... | def iter_rows(self, start=None, end=None):
"""Iterate each of the Region rows in this region"""
start = start or 0
end = end or self.nrows
for i in range(start, end):
yield self.iloc[i, :] # depends on [control=['for'], data=['i']] |
def IntGreaterThanZero(n):
"""If *n* is an integer > 0, returns it, otherwise an error."""
try:
n = int(n)
except:
raise ValueError("%s is not an integer" % n)
if n <= 0:
raise ValueError("%d is not > 0" % n)
else:
return n | def function[IntGreaterThanZero, parameter[n]]:
constant[If *n* is an integer > 0, returns it, otherwise an error.]
<ast.Try object at 0x7da1b2346110>
if compare[name[n] less_or_equal[<=] constant[0]] begin[:]
<ast.Raise object at 0x7da1b2344a90> | keyword[def] identifier[IntGreaterThanZero] ( identifier[n] ):
literal[string]
keyword[try] :
identifier[n] = identifier[int] ( identifier[n] )
keyword[except] :
keyword[raise] identifier[ValueError] ( literal[string] % identifier[n] )
keyword[if] identifier[n] <= literal[int]... | def IntGreaterThanZero(n):
"""If *n* is an integer > 0, returns it, otherwise an error."""
try:
n = int(n) # depends on [control=['try'], data=[]]
except:
raise ValueError('%s is not an integer' % n) # depends on [control=['except'], data=[]]
if n <= 0:
raise ValueError('%d is ... |
def project(self, x, vector):
'''Project a vector (gradient or direction) on the active constraints.
Arguments:
| ``x`` -- The unknowns.
| ``vector`` -- A numpy array with a direction or a gradient.
The return value is a gradient or direction, where the components... | def function[project, parameter[self, x, vector]]:
constant[Project a vector (gradient or direction) on the active constraints.
Arguments:
| ``x`` -- The unknowns.
| ``vector`` -- A numpy array with a direction or a gradient.
The return value is a gradient or dire... | keyword[def] identifier[project] ( identifier[self] , identifier[x] , identifier[vector] ):
literal[string]
identifier[scale] = identifier[np] . identifier[linalg] . identifier[norm] ( identifier[vector] )
keyword[if] identifier[scale] == literal[int] :
keyword[return] ident... | def project(self, x, vector):
"""Project a vector (gradient or direction) on the active constraints.
Arguments:
| ``x`` -- The unknowns.
| ``vector`` -- A numpy array with a direction or a gradient.
The return value is a gradient or direction, where the components
... |
def project_variant_forward(self, c_variant):
"""
project c_variant on the source transcript onto the destination transcript
:param c_variant: an :class:`hgvs.sequencevariant.SequenceVariant` object on the source transcript
:returns: c_variant: an :class:`hgvs.sequencevariant.SequenceVa... | def function[project_variant_forward, parameter[self, c_variant]]:
constant[
project c_variant on the source transcript onto the destination transcript
:param c_variant: an :class:`hgvs.sequencevariant.SequenceVariant` object on the source transcript
:returns: c_variant: an :class:`hgvs... | keyword[def] identifier[project_variant_forward] ( identifier[self] , identifier[c_variant] ):
literal[string]
keyword[if] identifier[c_variant] . identifier[ac] != identifier[self] . identifier[src_tm] . identifier[tx_ac] :
keyword[raise] identifier[RuntimeError] ( literal[string] +... | def project_variant_forward(self, c_variant):
"""
project c_variant on the source transcript onto the destination transcript
:param c_variant: an :class:`hgvs.sequencevariant.SequenceVariant` object on the source transcript
:returns: c_variant: an :class:`hgvs.sequencevariant.SequenceVarian... |
def predict(self, a, b):
""" Compute the test statistic
Args:
a (array-like): Variable 1
b (array-like): Variable 2
Returns:
float: test statistic
"""
a = np.array(a).reshape((-1, 1))
b = np.array(b).reshape((-1, 1))
return sp... | def function[predict, parameter[self, a, b]]:
constant[ Compute the test statistic
Args:
a (array-like): Variable 1
b (array-like): Variable 2
Returns:
float: test statistic
]
variable[a] assign[=] call[call[name[np].array, parameter[name[a]]... | keyword[def] identifier[predict] ( identifier[self] , identifier[a] , identifier[b] ):
literal[string]
identifier[a] = identifier[np] . identifier[array] ( identifier[a] ). identifier[reshape] ((- literal[int] , literal[int] ))
identifier[b] = identifier[np] . identifier[array] ( identifie... | def predict(self, a, b):
""" Compute the test statistic
Args:
a (array-like): Variable 1
b (array-like): Variable 2
Returns:
float: test statistic
"""
a = np.array(a).reshape((-1, 1))
b = np.array(b).reshape((-1, 1))
return sp.kendalltau(a, b... |
def make_class_method_decorator(classkey, modname=None):
"""
register a class to be injectable
classkey is a key that identifies the injected class
REMEMBER to call inject_instance in __init__
Args:
classkey : the class to be injected into
modname : the global __name__ of the module... | def function[make_class_method_decorator, parameter[classkey, modname]]:
constant[
register a class to be injectable
classkey is a key that identifies the injected class
REMEMBER to call inject_instance in __init__
Args:
classkey : the class to be injected into
modname : the glo... | keyword[def] identifier[make_class_method_decorator] ( identifier[classkey] , identifier[modname] = keyword[None] ):
literal[string]
keyword[global] identifier[__APP_MODNAME_REGISTER__]
keyword[if] identifier[VERBOSE_CLASS] :
identifier[print] ( literal[string]
%( identifier[... | def make_class_method_decorator(classkey, modname=None):
"""
register a class to be injectable
classkey is a key that identifies the injected class
REMEMBER to call inject_instance in __init__
Args:
classkey : the class to be injected into
modname : the global __name__ of the module... |
def do_step(self, values, xy_values,coeff, width):
"""Calculates forces between two diagrams and pushes them apart by tenth of width"""
forces = {k:[] for k,i in enumerate(xy_values)}
for (index1, value1), (index2,value2) in combinations(enumerate(xy_values),2):
f = self.calc_2d_forc... | def function[do_step, parameter[self, values, xy_values, coeff, width]]:
constant[Calculates forces between two diagrams and pushes them apart by tenth of width]
variable[forces] assign[=] <ast.DictComp object at 0x7da18bc73df0>
for taget[tuple[[<ast.Tuple object at 0x7da18bc705b0>, <ast.Tuple o... | keyword[def] identifier[do_step] ( identifier[self] , identifier[values] , identifier[xy_values] , identifier[coeff] , identifier[width] ):
literal[string]
identifier[forces] ={ identifier[k] :[] keyword[for] identifier[k] , identifier[i] keyword[in] identifier[enumerate] ( identifier[xy_values]... | def do_step(self, values, xy_values, coeff, width):
"""Calculates forces between two diagrams and pushes them apart by tenth of width"""
forces = {k: [] for (k, i) in enumerate(xy_values)}
for ((index1, value1), (index2, value2)) in combinations(enumerate(xy_values), 2):
f = self.calc_2d_forces(valu... |
def _DecodeUnknownMessages(message, encoded_message, pair_type):
"""Process unknown fields in encoded_message of a message type."""
field_type = pair_type.value.type
new_values = []
all_field_names = [x.name for x in message.all_fields()]
for name, value_dict in six.iteritems(encoded_message):
... | def function[_DecodeUnknownMessages, parameter[message, encoded_message, pair_type]]:
constant[Process unknown fields in encoded_message of a message type.]
variable[field_type] assign[=] name[pair_type].value.type
variable[new_values] assign[=] list[[]]
variable[all_field_names] assign[... | keyword[def] identifier[_DecodeUnknownMessages] ( identifier[message] , identifier[encoded_message] , identifier[pair_type] ):
literal[string]
identifier[field_type] = identifier[pair_type] . identifier[value] . identifier[type]
identifier[new_values] =[]
identifier[all_field_names] =[ identifie... | def _DecodeUnknownMessages(message, encoded_message, pair_type):
"""Process unknown fields in encoded_message of a message type."""
field_type = pair_type.value.type
new_values = []
all_field_names = [x.name for x in message.all_fields()]
for (name, value_dict) in six.iteritems(encoded_message):
... |
def extend(self, xs: Union['List[T]', typing.List[T]]) -> 'List[T]': # type: ignore
"""doufo.List.extend
Args:
`self`
`xs` (`Union['List[T]', typing.List[T]]`): Another List object or Typing.List
Returns:
extented `List` (`List[T]`)
"""
... | def function[extend, parameter[self, xs]]:
constant[doufo.List.extend
Args:
`self`
`xs` (`Union['List[T]', typing.List[T]]`): Another List object or Typing.List
Returns:
extented `List` (`List[T]`)
]
return[call[call[name[type], parameter... | keyword[def] identifier[extend] ( identifier[self] , identifier[xs] : identifier[Union] [ literal[string] , identifier[typing] . identifier[List] [ identifier[T] ]])-> literal[string] :
literal[string]
keyword[return] identifier[type] ( identifier[self] )( identifier[self] . identifier[unbox] ()+ ... | def extend(self, xs: Union['List[T]', typing.List[T]]) -> 'List[T]': # type: ignore
"doufo.List.extend \n Args: \n `self` \n `xs` (`Union['List[T]', typing.List[T]]`): Another List object or Typing.List \n Returns: \n extented `List` (`List[T]`)\n "
re... |
def get_stp_mst_detail_output_cist_port_if_role(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
cist = ... | def function[get_stp_mst_detail_output_cist_port_if_role, parameter[self]]:
constant[Auto Generated Code
]
variable[config] assign[=] call[name[ET].Element, parameter[constant[config]]]
variable[get_stp_mst_detail] assign[=] call[name[ET].Element, parameter[constant[get_stp_mst_detail]]]... | keyword[def] identifier[get_stp_mst_detail_output_cist_port_if_role] ( identifier[self] ,** identifier[kwargs] ):
literal[string]
identifier[config] = identifier[ET] . identifier[Element] ( literal[string] )
identifier[get_stp_mst_detail] = identifier[ET] . identifier[Element] ( literal[st... | def get_stp_mst_detail_output_cist_port_if_role(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element('config')
get_stp_mst_detail = ET.Element('get_stp_mst_detail')
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, 'output')
cist = ET.SubElement(output, 'c... |
def slice_to(self, s):
'''
Copy the slice into the supplied StringBuffer
@type s: string
'''
result = ''
if self.slice_check():
result = self.current[self.bra:self.ket]
return result | def function[slice_to, parameter[self, s]]:
constant[
Copy the slice into the supplied StringBuffer
@type s: string
]
variable[result] assign[=] constant[]
if call[name[self].slice_check, parameter[]] begin[:]
variable[result] assign[=] call[name[self].cu... | keyword[def] identifier[slice_to] ( identifier[self] , identifier[s] ):
literal[string]
identifier[result] = literal[string]
keyword[if] identifier[self] . identifier[slice_check] ():
identifier[result] = identifier[self] . identifier[current] [ identifier[self] . identifier... | def slice_to(self, s):
"""
Copy the slice into the supplied StringBuffer
@type s: string
"""
result = ''
if self.slice_check():
result = self.current[self.bra:self.ket] # depends on [control=['if'], data=[]]
return result |
def parse(self, rev_string):
"""
:param rev_string:
:type rev_string: str
"""
elements = rev_string.split(MESSAGE_LINE_SEPARATOR)
heading = elements[0]
heading_elements = heading.split(" ")
self.revision_id = heading_elements[2]
datetime_str = "... | def function[parse, parameter[self, rev_string]]:
constant[
:param rev_string:
:type rev_string: str
]
variable[elements] assign[=] call[name[rev_string].split, parameter[name[MESSAGE_LINE_SEPARATOR]]]
variable[heading] assign[=] call[name[elements]][constant[0]]
... | keyword[def] identifier[parse] ( identifier[self] , identifier[rev_string] ):
literal[string]
identifier[elements] = identifier[rev_string] . identifier[split] ( identifier[MESSAGE_LINE_SEPARATOR] )
identifier[heading] = identifier[elements] [ literal[int] ]
identifier[heading_e... | def parse(self, rev_string):
"""
:param rev_string:
:type rev_string: str
"""
elements = rev_string.split(MESSAGE_LINE_SEPARATOR)
heading = elements[0]
heading_elements = heading.split(' ')
self.revision_id = heading_elements[2]
datetime_str = '{} {}'.format(heading_eleme... |
def _iter_interleaved_items(self, elements):
"""Generate element or subtotal items in interleaved order.
This ordering corresponds to how value "rows" (or columns) are to
appear after subtotals have been inserted at their anchor locations.
Where more than one subtotal is anchored to the... | def function[_iter_interleaved_items, parameter[self, elements]]:
constant[Generate element or subtotal items in interleaved order.
This ordering corresponds to how value "rows" (or columns) are to
appear after subtotals have been inserted at their anchor locations.
Where more than one ... | keyword[def] identifier[_iter_interleaved_items] ( identifier[self] , identifier[elements] ):
literal[string]
identifier[subtotals] = identifier[self] . identifier[_subtotals]
keyword[for] identifier[subtotal] keyword[in] identifier[subtotals] . identifier[iter_for_anchor] ( literal[s... | def _iter_interleaved_items(self, elements):
"""Generate element or subtotal items in interleaved order.
This ordering corresponds to how value "rows" (or columns) are to
appear after subtotals have been inserted at their anchor locations.
Where more than one subtotal is anchored to the sam... |
def get_predictions_under_consistency(instance):
'''
Computes the set of signs on edges/vertices that can be cautiously
derived from [instance], minus those that are a direct consequence
of obs_[ev]label predicates
'''
inst = instance.to_file()
prg = [ prediction_prg, inst, exclude_sol(... | def function[get_predictions_under_consistency, parameter[instance]]:
constant[
Computes the set of signs on edges/vertices that can be cautiously
derived from [instance], minus those that are a direct consequence
of obs_[ev]label predicates
]
variable[inst] assign[=] call[name[instance]... | keyword[def] identifier[get_predictions_under_consistency] ( identifier[instance] ):
literal[string]
identifier[inst] = identifier[instance] . identifier[to_file] ()
identifier[prg] =[ identifier[prediction_prg] , identifier[inst] , identifier[exclude_sol] ([])]
identifier[solver] = identifier[Gr... | def get_predictions_under_consistency(instance):
"""
Computes the set of signs on edges/vertices that can be cautiously
derived from [instance], minus those that are a direct consequence
of obs_[ev]label predicates
"""
inst = instance.to_file()
prg = [prediction_prg, inst, exclude_sol([])]
... |
def get_doctree(path, **kwargs):
"""
Obtain a Sphinx doctree from the RST file at ``path``.
Performs no Releases-specific processing; this code would, ideally, be in
Sphinx itself, but things there are pretty tightly coupled. So we wrote
this.
Any additional kwargs are passed unmodified into a... | def function[get_doctree, parameter[path]]:
constant[
Obtain a Sphinx doctree from the RST file at ``path``.
Performs no Releases-specific processing; this code would, ideally, be in
Sphinx itself, but things there are pretty tightly coupled. So we wrote
this.
Any additional kwargs are pas... | keyword[def] identifier[get_doctree] ( identifier[path] ,** identifier[kwargs] ):
literal[string]
identifier[root] , identifier[filename] = identifier[os] . identifier[path] . identifier[split] ( identifier[path] )
identifier[docname] , identifier[_] = identifier[os] . identifier[path] . identifier[sp... | def get_doctree(path, **kwargs):
"""
Obtain a Sphinx doctree from the RST file at ``path``.
Performs no Releases-specific processing; this code would, ideally, be in
Sphinx itself, but things there are pretty tightly coupled. So we wrote
this.
Any additional kwargs are passed unmodified into a... |
def save(self, *args, **kwargs):
"""
Overrides the save method
"""
self.slug = self.create_slug()
super(Slugable, self).save(*args, **kwargs) | def function[save, parameter[self]]:
constant[
Overrides the save method
]
name[self].slug assign[=] call[name[self].create_slug, parameter[]]
call[call[name[super], parameter[name[Slugable], name[self]]].save, parameter[<ast.Starred object at 0x7da1b27e0a60>]] | keyword[def] identifier[save] ( identifier[self] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
identifier[self] . identifier[slug] = identifier[self] . identifier[create_slug] ()
identifier[super] ( identifier[Slugable] , identifier[self] ). identifier[save] (* identifier[a... | def save(self, *args, **kwargs):
"""
Overrides the save method
"""
self.slug = self.create_slug()
super(Slugable, self).save(*args, **kwargs) |
def preprocess(*_unused, **processors):
"""
Decorator that applies pre-processors to the arguments of a function before
calling the function.
Parameters
----------
**processors : dict
Map from argument name -> processor function.
A processor function takes three arguments: (fun... | def function[preprocess, parameter[]]:
constant[
Decorator that applies pre-processors to the arguments of a function before
calling the function.
Parameters
----------
**processors : dict
Map from argument name -> processor function.
A processor function takes three argume... | keyword[def] identifier[preprocess] (* identifier[_unused] ,** identifier[processors] ):
literal[string]
keyword[if] identifier[_unused] :
keyword[raise] identifier[TypeError] ( literal[string] )
keyword[def] identifier[_decorator] ( identifier[f] ):
identifier[args] , identifier... | def preprocess(*_unused, **processors):
"""
Decorator that applies pre-processors to the arguments of a function before
calling the function.
Parameters
----------
**processors : dict
Map from argument name -> processor function.
A processor function takes three arguments: (fun... |
def _evaluate_standard(op, op_str, a, b, **eval_kwargs):
""" standard evaluation """
if _TEST_MODE:
_store_test_result(False)
with np.errstate(all='ignore'):
return op(a, b) | def function[_evaluate_standard, parameter[op, op_str, a, b]]:
constant[ standard evaluation ]
if name[_TEST_MODE] begin[:]
call[name[_store_test_result], parameter[constant[False]]]
with call[name[np].errstate, parameter[]] begin[:]
return[call[name[op], parameter[name[a... | keyword[def] identifier[_evaluate_standard] ( identifier[op] , identifier[op_str] , identifier[a] , identifier[b] ,** identifier[eval_kwargs] ):
literal[string]
keyword[if] identifier[_TEST_MODE] :
identifier[_store_test_result] ( keyword[False] )
keyword[with] identifier[np] . identifier[e... | def _evaluate_standard(op, op_str, a, b, **eval_kwargs):
""" standard evaluation """
if _TEST_MODE:
_store_test_result(False) # depends on [control=['if'], data=[]]
with np.errstate(all='ignore'):
return op(a, b) # depends on [control=['with'], data=[]] |
def write(self, __text: str) -> None:
"""Write text to the debug stream.
Args:
__text: Text to write
"""
if __text == os.linesep:
self.handle.write(__text)
else:
frame = inspect.currentframe()
if frame is None:
file... | def function[write, parameter[self, __text]]:
constant[Write text to the debug stream.
Args:
__text: Text to write
]
if compare[name[__text] equal[==] name[os].linesep] begin[:]
call[name[self].handle.write, parameter[name[__text]]] | keyword[def] identifier[write] ( identifier[self] , identifier[__text] : identifier[str] )-> keyword[None] :
literal[string]
keyword[if] identifier[__text] == identifier[os] . identifier[linesep] :
identifier[self] . identifier[handle] . identifier[write] ( identifier[__text] )
... | def write(self, __text: str) -> None:
"""Write text to the debug stream.
Args:
__text: Text to write
"""
if __text == os.linesep:
self.handle.write(__text) # depends on [control=['if'], data=['__text']]
else:
frame = inspect.currentframe()
if frame is No... |
def mean_rate(self):
"""
Returns the mean rate of the events since the start of the process.
"""
if self.counter.value == 0:
return 0.0
else:
elapsed = time() - self.start_time
return self.counter.value / elapsed | def function[mean_rate, parameter[self]]:
constant[
Returns the mean rate of the events since the start of the process.
]
if compare[name[self].counter.value equal[==] constant[0]] begin[:]
return[constant[0.0]] | keyword[def] identifier[mean_rate] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[counter] . identifier[value] == literal[int] :
keyword[return] literal[int]
keyword[else] :
identifier[elapsed] = identifier[time] ()- identifier[... | def mean_rate(self):
"""
Returns the mean rate of the events since the start of the process.
"""
if self.counter.value == 0:
return 0.0 # depends on [control=['if'], data=[]]
else:
elapsed = time() - self.start_time
return self.counter.value / elapsed |
def sine(x):
'''
sine(x) is equivalent to sin(x) except that it also works on sparse arrays.
'''
if sps.issparse(x):
x = x.copy()
x.data = np.sine(x.data)
return x
else: return np.sin(x) | def function[sine, parameter[x]]:
constant[
sine(x) is equivalent to sin(x) except that it also works on sparse arrays.
]
if call[name[sps].issparse, parameter[name[x]]] begin[:]
variable[x] assign[=] call[name[x].copy, parameter[]]
name[x].data assign[=] call[nam... | keyword[def] identifier[sine] ( identifier[x] ):
literal[string]
keyword[if] identifier[sps] . identifier[issparse] ( identifier[x] ):
identifier[x] = identifier[x] . identifier[copy] ()
identifier[x] . identifier[data] = identifier[np] . identifier[sine] ( identifier[x] . identifier[dat... | def sine(x):
"""
sine(x) is equivalent to sin(x) except that it also works on sparse arrays.
"""
if sps.issparse(x):
x = x.copy()
x.data = np.sine(x.data)
return x # depends on [control=['if'], data=[]]
else:
return np.sin(x) |
def GetMessages(self, formatter_mediator, event):
"""Determines the formatted message strings for an event object.
Args:
formatter_mediator (FormatterMediator): mediates the interactions
between formatters and other components, such as storage and Windows
EventLog resources.
eve... | def function[GetMessages, parameter[self, formatter_mediator, event]]:
constant[Determines the formatted message strings for an event object.
Args:
formatter_mediator (FormatterMediator): mediates the interactions
between formatters and other components, such as storage and Windows
... | keyword[def] identifier[GetMessages] ( identifier[self] , identifier[formatter_mediator] , identifier[event] ):
literal[string]
keyword[if] identifier[self] . identifier[DATA_TYPE] != identifier[event] . identifier[data_type] :
keyword[raise] identifier[errors] . identifier[WrongFormatter] ( liter... | def GetMessages(self, formatter_mediator, event):
"""Determines the formatted message strings for an event object.
Args:
formatter_mediator (FormatterMediator): mediates the interactions
between formatters and other components, such as storage and Windows
EventLog resources.
eve... |
def compareSNPs(before, after, outFileName):
"""Compares two set of SNPs.
:param before: the names of the markers in the ``before`` file.
:param after: the names of the markers in the ``after`` file.
:param outFileName: the name of the output file.
:type before: set
:type after: set
:type ... | def function[compareSNPs, parameter[before, after, outFileName]]:
constant[Compares two set of SNPs.
:param before: the names of the markers in the ``before`` file.
:param after: the names of the markers in the ``after`` file.
:param outFileName: the name of the output file.
:type before: set
... | keyword[def] identifier[compareSNPs] ( identifier[before] , identifier[after] , identifier[outFileName] ):
literal[string]
keyword[if] identifier[len] ( identifier[after] )> identifier[len] ( identifier[before] ):
identifier[msg] = literal[string]
keyword[raise] identifier[Program... | def compareSNPs(before, after, outFileName):
"""Compares two set of SNPs.
:param before: the names of the markers in the ``before`` file.
:param after: the names of the markers in the ``after`` file.
:param outFileName: the name of the output file.
:type before: set
:type after: set
:type ... |
def _read(self, directory, filename, session, path, name, extension, spatial, spatialReferenceID, replaceParamFile):
"""
Projection File Read from File Method
"""
# Set file extension property
self.fileExtension = extension
# Open file and parse into a data structure
... | def function[_read, parameter[self, directory, filename, session, path, name, extension, spatial, spatialReferenceID, replaceParamFile]]:
constant[
Projection File Read from File Method
]
name[self].fileExtension assign[=] name[extension]
with call[name[io_open], parameter[name[p... | keyword[def] identifier[_read] ( identifier[self] , identifier[directory] , identifier[filename] , identifier[session] , identifier[path] , identifier[name] , identifier[extension] , identifier[spatial] , identifier[spatialReferenceID] , identifier[replaceParamFile] ):
literal[string]
iden... | def _read(self, directory, filename, session, path, name, extension, spatial, spatialReferenceID, replaceParamFile):
"""
Projection File Read from File Method
"""
# Set file extension property
self.fileExtension = extension
# Open file and parse into a data structure
with io_open(pat... |
def light_general_attention(key, context, hidden_size, projected_align=False):
""" It is a implementation of the Luong et al. attention mechanism with general score. Based on the paper:
https://arxiv.org/abs/1508.04025 "Effective Approaches to Attention-based Neural Machine Translation"
Args:
ke... | def function[light_general_attention, parameter[key, context, hidden_size, projected_align]]:
constant[ It is a implementation of the Luong et al. attention mechanism with general score. Based on the paper:
https://arxiv.org/abs/1508.04025 "Effective Approaches to Attention-based Neural Machine Translat... | keyword[def] identifier[light_general_attention] ( identifier[key] , identifier[context] , identifier[hidden_size] , identifier[projected_align] = keyword[False] ):
literal[string]
identifier[batch_size] = identifier[tf] . identifier[shape] ( identifier[context] )[ literal[int] ]
identifier[max_num_to... | def light_general_attention(key, context, hidden_size, projected_align=False):
""" It is a implementation of the Luong et al. attention mechanism with general score. Based on the paper:
https://arxiv.org/abs/1508.04025 "Effective Approaches to Attention-based Neural Machine Translation"
Args:
ke... |
def ccmod_class_label_lookup(label):
"""Get a CCMOD class from a label string."""
clsmod = {'ism': admm_ccmod.ConvCnstrMOD_IterSM,
'cg': admm_ccmod.ConvCnstrMOD_CG,
'cns': admm_ccmod.ConvCnstrMOD_Consensus,
'fista': fista_ccmod.ConvCnstrMOD}
if label in clsmod:
... | def function[ccmod_class_label_lookup, parameter[label]]:
constant[Get a CCMOD class from a label string.]
variable[clsmod] assign[=] dictionary[[<ast.Constant object at 0x7da1b0798d90>, <ast.Constant object at 0x7da1b0798160>, <ast.Constant object at 0x7da1b0798910>, <ast.Constant object at 0x7da1b0798... | keyword[def] identifier[ccmod_class_label_lookup] ( identifier[label] ):
literal[string]
identifier[clsmod] ={ literal[string] : identifier[admm_ccmod] . identifier[ConvCnstrMOD_IterSM] ,
literal[string] : identifier[admm_ccmod] . identifier[ConvCnstrMOD_CG] ,
literal[string] : identifier[admm_c... | def ccmod_class_label_lookup(label):
"""Get a CCMOD class from a label string."""
clsmod = {'ism': admm_ccmod.ConvCnstrMOD_IterSM, 'cg': admm_ccmod.ConvCnstrMOD_CG, 'cns': admm_ccmod.ConvCnstrMOD_Consensus, 'fista': fista_ccmod.ConvCnstrMOD}
if label in clsmod:
return clsmod[label] # depends on [co... |
def used_labels(self):
""" Returns a list of required labels for this instruction
"""
result = []
tmp = self.asm.strip(' \n\r\t')
if not len(tmp) or tmp[0] in ('#', ';'):
return result
try:
tmpLexer = asmlex.lex.lex(object=asmlex.Lexer(), lextab=... | def function[used_labels, parameter[self]]:
constant[ Returns a list of required labels for this instruction
]
variable[result] assign[=] list[[]]
variable[tmp] assign[=] call[name[self].asm.strip, parameter[constant[
]]]
if <ast.BoolOp object at 0x7da18dc048b0> begin[:]
... | keyword[def] identifier[used_labels] ( identifier[self] ):
literal[string]
identifier[result] =[]
identifier[tmp] = identifier[self] . identifier[asm] . identifier[strip] ( literal[string] )
keyword[if] keyword[not] identifier[len] ( identifier[tmp] ) keyword[or] identifier[tm... | def used_labels(self):
""" Returns a list of required labels for this instruction
"""
result = []
tmp = self.asm.strip(' \n\r\t')
if not len(tmp) or tmp[0] in ('#', ';'):
return result # depends on [control=['if'], data=[]]
try:
tmpLexer = asmlex.lex.lex(object=asmlex.Lexer(... |
def set_items_shuffled(self, shuffle):
"""Sets the shuffle flag.
The shuffle flag may be overidden by other assessment sequencing
rules.
arg: shuffle (boolean): ``true`` if the items are shuffled,
``false`` if the items appear in the designated order
raise: ... | def function[set_items_shuffled, parameter[self, shuffle]]:
constant[Sets the shuffle flag.
The shuffle flag may be overidden by other assessment sequencing
rules.
arg: shuffle (boolean): ``true`` if the items are shuffled,
``false`` if the items appear in the design... | keyword[def] identifier[set_items_shuffled] ( identifier[self] , identifier[shuffle] ):
literal[string]
keyword[if] identifier[self] . identifier[get_items_shuffled_metadata] (). identifier[is_read_only] ():
keyword[raise] identifier[errors] . identifier[NoAccess] ()
... | def set_items_shuffled(self, shuffle):
"""Sets the shuffle flag.
The shuffle flag may be overidden by other assessment sequencing
rules.
arg: shuffle (boolean): ``true`` if the items are shuffled,
``false`` if the items appear in the designated order
raise: Inva... |
def addMargin(self, margin, index=None):
"""Adds a new margin.
index: index in the list of margins. Default: to the end of the list
"""
if index is None:
self._margins.append(margin)
else:
self._margins.insert(index, margin)
if margin.isVisible(... | def function[addMargin, parameter[self, margin, index]]:
constant[Adds a new margin.
index: index in the list of margins. Default: to the end of the list
]
if compare[name[index] is constant[None]] begin[:]
call[name[self]._margins.append, parameter[name[margin]]]
... | keyword[def] identifier[addMargin] ( identifier[self] , identifier[margin] , identifier[index] = keyword[None] ):
literal[string]
keyword[if] identifier[index] keyword[is] keyword[None] :
identifier[self] . identifier[_margins] . identifier[append] ( identifier[margin] )
ke... | def addMargin(self, margin, index=None):
"""Adds a new margin.
index: index in the list of margins. Default: to the end of the list
"""
if index is None:
self._margins.append(margin) # depends on [control=['if'], data=[]]
else:
self._margins.insert(index, margin)
if m... |
def _apply_decorators(func, decorators):
"""Apply a list of decorators to a given function.
``decorators`` may contain items that are ``None`` or ``False`` which will
be ignored.
"""
decorators = filter(_is_not_none_or_false, reversed(decorators))
for decorator in decorators:
func = de... | def function[_apply_decorators, parameter[func, decorators]]:
constant[Apply a list of decorators to a given function.
``decorators`` may contain items that are ``None`` or ``False`` which will
be ignored.
]
variable[decorators] assign[=] call[name[filter], parameter[name[_is_not_none_or_fa... | keyword[def] identifier[_apply_decorators] ( identifier[func] , identifier[decorators] ):
literal[string]
identifier[decorators] = identifier[filter] ( identifier[_is_not_none_or_false] , identifier[reversed] ( identifier[decorators] ))
keyword[for] identifier[decorator] keyword[in] identifier[dec... | def _apply_decorators(func, decorators):
"""Apply a list of decorators to a given function.
``decorators`` may contain items that are ``None`` or ``False`` which will
be ignored.
"""
decorators = filter(_is_not_none_or_false, reversed(decorators))
for decorator in decorators:
func = dec... |
def findRecordItem(self, record, parent=None):
"""
Looks through the tree hierarchy for the given record.
:param record | <orb.Record>
parent | <QTreeWidgetItem> || None
:return <XOrbRecordItem> || None
"""
try:
... | def function[findRecordItem, parameter[self, record, parent]]:
constant[
Looks through the tree hierarchy for the given record.
:param record | <orb.Record>
parent | <QTreeWidgetItem> || None
:return <XOrbRecordItem> || None
]
<a... | keyword[def] identifier[findRecordItem] ( identifier[self] , identifier[record] , identifier[parent] = keyword[None] ):
literal[string]
keyword[try] :
identifier[item] = identifier[self] . identifier[_recordMapping] [ identifier[record] ]()
keyword[except] identifier[KeyE... | def findRecordItem(self, record, parent=None):
"""
Looks through the tree hierarchy for the given record.
:param record | <orb.Record>
parent | <QTreeWidgetItem> || None
:return <XOrbRecordItem> || None
"""
try:
item = self._... |
def combine_columns(columns):
"""Combine ``columns`` into a single string.
Example:
>>> combine_columns(['eape', 'xml'])
'example'
Args:
columns (iterable): ordered columns to combine
Returns:
String of combined columns
"""
columns_zipped = itertools.zip_longes... | def function[combine_columns, parameter[columns]]:
constant[Combine ``columns`` into a single string.
Example:
>>> combine_columns(['eape', 'xml'])
'example'
Args:
columns (iterable): ordered columns to combine
Returns:
String of combined columns
]
vari... | keyword[def] identifier[combine_columns] ( identifier[columns] ):
literal[string]
identifier[columns_zipped] = identifier[itertools] . identifier[zip_longest] (* identifier[columns] )
keyword[return] literal[string] . identifier[join] ( identifier[x] keyword[for] identifier[zipped] keyword[in] id... | def combine_columns(columns):
"""Combine ``columns`` into a single string.
Example:
>>> combine_columns(['eape', 'xml'])
'example'
Args:
columns (iterable): ordered columns to combine
Returns:
String of combined columns
"""
columns_zipped = itertools.zip_longes... |
def _constraints_are_whitelisted(self, constraint_tuple):
"""
Detect whether a tuple of compatibility constraints
matches constraints imposed by the merged list of the global
constraints from PythonSetup and a user-supplied whitelist.
"""
if self._acceptable_interpreter_constraints == []:
... | def function[_constraints_are_whitelisted, parameter[self, constraint_tuple]]:
constant[
Detect whether a tuple of compatibility constraints
matches constraints imposed by the merged list of the global
constraints from PythonSetup and a user-supplied whitelist.
]
if compare[name[self]._a... | keyword[def] identifier[_constraints_are_whitelisted] ( identifier[self] , identifier[constraint_tuple] ):
literal[string]
keyword[if] identifier[self] . identifier[_acceptable_interpreter_constraints] ==[]:
keyword[return] keyword[True]
keyword[return] identifier[all] ( identifier[ver... | def _constraints_are_whitelisted(self, constraint_tuple):
"""
Detect whether a tuple of compatibility constraints
matches constraints imposed by the merged list of the global
constraints from PythonSetup and a user-supplied whitelist.
"""
if self._acceptable_interpreter_constraints == []:
... |
def save(self, filename):
"""
Save the current buffer to `filename`
Exisiting files with the same name will be overwritten.
:param str filename: the name of the file to save to
"""
with open(filename, "wb") as fd:
fd.write(self.__buff) | def function[save, parameter[self, filename]]:
constant[
Save the current buffer to `filename`
Exisiting files with the same name will be overwritten.
:param str filename: the name of the file to save to
]
with call[name[open], parameter[name[filename], constant[wb]]] b... | keyword[def] identifier[save] ( identifier[self] , identifier[filename] ):
literal[string]
keyword[with] identifier[open] ( identifier[filename] , literal[string] ) keyword[as] identifier[fd] :
identifier[fd] . identifier[write] ( identifier[self] . identifier[__buff] ) | def save(self, filename):
"""
Save the current buffer to `filename`
Exisiting files with the same name will be overwritten.
:param str filename: the name of the file to save to
"""
with open(filename, 'wb') as fd:
fd.write(self.__buff) # depends on [control=['with'], d... |
def length(self, error=ERROR, min_depth=MIN_DEPTH):
"""Calculate the length of the path up to a certain position"""
start_point = self.point(0)
end_point = self.point(1)
return segment_length(self, 0, 1, start_point, end_point, error, min_depth, 0) | def function[length, parameter[self, error, min_depth]]:
constant[Calculate the length of the path up to a certain position]
variable[start_point] assign[=] call[name[self].point, parameter[constant[0]]]
variable[end_point] assign[=] call[name[self].point, parameter[constant[1]]]
return[call... | keyword[def] identifier[length] ( identifier[self] , identifier[error] = identifier[ERROR] , identifier[min_depth] = identifier[MIN_DEPTH] ):
literal[string]
identifier[start_point] = identifier[self] . identifier[point] ( literal[int] )
identifier[end_point] = identifier[self] . identifie... | def length(self, error=ERROR, min_depth=MIN_DEPTH):
"""Calculate the length of the path up to a certain position"""
start_point = self.point(0)
end_point = self.point(1)
return segment_length(self, 0, 1, start_point, end_point, error, min_depth, 0) |
def api_request(
self,
method,
path,
query_params=None,
data=None,
content_type=None,
headers=None,
api_base_url=None,
api_version=None,
expect_json=True,
_target_object=None,
):
"""Make a request over the HTTP transport... | def function[api_request, parameter[self, method, path, query_params, data, content_type, headers, api_base_url, api_version, expect_json, _target_object]]:
constant[Make a request over the HTTP transport to the API.
You shouldn't need to use this method, but if you plan to
interact with the AP... | keyword[def] identifier[api_request] (
identifier[self] ,
identifier[method] ,
identifier[path] ,
identifier[query_params] = keyword[None] ,
identifier[data] = keyword[None] ,
identifier[content_type] = keyword[None] ,
identifier[headers] = keyword[None] ,
identifier[api_base_url] = keyword[None] ,
identifie... | def api_request(self, method, path, query_params=None, data=None, content_type=None, headers=None, api_base_url=None, api_version=None, expect_json=True, _target_object=None):
"""Make a request over the HTTP transport to the API.
You shouldn't need to use this method, but if you plan to
interact wi... |
def option2tuple(opt):
"""Return a tuple of option, taking possible presence of level into account"""
if isinstance(opt[0], int):
tup = opt[1], opt[2:]
else:
tup = opt[0], opt[1:]
return tup | def function[option2tuple, parameter[opt]]:
constant[Return a tuple of option, taking possible presence of level into account]
if call[name[isinstance], parameter[call[name[opt]][constant[0]], name[int]]] begin[:]
variable[tup] assign[=] tuple[[<ast.Subscript object at 0x7da2054a7580>, <... | keyword[def] identifier[option2tuple] ( identifier[opt] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[opt] [ literal[int] ], identifier[int] ):
identifier[tup] = identifier[opt] [ literal[int] ], identifier[opt] [ literal[int] :]
keyword[else] :
identifier[tup]... | def option2tuple(opt):
"""Return a tuple of option, taking possible presence of level into account"""
if isinstance(opt[0], int):
tup = (opt[1], opt[2:]) # depends on [control=['if'], data=[]]
else:
tup = (opt[0], opt[1:])
return tup |
def get_item_ids(self):
"""This is out of spec, but required for adaptive assessment parts?"""
item_ids = []
if self.has_items():
for idstr in self._my_map['itemIds']:
item_ids.append(idstr)
return IdList(item_ids) | def function[get_item_ids, parameter[self]]:
constant[This is out of spec, but required for adaptive assessment parts?]
variable[item_ids] assign[=] list[[]]
if call[name[self].has_items, parameter[]] begin[:]
for taget[name[idstr]] in starred[call[name[self]._my_map][constant[it... | keyword[def] identifier[get_item_ids] ( identifier[self] ):
literal[string]
identifier[item_ids] =[]
keyword[if] identifier[self] . identifier[has_items] ():
keyword[for] identifier[idstr] keyword[in] identifier[self] . identifier[_my_map] [ literal[string] ]:
... | def get_item_ids(self):
"""This is out of spec, but required for adaptive assessment parts?"""
item_ids = []
if self.has_items():
for idstr in self._my_map['itemIds']:
item_ids.append(idstr) # depends on [control=['for'], data=['idstr']] # depends on [control=['if'], data=[]]
retur... |
def align_with(self, other):
"""
Align the dataframe's index with another.
"""
return self.__class__(self.data.reindex_like(other), **self._kwargs) | def function[align_with, parameter[self, other]]:
constant[
Align the dataframe's index with another.
]
return[call[name[self].__class__, parameter[call[name[self].data.reindex_like, parameter[name[other]]]]]] | keyword[def] identifier[align_with] ( identifier[self] , identifier[other] ):
literal[string]
keyword[return] identifier[self] . identifier[__class__] ( identifier[self] . identifier[data] . identifier[reindex_like] ( identifier[other] ),** identifier[self] . identifier[_kwargs] ) | def align_with(self, other):
"""
Align the dataframe's index with another.
"""
return self.__class__(self.data.reindex_like(other), **self._kwargs) |
def cut_region(self, x, y, radius, data):
"""Return a cut region (radius) pixels away from (x, y) in (data).
"""
n = radius
ht, wd = data.shape
x0, x1 = max(0, x - n), min(wd - 1, x + n)
y0, y1 = max(0, y - n), min(ht - 1, y + n)
arr = data[y0:y1 + 1, x0:x1 + 1]
... | def function[cut_region, parameter[self, x, y, radius, data]]:
constant[Return a cut region (radius) pixels away from (x, y) in (data).
]
variable[n] assign[=] name[radius]
<ast.Tuple object at 0x7da20e957490> assign[=] name[data].shape
<ast.Tuple object at 0x7da20e956f80> assign... | keyword[def] identifier[cut_region] ( identifier[self] , identifier[x] , identifier[y] , identifier[radius] , identifier[data] ):
literal[string]
identifier[n] = identifier[radius]
identifier[ht] , identifier[wd] = identifier[data] . identifier[shape]
identifier[x0] , identifier... | def cut_region(self, x, y, radius, data):
"""Return a cut region (radius) pixels away from (x, y) in (data).
"""
n = radius
(ht, wd) = data.shape
(x0, x1) = (max(0, x - n), min(wd - 1, x + n))
(y0, y1) = (max(0, y - n), min(ht - 1, y + n))
arr = data[y0:y1 + 1, x0:x1 + 1]
return (x0,... |
def save_prov_to_files(self, showattributes=False):
"""
Write-out provn serialisation to nidm.provn.
"""
self.doc.add_bundle(self.bundle)
# provn_file = os.path.join(self.export_dir, 'nidm.provn')
# provn_fid = open(provn_file, 'w')
# # FIXME None
# # prov... | def function[save_prov_to_files, parameter[self, showattributes]]:
constant[
Write-out provn serialisation to nidm.provn.
]
call[name[self].doc.add_bundle, parameter[name[self].bundle]]
variable[ttl_file] assign[=] call[name[os].path.join, parameter[name[self].export_dir, constan... | keyword[def] identifier[save_prov_to_files] ( identifier[self] , identifier[showattributes] = keyword[False] ):
literal[string]
identifier[self] . identifier[doc] . identifier[add_bundle] ( identifier[self] . identifier[bundle] )
identifier[ttl... | def save_prov_to_files(self, showattributes=False):
"""
Write-out provn serialisation to nidm.provn.
"""
self.doc.add_bundle(self.bundle)
# provn_file = os.path.join(self.export_dir, 'nidm.provn')
# provn_fid = open(provn_file, 'w')
# # FIXME None
# # provn_fid.write(self.doc.get... |
def possible_version_evaluation(self):
"""Evaluate the possible range of versions for each target, yielding the output analysis."""
only_broken = self.get_options().only_broken
ranges = self._ranges
yield 'Allowable JVM platform ranges (* = anything):'
for target in sorted(filter(self._is_relevant, ... | def function[possible_version_evaluation, parameter[self]]:
constant[Evaluate the possible range of versions for each target, yielding the output analysis.]
variable[only_broken] assign[=] call[name[self].get_options, parameter[]].only_broken
variable[ranges] assign[=] name[self]._ranges
... | keyword[def] identifier[possible_version_evaluation] ( identifier[self] ):
literal[string]
identifier[only_broken] = identifier[self] . identifier[get_options] (). identifier[only_broken]
identifier[ranges] = identifier[self] . identifier[_ranges]
keyword[yield] literal[string]
keyword[f... | def possible_version_evaluation(self):
"""Evaluate the possible range of versions for each target, yielding the output analysis."""
only_broken = self.get_options().only_broken
ranges = self._ranges
yield 'Allowable JVM platform ranges (* = anything):'
for target in sorted(filter(self._is_relevant, ... |
def tcp_traceflow(packet, *, count=NotImplemented):
"""Trace packet flow for TCP."""
if 'TCP' in packet:
ip = packet['IP'] if 'IP' in packet else packet['IPv6']
tcp = packet['TCP']
data = dict(
protocol=LINKTYPE.get(packet.name.upper()), # data link type from global heade... | def function[tcp_traceflow, parameter[packet]]:
constant[Trace packet flow for TCP.]
if compare[constant[TCP] in name[packet]] begin[:]
variable[ip] assign[=] <ast.IfExp object at 0x7da1b060b190>
variable[tcp] assign[=] call[name[packet]][constant[TCP]]
va... | keyword[def] identifier[tcp_traceflow] ( identifier[packet] ,*, identifier[count] = identifier[NotImplemented] ):
literal[string]
keyword[if] literal[string] keyword[in] identifier[packet] :
identifier[ip] = identifier[packet] [ literal[string] ] keyword[if] literal[string] keyword[in] ident... | def tcp_traceflow(packet, *, count=NotImplemented):
"""Trace packet flow for TCP."""
if 'TCP' in packet:
ip = packet['IP'] if 'IP' in packet else packet['IPv6']
tcp = packet['TCP'] # data link type from global header
# frame number
# extracted packet
# TCP synchronise (S... |
def get_curie(self, uri):
'''Get a CURIE from a URI '''
prefix = self.get_curie_prefix(uri)
if prefix is not None:
key = self.curie_map[prefix]
return '%s:%s' % (prefix, uri[len(key):len(uri)])
return None | def function[get_curie, parameter[self, uri]]:
constant[Get a CURIE from a URI ]
variable[prefix] assign[=] call[name[self].get_curie_prefix, parameter[name[uri]]]
if compare[name[prefix] is_not constant[None]] begin[:]
variable[key] assign[=] call[name[self].curie_map][name[pref... | keyword[def] identifier[get_curie] ( identifier[self] , identifier[uri] ):
literal[string]
identifier[prefix] = identifier[self] . identifier[get_curie_prefix] ( identifier[uri] )
keyword[if] identifier[prefix] keyword[is] keyword[not] keyword[None] :
identifier[key] = ide... | def get_curie(self, uri):
"""Get a CURIE from a URI """
prefix = self.get_curie_prefix(uri)
if prefix is not None:
key = self.curie_map[prefix]
return '%s:%s' % (prefix, uri[len(key):len(uri)]) # depends on [control=['if'], data=['prefix']]
return None |
def longest_interval(self) -> Optional[Interval]:
"""
Returns the longest interval, or ``None`` if none.
"""
longest_duration = self.longest_duration()
for i in self.intervals:
if i.duration() == longest_duration:
return i
return None | def function[longest_interval, parameter[self]]:
constant[
Returns the longest interval, or ``None`` if none.
]
variable[longest_duration] assign[=] call[name[self].longest_duration, parameter[]]
for taget[name[i]] in starred[name[self].intervals] begin[:]
if comp... | keyword[def] identifier[longest_interval] ( identifier[self] )-> identifier[Optional] [ identifier[Interval] ]:
literal[string]
identifier[longest_duration] = identifier[self] . identifier[longest_duration] ()
keyword[for] identifier[i] keyword[in] identifier[self] . identifier[interval... | def longest_interval(self) -> Optional[Interval]:
"""
Returns the longest interval, or ``None`` if none.
"""
longest_duration = self.longest_duration()
for i in self.intervals:
if i.duration() == longest_duration:
return i # depends on [control=['if'], data=[]] # depend... |
def describe_jobflow(self, jobflow_id):
"""
Describes a single Elastic MapReduce job flow
:type jobflow_id: str
:param jobflow_id: The job flow id of interest
"""
jobflows = self.describe_jobflows(jobflow_ids=[jobflow_id])
if jobflows:
return jobflows... | def function[describe_jobflow, parameter[self, jobflow_id]]:
constant[
Describes a single Elastic MapReduce job flow
:type jobflow_id: str
:param jobflow_id: The job flow id of interest
]
variable[jobflows] assign[=] call[name[self].describe_jobflows, parameter[]]
... | keyword[def] identifier[describe_jobflow] ( identifier[self] , identifier[jobflow_id] ):
literal[string]
identifier[jobflows] = identifier[self] . identifier[describe_jobflows] ( identifier[jobflow_ids] =[ identifier[jobflow_id] ])
keyword[if] identifier[jobflows] :
keyword[r... | def describe_jobflow(self, jobflow_id):
"""
Describes a single Elastic MapReduce job flow
:type jobflow_id: str
:param jobflow_id: The job flow id of interest
"""
jobflows = self.describe_jobflows(jobflow_ids=[jobflow_id])
if jobflows:
return jobflows[0] # depends o... |
def install_integration(self, id, **kwargs): # noqa: E501
"""Installs a Wavefront integration # noqa: E501
# noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.install_integrat... | def function[install_integration, parameter[self, id]]:
constant[Installs a Wavefront integration # noqa: E501
# noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.install_integ... | keyword[def] identifier[install_integration] ( identifier[self] , identifier[id] ,** identifier[kwargs] ):
literal[string]
identifier[kwargs] [ literal[string] ]= keyword[True]
keyword[if] identifier[kwargs] . identifier[get] ( literal[string] ):
keyword[return] identifier[... | def install_integration(self, id, **kwargs): # noqa: E501
'Installs a Wavefront integration # noqa: E501\n\n # noqa: E501\n This method makes a synchronous HTTP request by default. To make an\n asynchronous HTTP request, please pass async_req=True\n >>> thread = api.install_integrati... |
def copy_current_app_context(func: Callable) -> Callable:
"""Share the current app context with the function decorated.
The app context is local per task and hence will not be available
in any other task. This decorator can be used to make the context
available,
.. code-block:: python
@co... | def function[copy_current_app_context, parameter[func]]:
constant[Share the current app context with the function decorated.
The app context is local per task and hence will not be available
in any other task. This decorator can be used to make the context
available,
.. code-block:: python
... | keyword[def] identifier[copy_current_app_context] ( identifier[func] : identifier[Callable] )-> identifier[Callable] :
literal[string]
keyword[if] keyword[not] identifier[has_app_context] ():
keyword[raise] identifier[RuntimeError] ( literal[string] )
identifier[app_context] = identifier[... | def copy_current_app_context(func: Callable) -> Callable:
"""Share the current app context with the function decorated.
The app context is local per task and hence will not be available
in any other task. This decorator can be used to make the context
available,
.. code-block:: python
@co... |
def make_table_map(table, headers):
"""Create a function to map from rows with the structure of the headers to the structure of the table."""
header_parts = {}
for i, h in enumerate(headers):
header_parts[h] = 'row[{}]'.format(i)
body_code = 'lambda row: [{}]'.format(','.join(header_parts.get(... | def function[make_table_map, parameter[table, headers]]:
constant[Create a function to map from rows with the structure of the headers to the structure of the table.]
variable[header_parts] assign[=] dictionary[[], []]
for taget[tuple[[<ast.Name object at 0x7da204347190>, <ast.Name object at 0x7... | keyword[def] identifier[make_table_map] ( identifier[table] , identifier[headers] ):
literal[string]
identifier[header_parts] ={}
keyword[for] identifier[i] , identifier[h] keyword[in] identifier[enumerate] ( identifier[headers] ):
identifier[header_parts] [ identifier[h] ]= literal[strin... | def make_table_map(table, headers):
"""Create a function to map from rows with the structure of the headers to the structure of the table."""
header_parts = {}
for (i, h) in enumerate(headers):
header_parts[h] = 'row[{}]'.format(i) # depends on [control=['for'], data=[]]
body_code = 'lambda row... |
def decompose_covariance(c):
"""
This decomposes a covariance matrix into an error vector and a correlation matrix
"""
# make it a kickass copy of the original
c = _n.array(c)
# first get the error vector
e = []
for n in range(0, len(c[0])): e.append(_n.sqrt(c[n][n]))
# now cycle ... | def function[decompose_covariance, parameter[c]]:
constant[
This decomposes a covariance matrix into an error vector and a correlation matrix
]
variable[c] assign[=] call[name[_n].array, parameter[name[c]]]
variable[e] assign[=] list[[]]
for taget[name[n]] in starred[call[name[ra... | keyword[def] identifier[decompose_covariance] ( identifier[c] ):
literal[string]
identifier[c] = identifier[_n] . identifier[array] ( identifier[c] )
identifier[e] =[]
keyword[for] identifier[n] keyword[in] identifier[range] ( literal[int] , identifier[len] ( identifier[c] [ litera... | def decompose_covariance(c):
"""
This decomposes a covariance matrix into an error vector and a correlation matrix
"""
# make it a kickass copy of the original
c = _n.array(c)
# first get the error vector
e = []
for n in range(0, len(c[0])):
e.append(_n.sqrt(c[n][n])) # depends ... |
def getSymmetricallyEncryptedVal(val, secretKey: Union[str, bytes] = None) -> \
Tuple[str, str]:
"""
Encrypt the provided value with symmetric encryption
:param val: the value to encrypt
:param secretKey: Optional key, if provided should be either in hex or bytes
:return: Tuple of the encry... | def function[getSymmetricallyEncryptedVal, parameter[val, secretKey]]:
constant[
Encrypt the provided value with symmetric encryption
:param val: the value to encrypt
:param secretKey: Optional key, if provided should be either in hex or bytes
:return: Tuple of the encrypted value and secret ke... | keyword[def] identifier[getSymmetricallyEncryptedVal] ( identifier[val] , identifier[secretKey] : identifier[Union] [ identifier[str] , identifier[bytes] ]= keyword[None] )-> identifier[Tuple] [ identifier[str] , identifier[str] ]:
literal[string]
keyword[if] identifier[isinstance] ( identifier[val] , id... | def getSymmetricallyEncryptedVal(val, secretKey: Union[str, bytes]=None) -> Tuple[str, str]:
"""
Encrypt the provided value with symmetric encryption
:param val: the value to encrypt
:param secretKey: Optional key, if provided should be either in hex or bytes
:return: Tuple of the encrypted value a... |
def set_connection_params(self, address, local_tsap, remote_tsap):
"""
Sets internally (IP, LocalTSAP, RemoteTSAP) Coordinates.
This function must be called just before Cli_Connect().
:param address: PLC/Equipment IPV4 Address, for example "192.168.1.12"
:param local_tsap: Local... | def function[set_connection_params, parameter[self, address, local_tsap, remote_tsap]]:
constant[
Sets internally (IP, LocalTSAP, RemoteTSAP) Coordinates.
This function must be called just before Cli_Connect().
:param address: PLC/Equipment IPV4 Address, for example "192.168.1.12"
... | keyword[def] identifier[set_connection_params] ( identifier[self] , identifier[address] , identifier[local_tsap] , identifier[remote_tsap] ):
literal[string]
keyword[assert] identifier[re] . identifier[match] ( identifier[ipv4] , identifier[address] ), literal[string] % identifier[address]
... | def set_connection_params(self, address, local_tsap, remote_tsap):
"""
Sets internally (IP, LocalTSAP, RemoteTSAP) Coordinates.
This function must be called just before Cli_Connect().
:param address: PLC/Equipment IPV4 Address, for example "192.168.1.12"
:param local_tsap: Local TSA... |
def movav(y, Dx, dx):
"""
Moving average rectangular window filter:
calculate average of signal y by using sliding rectangular
window of size Dx using binsize dx
Parameters
----------
y : numpy.ndarray
Signal
Dx : float
Window length of filter.
dx : float
... | def function[movav, parameter[y, Dx, dx]]:
constant[
Moving average rectangular window filter:
calculate average of signal y by using sliding rectangular
window of size Dx using binsize dx
Parameters
----------
y : numpy.ndarray
Signal
Dx : float
Window leng... | keyword[def] identifier[movav] ( identifier[y] , identifier[Dx] , identifier[dx] ):
literal[string]
keyword[if] identifier[Dx] <= identifier[dx] :
keyword[return] identifier[y]
keyword[else] :
identifier[ly] = identifier[len] ( identifier[y] )
identifier[r] = identifier[n... | def movav(y, Dx, dx):
"""
Moving average rectangular window filter:
calculate average of signal y by using sliding rectangular
window of size Dx using binsize dx
Parameters
----------
y : numpy.ndarray
Signal
Dx : float
Window length of filter.
dx : float
... |
def Add(self, value, *optional):
"""
Overload ROOT's basic TList::Add to support supplying
TListItemWithOption
"""
if isinstance(value, TListItemWithOption):
if optional:
raise RuntimeError(
"option specified along with "
... | def function[Add, parameter[self, value]]:
constant[
Overload ROOT's basic TList::Add to support supplying
TListItemWithOption
]
if call[name[isinstance], parameter[name[value], name[TListItemWithOption]]] begin[:]
if name[optional] begin[:]
<ast.Raise... | keyword[def] identifier[Add] ( identifier[self] , identifier[value] ,* identifier[optional] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[value] , identifier[TListItemWithOption] ):
keyword[if] identifier[optional] :
keyword[raise] identifier[Ru... | def Add(self, value, *optional):
"""
Overload ROOT's basic TList::Add to support supplying
TListItemWithOption
"""
if isinstance(value, TListItemWithOption):
if optional:
raise RuntimeError('option specified along with TListItemWithOption. Specify one or the other but... |
def set_classifier_mask(self, v, base_mask=True):
"""Computes the mask used to create the training and validation set"""
base = self._base
v = tonparray(v)
a = np.unique(v)
if a[0] != -1 or a[1] != 1:
raise RuntimeError("The labels must be -1 and 1 (%s)" % a)
... | def function[set_classifier_mask, parameter[self, v, base_mask]]:
constant[Computes the mask used to create the training and validation set]
variable[base] assign[=] name[self]._base
variable[v] assign[=] call[name[tonparray], parameter[name[v]]]
variable[a] assign[=] call[name[np].uniqu... | keyword[def] identifier[set_classifier_mask] ( identifier[self] , identifier[v] , identifier[base_mask] = keyword[True] ):
literal[string]
identifier[base] = identifier[self] . identifier[_base]
identifier[v] = identifier[tonparray] ( identifier[v] )
identifier[a] = identifier[np... | def set_classifier_mask(self, v, base_mask=True):
"""Computes the mask used to create the training and validation set"""
base = self._base
v = tonparray(v)
a = np.unique(v)
if a[0] != -1 or a[1] != 1:
raise RuntimeError('The labels must be -1 and 1 (%s)' % a) # depends on [control=['if'], d... |
def hide_defaults(self):
"""Removes fields' values that are the same as default values."""
# use list(): self.fields is modified in the loop
for k, v in list(six.iteritems(self.fields)):
v = self.fields[k]
if k in self.default_fields:
if self.default_field... | def function[hide_defaults, parameter[self]]:
constant[Removes fields' values that are the same as default values.]
for taget[tuple[[<ast.Name object at 0x7da1b2195e40>, <ast.Name object at 0x7da1b2194490>]]] in starred[call[name[list], parameter[call[name[six].iteritems, parameter[name[self].fields]]]]... | keyword[def] identifier[hide_defaults] ( identifier[self] ):
literal[string]
keyword[for] identifier[k] , identifier[v] keyword[in] identifier[list] ( identifier[six] . identifier[iteritems] ( identifier[self] . identifier[fields] )):
identifier[v] = identifier[self] . iden... | def hide_defaults(self):
"""Removes fields' values that are the same as default values."""
# use list(): self.fields is modified in the loop
for (k, v) in list(six.iteritems(self.fields)):
v = self.fields[k]
if k in self.default_fields:
if self.default_fields[k] == v:
... |
def _ParseRecurseKeys(self, parser_mediator, root_key):
"""Parses the Registry keys recursively.
Args:
parser_mediator (ParserMediator): parser mediator.
root_key (dfwinreg.WinRegistryKey): root Windows Registry key.
"""
for registry_key in root_key.RecurseKeys():
if parser_mediator.a... | def function[_ParseRecurseKeys, parameter[self, parser_mediator, root_key]]:
constant[Parses the Registry keys recursively.
Args:
parser_mediator (ParserMediator): parser mediator.
root_key (dfwinreg.WinRegistryKey): root Windows Registry key.
]
for taget[name[registry_key]] in star... | keyword[def] identifier[_ParseRecurseKeys] ( identifier[self] , identifier[parser_mediator] , identifier[root_key] ):
literal[string]
keyword[for] identifier[registry_key] keyword[in] identifier[root_key] . identifier[RecurseKeys] ():
keyword[if] identifier[parser_mediator] . identifier[abort] :... | def _ParseRecurseKeys(self, parser_mediator, root_key):
"""Parses the Registry keys recursively.
Args:
parser_mediator (ParserMediator): parser mediator.
root_key (dfwinreg.WinRegistryKey): root Windows Registry key.
"""
for registry_key in root_key.RecurseKeys():
if parser_mediator... |
def GetHostMemMappedMB(self):
'''Undocumented.'''
counter = c_uint()
ret = vmGuestLib.VMGuestLib_GetHostMemMappedMB(self.handle.value, byref(counter))
if ret != VMGUESTLIB_ERROR_SUCCESS: raise VMGuestLibException(ret)
return counter.value | def function[GetHostMemMappedMB, parameter[self]]:
constant[Undocumented.]
variable[counter] assign[=] call[name[c_uint], parameter[]]
variable[ret] assign[=] call[name[vmGuestLib].VMGuestLib_GetHostMemMappedMB, parameter[name[self].handle.value, call[name[byref], parameter[name[counter]]]]]
... | keyword[def] identifier[GetHostMemMappedMB] ( identifier[self] ):
literal[string]
identifier[counter] = identifier[c_uint] ()
identifier[ret] = identifier[vmGuestLib] . identifier[VMGuestLib_GetHostMemMappedMB] ( identifier[self] . identifier[handle] . identifier[value] , identifier[byref]... | def GetHostMemMappedMB(self):
"""Undocumented."""
counter = c_uint()
ret = vmGuestLib.VMGuestLib_GetHostMemMappedMB(self.handle.value, byref(counter))
if ret != VMGUESTLIB_ERROR_SUCCESS:
raise VMGuestLibException(ret) # depends on [control=['if'], data=['ret']]
return counter.value |
def kl(self):
r'''Thermal conductivity of the mixture in the liquid phase at its current
temperature, pressure, and composition in units of [Pa*s].
For calculation of this property at other temperatures and pressures,
or specifying manually the method used to calculate it, and more - se... | def function[kl, parameter[self]]:
constant[Thermal conductivity of the mixture in the liquid phase at its current
temperature, pressure, and composition in units of [Pa*s].
For calculation of this property at other temperatures and pressures,
or specifying manually the method used to c... | keyword[def] identifier[kl] ( identifier[self] ):
literal[string]
keyword[return] identifier[self] . identifier[ThermalConductivityLiquidMixture] ( identifier[self] . identifier[T] , identifier[self] . identifier[P] , identifier[self] . identifier[zs] , identifier[self] . identifier[ws] ) | def kl(self):
"""Thermal conductivity of the mixture in the liquid phase at its current
temperature, pressure, and composition in units of [Pa*s].
For calculation of this property at other temperatures and pressures,
or specifying manually the method used to calculate it, and more - see
... |
def _interval_sum(interval, start=None, end=None, context=None):
""" Return sum of intervals between "R"esume and "P"aused events
in C{interval}, optionally limited by a time window defined
by C{start} and C{end}. Return ``None`` if there's no sensible
information.
C{interval} is a ... | def function[_interval_sum, parameter[interval, start, end, context]]:
constant[ Return sum of intervals between "R"esume and "P"aused events
in C{interval}, optionally limited by a time window defined
by C{start} and C{end}. Return ``None`` if there's no sensible
information.
C... | keyword[def] identifier[_interval_sum] ( identifier[interval] , identifier[start] = keyword[None] , identifier[end] = keyword[None] , identifier[context] = keyword[None] ):
literal[string]
identifier[end] = identifier[float] ( identifier[end] ) keyword[if] identifier[end] keyword[else] identifier[time] ... | def _interval_sum(interval, start=None, end=None, context=None):
""" Return sum of intervals between "R"esume and "P"aused events
in C{interval}, optionally limited by a time window defined
by C{start} and C{end}. Return ``None`` if there's no sensible
information.
C{interval} is a ... |
def transfer_pos_tags(self):
"""Returns an list of tuples of the form (word, POS tag), using transfer POS tagger"""
tagged_words = []
for word,t in self.transfer_pos_tagger.annotate(self.words):
word.pos_tag = t
tagged_words.append((word, t))
return tagged_words | def function[transfer_pos_tags, parameter[self]]:
constant[Returns an list of tuples of the form (word, POS tag), using transfer POS tagger]
variable[tagged_words] assign[=] list[[]]
for taget[tuple[[<ast.Name object at 0x7da20cabeb30>, <ast.Name object at 0x7da20cabdb10>]]] in starred[call[nam... | keyword[def] identifier[transfer_pos_tags] ( identifier[self] ):
literal[string]
identifier[tagged_words] =[]
keyword[for] identifier[word] , identifier[t] keyword[in] identifier[self] . identifier[transfer_pos_tagger] . identifier[annotate] ( identifier[self] . identifier[words] ):
identifi... | def transfer_pos_tags(self):
"""Returns an list of tuples of the form (word, POS tag), using transfer POS tagger"""
tagged_words = []
for (word, t) in self.transfer_pos_tagger.annotate(self.words):
word.pos_tag = t
tagged_words.append((word, t)) # depends on [control=['for'], data=[]]
... |
def available(name):
'''
Return True if the named service is available.
CLI Example:
.. code-block:: bash
salt '*' service.available sshd
'''
cmd = '{0} get {1}'.format(_cmd(), name)
if __salt__['cmd.retcode'](cmd) == 2:
return False
return True | def function[available, parameter[name]]:
constant[
Return True if the named service is available.
CLI Example:
.. code-block:: bash
salt '*' service.available sshd
]
variable[cmd] assign[=] call[constant[{0} get {1}].format, parameter[call[name[_cmd], parameter[]], name[name]... | keyword[def] identifier[available] ( identifier[name] ):
literal[string]
identifier[cmd] = literal[string] . identifier[format] ( identifier[_cmd] (), identifier[name] )
keyword[if] identifier[__salt__] [ literal[string] ]( identifier[cmd] )== literal[int] :
keyword[return] keyword[False]
... | def available(name):
"""
Return True if the named service is available.
CLI Example:
.. code-block:: bash
salt '*' service.available sshd
"""
cmd = '{0} get {1}'.format(_cmd(), name)
if __salt__['cmd.retcode'](cmd) == 2:
return False # depends on [control=['if'], data=[]]... |
def apply_one_hot_encoding(self, one_hot_encoding):
"""Apply one hot encoding to generate a specific config.
Arguments:
one_hot_encoding (list): A list of one hot encodings,
1 for each parameter. The shape of each encoding
should match that ``ParameterSpace`... | def function[apply_one_hot_encoding, parameter[self, one_hot_encoding]]:
constant[Apply one hot encoding to generate a specific config.
Arguments:
one_hot_encoding (list): A list of one hot encodings,
1 for each parameter. The shape of each encoding
should m... | keyword[def] identifier[apply_one_hot_encoding] ( identifier[self] , identifier[one_hot_encoding] ):
literal[string]
identifier[config] ={}
keyword[for] identifier[ps] , identifier[one_hot] keyword[in] identifier[zip] ( identifier[self] . identifier[param_list] , identifier[one_hot_enco... | def apply_one_hot_encoding(self, one_hot_encoding):
"""Apply one hot encoding to generate a specific config.
Arguments:
one_hot_encoding (list): A list of one hot encodings,
1 for each parameter. The shape of each encoding
should match that ``ParameterSpace``
... |
def addHandler(name, basepath=None, baseurl=None, allowDownscale=False):
"""Add an event handler with given name."""
if basepath is None:
basepath = '.'
_handlers.append(_handler_classes[name](basepath, baseurl, allowDownscale)) | def function[addHandler, parameter[name, basepath, baseurl, allowDownscale]]:
constant[Add an event handler with given name.]
if compare[name[basepath] is constant[None]] begin[:]
variable[basepath] assign[=] constant[.]
call[name[_handlers].append, parameter[call[call[name[_hand... | keyword[def] identifier[addHandler] ( identifier[name] , identifier[basepath] = keyword[None] , identifier[baseurl] = keyword[None] , identifier[allowDownscale] = keyword[False] ):
literal[string]
keyword[if] identifier[basepath] keyword[is] keyword[None] :
identifier[basepath] = literal[string... | def addHandler(name, basepath=None, baseurl=None, allowDownscale=False):
"""Add an event handler with given name."""
if basepath is None:
basepath = '.' # depends on [control=['if'], data=['basepath']]
_handlers.append(_handler_classes[name](basepath, baseurl, allowDownscale)) |
def delete_model(self, key, ignoreMissingKey=True, timeoutSecs=60, **kwargs):
'''
Delete a model on the h2o cluster, given its key.
'''
assert key is not None, '"key" parameter is null'
result = self.do_json_request('/3/Models.json/' + key, cmd='delete', timeout=timeoutSecs)
# TODO: look for w... | def function[delete_model, parameter[self, key, ignoreMissingKey, timeoutSecs]]:
constant[
Delete a model on the h2o cluster, given its key.
]
assert[compare[name[key] is_not constant[None]]]
variable[result] assign[=] call[name[self].do_json_request, parameter[binary_operation[constant[/3/M... | keyword[def] identifier[delete_model] ( identifier[self] , identifier[key] , identifier[ignoreMissingKey] = keyword[True] , identifier[timeoutSecs] = literal[int] ,** identifier[kwargs] ):
literal[string]
keyword[assert] identifier[key] keyword[is] keyword[not] keyword[None] , literal[string]
id... | def delete_model(self, key, ignoreMissingKey=True, timeoutSecs=60, **kwargs):
"""
Delete a model on the h2o cluster, given its key.
"""
assert key is not None, '"key" parameter is null'
result = self.do_json_request('/3/Models.json/' + key, cmd='delete', timeout=timeoutSecs)
# TODO: look for wha... |
def summarize_sv(items):
"""CWL target: summarize structural variants for multiple samples.
XXX Need to support non-VCF output as tabix indexed output
"""
items = [utils.to_single_data(x) for x in vcvalidate.summarize_grading(items, "svvalidate")]
out = {"sv": {"calls": [],
"suppl... | def function[summarize_sv, parameter[items]]:
constant[CWL target: summarize structural variants for multiple samples.
XXX Need to support non-VCF output as tabix indexed output
]
variable[items] assign[=] <ast.ListComp object at 0x7da1b17a5750>
variable[out] assign[=] dictionary[[<ast.... | keyword[def] identifier[summarize_sv] ( identifier[items] ):
literal[string]
identifier[items] =[ identifier[utils] . identifier[to_single_data] ( identifier[x] ) keyword[for] identifier[x] keyword[in] identifier[vcvalidate] . identifier[summarize_grading] ( identifier[items] , literal[string] )]
i... | def summarize_sv(items):
"""CWL target: summarize structural variants for multiple samples.
XXX Need to support non-VCF output as tabix indexed output
"""
items = [utils.to_single_data(x) for x in vcvalidate.summarize_grading(items, 'svvalidate')]
out = {'sv': {'calls': [], 'supplemental': [], 'pri... |
def rethrow(self, msg, _type=InvalidResourceException):
"""
Raises an exception with custom type and modified error message.
Raised exception is based on current exc_info() and carries it's traceback
@type msg: str
@param msg: New error message
@type _type: type
... | def function[rethrow, parameter[self, msg, _type]]:
constant[
Raises an exception with custom type and modified error message.
Raised exception is based on current exc_info() and carries it's traceback
@type msg: str
@param msg: New error message
@type _type: type
... | keyword[def] identifier[rethrow] ( identifier[self] , identifier[msg] , identifier[_type] = identifier[InvalidResourceException] ):
literal[string]
identifier[exc_type] , identifier[exc_value] , identifier[exc_traceback] = identifier[sys] . identifier[exc_info] ()
identifier[msg] = identif... | def rethrow(self, msg, _type=InvalidResourceException):
"""
Raises an exception with custom type and modified error message.
Raised exception is based on current exc_info() and carries it's traceback
@type msg: str
@param msg: New error message
@type _type: type
@pa... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.