code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def main(demo=False, aschild=False, targets=[]):
"""Start the Qt-runtime and show the window
Arguments:
aschild (bool, optional): Run as child of parent process
"""
if aschild:
print("Starting pyblish-qml")
compat.main()
app = Application(APP_PATH, targets)
app... | def function[main, parameter[demo, aschild, targets]]:
constant[Start the Qt-runtime and show the window
Arguments:
aschild (bool, optional): Run as child of parent process
]
if name[aschild] begin[:]
call[name[print], parameter[constant[Starting pyblish-qml]]]
... | keyword[def] identifier[main] ( identifier[demo] = keyword[False] , identifier[aschild] = keyword[False] , identifier[targets] =[]):
literal[string]
keyword[if] identifier[aschild] :
identifier[print] ( literal[string] )
identifier[compat] . identifier[main] ()
identifier[app] ... | def main(demo=False, aschild=False, targets=[]):
"""Start the Qt-runtime and show the window
Arguments:
aschild (bool, optional): Run as child of parent process
"""
if aschild:
print('Starting pyblish-qml')
compat.main()
app = Application(APP_PATH, targets)
app.... |
def register_on_show_window(self, callback):
"""Set the callback function to consume on show window events.
This occurs when the console window is to be activated and brought to
the foreground of the desktop of the host PC.
Callback receives a IShowWindowEvent object.
Returns t... | def function[register_on_show_window, parameter[self, callback]]:
constant[Set the callback function to consume on show window events.
This occurs when the console window is to be activated and brought to
the foreground of the desktop of the host PC.
Callback receives a IShowWindowEvent... | keyword[def] identifier[register_on_show_window] ( identifier[self] , identifier[callback] ):
literal[string]
identifier[event_type] = identifier[library] . identifier[VBoxEventType] . identifier[on_show_window]
keyword[return] identifier[self] . identifier[event_source] . identifier[reg... | def register_on_show_window(self, callback):
"""Set the callback function to consume on show window events.
This occurs when the console window is to be activated and brought to
the foreground of the desktop of the host PC.
Callback receives a IShowWindowEvent object.
Returns the c... |
def open_dut(self, port=None):
"""
Open connection to dut.
:param port: com port to use.
:return:
"""
if port is not None:
self.comport = port
try:
self.open_connection()
except (DutConnectionError, ValueError) as err:
... | def function[open_dut, parameter[self, port]]:
constant[
Open connection to dut.
:param port: com port to use.
:return:
]
if compare[name[port] is_not constant[None]] begin[:]
name[self].comport assign[=] name[port]
<ast.Try object at 0x7da20e956710> | keyword[def] identifier[open_dut] ( identifier[self] , identifier[port] = keyword[None] ):
literal[string]
keyword[if] identifier[port] keyword[is] keyword[not] keyword[None] :
identifier[self] . identifier[comport] = identifier[port]
keyword[try] :
identifi... | def open_dut(self, port=None):
"""
Open connection to dut.
:param port: com port to use.
:return:
"""
if port is not None:
self.comport = port # depends on [control=['if'], data=['port']]
try:
self.open_connection() # depends on [control=['try'], data=[]]
... |
def run(self):
"""Main service entrypoint. Called via Thread.start() via PantsDaemon.run()."""
while not self._state.is_terminating:
self._maybe_garbage_collect()
self._maybe_extend_lease()
# Waiting with a timeout in maybe_pause has the effect of waiting until:
# 1) we are paused and th... | def function[run, parameter[self]]:
constant[Main service entrypoint. Called via Thread.start() via PantsDaemon.run().]
while <ast.UnaryOp object at 0x7da1b2278340> begin[:]
call[name[self]._maybe_garbage_collect, parameter[]]
call[name[self]._maybe_extend_lease, paramete... | keyword[def] identifier[run] ( identifier[self] ):
literal[string]
keyword[while] keyword[not] identifier[self] . identifier[_state] . identifier[is_terminating] :
identifier[self] . identifier[_maybe_garbage_collect] ()
identifier[self] . identifier[_maybe_extend_lease] ()
... | def run(self):
"""Main service entrypoint. Called via Thread.start() via PantsDaemon.run()."""
while not self._state.is_terminating:
self._maybe_garbage_collect()
self._maybe_extend_lease()
# Waiting with a timeout in maybe_pause has the effect of waiting until:
# 1) we are pause... |
def handleOneClientMsg(self, wrappedMsg):
"""
Validate and process a client message
:param wrappedMsg: a message from a client
"""
try:
vmsg = self.validateClientMsg(wrappedMsg)
if vmsg:
self.unpackClientMsg(*vmsg)
except BlowUp:
... | def function[handleOneClientMsg, parameter[self, wrappedMsg]]:
constant[
Validate and process a client message
:param wrappedMsg: a message from a client
]
<ast.Try object at 0x7da204962320> | keyword[def] identifier[handleOneClientMsg] ( identifier[self] , identifier[wrappedMsg] ):
literal[string]
keyword[try] :
identifier[vmsg] = identifier[self] . identifier[validateClientMsg] ( identifier[wrappedMsg] )
keyword[if] identifier[vmsg] :
identif... | def handleOneClientMsg(self, wrappedMsg):
"""
Validate and process a client message
:param wrappedMsg: a message from a client
"""
try:
vmsg = self.validateClientMsg(wrappedMsg)
if vmsg:
self.unpackClientMsg(*vmsg) # depends on [control=['if'], data=[]] # d... |
def _plunge(tasks, pausing, finish):
"""
(internal) calls the next method of weaved tasks until they are finished
or The ``Plumber`` instance is stopped see: ``Dagger.chinkup``.
"""
# If no result received either not started or start & stop
# could have been called before... | def function[_plunge, parameter[tasks, pausing, finish]]:
constant[
(internal) calls the next method of weaved tasks until they are finished
or The ``Plumber`` instance is stopped see: ``Dagger.chinkup``.
]
while constant[True] begin[:]
if call[name[pausing], para... | keyword[def] identifier[_plunge] ( identifier[tasks] , identifier[pausing] , identifier[finish] ):
literal[string]
keyword[while] keyword[True] :
keyword[if] identifier[pausing] ():
identifier[tasks] . identifier[stop] ()
keyword[try] :... | def _plunge(tasks, pausing, finish):
"""
(internal) calls the next method of weaved tasks until they are finished
or The ``Plumber`` instance is stopped see: ``Dagger.chinkup``.
"""
# If no result received either not started or start & stop
# could have been called before the plunger... |
def _check_dn(self, dn, attr_value):
"""Check dn attribute for issues."""
if dn is not None:
self._error('Two lines starting with dn: in one record.')
if not is_dn(attr_value):
self._error('No valid string-representation of '
'distinguished name %s.' % att... | def function[_check_dn, parameter[self, dn, attr_value]]:
constant[Check dn attribute for issues.]
if compare[name[dn] is_not constant[None]] begin[:]
call[name[self]._error, parameter[constant[Two lines starting with dn: in one record.]]]
if <ast.UnaryOp object at 0x7da1b1b0d540... | keyword[def] identifier[_check_dn] ( identifier[self] , identifier[dn] , identifier[attr_value] ):
literal[string]
keyword[if] identifier[dn] keyword[is] keyword[not] keyword[None] :
identifier[self] . identifier[_error] ( literal[string] )
keyword[if] keyword[not] ident... | def _check_dn(self, dn, attr_value):
"""Check dn attribute for issues."""
if dn is not None:
self._error('Two lines starting with dn: in one record.') # depends on [control=['if'], data=[]]
if not is_dn(attr_value):
self._error('No valid string-representation of distinguished name %s.' % at... |
def MatchBuildContext(self,
target_os,
target_arch,
target_package,
context=None):
"""Return true if target_platforms matches the supplied parameters.
Used by buildanddeploy to determine what clients need to be buil... | def function[MatchBuildContext, parameter[self, target_os, target_arch, target_package, context]]:
constant[Return true if target_platforms matches the supplied parameters.
Used by buildanddeploy to determine what clients need to be built.
Args:
target_os: which os we are building for in this ru... | keyword[def] identifier[MatchBuildContext] ( identifier[self] ,
identifier[target_os] ,
identifier[target_arch] ,
identifier[target_package] ,
identifier[context] = keyword[None] ):
literal[string]
keyword[for] identifier[spec] keyword[in] identifier[self] . identifier[Get] ( literal[string] , ident... | def MatchBuildContext(self, target_os, target_arch, target_package, context=None):
"""Return true if target_platforms matches the supplied parameters.
Used by buildanddeploy to determine what clients need to be built.
Args:
target_os: which os we are building for in this run (linux, windows,
... |
def set_mask(self, context_len, context):
"""
sets self.mask which is applied before softmax
ones for inactive context fields, zeros for active context fields
:param context_len: b
:param context: if batch_first: (b x t_k x n) else: (t_k x b x n)
self.mask: (b x t_k)
... | def function[set_mask, parameter[self, context_len, context]]:
constant[
sets self.mask which is applied before softmax
ones for inactive context fields, zeros for active context fields
:param context_len: b
:param context: if batch_first: (b x t_k x n) else: (t_k x b x n)
... | keyword[def] identifier[set_mask] ( identifier[self] , identifier[context_len] , identifier[context] ):
literal[string]
keyword[if] identifier[self] . identifier[batch_first] :
identifier[max_len] = identifier[context] . identifier[size] ( literal[int] )
keyword[else] :
... | def set_mask(self, context_len, context):
"""
sets self.mask which is applied before softmax
ones for inactive context fields, zeros for active context fields
:param context_len: b
:param context: if batch_first: (b x t_k x n) else: (t_k x b x n)
self.mask: (b x t_k)
... |
def get_state(self, scaling_group):
"""
Returns the current state of the specified scaling group as a
dictionary.
"""
uri = "/%s/%s/state" % (self.uri_base, utils.get_id(scaling_group))
resp, resp_body = self.api.method_get(uri)
data = resp_body["group"]
r... | def function[get_state, parameter[self, scaling_group]]:
constant[
Returns the current state of the specified scaling group as a
dictionary.
]
variable[uri] assign[=] binary_operation[constant[/%s/%s/state] <ast.Mod object at 0x7da2590d6920> tuple[[<ast.Attribute object at 0x7da1... | keyword[def] identifier[get_state] ( identifier[self] , identifier[scaling_group] ):
literal[string]
identifier[uri] = literal[string] %( identifier[self] . identifier[uri_base] , identifier[utils] . identifier[get_id] ( identifier[scaling_group] ))
identifier[resp] , identifier[resp_body]... | def get_state(self, scaling_group):
"""
Returns the current state of the specified scaling group as a
dictionary.
"""
uri = '/%s/%s/state' % (self.uri_base, utils.get_id(scaling_group))
(resp, resp_body) = self.api.method_get(uri)
data = resp_body['group']
ret = {}
ret['a... |
def unused_port(hostname):
"""Return a port that is unused on the current host."""
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind((hostname, 0))
return s.getsockname()[1] | def function[unused_port, parameter[hostname]]:
constant[Return a port that is unused on the current host.]
with call[name[socket].socket, parameter[name[socket].AF_INET, name[socket].SOCK_STREAM]] begin[:]
call[name[s].bind, parameter[tuple[[<ast.Name object at 0x7da1b0791ab0>, <ast.Con... | keyword[def] identifier[unused_port] ( identifier[hostname] ):
literal[string]
keyword[with] identifier[socket] . identifier[socket] ( identifier[socket] . identifier[AF_INET] , identifier[socket] . identifier[SOCK_STREAM] ) keyword[as] identifier[s] :
identifier[s] . identifier[bind] (( identif... | def unused_port(hostname):
"""Return a port that is unused on the current host."""
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind((hostname, 0))
return s.getsockname()[1] # depends on [control=['with'], data=['s']] |
def extract_endpoint_arguments(endpoint):
"""Extract the argument documentation from the endpoint."""
ep_args = endpoint._arguments
if ep_args is None:
return None
arg_docs = { k: format_endpoint_argument_doc(a) \
for k, a in ep_args.iteritems() }
return arg_docs | def function[extract_endpoint_arguments, parameter[endpoint]]:
constant[Extract the argument documentation from the endpoint.]
variable[ep_args] assign[=] name[endpoint]._arguments
if compare[name[ep_args] is constant[None]] begin[:]
return[constant[None]]
variable[arg_docs] assi... | keyword[def] identifier[extract_endpoint_arguments] ( identifier[endpoint] ):
literal[string]
identifier[ep_args] = identifier[endpoint] . identifier[_arguments]
keyword[if] identifier[ep_args] keyword[is] keyword[None] :
keyword[return] keyword[None]
identifier[arg_docs] ={ iden... | def extract_endpoint_arguments(endpoint):
"""Extract the argument documentation from the endpoint."""
ep_args = endpoint._arguments
if ep_args is None:
return None # depends on [control=['if'], data=[]]
arg_docs = {k: format_endpoint_argument_doc(a) for (k, a) in ep_args.iteritems()}
return... |
def _find_convertable_object(self, data):
"""
Get the first instance of a `self.pod_types`
"""
data = list(data)
convertable_object_idxs = [
idx
for idx, obj
in enumerate(data)
if obj.get('kind') in self.pod_types.keys()
]
... | def function[_find_convertable_object, parameter[self, data]]:
constant[
Get the first instance of a `self.pod_types`
]
variable[data] assign[=] call[name[list], parameter[name[data]]]
variable[convertable_object_idxs] assign[=] <ast.ListComp object at 0x7da2041d8cd0>
if ... | keyword[def] identifier[_find_convertable_object] ( identifier[self] , identifier[data] ):
literal[string]
identifier[data] = identifier[list] ( identifier[data] )
identifier[convertable_object_idxs] =[
identifier[idx]
keyword[for] identifier[idx] , identifier[obj]
... | def _find_convertable_object(self, data):
"""
Get the first instance of a `self.pod_types`
"""
data = list(data)
convertable_object_idxs = [idx for (idx, obj) in enumerate(data) if obj.get('kind') in self.pod_types.keys()]
if len(convertable_object_idxs) < 1:
raise Exception("Kub... |
def __parse_tostr(self, text, **kwargs):
'''Builds and returns the MeCab function for parsing Unicode text.
Args:
fn_name: MeCab function name that determines the function
behavior, either 'mecab_sparse_tostr' or
'mecab_nbest_sparse_tostr'.
Returns:
... | def function[__parse_tostr, parameter[self, text]]:
constant[Builds and returns the MeCab function for parsing Unicode text.
Args:
fn_name: MeCab function name that determines the function
behavior, either 'mecab_sparse_tostr' or
'mecab_nbest_sparse_tostr'.
... | keyword[def] identifier[__parse_tostr] ( identifier[self] , identifier[text] ,** identifier[kwargs] ):
literal[string]
identifier[n] = identifier[self] . identifier[options] . identifier[get] ( literal[string] , literal[int] )
keyword[if] identifier[self] . identifier[_KW_BOUNDARY] keyw... | def __parse_tostr(self, text, **kwargs):
"""Builds and returns the MeCab function for parsing Unicode text.
Args:
fn_name: MeCab function name that determines the function
behavior, either 'mecab_sparse_tostr' or
'mecab_nbest_sparse_tostr'.
Returns:
... |
def debug_callback(event, *args, **kwds):
'''Example callback, useful for debugging.
'''
l = ['event %s' % (event.type,)]
if args:
l.extend(map(str, args))
if kwds:
l.extend(sorted('%s=%s' % t for t in kwds.items()))
print('Debug callback (%s)' % ', '.join(l)) | def function[debug_callback, parameter[event]]:
constant[Example callback, useful for debugging.
]
variable[l] assign[=] list[[<ast.BinOp object at 0x7da1b162b5b0>]]
if name[args] begin[:]
call[name[l].extend, parameter[call[name[map], parameter[name[str], name[args]]]]]
... | keyword[def] identifier[debug_callback] ( identifier[event] ,* identifier[args] ,** identifier[kwds] ):
literal[string]
identifier[l] =[ literal[string] %( identifier[event] . identifier[type] ,)]
keyword[if] identifier[args] :
identifier[l] . identifier[extend] ( identifier[map] ( identifie... | def debug_callback(event, *args, **kwds):
"""Example callback, useful for debugging.
"""
l = ['event %s' % (event.type,)]
if args:
l.extend(map(str, args)) # depends on [control=['if'], data=[]]
if kwds:
l.extend(sorted(('%s=%s' % t for t in kwds.items()))) # depends on [control=['... |
def _get_cursor(self, n_retries=1):
"""Returns a context manager for obtained from a single or pooled
connection, and sets the PostgreSQL search_path to the schema
specified in the connection URL.
Although *connections* are threadsafe, *cursors* are bound to
connections and are ... | def function[_get_cursor, parameter[self, n_retries]]:
constant[Returns a context manager for obtained from a single or pooled
connection, and sets the PostgreSQL search_path to the schema
specified in the connection URL.
Although *connections* are threadsafe, *cursors* are bound to
... | keyword[def] identifier[_get_cursor] ( identifier[self] , identifier[n_retries] = literal[int] ):
literal[string]
identifier[n_tries_rem] = identifier[n_retries] + literal[int]
keyword[while] identifier[n_tries_rem] > literal[int] :
keyword[try] :
identifi... | def _get_cursor(self, n_retries=1):
"""Returns a context manager for obtained from a single or pooled
connection, and sets the PostgreSQL search_path to the schema
specified in the connection URL.
Although *connections* are threadsafe, *cursors* are bound to
connections and are *not... |
def attribute(path, name):
"""Returns the two numbers found behind --[A-Z] in path. If several matches
are found, the last one is returned.
Parameters
----------
path : string
String with path of file/folder to get attribute from.
name : string
Name of attribute to get. Should b... | def function[attribute, parameter[path, name]]:
constant[Returns the two numbers found behind --[A-Z] in path. If several matches
are found, the last one is returned.
Parameters
----------
path : string
String with path of file/folder to get attribute from.
name : string
Nam... | keyword[def] identifier[attribute] ( identifier[path] , identifier[name] ):
literal[string]
identifier[matches] = identifier[re] . identifier[findall] ( literal[string] + identifier[name] . identifier[upper] ()+ literal[string] , identifier[path] )
keyword[if] identifier[matches] :
keyword[r... | def attribute(path, name):
"""Returns the two numbers found behind --[A-Z] in path. If several matches
are found, the last one is returned.
Parameters
----------
path : string
String with path of file/folder to get attribute from.
name : string
Name of attribute to get. Should b... |
def get_cg_volumes(self, group_id):
""" return all non snapshots volumes in cg """
for volume in self.xcli_client.cmd.vol_list(cg=group_id):
if volume.snapshot_of == '':
yield volume.name | def function[get_cg_volumes, parameter[self, group_id]]:
constant[ return all non snapshots volumes in cg ]
for taget[name[volume]] in starred[call[name[self].xcli_client.cmd.vol_list, parameter[]]] begin[:]
if compare[name[volume].snapshot_of equal[==] constant[]] begin[:]
... | keyword[def] identifier[get_cg_volumes] ( identifier[self] , identifier[group_id] ):
literal[string]
keyword[for] identifier[volume] keyword[in] identifier[self] . identifier[xcli_client] . identifier[cmd] . identifier[vol_list] ( identifier[cg] = identifier[group_id] ):
keyword[... | def get_cg_volumes(self, group_id):
""" return all non snapshots volumes in cg """
for volume in self.xcli_client.cmd.vol_list(cg=group_id):
if volume.snapshot_of == '':
yield volume.name # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['volume']] |
def fsroot(self):
"""Returns the file system root."""
if self.osname == 'windows':
return '{}:\\'.format(
self._handler.inspect_get_drive_mappings(self._root)[0][0])
else:
return self._handler.inspect_get_mountpoints(self._root)[0][0] | def function[fsroot, parameter[self]]:
constant[Returns the file system root.]
if compare[name[self].osname equal[==] constant[windows]] begin[:]
return[call[constant[{}:\].format, parameter[call[call[call[name[self]._handler.inspect_get_drive_mappings, parameter[name[self]._root]]][constant[0]]... | keyword[def] identifier[fsroot] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[osname] == literal[string] :
keyword[return] literal[string] . identifier[format] (
identifier[self] . identifier[_handler] . identifier[inspect_get_drive_mapp... | def fsroot(self):
"""Returns the file system root."""
if self.osname == 'windows':
return '{}:\\'.format(self._handler.inspect_get_drive_mappings(self._root)[0][0]) # depends on [control=['if'], data=[]]
else:
return self._handler.inspect_get_mountpoints(self._root)[0][0] |
def plot_decision_boundary(model, X, y, step=0.1, figsize=(10, 8), alpha=0.4, size=20):
"""Plots the classification decision boundary of `model` on `X` with labels `y`.
Using numpy and matplotlib.
"""
x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1
y_min, y_max = X[:, 1].min() - 1, X[:, 1].max(... | def function[plot_decision_boundary, parameter[model, X, y, step, figsize, alpha, size]]:
constant[Plots the classification decision boundary of `model` on `X` with labels `y`.
Using numpy and matplotlib.
]
<ast.Tuple object at 0x7da1b1e091e0> assign[=] tuple[[<ast.BinOp object at 0x7da1b1e08c40... | keyword[def] identifier[plot_decision_boundary] ( identifier[model] , identifier[X] , identifier[y] , identifier[step] = literal[int] , identifier[figsize] =( literal[int] , literal[int] ), identifier[alpha] = literal[int] , identifier[size] = literal[int] ):
literal[string]
identifier[x_min] , identifier... | def plot_decision_boundary(model, X, y, step=0.1, figsize=(10, 8), alpha=0.4, size=20):
"""Plots the classification decision boundary of `model` on `X` with labels `y`.
Using numpy and matplotlib.
"""
(x_min, x_max) = (X[:, 0].min() - 1, X[:, 0].max() + 1)
(y_min, y_max) = (X[:, 1].min() - 1, X[:, 1... |
def search_domain(self, searchterm):
"""Search for domains
:type searchterm: str
:rtype: list
"""
return self.__search(type_attribute=self.__mispdomaintypes(), value=searchterm) | def function[search_domain, parameter[self, searchterm]]:
constant[Search for domains
:type searchterm: str
:rtype: list
]
return[call[name[self].__search, parameter[]]] | keyword[def] identifier[search_domain] ( identifier[self] , identifier[searchterm] ):
literal[string]
keyword[return] identifier[self] . identifier[__search] ( identifier[type_attribute] = identifier[self] . identifier[__mispdomaintypes] (), identifier[value] = identifier[searchterm] ) | def search_domain(self, searchterm):
"""Search for domains
:type searchterm: str
:rtype: list
"""
return self.__search(type_attribute=self.__mispdomaintypes(), value=searchterm) |
def patSiemensStar(s0, n=72, vhigh=255, vlow=0, antiasing=False):
'''make line pattern'''
arr = np.full((s0,s0),vlow, dtype=np.uint8)
c = int(round(s0/2.))
s = 2*np.pi/(2*n)
step = 0
for i in range(2*n):
p0 = round(c+np.sin(step)*2*s0)
p1 = round(c+np.cos(step)*2*s0)
... | def function[patSiemensStar, parameter[s0, n, vhigh, vlow, antiasing]]:
constant[make line pattern]
variable[arr] assign[=] call[name[np].full, parameter[tuple[[<ast.Name object at 0x7da20c991a20>, <ast.Name object at 0x7da20c992050>]], name[vlow]]]
variable[c] assign[=] call[name[int], paramete... | keyword[def] identifier[patSiemensStar] ( identifier[s0] , identifier[n] = literal[int] , identifier[vhigh] = literal[int] , identifier[vlow] = literal[int] , identifier[antiasing] = keyword[False] ):
literal[string]
identifier[arr] = identifier[np] . identifier[full] (( identifier[s0] , identifier[s0] )... | def patSiemensStar(s0, n=72, vhigh=255, vlow=0, antiasing=False):
"""make line pattern"""
arr = np.full((s0, s0), vlow, dtype=np.uint8)
c = int(round(s0 / 2.0))
s = 2 * np.pi / (2 * n)
step = 0
for i in range(2 * n):
p0 = round(c + np.sin(step) * 2 * s0)
p1 = round(c + np.cos(ste... |
def GetVectorAsNumpy(numpy_type, buf, count, offset):
""" GetVecAsNumpy decodes values starting at buf[head] as
`numpy_type`, where `numpy_type` is a numpy dtype. """
if np is not None:
# TODO: could set .flags.writeable = False to make users jump through
# hoops before modifying...
... | def function[GetVectorAsNumpy, parameter[numpy_type, buf, count, offset]]:
constant[ GetVecAsNumpy decodes values starting at buf[head] as
`numpy_type`, where `numpy_type` is a numpy dtype. ]
if compare[name[np] is_not constant[None]] begin[:]
return[call[name[np].frombuffer, parameter[name[... | keyword[def] identifier[GetVectorAsNumpy] ( identifier[numpy_type] , identifier[buf] , identifier[count] , identifier[offset] ):
literal[string]
keyword[if] identifier[np] keyword[is] keyword[not] keyword[None] :
keyword[return] identifier[np] . identifier[frombuffer] ( identifier[b... | def GetVectorAsNumpy(numpy_type, buf, count, offset):
""" GetVecAsNumpy decodes values starting at buf[head] as
`numpy_type`, where `numpy_type` is a numpy dtype. """
if np is not None:
# TODO: could set .flags.writeable = False to make users jump through
# hoops before modifying...
... |
def extract(self, file_name: str, sheet_name: str, region: List, variables: Dict) -> List[Extraction]:
"""
Args:
file_name (str): file name
sheet_name (str): sheet name
region (List[]): from upper left cell to bottom right cell, e.g., ['A,1', 'Z,10']
varia... | def function[extract, parameter[self, file_name, sheet_name, region, variables]]:
constant[
Args:
file_name (str): file name
sheet_name (str): sheet name
region (List[]): from upper left cell to bottom right cell, e.g., ['A,1', 'Z,10']
variables (Dict): ke... | keyword[def] identifier[extract] ( identifier[self] , identifier[file_name] : identifier[str] , identifier[sheet_name] : identifier[str] , identifier[region] : identifier[List] , identifier[variables] : identifier[Dict] )-> identifier[List] [ identifier[Extraction] ]:
literal[string]
identifier[ext... | def extract(self, file_name: str, sheet_name: str, region: List, variables: Dict) -> List[Extraction]:
"""
Args:
file_name (str): file name
sheet_name (str): sheet name
region (List[]): from upper left cell to bottom right cell, e.g., ['A,1', 'Z,10']
variables... |
def parse_options():
"""
Parses command-line options:
"""
try:
opts, args = getopt.getopt(sys.argv[1:],
'k:n:ht:v',
['kval=',
'size=',
'help',
... | def function[parse_options, parameter[]]:
constant[
Parses command-line options:
]
<ast.Try object at 0x7da1b112acb0>
variable[kval] assign[=] constant[1]
variable[size] assign[=] constant[8]
variable[ftype] assign[=] constant[php]
variable[verb] assign[=] constan... | keyword[def] identifier[parse_options] ():
literal[string]
keyword[try] :
identifier[opts] , identifier[args] = identifier[getopt] . identifier[getopt] ( identifier[sys] . identifier[argv] [ literal[int] :],
literal[string] ,
[ literal[string] ,
literal[string] ,
... | def parse_options():
"""
Parses command-line options:
"""
try:
(opts, args) = getopt.getopt(sys.argv[1:], 'k:n:ht:v', ['kval=', 'size=', 'help', 'type=', 'verb']) # depends on [control=['try'], data=[]]
except getopt.GetoptError as err:
sys.stderr.write(str(err).capitalize())
... |
def fromPy(cls, val, typeObj, vldMask=None):
"""
:param val: value of python type int or None
:param typeObj: instance of Integer
:param vldMask: None vldMask is resolved from val,
if is 0 value is invalidated
if is 1 value has to be valid
"""
asse... | def function[fromPy, parameter[cls, val, typeObj, vldMask]]:
constant[
:param val: value of python type int or None
:param typeObj: instance of Integer
:param vldMask: None vldMask is resolved from val,
if is 0 value is invalidated
if is 1 value has to be valid
... | keyword[def] identifier[fromPy] ( identifier[cls] , identifier[val] , identifier[typeObj] , identifier[vldMask] = keyword[None] ):
literal[string]
keyword[assert] identifier[isinstance] ( identifier[typeObj] , identifier[Integer] )
identifier[vld] = identifier[int] ( identifier[val] keyw... | def fromPy(cls, val, typeObj, vldMask=None):
"""
:param val: value of python type int or None
:param typeObj: instance of Integer
:param vldMask: None vldMask is resolved from val,
if is 0 value is invalidated
if is 1 value has to be valid
"""
assert isins... |
def clear_published(self):
"""Removes the published status.
:raise: ``NoAccess`` -- ``Metadata.isRequired()`` is ``true`` or ``Metadata.isReadOnly()`` is ``true``
*compliance: mandatory -- This method must be implemented.*
"""
metadata = Metadata(**settings.METADATA['published... | def function[clear_published, parameter[self]]:
constant[Removes the published status.
:raise: ``NoAccess`` -- ``Metadata.isRequired()`` is ``true`` or ``Metadata.isReadOnly()`` is ``true``
*compliance: mandatory -- This method must be implemented.*
]
variable[metadata] assign... | keyword[def] identifier[clear_published] ( identifier[self] ):
literal[string]
identifier[metadata] = identifier[Metadata] (** identifier[settings] . identifier[METADATA] [ literal[string] ])
keyword[if] identifier[metadata] . identifier[is_read_only] () keyword[or] identifier[metadata] ... | def clear_published(self):
"""Removes the published status.
:raise: ``NoAccess`` -- ``Metadata.isRequired()`` is ``true`` or ``Metadata.isReadOnly()`` is ``true``
*compliance: mandatory -- This method must be implemented.*
"""
metadata = Metadata(**settings.METADATA['published'])
... |
def _read_body_by_chunk(self, response, file, raw=False):
'''Read the connection using chunked transfer encoding.
Coroutine.
'''
reader = ChunkedTransferReader(self._connection)
file_is_async = hasattr(file, 'drain')
while True:
chunk_size, data = yield fro... | def function[_read_body_by_chunk, parameter[self, response, file, raw]]:
constant[Read the connection using chunked transfer encoding.
Coroutine.
]
variable[reader] assign[=] call[name[ChunkedTransferReader], parameter[name[self]._connection]]
variable[file_is_async] assign[=] c... | keyword[def] identifier[_read_body_by_chunk] ( identifier[self] , identifier[response] , identifier[file] , identifier[raw] = keyword[False] ):
literal[string]
identifier[reader] = identifier[ChunkedTransferReader] ( identifier[self] . identifier[_connection] )
identifier[file_is_async] =... | def _read_body_by_chunk(self, response, file, raw=False):
"""Read the connection using chunked transfer encoding.
Coroutine.
"""
reader = ChunkedTransferReader(self._connection)
file_is_async = hasattr(file, 'drain')
while True:
(chunk_size, data) = (yield from reader.read_chunk... |
def cross_validate(self, ax):
'''
Performs the cross-validation step.
'''
# The CDPP to beat
cdpp_opt = self.get_cdpp_arr()
# Loop over all chunks
for b, brkpt in enumerate(self.breakpoints):
log.info("Cross-validating chunk %d/%d..." %
... | def function[cross_validate, parameter[self, ax]]:
constant[
Performs the cross-validation step.
]
variable[cdpp_opt] assign[=] call[name[self].get_cdpp_arr, parameter[]]
for taget[tuple[[<ast.Name object at 0x7da1b0e553f0>, <ast.Name object at 0x7da1b0e55420>]]] in starred[call... | keyword[def] identifier[cross_validate] ( identifier[self] , identifier[ax] ):
literal[string]
identifier[cdpp_opt] = identifier[self] . identifier[get_cdpp_arr] ()
keyword[for] identifier[b] , identifier[brkpt] keyword[in] identifier[enumerate] ( identifier[self] . ... | def cross_validate(self, ax):
"""
Performs the cross-validation step.
"""
# The CDPP to beat
cdpp_opt = self.get_cdpp_arr()
# Loop over all chunks
for (b, brkpt) in enumerate(self.breakpoints):
log.info('Cross-validating chunk %d/%d...' % (b + 1, len(self.breakpoints)))
... |
def auto_display_limits(self):
"""Calculate best display limits and set them."""
display_data_and_metadata = self.get_calculated_display_values(True).display_data_and_metadata
data = display_data_and_metadata.data if display_data_and_metadata else None
if data is not None:
# ... | def function[auto_display_limits, parameter[self]]:
constant[Calculate best display limits and set them.]
variable[display_data_and_metadata] assign[=] call[name[self].get_calculated_display_values, parameter[constant[True]]].display_data_and_metadata
variable[data] assign[=] <ast.IfExp object a... | keyword[def] identifier[auto_display_limits] ( identifier[self] ):
literal[string]
identifier[display_data_and_metadata] = identifier[self] . identifier[get_calculated_display_values] ( keyword[True] ). identifier[display_data_and_metadata]
identifier[data] = identifier[display_data_and_m... | def auto_display_limits(self):
"""Calculate best display limits and set them."""
display_data_and_metadata = self.get_calculated_display_values(True).display_data_and_metadata
data = display_data_and_metadata.data if display_data_and_metadata else None
if data is not None:
# The old algorithm wa... |
def halt(self, checkpoint=None, finished=False, raise_error=True):
"""
Stop the pipeline before completion point.
:param str checkpoint: Name of stage just reached or just completed.
:param bool finished: Whether the indicated stage was just finished
(True), or just reached ... | def function[halt, parameter[self, checkpoint, finished, raise_error]]:
constant[
Stop the pipeline before completion point.
:param str checkpoint: Name of stage just reached or just completed.
:param bool finished: Whether the indicated stage was just finished
(True), or ju... | keyword[def] identifier[halt] ( identifier[self] , identifier[checkpoint] = keyword[None] , identifier[finished] = keyword[False] , identifier[raise_error] = keyword[True] ):
literal[string]
identifier[self] . identifier[stop_pipeline] ( identifier[PAUSE_FLAG] )
identifier[self] . identifi... | def halt(self, checkpoint=None, finished=False, raise_error=True):
"""
Stop the pipeline before completion point.
:param str checkpoint: Name of stage just reached or just completed.
:param bool finished: Whether the indicated stage was just finished
(True), or just reached (Fal... |
def _check_create_parameters(self, **kwargs):
"""Override method for one in resource.py to check partition
The partition cannot be included as a parameter to create a guest.
Raise an exception if a consumer gives the partition parameter.
:raises: DisallowedCreationParameter
"""... | def function[_check_create_parameters, parameter[self]]:
constant[Override method for one in resource.py to check partition
The partition cannot be included as a parameter to create a guest.
Raise an exception if a consumer gives the partition parameter.
:raises: DisallowedCreationPara... | keyword[def] identifier[_check_create_parameters] ( identifier[self] ,** identifier[kwargs] ):
literal[string]
keyword[if] literal[string] keyword[in] identifier[kwargs] :
identifier[msg] = literal[string] literal[string]
keyword[raise] identifier[DisallowedCreation... | def _check_create_parameters(self, **kwargs):
"""Override method for one in resource.py to check partition
The partition cannot be included as a parameter to create a guest.
Raise an exception if a consumer gives the partition parameter.
:raises: DisallowedCreationParameter
"""
... |
def _connection_parameters(self):
"""Return connection parameters for a pika connection.
:rtype: pika.ConnectionParameters
"""
return pika.ConnectionParameters(
self.config.get('host', 'localhost'),
self.config.get('port', 5672),
self.config.get('vho... | def function[_connection_parameters, parameter[self]]:
constant[Return connection parameters for a pika connection.
:rtype: pika.ConnectionParameters
]
return[call[name[pika].ConnectionParameters, parameter[call[name[self].config.get, parameter[constant[host], constant[localhost]]], call[n... | keyword[def] identifier[_connection_parameters] ( identifier[self] ):
literal[string]
keyword[return] identifier[pika] . identifier[ConnectionParameters] (
identifier[self] . identifier[config] . identifier[get] ( literal[string] , literal[string] ),
identifier[self] . identifier... | def _connection_parameters(self):
"""Return connection parameters for a pika connection.
:rtype: pika.ConnectionParameters
"""
return pika.ConnectionParameters(self.config.get('host', 'localhost'), self.config.get('port', 5672), self.config.get('vhost', '/'), pika.PlainCredentials(self.config.... |
def dot_product(t1, t2, keep_dims=False, name=None, reduction_dim=None):
"""Computes the dot product of t1 and t2.
Args:
t1: A rank 2 tensor.
t2: A tensor that is the same size as t1.
keep_dims: If true, reduction does not change the rank of the input.
name: Optional name for this op.
reduction... | def function[dot_product, parameter[t1, t2, keep_dims, name, reduction_dim]]:
constant[Computes the dot product of t1 and t2.
Args:
t1: A rank 2 tensor.
t2: A tensor that is the same size as t1.
keep_dims: If true, reduction does not change the rank of the input.
name: Optional name for this ... | keyword[def] identifier[dot_product] ( identifier[t1] , identifier[t2] , identifier[keep_dims] = keyword[False] , identifier[name] = keyword[None] , identifier[reduction_dim] = keyword[None] ):
literal[string]
keyword[with] identifier[tf] . identifier[name_scope] ( identifier[name] , literal[string] ,[ identi... | def dot_product(t1, t2, keep_dims=False, name=None, reduction_dim=None):
"""Computes the dot product of t1 and t2.
Args:
t1: A rank 2 tensor.
t2: A tensor that is the same size as t1.
keep_dims: If true, reduction does not change the rank of the input.
name: Optional name for this op.
reducti... |
def _clean_path(path):
"""Create a fully fissile absolute system path with no symbolic links and environment variables"""
path = path.replace('"', '')
path = path.replace("'", '')
# Replace ~ with /home/user
path = os.path.expanduser(path)
# Replace environment variables
... | def function[_clean_path, parameter[path]]:
constant[Create a fully fissile absolute system path with no symbolic links and environment variables]
variable[path] assign[=] call[name[path].replace, parameter[constant["], constant[]]]
variable[path] assign[=] call[name[path].replace, parameter[con... | keyword[def] identifier[_clean_path] ( identifier[path] ):
literal[string]
identifier[path] = identifier[path] . identifier[replace] ( literal[string] , literal[string] )
identifier[path] = identifier[path] . identifier[replace] ( literal[string] , literal[string] )
ident... | def _clean_path(path):
"""Create a fully fissile absolute system path with no symbolic links and environment variables"""
path = path.replace('"', '')
path = path.replace("'", '')
# Replace ~ with /home/user
path = os.path.expanduser(path)
# Replace environment variables
path = os.path.expan... |
def copy_snapshot(kwargs=None, call=None):
'''
Copy a snapshot
'''
if call != 'function':
log.error(
'The copy_snapshot function must be called with -f or --function.'
)
return False
if 'source_region' not in kwargs:
log.error('A source_region must be spe... | def function[copy_snapshot, parameter[kwargs, call]]:
constant[
Copy a snapshot
]
if compare[name[call] not_equal[!=] constant[function]] begin[:]
call[name[log].error, parameter[constant[The copy_snapshot function must be called with -f or --function.]]]
return[constant[... | keyword[def] identifier[copy_snapshot] ( identifier[kwargs] = keyword[None] , identifier[call] = keyword[None] ):
literal[string]
keyword[if] identifier[call] != literal[string] :
identifier[log] . identifier[error] (
literal[string]
)
keyword[return] keyword[False]
... | def copy_snapshot(kwargs=None, call=None):
"""
Copy a snapshot
"""
if call != 'function':
log.error('The copy_snapshot function must be called with -f or --function.')
return False # depends on [control=['if'], data=[]]
if 'source_region' not in kwargs:
log.error('A source_r... |
def WriteClientGraphSeries(self, graph_series,
client_label,
timestamp):
"""See db.Database."""
series_key = (client_label, graph_series.report_type, timestamp.Copy())
self.client_graph_series[series_key] = graph_series.Copy() | def function[WriteClientGraphSeries, parameter[self, graph_series, client_label, timestamp]]:
constant[See db.Database.]
variable[series_key] assign[=] tuple[[<ast.Name object at 0x7da1b1b6e0b0>, <ast.Attribute object at 0x7da1b1b6f490>, <ast.Call object at 0x7da1b1b6c970>]]
call[name[self].clie... | keyword[def] identifier[WriteClientGraphSeries] ( identifier[self] , identifier[graph_series] ,
identifier[client_label] ,
identifier[timestamp] ):
literal[string]
identifier[series_key] =( identifier[client_label] , identifier[graph_series] . identifier[report_type] , identifier[timestamp] . identifier[... | def WriteClientGraphSeries(self, graph_series, client_label, timestamp):
"""See db.Database."""
series_key = (client_label, graph_series.report_type, timestamp.Copy())
self.client_graph_series[series_key] = graph_series.Copy() |
def Lombardi_Pedrocchi(m, x, rhol, rhog, sigma, D, L=1):
r'''Calculates two-phase pressure drop with the Lombardi-Pedrocchi (1972)
correlation from [1]_ as shown in [2]_ and [3]_.
.. math::
\Delta P_{tp} = \frac{0.83 G_{tp}^{1.4} \sigma^{0.4} L}{D^{1.2}
\rho_{h}^{0.866}}
Parameters
... | def function[Lombardi_Pedrocchi, parameter[m, x, rhol, rhog, sigma, D, L]]:
constant[Calculates two-phase pressure drop with the Lombardi-Pedrocchi (1972)
correlation from [1]_ as shown in [2]_ and [3]_.
.. math::
\Delta P_{tp} = \frac{0.83 G_{tp}^{1.4} \sigma^{0.4} L}{D^{1.2}
\rho_{h}^... | keyword[def] identifier[Lombardi_Pedrocchi] ( identifier[m] , identifier[x] , identifier[rhol] , identifier[rhog] , identifier[sigma] , identifier[D] , identifier[L] = literal[int] ):
literal[string]
identifier[voidage_h] = identifier[homogeneous] ( identifier[x] , identifier[rhol] , identifier[rhog] )
... | def Lombardi_Pedrocchi(m, x, rhol, rhog, sigma, D, L=1):
"""Calculates two-phase pressure drop with the Lombardi-Pedrocchi (1972)
correlation from [1]_ as shown in [2]_ and [3]_.
.. math::
\\Delta P_{tp} = \\frac{0.83 G_{tp}^{1.4} \\sigma^{0.4} L}{D^{1.2}
\\rho_{h}^{0.866}}
Parameters
... |
def com_find2D(ar_grid, **kwargs):
"""
ARGS
**kwargs
ordering = 'rc' or 'xy' order the return either in (x,y)
or (row, col) order.
indexing = 'zero' or 'one' return positions relative to zero (i.e.
pytho... | def function[com_find2D, parameter[ar_grid]]:
constant[
ARGS
**kwargs
ordering = 'rc' or 'xy' order the return either in (x,y)
or (row, col) order.
indexing = 'zero' or 'one' return positions relative to zero (i.e.
... | keyword[def] identifier[com_find2D] ( identifier[ar_grid] ,** identifier[kwargs] ):
literal[string]
identifier[b_reorder] = keyword[True]
identifier[b_oneOffset] = keyword[True]
keyword[for] identifier[key] , identifier[value] keyword[in] identifier[kwargs] . identifier[iteritems] ():
... | def com_find2D(ar_grid, **kwargs):
"""
ARGS
**kwargs
ordering = 'rc' or 'xy' order the return either in (x,y)
or (row, col) order.
indexing = 'zero' or 'one' return positions relative to zero (i.e.
pytho... |
def modify_account(self, account, attrs):
"""
:param account: a zobjects.Account
:param attrs : a dictionary of attributes to set ({key:value,...})
"""
attrs = [{'n': k, '_content': v} for k, v in attrs.items()]
self.request('ModifyAccount', {
'id': self._get... | def function[modify_account, parameter[self, account, attrs]]:
constant[
:param account: a zobjects.Account
:param attrs : a dictionary of attributes to set ({key:value,...})
]
variable[attrs] assign[=] <ast.ListComp object at 0x7da18dc06e00>
call[name[self].request, par... | keyword[def] identifier[modify_account] ( identifier[self] , identifier[account] , identifier[attrs] ):
literal[string]
identifier[attrs] =[{ literal[string] : identifier[k] , literal[string] : identifier[v] } keyword[for] identifier[k] , identifier[v] keyword[in] identifier[attrs] . identifier[... | def modify_account(self, account, attrs):
"""
:param account: a zobjects.Account
:param attrs : a dictionary of attributes to set ({key:value,...})
"""
attrs = [{'n': k, '_content': v} for (k, v) in attrs.items()]
self.request('ModifyAccount', {'id': self._get_or_fetch_id(account, s... |
def encode_list(cls, value):
"""
Encodes a list *value* into a string via base64 encoding.
"""
encoded = base64.b64encode(six.b(" ".join(str(v) for v in value) or "-"))
return encoded.decode("utf-8") if six.PY3 else encoded | def function[encode_list, parameter[cls, value]]:
constant[
Encodes a list *value* into a string via base64 encoding.
]
variable[encoded] assign[=] call[name[base64].b64encode, parameter[call[name[six].b, parameter[<ast.BoolOp object at 0x7da1b05eda20>]]]]
return[<ast.IfExp object at... | keyword[def] identifier[encode_list] ( identifier[cls] , identifier[value] ):
literal[string]
identifier[encoded] = identifier[base64] . identifier[b64encode] ( identifier[six] . identifier[b] ( literal[string] . identifier[join] ( identifier[str] ( identifier[v] ) keyword[for] identifier[v] keyw... | def encode_list(cls, value):
"""
Encodes a list *value* into a string via base64 encoding.
"""
encoded = base64.b64encode(six.b(' '.join((str(v) for v in value)) or '-'))
return encoded.decode('utf-8') if six.PY3 else encoded |
def get_locus(sequences, kir=False, verbose=False, refdata=None, evalue=10):
"""
Gets the locus of the sequence by running blastn
:param sequences: sequenences to blast
:param kir: bool whether the sequences are KIR or not
:rtype: ``str``
Example usage:
>>> from Bio.Seq import Seq
... | def function[get_locus, parameter[sequences, kir, verbose, refdata, evalue]]:
constant[
Gets the locus of the sequence by running blastn
:param sequences: sequenences to blast
:param kir: bool whether the sequences are KIR or not
:rtype: ``str``
Example usage:
>>> from Bio.Seq imp... | keyword[def] identifier[get_locus] ( identifier[sequences] , identifier[kir] = keyword[False] , identifier[verbose] = keyword[False] , identifier[refdata] = keyword[None] , identifier[evalue] = literal[int] ):
literal[string]
keyword[if] keyword[not] identifier[refdata] :
identifier[refdata] = i... | def get_locus(sequences, kir=False, verbose=False, refdata=None, evalue=10):
"""
Gets the locus of the sequence by running blastn
:param sequences: sequenences to blast
:param kir: bool whether the sequences are KIR or not
:rtype: ``str``
Example usage:
>>> from Bio.Seq import Seq
... |
def group_bar(self, column_label, **vargs):
"""Plot a bar chart for the table.
The values of the specified column are grouped and counted, and one
bar is produced for each group.
Note: This differs from ``bar`` in that there is no need to specify
bar heights; the height of a ca... | def function[group_bar, parameter[self, column_label]]:
constant[Plot a bar chart for the table.
The values of the specified column are grouped and counted, and one
bar is produced for each group.
Note: This differs from ``bar`` in that there is no need to specify
bar heights; ... | keyword[def] identifier[group_bar] ( identifier[self] , identifier[column_label] ,** identifier[vargs] ):
literal[string]
identifier[self] . identifier[group] ( identifier[column_label] ). identifier[bar] ( identifier[column_label] ,** identifier[vargs] ) | def group_bar(self, column_label, **vargs):
"""Plot a bar chart for the table.
The values of the specified column are grouped and counted, and one
bar is produced for each group.
Note: This differs from ``bar`` in that there is no need to specify
bar heights; the height of a catego... |
def get_block_hash(self, height, id=None, endpoint=None):
"""
Get hash of a block by its height
Args:
height: (int) height of the block to lookup
id: (int, optional) id to use for response tracking
endpoint: (RPCEndpoint, optional) endpoint to specify to use
... | def function[get_block_hash, parameter[self, height, id, endpoint]]:
constant[
Get hash of a block by its height
Args:
height: (int) height of the block to lookup
id: (int, optional) id to use for response tracking
endpoint: (RPCEndpoint, optional) endpoint to... | keyword[def] identifier[get_block_hash] ( identifier[self] , identifier[height] , identifier[id] = keyword[None] , identifier[endpoint] = keyword[None] ):
literal[string]
keyword[return] identifier[self] . identifier[_call_endpoint] ( identifier[GET_BLOCK_HASH] , identifier[params] =[ identifier[h... | def get_block_hash(self, height, id=None, endpoint=None):
"""
Get hash of a block by its height
Args:
height: (int) height of the block to lookup
id: (int, optional) id to use for response tracking
endpoint: (RPCEndpoint, optional) endpoint to specify to use
... |
def process_request(self, request):
"""
Sets the current request's ``urlconf`` attribute to the urlconf
associated with the subdomain, if it is listed in
``settings.SUBDOMAIN_URLCONFS``.
"""
super(SubdomainURLRoutingMiddleware, self).process_request(request)
subd... | def function[process_request, parameter[self, request]]:
constant[
Sets the current request's ``urlconf`` attribute to the urlconf
associated with the subdomain, if it is listed in
``settings.SUBDOMAIN_URLCONFS``.
]
call[call[name[super], parameter[name[SubdomainURLRoutin... | keyword[def] identifier[process_request] ( identifier[self] , identifier[request] ):
literal[string]
identifier[super] ( identifier[SubdomainURLRoutingMiddleware] , identifier[self] ). identifier[process_request] ( identifier[request] )
identifier[subdomain] = identifier[getattr] ( identi... | def process_request(self, request):
"""
Sets the current request's ``urlconf`` attribute to the urlconf
associated with the subdomain, if it is listed in
``settings.SUBDOMAIN_URLCONFS``.
"""
super(SubdomainURLRoutingMiddleware, self).process_request(request)
subdomain = getat... |
def flow_pipeline(diameters, lengths, k_minors, target_headloss,
nu=con.WATER_NU, pipe_rough=mats.PVC_PIPE_ROUGH):
"""
This function takes a single pipeline with multiple sections, each potentially with different diameters,
lengths and minor loss coefficients and determines the flow rate f... | def function[flow_pipeline, parameter[diameters, lengths, k_minors, target_headloss, nu, pipe_rough]]:
constant[
This function takes a single pipeline with multiple sections, each potentially with different diameters,
lengths and minor loss coefficients and determines the flow rate for a given headloss.... | keyword[def] identifier[flow_pipeline] ( identifier[diameters] , identifier[lengths] , identifier[k_minors] , identifier[target_headloss] ,
identifier[nu] = identifier[con] . identifier[WATER_NU] , identifier[pipe_rough] = identifier[mats] . identifier[PVC_PIPE_ROUGH] ):
literal[string]
i... | def flow_pipeline(diameters, lengths, k_minors, target_headloss, nu=con.WATER_NU, pipe_rough=mats.PVC_PIPE_ROUGH):
"""
This function takes a single pipeline with multiple sections, each potentially with different diameters,
lengths and minor loss coefficients and determines the flow rate for a given headlos... |
def getInterpretation(self):
"""
Get the value of the previously POSTed Tropo action.
"""
actions = self._actions
if (type (actions) is list):
dict = actions[0]
else:
dict = actions
return dict['interpretation'] | def function[getInterpretation, parameter[self]]:
constant[
Get the value of the previously POSTed Tropo action.
]
variable[actions] assign[=] name[self]._actions
if compare[call[name[type], parameter[name[actions]]] is name[list]] begin[:]
variable[dict] assign[=... | keyword[def] identifier[getInterpretation] ( identifier[self] ):
literal[string]
identifier[actions] = identifier[self] . identifier[_actions]
keyword[if] ( identifier[type] ( identifier[actions] ) keyword[is] identifier[list] ):
identifier[dict] = identifier[actions] [ lit... | def getInterpretation(self):
"""
Get the value of the previously POSTed Tropo action.
"""
actions = self._actions
if type(actions) is list:
dict = actions[0] # depends on [control=['if'], data=[]]
else:
dict = actions
return dict['interpretation'] |
def load_python_file(moduleobject):
""" Try to create an indexable instance from a module"""
if isinstance(moduleobject, str):
moduleobject = load_module(moduleobject)
if not hasattr(moduleobject, "iclass"):
raise KeyError("Element" + str(moduleobject))
iclass = getattr(moduleobject, "ic... | def function[load_python_file, parameter[moduleobject]]:
constant[ Try to create an indexable instance from a module]
if call[name[isinstance], parameter[name[moduleobject], name[str]]] begin[:]
variable[moduleobject] assign[=] call[name[load_module], parameter[name[moduleobject]]]
... | keyword[def] identifier[load_python_file] ( identifier[moduleobject] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[moduleobject] , identifier[str] ):
identifier[moduleobject] = identifier[load_module] ( identifier[moduleobject] )
keyword[if] keyword[not] identifier[has... | def load_python_file(moduleobject):
""" Try to create an indexable instance from a module"""
if isinstance(moduleobject, str):
moduleobject = load_module(moduleobject) # depends on [control=['if'], data=[]]
if not hasattr(moduleobject, 'iclass'):
raise KeyError('Element' + str(moduleobject)... |
def dict_stack(dict_list, key_prefix=''):
r"""
stacks values from two dicts into a new dict where the values are list of
the input values. the keys are the same.
DEPRICATE in favor of dict_stack2
Args:
dict_list (list): list of dicts with similar keys
Returns:
dict dict_stacke... | def function[dict_stack, parameter[dict_list, key_prefix]]:
constant[
stacks values from two dicts into a new dict where the values are list of
the input values. the keys are the same.
DEPRICATE in favor of dict_stack2
Args:
dict_list (list): list of dicts with similar keys
Return... | keyword[def] identifier[dict_stack] ( identifier[dict_list] , identifier[key_prefix] = literal[string] ):
literal[string]
identifier[dict_stacked_] = identifier[defaultdict] ( identifier[list] )
keyword[for] identifier[dict_] keyword[in] identifier[dict_list] :
keyword[for] identifier[key... | def dict_stack(dict_list, key_prefix=''):
"""
stacks values from two dicts into a new dict where the values are list of
the input values. the keys are the same.
DEPRICATE in favor of dict_stack2
Args:
dict_list (list): list of dicts with similar keys
Returns:
dict dict_stacked... |
def clean_server_response(self, resp_dict):
"""cleans the server reponse by replacing:
'-' -> None
'1,000' -> 1000
:param resp_dict:
:return: dict with all above substitution
"""
# change all the keys from unicode to string
d = {}
for ... | def function[clean_server_response, parameter[self, resp_dict]]:
constant[cleans the server reponse by replacing:
'-' -> None
'1,000' -> 1000
:param resp_dict:
:return: dict with all above substitution
]
variable[d] assign[=] dictionary[[], []]
... | keyword[def] identifier[clean_server_response] ( identifier[self] , identifier[resp_dict] ):
literal[string]
identifier[d] ={}
keyword[for] identifier[key] , identifier[value] keyword[in] identifier[resp_dict] . identifier[items] ():
identifier[d] [ identifier[str... | def clean_server_response(self, resp_dict):
"""cleans the server reponse by replacing:
'-' -> None
'1,000' -> 1000
:param resp_dict:
:return: dict with all above substitution
"""
# change all the keys from unicode to string
d = {}
for (key, value) in r... |
def read_pickle(fn):
"""Load a GOParser object from a pickle file.
The function automatically detects whether the file is compressed
with gzip.
Parameters
----------
fn: str
Path of the pickle file.
Returns
-------
`GOParser`
... | def function[read_pickle, parameter[fn]]:
constant[Load a GOParser object from a pickle file.
The function automatically detects whether the file is compressed
with gzip.
Parameters
----------
fn: str
Path of the pickle file.
Returns
-------... | keyword[def] identifier[read_pickle] ( identifier[fn] ):
literal[string]
keyword[with] identifier[misc] . identifier[open_plain_or_gzip] ( identifier[fn] , literal[string] ) keyword[as] identifier[fh] :
identifier[parser] = identifier[pickle] . identifier[load] ( identifier[fh] )
... | def read_pickle(fn):
"""Load a GOParser object from a pickle file.
The function automatically detects whether the file is compressed
with gzip.
Parameters
----------
fn: str
Path of the pickle file.
Returns
-------
`GOParser`
... |
def read_until_close(self) -> Awaitable[bytes]:
"""Asynchronously reads all data from the socket until it is closed.
This will buffer all available data until ``max_buffer_size``
is reached. If flow control or cancellation are desired, use a
loop with `read_bytes(partial=True) <.read_by... | def function[read_until_close, parameter[self]]:
constant[Asynchronously reads all data from the socket until it is closed.
This will buffer all available data until ``max_buffer_size``
is reached. If flow control or cancellation are desired, use a
loop with `read_bytes(partial=True) <.... | keyword[def] identifier[read_until_close] ( identifier[self] )-> identifier[Awaitable] [ identifier[bytes] ]:
literal[string]
identifier[future] = identifier[self] . identifier[_start_read] ()
keyword[if] identifier[self] . identifier[closed] ():
identifier[self] . identifier... | def read_until_close(self) -> Awaitable[bytes]:
"""Asynchronously reads all data from the socket until it is closed.
This will buffer all available data until ``max_buffer_size``
is reached. If flow control or cancellation are desired, use a
loop with `read_bytes(partial=True) <.read_bytes>... |
def get_platforms(self, automation_api='all'):
"""Get a list of objects describing all the OS and browser platforms
currently supported on Sauce Labs."""
method = 'GET'
endpoint = '/rest/v1/info/platforms/{}'.format(automation_api)
return self.client.request(method, endpoint) | def function[get_platforms, parameter[self, automation_api]]:
constant[Get a list of objects describing all the OS and browser platforms
currently supported on Sauce Labs.]
variable[method] assign[=] constant[GET]
variable[endpoint] assign[=] call[constant[/rest/v1/info/platforms/{}].for... | keyword[def] identifier[get_platforms] ( identifier[self] , identifier[automation_api] = literal[string] ):
literal[string]
identifier[method] = literal[string]
identifier[endpoint] = literal[string] . identifier[format] ( identifier[automation_api] )
keyword[return] identifier[... | def get_platforms(self, automation_api='all'):
"""Get a list of objects describing all the OS and browser platforms
currently supported on Sauce Labs."""
method = 'GET'
endpoint = '/rest/v1/info/platforms/{}'.format(automation_api)
return self.client.request(method, endpoint) |
def pipeline(self):
"""Returns :class:`Pipeline` object to execute bulk of commands.
It is provided for convenience.
Commands can be pipelined without it.
Example:
>>> pipe = redis.pipeline()
>>> fut1 = pipe.incr('foo') # NO `await` as it will block forever!
>>... | def function[pipeline, parameter[self]]:
constant[Returns :class:`Pipeline` object to execute bulk of commands.
It is provided for convenience.
Commands can be pipelined without it.
Example:
>>> pipe = redis.pipeline()
>>> fut1 = pipe.incr('foo') # NO `await` as it wil... | keyword[def] identifier[pipeline] ( identifier[self] ):
literal[string]
keyword[return] identifier[Pipeline] ( identifier[self] . identifier[_pool_or_conn] , identifier[self] . identifier[__class__] ,
identifier[loop] = identifier[self] . identifier[_pool_or_conn] . identifier[_loop] ) | def pipeline(self):
"""Returns :class:`Pipeline` object to execute bulk of commands.
It is provided for convenience.
Commands can be pipelined without it.
Example:
>>> pipe = redis.pipeline()
>>> fut1 = pipe.incr('foo') # NO `await` as it will block forever!
>>> fu... |
def set_label(self, value,callb=None):
"""Convenience method to set the label of the device
This method will send a SetLabel message to the device, and request callb be executed
when an ACK is received. The default callback will simply cache the value.
:param value: The new label
... | def function[set_label, parameter[self, value, callb]]:
constant[Convenience method to set the label of the device
This method will send a SetLabel message to the device, and request callb be executed
when an ACK is received. The default callback will simply cache the value.
:param... | keyword[def] identifier[set_label] ( identifier[self] , identifier[value] , identifier[callb] = keyword[None] ):
literal[string]
keyword[if] identifier[len] ( identifier[value] )> literal[int] :
identifier[value] = identifier[value] [: literal[int] ]
identifier[mypartial] = i... | def set_label(self, value, callb=None):
"""Convenience method to set the label of the device
This method will send a SetLabel message to the device, and request callb be executed
when an ACK is received. The default callback will simply cache the value.
:param value: The new label
... |
def sawtooth(duration: int, amp: complex, period: float = None,
phase: float = 0, name: str = None) -> SamplePulse:
"""Generates sawtooth wave `SamplePulse`.
Args:
duration: Duration of pulse. Must be greater than zero.
amp: Pulse amplitude. Wave range is [-amp, amp].
perio... | def function[sawtooth, parameter[duration, amp, period, phase, name]]:
constant[Generates sawtooth wave `SamplePulse`.
Args:
duration: Duration of pulse. Must be greater than zero.
amp: Pulse amplitude. Wave range is [-amp, amp].
period: Pulse period, units of dt. If `None` defaults... | keyword[def] identifier[sawtooth] ( identifier[duration] : identifier[int] , identifier[amp] : identifier[complex] , identifier[period] : identifier[float] = keyword[None] ,
identifier[phase] : identifier[float] = literal[int] , identifier[name] : identifier[str] = keyword[None] )-> identifier[SamplePulse] :
li... | def sawtooth(duration: int, amp: complex, period: float=None, phase: float=0, name: str=None) -> SamplePulse:
"""Generates sawtooth wave `SamplePulse`.
Args:
duration: Duration of pulse. Must be greater than zero.
amp: Pulse amplitude. Wave range is [-amp, amp].
period: Pulse period, un... |
def setup_es(hosts, port, use_ssl=False, auth=None):
"""
Setup an Elasticsearch connection
Parameters
----------
hosts: list
Hostnames / IP addresses for elasticsearch cluster
port: string
Port for elasticsearch cluster
use_ssl: boolean
Whether to use SSL... | def function[setup_es, parameter[hosts, port, use_ssl, auth]]:
constant[
Setup an Elasticsearch connection
Parameters
----------
hosts: list
Hostnames / IP addresses for elasticsearch cluster
port: string
Port for elasticsearch cluster
use_ssl: boolean
... | keyword[def] identifier[setup_es] ( identifier[hosts] , identifier[port] , identifier[use_ssl] = keyword[False] , identifier[auth] = keyword[None] ):
literal[string]
identifier[kwargs] = identifier[dict] (
identifier[hosts] = identifier[hosts] keyword[or] [ literal[string] ],
identifier[port] = ... | def setup_es(hosts, port, use_ssl=False, auth=None):
"""
Setup an Elasticsearch connection
Parameters
----------
hosts: list
Hostnames / IP addresses for elasticsearch cluster
port: string
Port for elasticsearch cluster
use_ssl: boolean
Whether to use SSL... |
def save_favorite_query(arg, **_):
"""Save a new favorite query.
Returns (title, rows, headers, status)"""
usage = 'Syntax: \\fs name query.\n\n' + favoritequeries.usage
if not arg:
return [(None, None, None, usage)]
name, _, query = arg.partition(' ')
# If either name or query is mis... | def function[save_favorite_query, parameter[arg]]:
constant[Save a new favorite query.
Returns (title, rows, headers, status)]
variable[usage] assign[=] binary_operation[constant[Syntax: \fs name query.
] + name[favoritequeries].usage]
if <ast.UnaryOp object at 0x7da2041dada0> begin[:]
... | keyword[def] identifier[save_favorite_query] ( identifier[arg] ,** identifier[_] ):
literal[string]
identifier[usage] = literal[string] + identifier[favoritequeries] . identifier[usage]
keyword[if] keyword[not] identifier[arg] :
keyword[return] [( keyword[None] , keyword[None] , keyword[N... | def save_favorite_query(arg, **_):
"""Save a new favorite query.
Returns (title, rows, headers, status)"""
usage = 'Syntax: \\fs name query.\n\n' + favoritequeries.usage
if not arg:
return [(None, None, None, usage)] # depends on [control=['if'], data=[]]
(name, _, query) = arg.partition(' ... |
def has_changed_since_last_deploy(file_path, bucket):
"""
Checks if a file has changed since the last time it was deployed.
:param file_path: Path to file which should be checked. Should be relative
from root of bucket.
:param bucket_name: Name of S3 bucket to check against.
:... | def function[has_changed_since_last_deploy, parameter[file_path, bucket]]:
constant[
Checks if a file has changed since the last time it was deployed.
:param file_path: Path to file which should be checked. Should be relative
from root of bucket.
:param bucket_name: Name of S3... | keyword[def] identifier[has_changed_since_last_deploy] ( identifier[file_path] , identifier[bucket] ):
literal[string]
identifier[msg] = literal[string] . identifier[format] ( identifier[file_path] )
identifier[logger] . identifier[debug] ( identifier[msg] )
keyword[with] identifier[open] ( ide... | def has_changed_since_last_deploy(file_path, bucket):
"""
Checks if a file has changed since the last time it was deployed.
:param file_path: Path to file which should be checked. Should be relative
from root of bucket.
:param bucket_name: Name of S3 bucket to check against.
:... |
def mirror(self):
"""For a composite instruction, reverse the order of sub-gates.
This is done by recursively mirroring all sub-instructions.
It does not invert any gate.
Returns:
Instruction: a fresh gate with sub-gates reversed
"""
if not self._definition:... | def function[mirror, parameter[self]]:
constant[For a composite instruction, reverse the order of sub-gates.
This is done by recursively mirroring all sub-instructions.
It does not invert any gate.
Returns:
Instruction: a fresh gate with sub-gates reversed
]
... | keyword[def] identifier[mirror] ( identifier[self] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[_definition] :
keyword[return] identifier[self] . identifier[copy] ()
identifier[reverse_inst] = identifier[self] . identifier[copy] ( identifier[na... | def mirror(self):
"""For a composite instruction, reverse the order of sub-gates.
This is done by recursively mirroring all sub-instructions.
It does not invert any gate.
Returns:
Instruction: a fresh gate with sub-gates reversed
"""
if not self._definition:
... |
def _lease_owned(self, lease, current_uuid_path):
"""
Checks if the given lease is owned by the prefix whose uuid is in
the given path
Note:
The prefix must be also in the same path it was when it took the
lease
Args:
path (str): Path to the ... | def function[_lease_owned, parameter[self, lease, current_uuid_path]]:
constant[
Checks if the given lease is owned by the prefix whose uuid is in
the given path
Note:
The prefix must be also in the same path it was when it took the
lease
Args:
... | keyword[def] identifier[_lease_owned] ( identifier[self] , identifier[lease] , identifier[current_uuid_path] ):
literal[string]
identifier[prev_uuid_path] , identifier[prev_uuid] = identifier[lease] . identifier[metadata]
keyword[with] identifier[open] ( identifier[current_uuid_path] )... | def _lease_owned(self, lease, current_uuid_path):
"""
Checks if the given lease is owned by the prefix whose uuid is in
the given path
Note:
The prefix must be also in the same path it was when it took the
lease
Args:
path (str): Path to the leas... |
def GetRootFileEntry(self):
"""Retrieves the root file entry.
Returns:
DataRangeFileEntry: a file entry or None if not available.
"""
path_spec = data_range_path_spec.DataRangePathSpec(
range_offset=self._range_offset,
range_size=self._range_size,
parent=self._path_spec.pa... | def function[GetRootFileEntry, parameter[self]]:
constant[Retrieves the root file entry.
Returns:
DataRangeFileEntry: a file entry or None if not available.
]
variable[path_spec] assign[=] call[name[data_range_path_spec].DataRangePathSpec, parameter[]]
return[call[name[self].GetFileEn... | keyword[def] identifier[GetRootFileEntry] ( identifier[self] ):
literal[string]
identifier[path_spec] = identifier[data_range_path_spec] . identifier[DataRangePathSpec] (
identifier[range_offset] = identifier[self] . identifier[_range_offset] ,
identifier[range_size] = identifier[self] . identifi... | def GetRootFileEntry(self):
"""Retrieves the root file entry.
Returns:
DataRangeFileEntry: a file entry or None if not available.
"""
path_spec = data_range_path_spec.DataRangePathSpec(range_offset=self._range_offset, range_size=self._range_size, parent=self._path_spec.parent)
return self.Get... |
def filter(subtags):
"""
Get a list of non-existing string subtag(s) given the input string subtag(s).
:param subtags: string subtag or a list of string subtags.
:return: list of non-existing string subtags. The return list can be empty.
"""
if not isinstance(subtags, li... | def function[filter, parameter[subtags]]:
constant[
Get a list of non-existing string subtag(s) given the input string subtag(s).
:param subtags: string subtag or a list of string subtags.
:return: list of non-existing string subtags. The return list can be empty.
]
if <... | keyword[def] identifier[filter] ( identifier[subtags] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[subtags] , identifier[list] ):
identifier[subtags] =[ identifier[subtags] ]
keyword[return] [ identifier[subtag] keyword[for] identifier[su... | def filter(subtags):
"""
Get a list of non-existing string subtag(s) given the input string subtag(s).
:param subtags: string subtag or a list of string subtags.
:return: list of non-existing string subtags. The return list can be empty.
"""
if not isinstance(subtags, list):
... |
def _get_struct_fillstyle(self, shape_number):
"""Get the values for the FILLSTYLE record."""
obj = _make_object("FillStyle")
obj.FillStyleType = style_type = unpack_ui8(self._src)
if style_type == 0x00:
if shape_number <= 2:
obj.Color = self._get_struct_rgb(... | def function[_get_struct_fillstyle, parameter[self, shape_number]]:
constant[Get the values for the FILLSTYLE record.]
variable[obj] assign[=] call[name[_make_object], parameter[constant[FillStyle]]]
name[obj].FillStyleType assign[=] call[name[unpack_ui8], parameter[name[self]._src]]
if ... | keyword[def] identifier[_get_struct_fillstyle] ( identifier[self] , identifier[shape_number] ):
literal[string]
identifier[obj] = identifier[_make_object] ( literal[string] )
identifier[obj] . identifier[FillStyleType] = identifier[style_type] = identifier[unpack_ui8] ( identifier[self] . ... | def _get_struct_fillstyle(self, shape_number):
"""Get the values for the FILLSTYLE record."""
obj = _make_object('FillStyle')
obj.FillStyleType = style_type = unpack_ui8(self._src)
if style_type == 0:
if shape_number <= 2:
obj.Color = self._get_struct_rgb() # depends on [control=['i... |
def writeMNIST(sc, input_images, input_labels, output, format, num_partitions):
"""Writes MNIST image/label vectors into parallelized files on HDFS"""
# load MNIST gzip into memory
with open(input_images, 'rb') as f:
images = numpy.array(mnist.extract_images(f))
with open(input_labels, 'rb') as f:
if f... | def function[writeMNIST, parameter[sc, input_images, input_labels, output, format, num_partitions]]:
constant[Writes MNIST image/label vectors into parallelized files on HDFS]
with call[name[open], parameter[name[input_images], constant[rb]]] begin[:]
variable[images] assign[=] call[name... | keyword[def] identifier[writeMNIST] ( identifier[sc] , identifier[input_images] , identifier[input_labels] , identifier[output] , identifier[format] , identifier[num_partitions] ):
literal[string]
keyword[with] identifier[open] ( identifier[input_images] , literal[string] ) keyword[as] identifier[f] :
... | def writeMNIST(sc, input_images, input_labels, output, format, num_partitions):
"""Writes MNIST image/label vectors into parallelized files on HDFS"""
# load MNIST gzip into memory
with open(input_images, 'rb') as f:
images = numpy.array(mnist.extract_images(f)) # depends on [control=['with'], data... |
def _get_amp_pha(self, data, which_data):
"""Convert input data to phase and amplitude
Parameters
----------
data: 2d ndarray (float or complex) or list
The experimental data (see `which_data`)
which_data: str
String or comma-separated list of strings ind... | def function[_get_amp_pha, parameter[self, data, which_data]]:
constant[Convert input data to phase and amplitude
Parameters
----------
data: 2d ndarray (float or complex) or list
The experimental data (see `which_data`)
which_data: str
String or comma-se... | keyword[def] identifier[_get_amp_pha] ( identifier[self] , identifier[data] , identifier[which_data] ):
literal[string]
identifier[which_data] = identifier[QPImage] . identifier[_conv_which_data] ( identifier[which_data] )
keyword[if] identifier[which_data] keyword[not] keyword[in] ide... | def _get_amp_pha(self, data, which_data):
"""Convert input data to phase and amplitude
Parameters
----------
data: 2d ndarray (float or complex) or list
The experimental data (see `which_data`)
which_data: str
String or comma-separated list of strings indicat... |
def checkTransitionType(self,state):
"""
Check whether the transition function returns output of the correct types.
This can be either a dictionary with as keys ints/tuples and values floats.
Or a tuple consisting of a 2d integer numpy array with states and a 1d numpy array with rates. ... | def function[checkTransitionType, parameter[self, state]]:
constant[
Check whether the transition function returns output of the correct types.
This can be either a dictionary with as keys ints/tuples and values floats.
Or a tuple consisting of a 2d integer numpy array with states and a ... | keyword[def] identifier[checkTransitionType] ( identifier[self] , identifier[state] ):
literal[string]
identifier[test] = identifier[self] . identifier[transition] ( identifier[state] )
keyword[assert] identifier[isinstance] ( identifier[test] ,( identifier[dict] , identifier[tuple] )), l... | def checkTransitionType(self, state):
"""
Check whether the transition function returns output of the correct types.
This can be either a dictionary with as keys ints/tuples and values floats.
Or a tuple consisting of a 2d integer numpy array with states and a 1d numpy array with rates.
... |
def cfnumber_to_number(cfnumber):
"""Convert CFNumber to python int or float."""
numeric_type = cf.CFNumberGetType(cfnumber)
cfnum_to_ctype = {kCFNumberSInt8Type: c_int8, kCFNumberSInt16Type: c_int16,
kCFNumberSInt32Type: c_int32,
kCFNumberSInt64Type: c_int64,
... | def function[cfnumber_to_number, parameter[cfnumber]]:
constant[Convert CFNumber to python int or float.]
variable[numeric_type] assign[=] call[name[cf].CFNumberGetType, parameter[name[cfnumber]]]
variable[cfnum_to_ctype] assign[=] dictionary[[<ast.Name object at 0x7da1b0e427d0>, <ast.Name objec... | keyword[def] identifier[cfnumber_to_number] ( identifier[cfnumber] ):
literal[string]
identifier[numeric_type] = identifier[cf] . identifier[CFNumberGetType] ( identifier[cfnumber] )
identifier[cfnum_to_ctype] ={ identifier[kCFNumberSInt8Type] : identifier[c_int8] , identifier[kCFNumberSInt16Type] : i... | def cfnumber_to_number(cfnumber):
"""Convert CFNumber to python int or float."""
numeric_type = cf.CFNumberGetType(cfnumber)
cfnum_to_ctype = {kCFNumberSInt8Type: c_int8, kCFNumberSInt16Type: c_int16, kCFNumberSInt32Type: c_int32, kCFNumberSInt64Type: c_int64, kCFNumberFloat32Type: c_float, kCFNumberFloat64... |
def insert(self, doc_or_docs, **kwargs):
"""Insert method
"""
check = kwargs.pop('check', True)
if isinstance(doc_or_docs, dict):
if check is True:
doc_or_docs = self._valid_record(doc_or_docs)
result = self.__collect.insert_one(doc_or_docs, **kwar... | def function[insert, parameter[self, doc_or_docs]]:
constant[Insert method
]
variable[check] assign[=] call[name[kwargs].pop, parameter[constant[check], constant[True]]]
if call[name[isinstance], parameter[name[doc_or_docs], name[dict]]] begin[:]
if compare[name[check] is... | keyword[def] identifier[insert] ( identifier[self] , identifier[doc_or_docs] ,** identifier[kwargs] ):
literal[string]
identifier[check] = identifier[kwargs] . identifier[pop] ( literal[string] , keyword[True] )
keyword[if] identifier[isinstance] ( identifier[doc_or_docs] , identifier[dic... | def insert(self, doc_or_docs, **kwargs):
"""Insert method
"""
check = kwargs.pop('check', True)
if isinstance(doc_or_docs, dict):
if check is True:
doc_or_docs = self._valid_record(doc_or_docs) # depends on [control=['if'], data=[]]
result = self.__collect.insert_one(doc... |
def plot_site(fignum, SiteRec, data, key):
"""
deprecated (used in ipmag)
"""
print('Site mean data: ')
print(' dec inc n_lines n_planes kappa R alpha_95 comp coord')
print(SiteRec['site_dec'], SiteRec['site_inc'], SiteRec['site_n_lines'], SiteRec['site_n_planes'], SiteRec['site_k'],
... | def function[plot_site, parameter[fignum, SiteRec, data, key]]:
constant[
deprecated (used in ipmag)
]
call[name[print], parameter[constant[Site mean data: ]]]
call[name[print], parameter[constant[ dec inc n_lines n_planes kappa R alpha_95 comp coord]]]
call[name[print], par... | keyword[def] identifier[plot_site] ( identifier[fignum] , identifier[SiteRec] , identifier[data] , identifier[key] ):
literal[string]
identifier[print] ( literal[string] )
identifier[print] ( literal[string] )
identifier[print] ( identifier[SiteRec] [ literal[string] ], identifier[SiteRec] [ lite... | def plot_site(fignum, SiteRec, data, key):
"""
deprecated (used in ipmag)
"""
print('Site mean data: ')
print(' dec inc n_lines n_planes kappa R alpha_95 comp coord')
print(SiteRec['site_dec'], SiteRec['site_inc'], SiteRec['site_n_lines'], SiteRec['site_n_planes'], SiteRec['site_k'], SiteRe... |
def key(self, user="", areq=None):
"""
Return a key (the session id)
:param user: User id
:param areq: The authorization request
:return: An ID
"""
csum = hashlib.new('sha224')
csum.update(rndstr(32).encode('utf-8'))
return csum.hexdigest() | def function[key, parameter[self, user, areq]]:
constant[
Return a key (the session id)
:param user: User id
:param areq: The authorization request
:return: An ID
]
variable[csum] assign[=] call[name[hashlib].new, parameter[constant[sha224]]]
call[name[cs... | keyword[def] identifier[key] ( identifier[self] , identifier[user] = literal[string] , identifier[areq] = keyword[None] ):
literal[string]
identifier[csum] = identifier[hashlib] . identifier[new] ( literal[string] )
identifier[csum] . identifier[update] ( identifier[rndstr] ( literal[int] ... | def key(self, user='', areq=None):
"""
Return a key (the session id)
:param user: User id
:param areq: The authorization request
:return: An ID
"""
csum = hashlib.new('sha224')
csum.update(rndstr(32).encode('utf-8'))
return csum.hexdigest() |
def abusecheck(self, send, nick, target, limit, cmd):
""" Rate-limits commands.
| If a nick uses commands with the limit attr set, record the time
| at which they were used.
| If the command is used more than `limit` times in a
| minute, ignore the nick.
"""
if n... | def function[abusecheck, parameter[self, send, nick, target, limit, cmd]]:
constant[ Rate-limits commands.
| If a nick uses commands with the limit attr set, record the time
| at which they were used.
| If the command is used more than `limit` times in a
| minute, ignore the nic... | keyword[def] identifier[abusecheck] ( identifier[self] , identifier[send] , identifier[nick] , identifier[target] , identifier[limit] , identifier[cmd] ):
literal[string]
keyword[if] identifier[nick] keyword[not] keyword[in] identifier[self] . identifier[abuselist] :
identifier[sel... | def abusecheck(self, send, nick, target, limit, cmd):
""" Rate-limits commands.
| If a nick uses commands with the limit attr set, record the time
| at which they were used.
| If the command is used more than `limit` times in a
| minute, ignore the nick.
"""
if nick not ... |
def analyze(problem, X, Y, num_resamples=1000,
conf_level=0.95, print_to_console=False, seed=None):
"""Calculates Derivative-based Global Sensitivity Measure on model outputs.
Returns a dictionary with keys 'vi', 'vi_std', 'dgsm', and 'dgsm_conf',
where each entry is a list of size D (the ... | def function[analyze, parameter[problem, X, Y, num_resamples, conf_level, print_to_console, seed]]:
constant[Calculates Derivative-based Global Sensitivity Measure on model outputs.
Returns a dictionary with keys 'vi', 'vi_std', 'dgsm', and 'dgsm_conf',
where each entry is a list of size D (the number ... | keyword[def] identifier[analyze] ( identifier[problem] , identifier[X] , identifier[Y] , identifier[num_resamples] = literal[int] ,
identifier[conf_level] = literal[int] , identifier[print_to_console] = keyword[False] , identifier[seed] = keyword[None] ):
literal[string]
keyword[if] identifier[seed] :... | def analyze(problem, X, Y, num_resamples=1000, conf_level=0.95, print_to_console=False, seed=None):
"""Calculates Derivative-based Global Sensitivity Measure on model outputs.
Returns a dictionary with keys 'vi', 'vi_std', 'dgsm', and 'dgsm_conf',
where each entry is a list of size D (the number of paramet... |
def summarize_dist_params(dist, name, name_scope="dist_params"):
"""Summarize the parameters of a distribution.
Args:
dist: A Distribution object with mean and standard deviation
parameters.
name: The name of the distribution.
name_scope: The name scope of this summary.
"""
with tf.compat.v1.... | def function[summarize_dist_params, parameter[dist, name, name_scope]]:
constant[Summarize the parameters of a distribution.
Args:
dist: A Distribution object with mean and standard deviation
parameters.
name: The name of the distribution.
name_scope: The name scope of this summary.
]
... | keyword[def] identifier[summarize_dist_params] ( identifier[dist] , identifier[name] , identifier[name_scope] = literal[string] ):
literal[string]
keyword[with] identifier[tf] . identifier[compat] . identifier[v1] . identifier[name_scope] ( identifier[name_scope] ):
identifier[tf] . identifier[compat] . ... | def summarize_dist_params(dist, name, name_scope='dist_params'):
"""Summarize the parameters of a distribution.
Args:
dist: A Distribution object with mean and standard deviation
parameters.
name: The name of the distribution.
name_scope: The name scope of this summary.
"""
with tf.compat... |
def how_many(self):
"""
Ascertain where to start downloading, and how many entries.
"""
if self.linkdates != []:
# What follows is a quick sanity check: if the entry date is in the
# future, this is probably a mistake, and we just count the entry
# dat... | def function[how_many, parameter[self]]:
constant[
Ascertain where to start downloading, and how many entries.
]
if compare[name[self].linkdates not_equal[!=] list[[]]] begin[:]
if compare[call[name[max], parameter[name[self].linkdates]] less_or_equal[<=] call[name[list],... | keyword[def] identifier[how_many] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[linkdates] !=[]:
keyword[if] identifier[max] ( identifier[self] . identifier[linkdates] )<= identifier[list] ( identifier[time] . identifier[lo... | def how_many(self):
"""
Ascertain where to start downloading, and how many entries.
"""
if self.linkdates != []:
# What follows is a quick sanity check: if the entry date is in the
# future, this is probably a mistake, and we just count the entry
# date as right now.
... |
def apply(
self,
func,
num_splits=None,
other_axis_partition=None,
maintain_partitioning=True,
**kwargs
):
"""Applies func to the object.
See notes in Parent class about this method.
Args:
func: The function to apply.
... | def function[apply, parameter[self, func, num_splits, other_axis_partition, maintain_partitioning]]:
constant[Applies func to the object.
See notes in Parent class about this method.
Args:
func: The function to apply.
num_splits: The number of times to split the result ... | keyword[def] identifier[apply] (
identifier[self] ,
identifier[func] ,
identifier[num_splits] = keyword[None] ,
identifier[other_axis_partition] = keyword[None] ,
identifier[maintain_partitioning] = keyword[True] ,
** identifier[kwargs]
):
literal[string]
keyword[import] identifier[dask]
... | def apply(self, func, num_splits=None, other_axis_partition=None, maintain_partitioning=True, **kwargs):
"""Applies func to the object.
See notes in Parent class about this method.
Args:
func: The function to apply.
num_splits: The number of times to split the result object... |
def main():
"""
NAME
cart_dir.py
DESCRIPTION
converts cartesian coordinates to geomagnetic elements
INPUT (COMMAND LINE ENTRY)
x1 x2 x3
if only two columns, assumes magnitude of unity
OUTPUT
declination inclination magnitude
SYNTAX
... | def function[main, parameter[]]:
constant[
NAME
cart_dir.py
DESCRIPTION
converts cartesian coordinates to geomagnetic elements
INPUT (COMMAND LINE ENTRY)
x1 x2 x3
if only two columns, assumes magnitude of unity
OUTPUT
declination inclinatio... | keyword[def] identifier[main] ():
literal[string]
identifier[ofile] = literal[string]
keyword[if] literal[string] keyword[in] identifier[sys] . identifier[argv] :
identifier[print] ( identifier[main] . identifier[__doc__] )
identifier[sys] . identifier[exit] ()
keyword[if] ... | def main():
"""
NAME
cart_dir.py
DESCRIPTION
converts cartesian coordinates to geomagnetic elements
INPUT (COMMAND LINE ENTRY)
x1 x2 x3
if only two columns, assumes magnitude of unity
OUTPUT
declination inclination magnitude
SYNTAX
... |
def __is_file_to_be_busted(self, filepath):
"""
:param filepath:
:return: True or False
"""
if not self.extensions:
return True
return Path(filepath).suffix in self.extensions if filepath else False | def function[__is_file_to_be_busted, parameter[self, filepath]]:
constant[
:param filepath:
:return: True or False
]
if <ast.UnaryOp object at 0x7da1b25f6380> begin[:]
return[constant[True]]
return[<ast.IfExp object at 0x7da1b25f62f0>] | keyword[def] identifier[__is_file_to_be_busted] ( identifier[self] , identifier[filepath] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[extensions] :
keyword[return] keyword[True]
keyword[return] identifier[Path] ( identifier[filepath] ). ident... | def __is_file_to_be_busted(self, filepath):
"""
:param filepath:
:return: True or False
"""
if not self.extensions:
return True # depends on [control=['if'], data=[]]
return Path(filepath).suffix in self.extensions if filepath else False |
def transDrift(length=0.0, gamma=None):
""" Transport matrix of drift
:param length: drift length in [m]
:param gamma: electron energy, gamma value
:return: 6x6 numpy array
"""
m = np.eye(6, 6, dtype=np.float64)
if length == 0.0:
print("warning: 'length' should be a positive float n... | def function[transDrift, parameter[length, gamma]]:
constant[ Transport matrix of drift
:param length: drift length in [m]
:param gamma: electron energy, gamma value
:return: 6x6 numpy array
]
variable[m] assign[=] call[name[np].eye, parameter[constant[6], constant[6]]]
if compa... | keyword[def] identifier[transDrift] ( identifier[length] = literal[int] , identifier[gamma] = keyword[None] ):
literal[string]
identifier[m] = identifier[np] . identifier[eye] ( literal[int] , literal[int] , identifier[dtype] = identifier[np] . identifier[float64] )
keyword[if] identifier[length] == ... | def transDrift(length=0.0, gamma=None):
""" Transport matrix of drift
:param length: drift length in [m]
:param gamma: electron energy, gamma value
:return: 6x6 numpy array
"""
m = np.eye(6, 6, dtype=np.float64)
if length == 0.0:
print("warning: 'length' should be a positive float n... |
def serialize(self):
"""This function serialize into a simple dict object.
It is used when transferring data to other daemons over the network (http)
Here we directly return all attributes
:return: json representation of a Timeperiod
:rtype: dict
"""
res = super... | def function[serialize, parameter[self]]:
constant[This function serialize into a simple dict object.
It is used when transferring data to other daemons over the network (http)
Here we directly return all attributes
:return: json representation of a Timeperiod
:rtype: dict
... | keyword[def] identifier[serialize] ( identifier[self] ):
literal[string]
identifier[res] = identifier[super] ( identifier[Notification] , identifier[self] ). identifier[serialize] ()
keyword[if] identifier[res] [ literal[string] ] keyword[is] keyword[not] keyword[None] :
k... | def serialize(self):
"""This function serialize into a simple dict object.
It is used when transferring data to other daemons over the network (http)
Here we directly return all attributes
:return: json representation of a Timeperiod
:rtype: dict
"""
res = super(Notific... |
def delete_host_from_segment(hostipaddress, networkaddress, auth, url):
"""
:param hostipaddress: str ipv4 address of the target host to be deleted
:param networkaddress: ipv4 network address + subnet bits of target scope
:param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.cl... | def function[delete_host_from_segment, parameter[hostipaddress, networkaddress, auth, url]]:
constant[
:param hostipaddress: str ipv4 address of the target host to be deleted
:param networkaddress: ipv4 network address + subnet bits of target scope
:param auth: requests auth object #usually auth.c... | keyword[def] identifier[delete_host_from_segment] ( identifier[hostipaddress] , identifier[networkaddress] , identifier[auth] , identifier[url] ):
literal[string]
identifier[host_id] = identifier[get_host_id] ( identifier[hostipaddress] , identifier[networkaddress] , identifier[auth] , identifier[url] )
... | def delete_host_from_segment(hostipaddress, networkaddress, auth, url):
"""
:param hostipaddress: str ipv4 address of the target host to be deleted
:param networkaddress: ipv4 network address + subnet bits of target scope
:param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.cl... |
def _set_node_hw_sync_state(self, v, load=False):
"""
Setter method for node_hw_sync_state, mapped from YANG variable /brocade_vcs_rpc/show_vcs/output/vcs_nodes/vcs_node_info/node_hw_sync_state (node-hw-sync-state-type)
If this variable is read-only (config: false) in the
source YANG file, then _set_nod... | def function[_set_node_hw_sync_state, parameter[self, v, load]]:
constant[
Setter method for node_hw_sync_state, mapped from YANG variable /brocade_vcs_rpc/show_vcs/output/vcs_nodes/vcs_node_info/node_hw_sync_state (node-hw-sync-state-type)
If this variable is read-only (config: false) in the
source... | keyword[def] identifier[_set_node_hw_sync_state] ( identifier[self] , identifier[v] , identifier[load] = keyword[False] ):
literal[string]
keyword[if] identifier[hasattr] ( identifier[v] , literal[string] ):
identifier[v] = identifier[v] . identifier[_utype] ( identifier[v] )
keyword[try] :
... | def _set_node_hw_sync_state(self, v, load=False):
"""
Setter method for node_hw_sync_state, mapped from YANG variable /brocade_vcs_rpc/show_vcs/output/vcs_nodes/vcs_node_info/node_hw_sync_state (node-hw-sync-state-type)
If this variable is read-only (config: false) in the
source YANG file, then _set_nod... |
def expand(self, tags, clique_scoring_func=None):
"""This is the main function to expand tags into cliques
Args:
tags (list): a list of tags to find the cliques.
clique_scoring_func (func): a function that returns a float
value for the clique
Returns:
... | def function[expand, parameter[self, tags, clique_scoring_func]]:
constant[This is the main function to expand tags into cliques
Args:
tags (list): a list of tags to find the cliques.
clique_scoring_func (func): a function that returns a float
value for the cliqu... | keyword[def] identifier[expand] ( identifier[self] , identifier[tags] , identifier[clique_scoring_func] = keyword[None] ):
literal[string]
identifier[lattice] = identifier[Lattice] ()
identifier[overlapping_spans] =[]
keyword[def] identifier[end_token_index] ():
key... | def expand(self, tags, clique_scoring_func=None):
"""This is the main function to expand tags into cliques
Args:
tags (list): a list of tags to find the cliques.
clique_scoring_func (func): a function that returns a float
value for the clique
Returns:
... |
def parse(self, pointer):
"""parse pointer into tokens"""
if isinstance(pointer, Pointer):
return pointer.tokens[:]
elif pointer == '':
return []
tokens = []
staged, _, children = pointer.partition('/')
if staged:
try:
... | def function[parse, parameter[self, pointer]]:
constant[parse pointer into tokens]
if call[name[isinstance], parameter[name[pointer], name[Pointer]]] begin[:]
return[call[name[pointer].tokens][<ast.Slice object at 0x7da1b236c580>]]
variable[tokens] assign[=] list[[]]
<ast.Tuple o... | keyword[def] identifier[parse] ( identifier[self] , identifier[pointer] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[pointer] , identifier[Pointer] ):
keyword[return] identifier[pointer] . identifier[tokens] [:]
keyword[elif] identifier[pointer] == lit... | def parse(self, pointer):
"""parse pointer into tokens"""
if isinstance(pointer, Pointer):
return pointer.tokens[:] # depends on [control=['if'], data=[]]
elif pointer == '':
return [] # depends on [control=['if'], data=[]]
tokens = []
(staged, _, children) = pointer.partition('/')... |
def swap_word_order(source):
""" Swap the order of the words in 'source' bitstring """
assert len(source) % 4 == 0
words = "I" * (len(source) // 4)
return struct.pack(words, *reversed(struct.unpack(words, source))) | def function[swap_word_order, parameter[source]]:
constant[ Swap the order of the words in 'source' bitstring ]
assert[compare[binary_operation[call[name[len], parameter[name[source]]] <ast.Mod object at 0x7da2590d6920> constant[4]] equal[==] constant[0]]]
variable[words] assign[=] binary_operation[... | keyword[def] identifier[swap_word_order] ( identifier[source] ):
literal[string]
keyword[assert] identifier[len] ( identifier[source] )% literal[int] == literal[int]
identifier[words] = literal[string] *( identifier[len] ( identifier[source] )// literal[int] )
keyword[return] identifier[struct... | def swap_word_order(source):
""" Swap the order of the words in 'source' bitstring """
assert len(source) % 4 == 0
words = 'I' * (len(source) // 4)
return struct.pack(words, *reversed(struct.unpack(words, source))) |
def pad(self, start_duration=0.0, end_duration=0.0):
'''Add silence to the beginning or end of a file.
Calling this with the default arguments has no effect.
Parameters
----------
start_duration : float
Number of seconds of silence to add to beginning.
end_du... | def function[pad, parameter[self, start_duration, end_duration]]:
constant[Add silence to the beginning or end of a file.
Calling this with the default arguments has no effect.
Parameters
----------
start_duration : float
Number of seconds of silence to add to beginn... | keyword[def] identifier[pad] ( identifier[self] , identifier[start_duration] = literal[int] , identifier[end_duration] = literal[int] ):
literal[string]
keyword[if] keyword[not] identifier[is_number] ( identifier[start_duration] ) keyword[or] identifier[start_duration] < literal[int] :
... | def pad(self, start_duration=0.0, end_duration=0.0):
"""Add silence to the beginning or end of a file.
Calling this with the default arguments has no effect.
Parameters
----------
start_duration : float
Number of seconds of silence to add to beginning.
end_durati... |
def render_long_description(self, dirname):
"""Convert a package's long description to HTML.
"""
with changedir(dirname):
self.setuptools.check_valid_package()
long_description = self.setuptools.get_long_description()
outfile = abspath('.long-description.html'... | def function[render_long_description, parameter[self, dirname]]:
constant[Convert a package's long description to HTML.
]
with call[name[changedir], parameter[name[dirname]]] begin[:]
call[name[self].setuptools.check_valid_package, parameter[]]
variable[long_descr... | keyword[def] identifier[render_long_description] ( identifier[self] , identifier[dirname] ):
literal[string]
keyword[with] identifier[changedir] ( identifier[dirname] ):
identifier[self] . identifier[setuptools] . identifier[check_valid_package] ()
identifier[long_descrip... | def render_long_description(self, dirname):
"""Convert a package's long description to HTML.
"""
with changedir(dirname):
self.setuptools.check_valid_package()
long_description = self.setuptools.get_long_description()
outfile = abspath('.long-description.html')
self.docut... |
def encrypt_encoded(self, encoding, r_value):
"""Paillier encrypt an encoded value.
Args:
encoding: The EncodedNumber instance.
r_value (int): obfuscator for the ciphertext; by default (i.e.
if *r_value* is None), a random value is used.
Returns:
Encry... | def function[encrypt_encoded, parameter[self, encoding, r_value]]:
constant[Paillier encrypt an encoded value.
Args:
encoding: The EncodedNumber instance.
r_value (int): obfuscator for the ciphertext; by default (i.e.
if *r_value* is None), a random value is used.
... | keyword[def] identifier[encrypt_encoded] ( identifier[self] , identifier[encoding] , identifier[r_value] ):
literal[string]
identifier[obfuscator] = identifier[r_value] keyword[or] literal[int]
identifier[ciphertext] = identifier[self] . identifier[raw_encrypt] ( identifier[enc... | def encrypt_encoded(self, encoding, r_value):
"""Paillier encrypt an encoded value.
Args:
encoding: The EncodedNumber instance.
r_value (int): obfuscator for the ciphertext; by default (i.e.
if *r_value* is None), a random value is used.
Returns:
Encrypted... |
def merge_dict(lhs, rhs):
""" Merge content of a dict in another
:param: dict: lhs
dict where is merged the second one
:param: dict: rhs
dict whose content is merged
"""
assert isinstance(lhs, dict)
assert isinstance(rhs, dict)
for k, v in rhs.iteritems():
if k not in lh... | def function[merge_dict, parameter[lhs, rhs]]:
constant[ Merge content of a dict in another
:param: dict: lhs
dict where is merged the second one
:param: dict: rhs
dict whose content is merged
]
assert[call[name[isinstance], parameter[name[lhs], name[dict]]]]
assert[call[name[is... | keyword[def] identifier[merge_dict] ( identifier[lhs] , identifier[rhs] ):
literal[string]
keyword[assert] identifier[isinstance] ( identifier[lhs] , identifier[dict] )
keyword[assert] identifier[isinstance] ( identifier[rhs] , identifier[dict] )
keyword[for] identifier[k] , identifier[v] key... | def merge_dict(lhs, rhs):
""" Merge content of a dict in another
:param: dict: lhs
dict where is merged the second one
:param: dict: rhs
dict whose content is merged
"""
assert isinstance(lhs, dict)
assert isinstance(rhs, dict)
for (k, v) in rhs.iteritems():
if k not in ... |
def calc_circuit_breaker_position(self, debug=False):
""" Calculates the optimal position of a circuit breaker on route.
Parameters
----------
debug: bool, defaults to False
If True, prints process information.
Returns
-------
int
... | def function[calc_circuit_breaker_position, parameter[self, debug]]:
constant[ Calculates the optimal position of a circuit breaker on route.
Parameters
----------
debug: bool, defaults to False
If True, prints process information.
Returns
--... | keyword[def] identifier[calc_circuit_breaker_position] ( identifier[self] , identifier[debug] = keyword[False] ):
literal[string]
identifier[demand_diff_min] = literal[int]
keyword[for] identifier[ctr] keyword[in] identifier[range] ( identifier[len] ( ident... | def calc_circuit_breaker_position(self, debug=False):
""" Calculates the optimal position of a circuit breaker on route.
Parameters
----------
debug: bool, defaults to False
If True, prints process information.
Returns
-------
int
... |
def to_dict(self, lev=0):
"""
Return a dictionary representation of the class
:return: A dict
"""
_spec = self.c_param
_res = {}
lev += 1
for key, val in self._dict.items():
try:
(_, req, _ser, _, null_allowed) = _spec[str(ke... | def function[to_dict, parameter[self, lev]]:
constant[
Return a dictionary representation of the class
:return: A dict
]
variable[_spec] assign[=] name[self].c_param
variable[_res] assign[=] dictionary[[], []]
<ast.AugAssign object at 0x7da18f722b00>
for tage... | keyword[def] identifier[to_dict] ( identifier[self] , identifier[lev] = literal[int] ):
literal[string]
identifier[_spec] = identifier[self] . identifier[c_param]
identifier[_res] ={}
identifier[lev] += literal[int]
keyword[for] identifier[key] , identifier[val] key... | def to_dict(self, lev=0):
"""
Return a dictionary representation of the class
:return: A dict
"""
_spec = self.c_param
_res = {}
lev += 1
for (key, val) in self._dict.items():
try:
(_, req, _ser, _, null_allowed) = _spec[str(key)] # depends on [control=[... |
def undo_last_save(self, logMessage=None):
"""Undo the last change made to the datastream content and profile, effectively
reverting to the object state in Fedora as of the specified timestamp.
For a versioned datastream, this will purge the most recent datastream.
For an unversioned da... | def function[undo_last_save, parameter[self, logMessage]]:
constant[Undo the last change made to the datastream content and profile, effectively
reverting to the object state in Fedora as of the specified timestamp.
For a versioned datastream, this will purge the most recent datastream.
... | keyword[def] identifier[undo_last_save] ( identifier[self] , identifier[logMessage] = keyword[None] ):
literal[string]
keyword[if] identifier[self] . identifier[versionable] :
identifier[last_save] = identifier[self] . identifier[history] ... | def undo_last_save(self, logMessage=None):
"""Undo the last change made to the datastream content and profile, effectively
reverting to the object state in Fedora as of the specified timestamp.
For a versioned datastream, this will purge the most recent datastream.
For an unversioned datast... |
def create(self, friendly_name=values.unset, unique_name=values.unset,
attributes=values.unset, type=values.unset):
"""
Create a new ChannelInstance
:param unicode friendly_name: A human-readable name for the Channel.
:param unicode unique_name: A unique, addressable name... | def function[create, parameter[self, friendly_name, unique_name, attributes, type]]:
constant[
Create a new ChannelInstance
:param unicode friendly_name: A human-readable name for the Channel.
:param unicode unique_name: A unique, addressable name for the Channel.
:param unicode... | keyword[def] identifier[create] ( identifier[self] , identifier[friendly_name] = identifier[values] . identifier[unset] , identifier[unique_name] = identifier[values] . identifier[unset] ,
identifier[attributes] = identifier[values] . identifier[unset] , identifier[type] = identifier[values] . identifier[unset] ):
... | def create(self, friendly_name=values.unset, unique_name=values.unset, attributes=values.unset, type=values.unset):
"""
Create a new ChannelInstance
:param unicode friendly_name: A human-readable name for the Channel.
:param unicode unique_name: A unique, addressable name for the Channel.
... |
def get_dataframe(self, force_computation=False):
"""
Preprocesses then transforms the return of fetch().
Args:
force_computation (bool, optional) : Defaults to False. If set to True, forces the computation of DataFrame at each call.
Returns:
pandas.DataFrame: P... | def function[get_dataframe, parameter[self, force_computation]]:
constant[
Preprocesses then transforms the return of fetch().
Args:
force_computation (bool, optional) : Defaults to False. If set to True, forces the computation of DataFrame at each call.
Returns:
... | keyword[def] identifier[get_dataframe] ( identifier[self] , identifier[force_computation] = keyword[False] ):
literal[string]
keyword[if] identifier[self] . identifier[df] keyword[is] keyword[not] keyword[None] keyword[and] keyword[not] identifier[force_computation] : keyword[return... | def get_dataframe(self, force_computation=False):
"""
Preprocesses then transforms the return of fetch().
Args:
force_computation (bool, optional) : Defaults to False. If set to True, forces the computation of DataFrame at each call.
Returns:
pandas.DataFrame: Prepr... |
def verify(signature: Signature, message: bytes, ver_key: VerKey, gen: Generator) -> bool:
"""
Verifies the message signature and returns true - if signature valid or false otherwise.
:param: signature - Signature to verify
:param: message - Message to verify
:param: ver_key - V... | def function[verify, parameter[signature, message, ver_key, gen]]:
constant[
Verifies the message signature and returns true - if signature valid or false otherwise.
:param: signature - Signature to verify
:param: message - Message to verify
:param: ver_key - Verification key
... | keyword[def] identifier[verify] ( identifier[signature] : identifier[Signature] , identifier[message] : identifier[bytes] , identifier[ver_key] : identifier[VerKey] , identifier[gen] : identifier[Generator] )-> identifier[bool] :
literal[string]
identifier[logger] = identifier[logging] . identifie... | def verify(signature: Signature, message: bytes, ver_key: VerKey, gen: Generator) -> bool:
"""
Verifies the message signature and returns true - if signature valid or false otherwise.
:param: signature - Signature to verify
:param: message - Message to verify
:param: ver_key - Verif... |
def concat(self, *dss, **kwargs):
"""
Concatenate dataswim instances from and
set it to the main dataframe
:param dss: dataswim instances to concatenate
:type dss: Ds
:param kwargs: keyword arguments for ``pd.concat``
"""
try:
df = p... | def function[concat, parameter[self]]:
constant[
Concatenate dataswim instances from and
set it to the main dataframe
:param dss: dataswim instances to concatenate
:type dss: Ds
:param kwargs: keyword arguments for ``pd.concat``
]
<ast.Try object at... | keyword[def] identifier[concat] ( identifier[self] ,* identifier[dss] ,** identifier[kwargs] ):
literal[string]
keyword[try] :
identifier[df] = identifier[pd] . identifier[DataFrame] ()
keyword[for] identifier[dsx] keyword[in] identifier[dss] :
identifi... | def concat(self, *dss, **kwargs):
"""
Concatenate dataswim instances from and
set it to the main dataframe
:param dss: dataswim instances to concatenate
:type dss: Ds
:param kwargs: keyword arguments for ``pd.concat``
"""
try:
df = pd.DataFrame(... |
def render_inner(self, token):
"""
Recursively renders child tokens. Joins the rendered
strings with no space in between.
If newlines / spaces are needed between tokens, add them
in their respective templates, or override this function
in the renderer subclass, so that w... | def function[render_inner, parameter[self, token]]:
constant[
Recursively renders child tokens. Joins the rendered
strings with no space in between.
If newlines / spaces are needed between tokens, add them
in their respective templates, or override this function
in the r... | keyword[def] identifier[render_inner] ( identifier[self] , identifier[token] ):
literal[string]
identifier[rendered] =[ identifier[self] . identifier[render] ( identifier[child] ) keyword[for] identifier[child] keyword[in] identifier[token] . identifier[children] ]
keyword[return] lite... | def render_inner(self, token):
"""
Recursively renders child tokens. Joins the rendered
strings with no space in between.
If newlines / spaces are needed between tokens, add them
in their respective templates, or override this function
in the renderer subclass, so that white... |
def setcal(self, cal, cal_error, offset, offset_err, data_type):
"""Set the dataset calibration coefficients.
Args::
cal the calibraton factor (attribute 'scale_factor')
cal_error calibration factor error
(attribute 'scale_factor_err')
offs... | def function[setcal, parameter[self, cal, cal_error, offset, offset_err, data_type]]:
constant[Set the dataset calibration coefficients.
Args::
cal the calibraton factor (attribute 'scale_factor')
cal_error calibration factor error
(attribute 'scale_... | keyword[def] identifier[setcal] ( identifier[self] , identifier[cal] , identifier[cal_error] , identifier[offset] , identifier[offset_err] , identifier[data_type] ):
literal[string]
identifier[status] = identifier[_C] . identifier[SDsetcal] ( identifier[self] . identifier[_id] , identifier[cal] , ... | def setcal(self, cal, cal_error, offset, offset_err, data_type):
"""Set the dataset calibration coefficients.
Args::
cal the calibraton factor (attribute 'scale_factor')
cal_error calibration factor error
(attribute 'scale_factor_err')
offset ... |
def to_serializable(self, use_bytes=False, bytes_type=bytes):
"""Convert a :class:`SampleSet` to a serializable object.
Note that the contents of the :attr:`.SampleSet.info` field are assumed
to be serializable.
Args:
use_bytes (bool, optional, default=False):
... | def function[to_serializable, parameter[self, use_bytes, bytes_type]]:
constant[Convert a :class:`SampleSet` to a serializable object.
Note that the contents of the :attr:`.SampleSet.info` field are assumed
to be serializable.
Args:
use_bytes (bool, optional, default=False)... | keyword[def] identifier[to_serializable] ( identifier[self] , identifier[use_bytes] = keyword[False] , identifier[bytes_type] = identifier[bytes] ):
literal[string]
identifier[schema_version] = literal[string]
identifier[record] ={ identifier[name] : identifier[array2bytes] ( identifier[... | def to_serializable(self, use_bytes=False, bytes_type=bytes):
"""Convert a :class:`SampleSet` to a serializable object.
Note that the contents of the :attr:`.SampleSet.info` field are assumed
to be serializable.
Args:
use_bytes (bool, optional, default=False):
I... |
def get_catch_vars(catch):
"""Returns 2-tuple with names of catch control vars, e.g. for "catch $was_exc, $exc"
it returns ('was_exc', 'err').
Args:
catch: the whole catch line
Returns:
2-tuple with names of catch control variables
Raises:
exceptions.YamlSyntaxError if the... | def function[get_catch_vars, parameter[catch]]:
constant[Returns 2-tuple with names of catch control vars, e.g. for "catch $was_exc, $exc"
it returns ('was_exc', 'err').
Args:
catch: the whole catch line
Returns:
2-tuple with names of catch control variables
Raises:
ex... | keyword[def] identifier[get_catch_vars] ( identifier[catch] ):
literal[string]
identifier[catch_re] = identifier[re] . identifier[compile] ( literal[string] )
identifier[res] = identifier[catch_re] . identifier[match] ( identifier[catch] )
keyword[if] identifier[res] keyword[is] keyword[None] ... | def get_catch_vars(catch):
"""Returns 2-tuple with names of catch control vars, e.g. for "catch $was_exc, $exc"
it returns ('was_exc', 'err').
Args:
catch: the whole catch line
Returns:
2-tuple with names of catch control variables
Raises:
exceptions.YamlSyntaxError if the... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.