code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def process_edge_flow(self, source, sink, i, j, algo, q):
'''
API: process_edge_flow(self, source, sink, i, j, algo, q)
Description:
Used by by max_flow_preflowpush() method. Processes edges along
prefolow push.
Input:
source: Source node name of flow graph.
... | def function[process_edge_flow, parameter[self, source, sink, i, j, algo, q]]:
constant[
API: process_edge_flow(self, source, sink, i, j, algo, q)
Description:
Used by by max_flow_preflowpush() method. Processes edges along
prefolow push.
Input:
source: Source... | keyword[def] identifier[process_edge_flow] ( identifier[self] , identifier[source] , identifier[sink] , identifier[i] , identifier[j] , identifier[algo] , identifier[q] ):
literal[string]
keyword[if] ( identifier[self] . identifier[get_node_attr] ( identifier[i] , literal[string] )!=
ident... | def process_edge_flow(self, source, sink, i, j, algo, q):
"""
API: process_edge_flow(self, source, sink, i, j, algo, q)
Description:
Used by by max_flow_preflowpush() method. Processes edges along
prefolow push.
Input:
source: Source node name of flow graph.
... |
def reinit(self):
"""Use carefully to reset the episode count to 0."""
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((self.server, self.port))
self._hello(sock)
comms.send_message(sock, ("<Init>" + self._get_token() + "</Init>").encode())
reply = ... | def function[reinit, parameter[self]]:
constant[Use carefully to reset the episode count to 0.]
variable[sock] assign[=] call[name[socket].socket, parameter[name[socket].AF_INET, name[socket].SOCK_STREAM]]
call[name[sock].connect, parameter[tuple[[<ast.Attribute object at 0x7da1b1b11d20>, <ast.A... | keyword[def] identifier[reinit] ( identifier[self] ):
literal[string]
identifier[sock] = identifier[socket] . identifier[socket] ( identifier[socket] . identifier[AF_INET] , identifier[socket] . identifier[SOCK_STREAM] )
identifier[sock] . identifier[connect] (( identifier[self] . identifi... | def reinit(self):
"""Use carefully to reset the episode count to 0."""
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((self.server, self.port))
self._hello(sock)
comms.send_message(sock, ('<Init>' + self._get_token() + '</Init>').encode())
reply = comms.recv_message(sock)
... |
def _graphic(self):
"""
Adds the correct graphic options depending of the OS
"""
if sys.platform.startswith("win"):
return []
if len(os.environ.get("DISPLAY", "")) > 0:
return []
if "-nographic" not in self._options:
return ["-nographi... | def function[_graphic, parameter[self]]:
constant[
Adds the correct graphic options depending of the OS
]
if call[name[sys].platform.startswith, parameter[constant[win]]] begin[:]
return[list[[]]]
if compare[call[name[len], parameter[call[name[os].environ.get, parameter[c... | keyword[def] identifier[_graphic] ( identifier[self] ):
literal[string]
keyword[if] identifier[sys] . identifier[platform] . identifier[startswith] ( literal[string] ):
keyword[return] []
keyword[if] identifier[len] ( identifier[os] . identifier[environ] . identifier[get] (... | def _graphic(self):
"""
Adds the correct graphic options depending of the OS
"""
if sys.platform.startswith('win'):
return [] # depends on [control=['if'], data=[]]
if len(os.environ.get('DISPLAY', '')) > 0:
return [] # depends on [control=['if'], data=[]]
if '-nographi... |
def take_snapshot(self, name, wait=True):
"""
Take a snapshot of this droplet (must be powered off)
Parameters
----------
name: str
Name of the snapshot
wait: bool, default True
Whether to block until the pending action is completed
"""
... | def function[take_snapshot, parameter[self, name, wait]]:
constant[
Take a snapshot of this droplet (must be powered off)
Parameters
----------
name: str
Name of the snapshot
wait: bool, default True
Whether to block until the pending action is co... | keyword[def] identifier[take_snapshot] ( identifier[self] , identifier[name] , identifier[wait] = keyword[True] ):
literal[string]
keyword[return] identifier[self] . identifier[_action] ( literal[string] , identifier[name] = identifier[name] , identifier[wait] = identifier[wait] ) | def take_snapshot(self, name, wait=True):
"""
Take a snapshot of this droplet (must be powered off)
Parameters
----------
name: str
Name of the snapshot
wait: bool, default True
Whether to block until the pending action is completed
"""
re... |
def _apply_advanced_config(config_spec, advanced_config, vm_extra_config=None):
'''
Sets configuration parameters for the vm
config_spec
vm.ConfigSpec object
advanced_config
config key value pairs
vm_extra_config
Virtual machine vm_ref.config.extraConfig object
'''
... | def function[_apply_advanced_config, parameter[config_spec, advanced_config, vm_extra_config]]:
constant[
Sets configuration parameters for the vm
config_spec
vm.ConfigSpec object
advanced_config
config key value pairs
vm_extra_config
Virtual machine vm_ref.config.extr... | keyword[def] identifier[_apply_advanced_config] ( identifier[config_spec] , identifier[advanced_config] , identifier[vm_extra_config] = keyword[None] ):
literal[string]
identifier[log] . identifier[trace] ( literal[string]
literal[string] , identifier[advanced_config] )
keyword[if] identifier[i... | def _apply_advanced_config(config_spec, advanced_config, vm_extra_config=None):
"""
Sets configuration parameters for the vm
config_spec
vm.ConfigSpec object
advanced_config
config key value pairs
vm_extra_config
Virtual machine vm_ref.config.extraConfig object
"""
... |
def get_consensus(block):
"""Calculate a simple consensus sequence for the block."""
from collections import Counter
# Take aligned (non-insert) chars from all rows; transpose
columns = zip(*[[c for c in row['seq'] if not c.islower()]
for row in block['sequences']])
cons_chars =... | def function[get_consensus, parameter[block]]:
constant[Calculate a simple consensus sequence for the block.]
from relative_module[collections] import module[Counter]
variable[columns] assign[=] call[name[zip], parameter[<ast.Starred object at 0x7da18fe90eb0>]]
variable[cons_chars] assign[=]... | keyword[def] identifier[get_consensus] ( identifier[block] ):
literal[string]
keyword[from] identifier[collections] keyword[import] identifier[Counter]
identifier[columns] = identifier[zip] (*[[ identifier[c] keyword[for] identifier[c] keyword[in] identifier[row] [ literal[string] ] keyw... | def get_consensus(block):
"""Calculate a simple consensus sequence for the block."""
from collections import Counter
# Take aligned (non-insert) chars from all rows; transpose
columns = zip(*[[c for c in row['seq'] if not c.islower()] for row in block['sequences']])
cons_chars = [Counter(col).most_c... |
def _correlation_computation(self, task):
"""Use BLAS API to do correlation computation (matrix multiplication).
Parameters
----------
task: tuple (start_voxel_id, num_processed_voxels)
depicting the voxels assigned to compute
Returns
-------
corr: 3... | def function[_correlation_computation, parameter[self, task]]:
constant[Use BLAS API to do correlation computation (matrix multiplication).
Parameters
----------
task: tuple (start_voxel_id, num_processed_voxels)
depicting the voxels assigned to compute
Returns
... | keyword[def] identifier[_correlation_computation] ( identifier[self] , identifier[task] ):
literal[string]
identifier[time1] = identifier[time] . identifier[time] ()
identifier[s] = identifier[task] [ literal[int] ]
identifier[nEpochs] = identifier[len] ( identifier[self] . identi... | def _correlation_computation(self, task):
"""Use BLAS API to do correlation computation (matrix multiplication).
Parameters
----------
task: tuple (start_voxel_id, num_processed_voxels)
depicting the voxels assigned to compute
Returns
-------
corr: 3D ar... |
def _load_char(self, char):
"""Build and store a glyph corresponding to an individual character
Parameters
----------
char : str
A single character to be represented.
"""
assert isinstance(char, string_types) and len(char) == 1
assert char not in self... | def function[_load_char, parameter[self, char]]:
constant[Build and store a glyph corresponding to an individual character
Parameters
----------
char : str
A single character to be represented.
]
assert[<ast.BoolOp object at 0x7da1b0e49d50>]
assert[compare[na... | keyword[def] identifier[_load_char] ( identifier[self] , identifier[char] ):
literal[string]
keyword[assert] identifier[isinstance] ( identifier[char] , identifier[string_types] ) keyword[and] identifier[len] ( identifier[char] )== literal[int]
keyword[assert] identifier[char] keyword... | def _load_char(self, char):
"""Build and store a glyph corresponding to an individual character
Parameters
----------
char : str
A single character to be represented.
"""
assert isinstance(char, string_types) and len(char) == 1
assert char not in self._glyphs
... |
def encode(cls, value):
"""Encodes a value into bencoded bytes.
:param value: Python object to be encoded (str, int, list, dict).
:param str val_encoding: Encoding used by strings in a given object.
:rtype: bytes
"""
val_encoding = 'utf-8'
def encode_str(v):
... | def function[encode, parameter[cls, value]]:
constant[Encodes a value into bencoded bytes.
:param value: Python object to be encoded (str, int, list, dict).
:param str val_encoding: Encoding used by strings in a given object.
:rtype: bytes
]
variable[val_encoding] assign... | keyword[def] identifier[encode] ( identifier[cls] , identifier[value] ):
literal[string]
identifier[val_encoding] = literal[string]
keyword[def] identifier[encode_str] ( identifier[v] ):
keyword[try] :
identifier[v_enc] = identifier[encode] ( identifier[v] ... | def encode(cls, value):
"""Encodes a value into bencoded bytes.
:param value: Python object to be encoded (str, int, list, dict).
:param str val_encoding: Encoding used by strings in a given object.
:rtype: bytes
"""
val_encoding = 'utf-8'
def encode_str(v):
try:
... |
def dump_config(self):
"""Pretty print the configuration dict to stdout."""
yaml_content = self.get_merged_config()
print('YAML Configuration\n%s\n' % yaml_content.read())
try:
self.load()
print('Python Configuration\n%s\n' % pretty(self.yamldocs))
except ... | def function[dump_config, parameter[self]]:
constant[Pretty print the configuration dict to stdout.]
variable[yaml_content] assign[=] call[name[self].get_merged_config, parameter[]]
call[name[print], parameter[binary_operation[constant[YAML Configuration
%s
] <ast.Mod object at 0x7da2590d6920> c... | keyword[def] identifier[dump_config] ( identifier[self] ):
literal[string]
identifier[yaml_content] = identifier[self] . identifier[get_merged_config] ()
identifier[print] ( literal[string] % identifier[yaml_content] . identifier[read] ())
keyword[try] :
identifier[se... | def dump_config(self):
"""Pretty print the configuration dict to stdout."""
yaml_content = self.get_merged_config()
print('YAML Configuration\n%s\n' % yaml_content.read())
try:
self.load()
print('Python Configuration\n%s\n' % pretty(self.yamldocs)) # depends on [control=['try'], data=[]... |
def dump(self):
"""Writes the changes to the configuration file."""
try:
import yaml
cfg_file = self._cfg_file()
cfg_dir, __ = os.path.split(cfg_file)
os.makedirs(cfg_dir, exist_ok=True)
with open(cfg_file, 'w') as f:
yaml.dump(... | def function[dump, parameter[self]]:
constant[Writes the changes to the configuration file.]
<ast.Try object at 0x7da1b121b760> | keyword[def] identifier[dump] ( identifier[self] ):
literal[string]
keyword[try] :
keyword[import] identifier[yaml]
identifier[cfg_file] = identifier[self] . identifier[_cfg_file] ()
identifier[cfg_dir] , identifier[__] = identifier[os] . identifier[path] . ... | def dump(self):
"""Writes the changes to the configuration file."""
try:
import yaml
cfg_file = self._cfg_file()
(cfg_dir, __) = os.path.split(cfg_file)
os.makedirs(cfg_dir, exist_ok=True)
with open(cfg_file, 'w') as f:
yaml.dump(self, f) # depends on [contro... |
def initial_refcounts(self, initial_terms):
"""
Calculate initial refcounts for execution of this graph.
Parameters
----------
initial_terms : iterable[Term]
An iterable of terms that were pre-computed before graph execution.
Each node starts with a refcount... | def function[initial_refcounts, parameter[self, initial_terms]]:
constant[
Calculate initial refcounts for execution of this graph.
Parameters
----------
initial_terms : iterable[Term]
An iterable of terms that were pre-computed before graph execution.
Each ... | keyword[def] identifier[initial_refcounts] ( identifier[self] , identifier[initial_terms] ):
literal[string]
identifier[refcounts] = identifier[self] . identifier[graph] . identifier[out_degree] ()
keyword[for] identifier[t] keyword[in] identifier[self] . identifier[outputs] . identifie... | def initial_refcounts(self, initial_terms):
"""
Calculate initial refcounts for execution of this graph.
Parameters
----------
initial_terms : iterable[Term]
An iterable of terms that were pre-computed before graph execution.
Each node starts with a refcount equ... |
def _filter_data_frame(df, data_col, filter_col, filter_str=None):
"""Return a filtered data frame as a dictionary."""
if filter_str is not None:
relevant_cols = data_col + [filter_col]
df.dropna(inplace=True, subset=relevant_cols)
row_filter = df[filter_col].str.contains(filter_str, cas... | def function[_filter_data_frame, parameter[df, data_col, filter_col, filter_str]]:
constant[Return a filtered data frame as a dictionary.]
if compare[name[filter_str] is_not constant[None]] begin[:]
variable[relevant_cols] assign[=] binary_operation[name[data_col] + list[[<ast.Name objec... | keyword[def] identifier[_filter_data_frame] ( identifier[df] , identifier[data_col] , identifier[filter_col] , identifier[filter_str] = keyword[None] ):
literal[string]
keyword[if] identifier[filter_str] keyword[is] keyword[not] keyword[None] :
identifier[relevant_cols] = identifier[data_col] ... | def _filter_data_frame(df, data_col, filter_col, filter_str=None):
"""Return a filtered data frame as a dictionary."""
if filter_str is not None:
relevant_cols = data_col + [filter_col]
df.dropna(inplace=True, subset=relevant_cols)
row_filter = df[filter_col].str.contains(filter_str, cas... |
def dskgtl(keywrd):
"""
Retrieve the value of a specified DSK tolerance or margin parameter.
https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/dskgtl_c.html
:param keywrd: Code specifying parameter to retrieve.
:type keywrd: int
:return: Value of parameter.
:rtype: float
... | def function[dskgtl, parameter[keywrd]]:
constant[
Retrieve the value of a specified DSK tolerance or margin parameter.
https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/dskgtl_c.html
:param keywrd: Code specifying parameter to retrieve.
:type keywrd: int
:return: Value of ... | keyword[def] identifier[dskgtl] ( identifier[keywrd] ):
literal[string]
identifier[keywrd] = identifier[ctypes] . identifier[c_int] ( identifier[keywrd] )
identifier[dpval] = identifier[ctypes] . identifier[c_double] ( literal[int] )
identifier[libspice] . identifier[dskgtl_c] ( identifier[keywrd... | def dskgtl(keywrd):
"""
Retrieve the value of a specified DSK tolerance or margin parameter.
https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/dskgtl_c.html
:param keywrd: Code specifying parameter to retrieve.
:type keywrd: int
:return: Value of parameter.
:rtype: float
... |
def get_host(name):
"""
Prints the public dns name of `name`, if it exists.
:param name: The instance name.
:type name: ``str``
"""
f = {'instance-state-name': 'running', 'tag:Name': name}
ec2 = boto.connect_ec2(region=get_region())
rs = ec2.get_all_instances(filters=f)
if len(rs) =... | def function[get_host, parameter[name]]:
constant[
Prints the public dns name of `name`, if it exists.
:param name: The instance name.
:type name: ``str``
]
variable[f] assign[=] dictionary[[<ast.Constant object at 0x7da18fe93a30>, <ast.Constant object at 0x7da18fe92410>], [<ast.Constan... | keyword[def] identifier[get_host] ( identifier[name] ):
literal[string]
identifier[f] ={ literal[string] : literal[string] , literal[string] : identifier[name] }
identifier[ec2] = identifier[boto] . identifier[connect_ec2] ( identifier[region] = identifier[get_region] ())
identifier[rs] = identif... | def get_host(name):
"""
Prints the public dns name of `name`, if it exists.
:param name: The instance name.
:type name: ``str``
"""
f = {'instance-state-name': 'running', 'tag:Name': name}
ec2 = boto.connect_ec2(region=get_region())
rs = ec2.get_all_instances(filters=f)
if len(rs) =... |
def merge_lists(*args):
"""Merge an arbitrary number of lists into a single list and dedupe it
Args:
*args: Two or more lists
Returns:
A deduped merged list of all the provided lists as a single list
"""
out = {}
for contacts in filter(None, args):
for contact in conta... | def function[merge_lists, parameter[]]:
constant[Merge an arbitrary number of lists into a single list and dedupe it
Args:
*args: Two or more lists
Returns:
A deduped merged list of all the provided lists as a single list
]
variable[out] assign[=] dictionary[[], []]
... | keyword[def] identifier[merge_lists] (* identifier[args] ):
literal[string]
identifier[out] ={}
keyword[for] identifier[contacts] keyword[in] identifier[filter] ( keyword[None] , identifier[args] ):
keyword[for] identifier[contact] keyword[in] identifier[contacts] :
identi... | def merge_lists(*args):
"""Merge an arbitrary number of lists into a single list and dedupe it
Args:
*args: Two or more lists
Returns:
A deduped merged list of all the provided lists as a single list
"""
out = {}
for contacts in filter(None, args):
for contact in contac... |
def do(self, x_orig):
"""Transform the unknowns to preconditioned coordinates
This method also transforms the gradient to original coordinates
"""
if self.scales is None:
return x_orig
else:
return np.dot(self.rotation.transpose(), x_orig)*self.scales | def function[do, parameter[self, x_orig]]:
constant[Transform the unknowns to preconditioned coordinates
This method also transforms the gradient to original coordinates
]
if compare[name[self].scales is constant[None]] begin[:]
return[name[x_orig]] | keyword[def] identifier[do] ( identifier[self] , identifier[x_orig] ):
literal[string]
keyword[if] identifier[self] . identifier[scales] keyword[is] keyword[None] :
keyword[return] identifier[x_orig]
keyword[else] :
keyword[return] identifier[np] . identifie... | def do(self, x_orig):
"""Transform the unknowns to preconditioned coordinates
This method also transforms the gradient to original coordinates
"""
if self.scales is None:
return x_orig # depends on [control=['if'], data=[]]
else:
return np.dot(self.rotation.transpose(), ... |
def set_storage(self, storage):
"""Set storage backend for downloader
For full list of storage backend supported, please see :mod:`storage`.
Args:
storage (dict or BaseStorage): storage backend configuration or instance
"""
if isinstance(storage, BaseStorage):
... | def function[set_storage, parameter[self, storage]]:
constant[Set storage backend for downloader
For full list of storage backend supported, please see :mod:`storage`.
Args:
storage (dict or BaseStorage): storage backend configuration or instance
]
if call[name[isi... | keyword[def] identifier[set_storage] ( identifier[self] , identifier[storage] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[storage] , identifier[BaseStorage] ):
identifier[self] . identifier[storage] = identifier[storage]
keyword[elif] identifier[isins... | def set_storage(self, storage):
"""Set storage backend for downloader
For full list of storage backend supported, please see :mod:`storage`.
Args:
storage (dict or BaseStorage): storage backend configuration or instance
"""
if isinstance(storage, BaseStorage):
self... |
def _extract_docs_raises(self):
"""Extract raises description from docstring. The internal computed raises list is
composed by tuples (raise, description).
"""
if self.dst.style['in'] == 'numpydoc':
data = '\n'.join([d.rstrip().replace(self.docs['out']['spaces'], '', 1) for ... | def function[_extract_docs_raises, parameter[self]]:
constant[Extract raises description from docstring. The internal computed raises list is
composed by tuples (raise, description).
]
if compare[call[name[self].dst.style][constant[in]] equal[==] constant[numpydoc]] begin[:]
... | keyword[def] identifier[_extract_docs_raises] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[dst] . identifier[style] [ literal[string] ]== literal[string] :
identifier[data] = literal[string] . identifier[join] ([ identifier[d] . identifier[rstrip] ()... | def _extract_docs_raises(self):
"""Extract raises description from docstring. The internal computed raises list is
composed by tuples (raise, description).
"""
if self.dst.style['in'] == 'numpydoc':
data = '\n'.join([d.rstrip().replace(self.docs['out']['spaces'], '', 1) for d in self.do... |
def in_casapy (helper, vis=None, figfile=None):
"""This function is run inside the weirdo casapy IPython environment! A
strange set of modules is available, and the
`pwkit.environments.casa.scripting` system sets up a very particular
environment to allow encapsulated scripting.
"""
if vis is No... | def function[in_casapy, parameter[helper, vis, figfile]]:
constant[This function is run inside the weirdo casapy IPython environment! A
strange set of modules is available, and the
`pwkit.environments.casa.scripting` system sets up a very particular
environment to allow encapsulated scripting.
... | keyword[def] identifier[in_casapy] ( identifier[helper] , identifier[vis] = keyword[None] , identifier[figfile] = keyword[None] ):
literal[string]
keyword[if] identifier[vis] keyword[is] keyword[None] :
keyword[raise] identifier[ValueError] ( literal[string] )
identifier[helper] . identi... | def in_casapy(helper, vis=None, figfile=None):
"""This function is run inside the weirdo casapy IPython environment! A
strange set of modules is available, and the
`pwkit.environments.casa.scripting` system sets up a very particular
environment to allow encapsulated scripting.
"""
if vis is Non... |
def _compute_edges(self):
"""Compute the edges of the current surface.
Returns:
Tuple[~curve.Curve, ~curve.Curve, ~curve.Curve]: The edges of
the surface.
"""
nodes1, nodes2, nodes3 = _surface_helpers.compute_edge_nodes(
self._nodes, self._degree
... | def function[_compute_edges, parameter[self]]:
constant[Compute the edges of the current surface.
Returns:
Tuple[~curve.Curve, ~curve.Curve, ~curve.Curve]: The edges of
the surface.
]
<ast.Tuple object at 0x7da204620a60> assign[=] call[name[_surface_helpers].comp... | keyword[def] identifier[_compute_edges] ( identifier[self] ):
literal[string]
identifier[nodes1] , identifier[nodes2] , identifier[nodes3] = identifier[_surface_helpers] . identifier[compute_edge_nodes] (
identifier[self] . identifier[_nodes] , identifier[self] . identifier[_degree]
... | def _compute_edges(self):
"""Compute the edges of the current surface.
Returns:
Tuple[~curve.Curve, ~curve.Curve, ~curve.Curve]: The edges of
the surface.
"""
(nodes1, nodes2, nodes3) = _surface_helpers.compute_edge_nodes(self._nodes, self._degree)
edge1 = _curve_mod... |
def minimum(lhs, rhs):
"""Returns element-wise minimum of the input arrays with broadcasting.
Equivalent to ``mx.nd.broadcast_minimum(lhs, rhs)``.
.. note::
If the corresponding dimensions of two arrays have the same size or one of them has size 1,
then the arrays are broadcastable to a com... | def function[minimum, parameter[lhs, rhs]]:
constant[Returns element-wise minimum of the input arrays with broadcasting.
Equivalent to ``mx.nd.broadcast_minimum(lhs, rhs)``.
.. note::
If the corresponding dimensions of two arrays have the same size or one of them has size 1,
then the ar... | keyword[def] identifier[minimum] ( identifier[lhs] , identifier[rhs] ):
literal[string]
keyword[return] identifier[_ufunc_helper] (
identifier[lhs] ,
identifier[rhs] ,
identifier[op] . identifier[broadcast_minimum] ,
keyword[lambda] identifier[x] , identifier[y] : identifier[x] ... | def minimum(lhs, rhs):
"""Returns element-wise minimum of the input arrays with broadcasting.
Equivalent to ``mx.nd.broadcast_minimum(lhs, rhs)``.
.. note::
If the corresponding dimensions of two arrays have the same size or one of them has size 1,
then the arrays are broadcastable to a com... |
def expire(self, current_time=None):
"""Expire any old entries
`current_time`
Optional time to be used to clean up queue (can be used in unit tests)
"""
if not self._queue:
return
if current_time is None:
current_time = time()
while ... | def function[expire, parameter[self, current_time]]:
constant[Expire any old entries
`current_time`
Optional time to be used to clean up queue (can be used in unit tests)
]
if <ast.UnaryOp object at 0x7da1b0bf4fa0> begin[:]
return[None]
if compare[name[curren... | keyword[def] identifier[expire] ( identifier[self] , identifier[current_time] = keyword[None] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[_queue] :
keyword[return]
keyword[if] identifier[current_time] keyword[is] keyword[None] :
... | def expire(self, current_time=None):
"""Expire any old entries
`current_time`
Optional time to be used to clean up queue (can be used in unit tests)
"""
if not self._queue:
return # depends on [control=['if'], data=[]]
if current_time is None:
current_time = tim... |
def edge_detect(image, size):
"""
Applies a Sobel filter to the given image.
:param image: An image as a list of (R,G,B) values
:param size: The size of the image as a tuple (width, height)
:return: An array of the Sobel gradient value of each image pixel
This value roughly corresponds to how mu... | def function[edge_detect, parameter[image, size]]:
constant[
Applies a Sobel filter to the given image.
:param image: An image as a list of (R,G,B) values
:param size: The size of the image as a tuple (width, height)
:return: An array of the Sobel gradient value of each image pixel
This valu... | keyword[def] identifier[edge_detect] ( identifier[image] , identifier[size] ):
literal[string]
identifier[width] , identifier[height] = identifier[size]
identifier[edge_data] =[ literal[int] ]* identifier[len] ( identifier[image] )
identifier[gray_scale_img] = identifier[list] ( identifier[... | def edge_detect(image, size):
"""
Applies a Sobel filter to the given image.
:param image: An image as a list of (R,G,B) values
:param size: The size of the image as a tuple (width, height)
:return: An array of the Sobel gradient value of each image pixel
This value roughly corresponds to how mu... |
def reconcile(self, server):
"""
Reconcile this collection with the server.
"""
if not self.challenge.exists(server):
raise Exception('Challenge does not exist on server')
existing = MapRouletteTaskCollection.from_server(server, self.challenge)
same = []
... | def function[reconcile, parameter[self, server]]:
constant[
Reconcile this collection with the server.
]
if <ast.UnaryOp object at 0x7da20c6c4430> begin[:]
<ast.Raise object at 0x7da20c6c78e0>
variable[existing] assign[=] call[name[MapRouletteTaskCollection].from_server, ... | keyword[def] identifier[reconcile] ( identifier[self] , identifier[server] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[challenge] . identifier[exists] ( identifier[server] ):
keyword[raise] identifier[Exception] ( literal[string] )
identifier[... | def reconcile(self, server):
"""
Reconcile this collection with the server.
"""
if not self.challenge.exists(server):
raise Exception('Challenge does not exist on server') # depends on [control=['if'], data=[]]
existing = MapRouletteTaskCollection.from_server(server, self.challenge)... |
def disconnect_relationship(cls, id, related_collection_name, request_json):
"""
Disconnect one or more relationship in a collection with cardinality 'Many'.
:param id: The 'id' field of the node on the left side of the relationship in the database. The id field must \
be set in the mo... | def function[disconnect_relationship, parameter[cls, id, related_collection_name, request_json]]:
constant[
Disconnect one or more relationship in a collection with cardinality 'Many'.
:param id: The 'id' field of the node on the left side of the relationship in the database. The id field must... | keyword[def] identifier[disconnect_relationship] ( identifier[cls] , identifier[id] , identifier[related_collection_name] , identifier[request_json] ):
literal[string]
keyword[try] :
identifier[this_resource] = identifier[cls] . identifier[nodes] . identifier[get] ( identifier[id] = id... | def disconnect_relationship(cls, id, related_collection_name, request_json):
"""
Disconnect one or more relationship in a collection with cardinality 'Many'.
:param id: The 'id' field of the node on the left side of the relationship in the database. The id field must be set in the model --... |
def poll(self):
"""Retrieves older requests that may not make it back quick
enough"""
if self.redis_connected:
json_item = request.get_json()
result = None
try:
key = "rest:poll:{u}".format(u=json_item['poll_id'])
result = self.... | def function[poll, parameter[self]]:
constant[Retrieves older requests that may not make it back quick
enough]
if name[self].redis_connected begin[:]
variable[json_item] assign[=] call[name[request].get_json, parameter[]]
variable[result] assign[=] constant[None]
... | keyword[def] identifier[poll] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[redis_connected] :
identifier[json_item] = identifier[request] . identifier[get_json] ()
identifier[result] = keyword[None]
keyword[try] :
... | def poll(self):
"""Retrieves older requests that may not make it back quick
enough"""
if self.redis_connected:
json_item = request.get_json()
result = None
try:
key = 'rest:poll:{u}'.format(u=json_item['poll_id'])
result = self.redis_conn.get(key)
... |
def _parse_match_info(match, soccer=False):
"""
Parse string containing info of a specific match
:param match: Match data
:type match: string
:param soccer: Set to true if match contains soccer data, defaults to False
:type soccer: bool, optional
:return: Dictionary containing match informa... | def function[_parse_match_info, parameter[match, soccer]]:
constant[
Parse string containing info of a specific match
:param match: Match data
:type match: string
:param soccer: Set to true if match contains soccer data, defaults to False
:type soccer: bool, optional
:return: Dictionary... | keyword[def] identifier[_parse_match_info] ( identifier[match] , identifier[soccer] = keyword[False] ):
literal[string]
identifier[match_info] ={}
identifier[i_open] = identifier[match] . identifier[index] ( literal[string] )
identifier[i_close] = identifier[match] . identifier[index] ( literal[... | def _parse_match_info(match, soccer=False):
"""
Parse string containing info of a specific match
:param match: Match data
:type match: string
:param soccer: Set to true if match contains soccer data, defaults to False
:type soccer: bool, optional
:return: Dictionary containing match informa... |
def _rel(self, copy=False):
"""
Get descriptive kwargs of the container (e.g. name, description, meta).
"""
rel = {}
for key, obj in vars(self).items():
if not isinstance(obj, (pd.Series, pd.DataFrame, pd.SparseSeries, pd.SparseDataFrame)) and not key.startswith('_'):... | def function[_rel, parameter[self, copy]]:
constant[
Get descriptive kwargs of the container (e.g. name, description, meta).
]
variable[rel] assign[=] dictionary[[], []]
for taget[tuple[[<ast.Name object at 0x7da18f00fdc0>, <ast.Name object at 0x7da18f00fc40>]]] in starred[call[c... | keyword[def] identifier[_rel] ( identifier[self] , identifier[copy] = keyword[False] ):
literal[string]
identifier[rel] ={}
keyword[for] identifier[key] , identifier[obj] keyword[in] identifier[vars] ( identifier[self] ). identifier[items] ():
keyword[if] keyword[not] ide... | def _rel(self, copy=False):
"""
Get descriptive kwargs of the container (e.g. name, description, meta).
"""
rel = {}
for (key, obj) in vars(self).items():
if not isinstance(obj, (pd.Series, pd.DataFrame, pd.SparseSeries, pd.SparseDataFrame)) and (not key.startswith('_')):
... |
def _dataframe_to_csv(writer, dataframe, delimiter, with_header):
"""serialize the dataframe with different delimiters"""
encoding_writer = codecs.getwriter('utf-8')(writer)
dataframe.to_csv(
path_or_buf=encoding_writer,
sep=delimiter,
header=with_header,
index=False
) | def function[_dataframe_to_csv, parameter[writer, dataframe, delimiter, with_header]]:
constant[serialize the dataframe with different delimiters]
variable[encoding_writer] assign[=] call[call[name[codecs].getwriter, parameter[constant[utf-8]]], parameter[name[writer]]]
call[name[dataframe].to_c... | keyword[def] identifier[_dataframe_to_csv] ( identifier[writer] , identifier[dataframe] , identifier[delimiter] , identifier[with_header] ):
literal[string]
identifier[encoding_writer] = identifier[codecs] . identifier[getwriter] ( literal[string] )( identifier[writer] )
identifier[dataframe] . identi... | def _dataframe_to_csv(writer, dataframe, delimiter, with_header):
"""serialize the dataframe with different delimiters"""
encoding_writer = codecs.getwriter('utf-8')(writer)
dataframe.to_csv(path_or_buf=encoding_writer, sep=delimiter, header=with_header, index=False) |
def query(self, tablename, attributes=None, consistent=False, count=False,
index=None, limit=None, desc=False, return_capacity=None,
filter=None, filter_or=False, exclusive_start_key=None, **kwargs):
"""
Perform an index query on a table
This uses the older version o... | def function[query, parameter[self, tablename, attributes, consistent, count, index, limit, desc, return_capacity, filter, filter_or, exclusive_start_key]]:
constant[
Perform an index query on a table
This uses the older version of the DynamoDB API.
See also: :meth:`~.query2`.
... | keyword[def] identifier[query] ( identifier[self] , identifier[tablename] , identifier[attributes] = keyword[None] , identifier[consistent] = keyword[False] , identifier[count] = keyword[False] ,
identifier[index] = keyword[None] , identifier[limit] = keyword[None] , identifier[desc] = keyword[False] , identifier[re... | def query(self, tablename, attributes=None, consistent=False, count=False, index=None, limit=None, desc=False, return_capacity=None, filter=None, filter_or=False, exclusive_start_key=None, **kwargs):
"""
Perform an index query on a table
This uses the older version of the DynamoDB API.
See ... |
def get_variant_info(genes):
"""Get variant information"""
data = {'canonical_transcripts': []}
for gene_obj in genes:
if not gene_obj.get('canonical_transcripts'):
tx = gene_obj['transcripts'][0]
tx_id = tx['transcript_id']
exon = tx.get('exon', '-')
... | def function[get_variant_info, parameter[genes]]:
constant[Get variant information]
variable[data] assign[=] dictionary[[<ast.Constant object at 0x7da20cabd690>], [<ast.List object at 0x7da20cabed70>]]
for taget[name[gene_obj]] in starred[name[genes]] begin[:]
if <ast.UnaryOp obj... | keyword[def] identifier[get_variant_info] ( identifier[genes] ):
literal[string]
identifier[data] ={ literal[string] :[]}
keyword[for] identifier[gene_obj] keyword[in] identifier[genes] :
keyword[if] keyword[not] identifier[gene_obj] . identifier[get] ( literal[string] ):
id... | def get_variant_info(genes):
"""Get variant information"""
data = {'canonical_transcripts': []}
for gene_obj in genes:
if not gene_obj.get('canonical_transcripts'):
tx = gene_obj['transcripts'][0]
tx_id = tx['transcript_id']
exon = tx.get('exon', '-')
... |
def filter(self, query: Query, entity: type) -> Tuple[Query, Any]:
"""Apply the `_method` to all childs of the node.
:param query: The sqlachemy query.
:type query: Query
:param entity: The entity model of the query.
:type entity: type
:return: A tuple with in ... | def function[filter, parameter[self, query, entity]]:
constant[Apply the `_method` to all childs of the node.
:param query: The sqlachemy query.
:type query: Query
:param entity: The entity model of the query.
:type entity: type
:return: A tuple with in first p... | keyword[def] identifier[filter] ( identifier[self] , identifier[query] : identifier[Query] , identifier[entity] : identifier[type] )-> identifier[Tuple] [ identifier[Query] , identifier[Any] ]:
literal[string]
identifier[new_query] = identifier[query]
identifier[c_filter_list] =[]
... | def filter(self, query: Query, entity: type) -> Tuple[Query, Any]:
"""Apply the `_method` to all childs of the node.
:param query: The sqlachemy query.
:type query: Query
:param entity: The entity model of the query.
:type entity: type
:return: A tuple with in firs... |
def dnde(self, x, params=None):
"""Evaluate differential flux."""
params = self.params if params is None else params
return np.squeeze(self.eval_dnde(x, params, self.scale,
self.extra_params)) | def function[dnde, parameter[self, x, params]]:
constant[Evaluate differential flux.]
variable[params] assign[=] <ast.IfExp object at 0x7da207f99de0>
return[call[name[np].squeeze, parameter[call[name[self].eval_dnde, parameter[name[x], name[params], name[self].scale, name[self].extra_params]]]]] | keyword[def] identifier[dnde] ( identifier[self] , identifier[x] , identifier[params] = keyword[None] ):
literal[string]
identifier[params] = identifier[self] . identifier[params] keyword[if] identifier[params] keyword[is] keyword[None] keyword[else] identifier[params]
keyword[retur... | def dnde(self, x, params=None):
"""Evaluate differential flux."""
params = self.params if params is None else params
return np.squeeze(self.eval_dnde(x, params, self.scale, self.extra_params)) |
def heap_push(heap, row, weight, index, flag):
"""Push a new element onto the heap. The heap stores potential neighbors
for each data point. The ``row`` parameter determines which data point we
are addressing, the ``weight`` determines the distance (for heap sorting),
the ``index`` is the element to add... | def function[heap_push, parameter[heap, row, weight, index, flag]]:
constant[Push a new element onto the heap. The heap stores potential neighbors
for each data point. The ``row`` parameter determines which data point we
are addressing, the ``weight`` determines the distance (for heap sorting),
the ... | keyword[def] identifier[heap_push] ( identifier[heap] , identifier[row] , identifier[weight] , identifier[index] , identifier[flag] ):
literal[string]
identifier[indices] = identifier[heap] [ literal[int] , identifier[row] ]
identifier[weights] = identifier[heap] [ literal[int] , identifier[row] ]
... | def heap_push(heap, row, weight, index, flag):
"""Push a new element onto the heap. The heap stores potential neighbors
for each data point. The ``row`` parameter determines which data point we
are addressing, the ``weight`` determines the distance (for heap sorting),
the ``index`` is the element to add... |
def create_circuit_termination(circuit, interface, device, speed, xconnect_id=None, term_side='A'):
'''
.. versionadded:: 2019.2.0
Terminate a circuit on an interface
circuit
The name of the circuit
interface
The name of the interface to terminate on
device
The name of ... | def function[create_circuit_termination, parameter[circuit, interface, device, speed, xconnect_id, term_side]]:
constant[
.. versionadded:: 2019.2.0
Terminate a circuit on an interface
circuit
The name of the circuit
interface
The name of the interface to terminate on
devic... | keyword[def] identifier[create_circuit_termination] ( identifier[circuit] , identifier[interface] , identifier[device] , identifier[speed] , identifier[xconnect_id] = keyword[None] , identifier[term_side] = literal[string] ):
literal[string]
identifier[nb_device] = identifier[get_] ( literal[string] , lit... | def create_circuit_termination(circuit, interface, device, speed, xconnect_id=None, term_side='A'):
"""
.. versionadded:: 2019.2.0
Terminate a circuit on an interface
circuit
The name of the circuit
interface
The name of the interface to terminate on
device
The name of ... |
def assert_deepcopy_idempotent(obj):
'''Assert that obj does not change (w.r.t. ==) under repeated deepcopies
'''
from copy import deepcopy
obj1 = deepcopy(obj)
obj2 = deepcopy(obj1)
obj3 = deepcopy(obj2)
assert_equivalent(obj, obj1)
assert_equivalent(obj, obj2)
assert_equivalent(obj... | def function[assert_deepcopy_idempotent, parameter[obj]]:
constant[Assert that obj does not change (w.r.t. ==) under repeated deepcopies
]
from relative_module[copy] import module[deepcopy]
variable[obj1] assign[=] call[name[deepcopy], parameter[name[obj]]]
variable[obj2] assign[=] call[... | keyword[def] identifier[assert_deepcopy_idempotent] ( identifier[obj] ):
literal[string]
keyword[from] identifier[copy] keyword[import] identifier[deepcopy]
identifier[obj1] = identifier[deepcopy] ( identifier[obj] )
identifier[obj2] = identifier[deepcopy] ( identifier[obj1] )
identifier... | def assert_deepcopy_idempotent(obj):
"""Assert that obj does not change (w.r.t. ==) under repeated deepcopies
"""
from copy import deepcopy
obj1 = deepcopy(obj)
obj2 = deepcopy(obj1)
obj3 = deepcopy(obj2)
assert_equivalent(obj, obj1)
assert_equivalent(obj, obj2)
assert_equivalent(obj... |
def copytree_and_gzip(self, source_dir, target_dir):
"""
Copies the provided source directory to the provided target directory.
Gzips JavaScript, CSS and HTML and other files along the way.
"""
# Figure out what we're building...
build_list = []
# Walk through th... | def function[copytree_and_gzip, parameter[self, source_dir, target_dir]]:
constant[
Copies the provided source directory to the provided target directory.
Gzips JavaScript, CSS and HTML and other files along the way.
]
variable[build_list] assign[=] list[[]]
for taget[tu... | keyword[def] identifier[copytree_and_gzip] ( identifier[self] , identifier[source_dir] , identifier[target_dir] ):
literal[string]
identifier[build_list] =[]
keyword[for] ( identifier[dirpath] , identifier[dirnames] , identifier[filenames] ) keyword[in] identifier[os] . ... | def copytree_and_gzip(self, source_dir, target_dir):
"""
Copies the provided source directory to the provided target directory.
Gzips JavaScript, CSS and HTML and other files along the way.
"""
# Figure out what we're building...
build_list = []
# Walk through the source directo... |
def implicit_dynamic(cls, for_type=None, for_types=None):
"""Automatically generate late dynamic dispatchers to type.
This is similar to 'implicit_static', except instead of binding the
instance methods, it generates a dispatcher that will call whatever
instance method of the same name ... | def function[implicit_dynamic, parameter[cls, for_type, for_types]]:
constant[Automatically generate late dynamic dispatchers to type.
This is similar to 'implicit_static', except instead of binding the
instance methods, it generates a dispatcher that will call whatever
instance method ... | keyword[def] identifier[implicit_dynamic] ( identifier[cls] , identifier[for_type] = keyword[None] , identifier[for_types] = keyword[None] ):
literal[string]
keyword[for] identifier[type_] keyword[in] identifier[cls] . identifier[__get_type_args] ( identifier[for_type] , identifier[for_types] ):... | def implicit_dynamic(cls, for_type=None, for_types=None):
"""Automatically generate late dynamic dispatchers to type.
This is similar to 'implicit_static', except instead of binding the
instance methods, it generates a dispatcher that will call whatever
instance method of the same name happ... |
def teardown_request(self, func: Callable) -> Callable:
"""Add a teardown request function to the Blueprint.
This is designed to be used as a decorator, and has the same arguments
as :meth:`~quart.Quart.teardown_request`. It applies only to requests that
are routed to an endpoint in thi... | def function[teardown_request, parameter[self, func]]:
constant[Add a teardown request function to the Blueprint.
This is designed to be used as a decorator, and has the same arguments
as :meth:`~quart.Quart.teardown_request`. It applies only to requests that
are routed to an endpoint i... | keyword[def] identifier[teardown_request] ( identifier[self] , identifier[func] : identifier[Callable] )-> identifier[Callable] :
literal[string]
identifier[self] . identifier[record_once] ( keyword[lambda] identifier[state] : identifier[state] . identifier[app] . identifier[teardown_request] ( id... | def teardown_request(self, func: Callable) -> Callable:
"""Add a teardown request function to the Blueprint.
This is designed to be used as a decorator, and has the same arguments
as :meth:`~quart.Quart.teardown_request`. It applies only to requests that
are routed to an endpoint in this bl... |
def interpret(self, msg):
""" Load input """
slides = msg.get('slides', [])
self.cache = msg.get('folder')
self.gallery = msg.get('gallery', '..')
with open(self.cache + '/slides.txt', 'w') as logfile:
for ix, item in enumerate(slides):
image = self.p... | def function[interpret, parameter[self, msg]]:
constant[ Load input ]
variable[slides] assign[=] call[name[msg].get, parameter[constant[slides], list[[]]]]
name[self].cache assign[=] call[name[msg].get, parameter[constant[folder]]]
name[self].gallery assign[=] call[name[msg].get, paramet... | keyword[def] identifier[interpret] ( identifier[self] , identifier[msg] ):
literal[string]
identifier[slides] = identifier[msg] . identifier[get] ( literal[string] ,[])
identifier[self] . identifier[cache] = identifier[msg] . identifier[get] ( literal[string] )
identifier[self] . ... | def interpret(self, msg):
""" Load input """
slides = msg.get('slides', [])
self.cache = msg.get('folder')
self.gallery = msg.get('gallery', '..')
with open(self.cache + '/slides.txt', 'w') as logfile:
for (ix, item) in enumerate(slides):
image = self.prepare_image(item)
... |
def _blank(*objs):
"""Returns true when the object is false, an empty string, or an empty list"""
for o in objs:
if bool(o):
return BooleanValue(False)
return BooleanValue(True) | def function[_blank, parameter[]]:
constant[Returns true when the object is false, an empty string, or an empty list]
for taget[name[o]] in starred[name[objs]] begin[:]
if call[name[bool], parameter[name[o]]] begin[:]
return[call[name[BooleanValue], parameter[constant[False]]... | keyword[def] identifier[_blank] (* identifier[objs] ):
literal[string]
keyword[for] identifier[o] keyword[in] identifier[objs] :
keyword[if] identifier[bool] ( identifier[o] ):
keyword[return] identifier[BooleanValue] ( keyword[False] )
keyword[return] identifier[BooleanVal... | def _blank(*objs):
"""Returns true when the object is false, an empty string, or an empty list"""
for o in objs:
if bool(o):
return BooleanValue(False) # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['o']]
return BooleanValue(True) |
def _apply_policy_config(policy_spec, policy_dict):
'''Applies a policy dictionary to a policy spec'''
log.trace('policy_dict = %s', policy_dict)
if policy_dict.get('name'):
policy_spec.name = policy_dict['name']
if policy_dict.get('description'):
policy_spec.description = policy_dict['d... | def function[_apply_policy_config, parameter[policy_spec, policy_dict]]:
constant[Applies a policy dictionary to a policy spec]
call[name[log].trace, parameter[constant[policy_dict = %s], name[policy_dict]]]
if call[name[policy_dict].get, parameter[constant[name]]] begin[:]
name[... | keyword[def] identifier[_apply_policy_config] ( identifier[policy_spec] , identifier[policy_dict] ):
literal[string]
identifier[log] . identifier[trace] ( literal[string] , identifier[policy_dict] )
keyword[if] identifier[policy_dict] . identifier[get] ( literal[string] ):
identifier[policy_... | def _apply_policy_config(policy_spec, policy_dict):
"""Applies a policy dictionary to a policy spec"""
log.trace('policy_dict = %s', policy_dict)
if policy_dict.get('name'):
policy_spec.name = policy_dict['name'] # depends on [control=['if'], data=[]]
if policy_dict.get('description'):
... |
def r_group(means, variances, n, critical_r=2., approx=False):
'''Group ``m`` (Markov) chains whose common :py:func:`.r_value` is
less than ``critical_r`` in each of the D dimensions.
:param means:
(m x D) Matrix-like array; the mean value estimates.
:param variances:
(m x D) Matrix-... | def function[r_group, parameter[means, variances, n, critical_r, approx]]:
constant[Group ``m`` (Markov) chains whose common :py:func:`.r_value` is
less than ``critical_r`` in each of the D dimensions.
:param means:
(m x D) Matrix-like array; the mean value estimates.
:param variances:
... | keyword[def] identifier[r_group] ( identifier[means] , identifier[variances] , identifier[n] , identifier[critical_r] = literal[int] , identifier[approx] = keyword[False] ):
literal[string]
keyword[assert] identifier[len] ( identifier[means] )== identifier[len] ( identifier[variances] ), literal[string] %... | def r_group(means, variances, n, critical_r=2.0, approx=False):
"""Group ``m`` (Markov) chains whose common :py:func:`.r_value` is
less than ``critical_r`` in each of the D dimensions.
:param means:
(m x D) Matrix-like array; the mean value estimates.
:param variances:
(m x D) Matrix... |
def format_csv(self, delim=',', qu='"'):
"""
Prepares the data in CSV format
"""
res = qu + self.name + qu + delim
if self.data:
for d in self.data:
res += qu + str(d) + qu + delim
return res + '\n' | def function[format_csv, parameter[self, delim, qu]]:
constant[
Prepares the data in CSV format
]
variable[res] assign[=] binary_operation[binary_operation[binary_operation[name[qu] + name[self].name] + name[qu]] + name[delim]]
if name[self].data begin[:]
for tage... | keyword[def] identifier[format_csv] ( identifier[self] , identifier[delim] = literal[string] , identifier[qu] = literal[string] ):
literal[string]
identifier[res] = identifier[qu] + identifier[self] . identifier[name] + identifier[qu] + identifier[delim]
keyword[if] identifier[self] . id... | def format_csv(self, delim=',', qu='"'):
"""
Prepares the data in CSV format
"""
res = qu + self.name + qu + delim
if self.data:
for d in self.data:
res += qu + str(d) + qu + delim # depends on [control=['for'], data=['d']] # depends on [control=['if'], data=[]]
ret... |
def jcrop_js(js_url=None, with_jquery=True):
"""Load jcrop Javascript file.
:param js_url: The custom JavaScript URL.
:param with_jquery: Include jQuery or not, default to ``True``.
"""
serve_local = current_app.config['AVATARS_SERVE_LOCAL']
if js_url is None:
... | def function[jcrop_js, parameter[js_url, with_jquery]]:
constant[Load jcrop Javascript file.
:param js_url: The custom JavaScript URL.
:param with_jquery: Include jQuery or not, default to ``True``.
]
variable[serve_local] assign[=] call[name[current_app].config][constant[AVATAR... | keyword[def] identifier[jcrop_js] ( identifier[js_url] = keyword[None] , identifier[with_jquery] = keyword[True] ):
literal[string]
identifier[serve_local] = identifier[current_app] . identifier[config] [ literal[string] ]
keyword[if] identifier[js_url] keyword[is] keyword[None] :
... | def jcrop_js(js_url=None, with_jquery=True):
"""Load jcrop Javascript file.
:param js_url: The custom JavaScript URL.
:param with_jquery: Include jQuery or not, default to ``True``.
"""
serve_local = current_app.config['AVATARS_SERVE_LOCAL']
if js_url is None:
if serve_local... |
def irfft2(a, s=None, axes=(-2, -1), norm=None):
"""
Compute the 2-dimensional inverse FFT of a real array.
Parameters
----------
a : array_like
The input array
s : sequence of ints, optional
Shape of the inverse FFT.
axes : sequence of ints, optional
The axes over w... | def function[irfft2, parameter[a, s, axes, norm]]:
constant[
Compute the 2-dimensional inverse FFT of a real array.
Parameters
----------
a : array_like
The input array
s : sequence of ints, optional
Shape of the inverse FFT.
axes : sequence of ints, optional
The... | keyword[def] identifier[irfft2] ( identifier[a] , identifier[s] = keyword[None] , identifier[axes] =(- literal[int] ,- literal[int] ), identifier[norm] = keyword[None] ):
literal[string]
keyword[return] identifier[irfftn] ( identifier[a] , identifier[s] , identifier[axes] , identifier[norm] ) | def irfft2(a, s=None, axes=(-2, -1), norm=None):
"""
Compute the 2-dimensional inverse FFT of a real array.
Parameters
----------
a : array_like
The input array
s : sequence of ints, optional
Shape of the inverse FFT.
axes : sequence of ints, optional
The axes over w... |
def participant(self):
"""
True if the tasks roles meet the legion's constraints,
False otherwise.
"""
log = self._params.get('log', self._discard)
context = self._context_build(pending=True)
conf = self._config_pending
if conf.get('control') == 'off':
... | def function[participant, parameter[self]]:
constant[
True if the tasks roles meet the legion's constraints,
False otherwise.
]
variable[log] assign[=] call[name[self]._params.get, parameter[constant[log], name[self]._discard]]
variable[context] assign[=] call[name[self]._con... | keyword[def] identifier[participant] ( identifier[self] ):
literal[string]
identifier[log] = identifier[self] . identifier[_params] . identifier[get] ( literal[string] , identifier[self] . identifier[_discard] )
identifier[context] = identifier[self] . identifier[_context_build] ( identifi... | def participant(self):
"""
True if the tasks roles meet the legion's constraints,
False otherwise.
"""
log = self._params.get('log', self._discard)
context = self._context_build(pending=True)
conf = self._config_pending
if conf.get('control') == 'off':
log.debug("Excludin... |
def _AddFieldPaths(node, prefix, field_mask):
"""Adds the field paths descended from node to field_mask."""
if not node:
field_mask.paths.append(prefix)
return
for name in sorted(node):
if prefix:
child_path = prefix + '.' + name
else:
child_path = name
_AddFieldPaths(node[name], c... | def function[_AddFieldPaths, parameter[node, prefix, field_mask]]:
constant[Adds the field paths descended from node to field_mask.]
if <ast.UnaryOp object at 0x7da20c9916f0> begin[:]
call[name[field_mask].paths.append, parameter[name[prefix]]]
return[None]
for taget[name... | keyword[def] identifier[_AddFieldPaths] ( identifier[node] , identifier[prefix] , identifier[field_mask] ):
literal[string]
keyword[if] keyword[not] identifier[node] :
identifier[field_mask] . identifier[paths] . identifier[append] ( identifier[prefix] )
keyword[return]
keyword[for] identifier... | def _AddFieldPaths(node, prefix, field_mask):
"""Adds the field paths descended from node to field_mask."""
if not node:
field_mask.paths.append(prefix)
return # depends on [control=['if'], data=[]]
for name in sorted(node):
if prefix:
child_path = prefix + '.' + name #... |
def delete_attachment(self, attachment):
"""Delete attachment from the AR or Analysis
The attachment will be only deleted if it is not further referenced by
another AR/Analysis.
"""
# Get the holding parent of this attachment
parent = None
if attachment.getLinke... | def function[delete_attachment, parameter[self, attachment]]:
constant[Delete attachment from the AR or Analysis
The attachment will be only deleted if it is not further referenced by
another AR/Analysis.
]
variable[parent] assign[=] constant[None]
if call[name[attachmen... | keyword[def] identifier[delete_attachment] ( identifier[self] , identifier[attachment] ):
literal[string]
identifier[parent] = keyword[None]
keyword[if] identifier[attachment] . identifier[getLinkedRequests] ():
identifier[parent] = identifier[attachment] ... | def delete_attachment(self, attachment):
"""Delete attachment from the AR or Analysis
The attachment will be only deleted if it is not further referenced by
another AR/Analysis.
"""
# Get the holding parent of this attachment
parent = None
if attachment.getLinkedRequests():
... |
def marvcli_user_list():
"""List existing users"""
app = create_app()
for name in db.session.query(User.name).order_by(User.name):
click.echo(name[0]) | def function[marvcli_user_list, parameter[]]:
constant[List existing users]
variable[app] assign[=] call[name[create_app], parameter[]]
for taget[name[name]] in starred[call[call[name[db].session.query, parameter[name[User].name]].order_by, parameter[name[User].name]]] begin[:]
c... | keyword[def] identifier[marvcli_user_list] ():
literal[string]
identifier[app] = identifier[create_app] ()
keyword[for] identifier[name] keyword[in] identifier[db] . identifier[session] . identifier[query] ( identifier[User] . identifier[name] ). identifier[order_by] ( identifier[User] . identifier... | def marvcli_user_list():
"""List existing users"""
app = create_app()
for name in db.session.query(User.name).order_by(User.name):
click.echo(name[0]) # depends on [control=['for'], data=['name']] |
def get_error(self):
"""Retrieve error data."""
col_offset = -1
if self.node is not None:
try:
col_offset = self.node.col_offset
except AttributeError:
pass
try:
exc_name = self.exc.__name__
except AttributeError... | def function[get_error, parameter[self]]:
constant[Retrieve error data.]
variable[col_offset] assign[=] <ast.UnaryOp object at 0x7da1b12c5300>
if compare[name[self].node is_not constant[None]] begin[:]
<ast.Try object at 0x7da1b12c4070>
<ast.Try object at 0x7da1b12c5c90>
if c... | keyword[def] identifier[get_error] ( identifier[self] ):
literal[string]
identifier[col_offset] =- literal[int]
keyword[if] identifier[self] . identifier[node] keyword[is] keyword[not] keyword[None] :
keyword[try] :
identifier[col_offset] = identifier[sel... | def get_error(self):
"""Retrieve error data."""
col_offset = -1
if self.node is not None:
try:
col_offset = self.node.col_offset # depends on [control=['try'], data=[]]
except AttributeError:
pass # depends on [control=['except'], data=[]] # depends on [control=['i... |
def get_client(name, description, base_url=None, middlewares=None,
reset=False):
""" Build a complete spore client and store it
:param name: name of the client
:param description: the REST API description as a file or URL
:param base_url: the base URL of the REST API
:param middlewar... | def function[get_client, parameter[name, description, base_url, middlewares, reset]]:
constant[ Build a complete spore client and store it
:param name: name of the client
:param description: the REST API description as a file or URL
:param base_url: the base URL of the REST API
:param middlewar... | keyword[def] identifier[get_client] ( identifier[name] , identifier[description] , identifier[base_url] = keyword[None] , identifier[middlewares] = keyword[None] ,
identifier[reset] = keyword[False] ):
literal[string]
keyword[if] identifier[name] keyword[in] identifier[__clients] keyword[and] keyword... | def get_client(name, description, base_url=None, middlewares=None, reset=False):
""" Build a complete spore client and store it
:param name: name of the client
:param description: the REST API description as a file or URL
:param base_url: the base URL of the REST API
:param middlewares: middlewares... |
def _loadf16(ins):
""" Load a 32 bit (16.16) fixed point value from a memory address
If 2nd arg. start with '*', it is always treated as
an indirect value.
"""
output = _f16_oper(ins.quad[2])
output.append('push de')
output.append('push hl')
return output | def function[_loadf16, parameter[ins]]:
constant[ Load a 32 bit (16.16) fixed point value from a memory address
If 2nd arg. start with '*', it is always treated as
an indirect value.
]
variable[output] assign[=] call[name[_f16_oper], parameter[call[name[ins].quad][constant[2]]]]
call... | keyword[def] identifier[_loadf16] ( identifier[ins] ):
literal[string]
identifier[output] = identifier[_f16_oper] ( identifier[ins] . identifier[quad] [ literal[int] ])
identifier[output] . identifier[append] ( literal[string] )
identifier[output] . identifier[append] ( literal[string] )
key... | def _loadf16(ins):
""" Load a 32 bit (16.16) fixed point value from a memory address
If 2nd arg. start with '*', it is always treated as
an indirect value.
"""
output = _f16_oper(ins.quad[2])
output.append('push de')
output.append('push hl')
return output |
def _noise_dict_update(noise_dict):
"""
Update the noise dictionary parameters with default values, in case any
were missing
Parameters
----------
noise_dict : dict
A dictionary specifying the types of noise in this experiment. The
noise types interact in important ways. First,... | def function[_noise_dict_update, parameter[noise_dict]]:
constant[
Update the noise dictionary parameters with default values, in case any
were missing
Parameters
----------
noise_dict : dict
A dictionary specifying the types of noise in this experiment. The
noise types int... | keyword[def] identifier[_noise_dict_update] ( identifier[noise_dict] ):
literal[string]
identifier[default_dict] ={ literal[string] : literal[int] , literal[string] : literal[int] , literal[string] : literal[int] ,
literal[string] :[ literal[int] ], literal[string] :[ literal[int] ],
literal... | def _noise_dict_update(noise_dict):
"""
Update the noise dictionary parameters with default values, in case any
were missing
Parameters
----------
noise_dict : dict
A dictionary specifying the types of noise in this experiment. The
noise types interact in important ways. First,... |
def decode(self, data, as_list=False):
"""
Decode given data.
:param data: sequence of bytes (string, list or generator of bytes)
:param as_list: whether to return as a list instead of
:return:
"""
return self._concat(self.decode_streaming(data)) | def function[decode, parameter[self, data, as_list]]:
constant[
Decode given data.
:param data: sequence of bytes (string, list or generator of bytes)
:param as_list: whether to return as a list instead of
:return:
]
return[call[name[self]._concat, parameter[call[nam... | keyword[def] identifier[decode] ( identifier[self] , identifier[data] , identifier[as_list] = keyword[False] ):
literal[string]
keyword[return] identifier[self] . identifier[_concat] ( identifier[self] . identifier[decode_streaming] ( identifier[data] )) | def decode(self, data, as_list=False):
"""
Decode given data.
:param data: sequence of bytes (string, list or generator of bytes)
:param as_list: whether to return as a list instead of
:return:
"""
return self._concat(self.decode_streaming(data)) |
def read_chemical_shielding(self):
"""
Parse the NMR chemical shieldings data. Only the second part "absolute, valence and core"
will be parsed. And only the three right most field (ISO_SHIELDING, SPAN, SKEW) will be retrieved.
Returns:
List of chemical shieldings in the ord... | def function[read_chemical_shielding, parameter[self]]:
constant[
Parse the NMR chemical shieldings data. Only the second part "absolute, valence and core"
will be parsed. And only the three right most field (ISO_SHIELDING, SPAN, SKEW) will be retrieved.
Returns:
List of che... | keyword[def] identifier[read_chemical_shielding] ( identifier[self] ):
literal[string]
identifier[header_pattern] = literal[string] literal[string] literal[string] literal[string] literal[string] literal[string] literal[string]
identifier[first_part_pattern] = literal[string]
... | def read_chemical_shielding(self):
"""
Parse the NMR chemical shieldings data. Only the second part "absolute, valence and core"
will be parsed. And only the three right most field (ISO_SHIELDING, SPAN, SKEW) will be retrieved.
Returns:
List of chemical shieldings in the order o... |
def perform(self, cfg):
"""
Performs transformation according to configuration
:param cfg: transformation configuration
"""
self.__src = self._load(cfg[Transformation.__CFG_KEY_LOAD])
self.__transform(cfg[Transformation.__CFG_KEY_TRANSFORM])
self.__cleanup(cfg[Tra... | def function[perform, parameter[self, cfg]]:
constant[
Performs transformation according to configuration
:param cfg: transformation configuration
]
name[self].__src assign[=] call[name[self]._load, parameter[call[name[cfg]][name[Transformation].__CFG_KEY_LOAD]]]
call[nam... | keyword[def] identifier[perform] ( identifier[self] , identifier[cfg] ):
literal[string]
identifier[self] . identifier[__src] = identifier[self] . identifier[_load] ( identifier[cfg] [ identifier[Transformation] . identifier[__CFG_KEY_LOAD] ])
identifier[self] . identifier[__transform] ( i... | def perform(self, cfg):
"""
Performs transformation according to configuration
:param cfg: transformation configuration
"""
self.__src = self._load(cfg[Transformation.__CFG_KEY_LOAD])
self.__transform(cfg[Transformation.__CFG_KEY_TRANSFORM])
self.__cleanup(cfg[Transformation.__CF... |
def _parse_template_vars(self):
""" find all template variables in self._code, excluding the
function name.
"""
template_vars = set()
for var in parsing.find_template_variables(self._code):
var = var.lstrip('$')
if var == self.name:
contin... | def function[_parse_template_vars, parameter[self]]:
constant[ find all template variables in self._code, excluding the
function name.
]
variable[template_vars] assign[=] call[name[set], parameter[]]
for taget[name[var]] in starred[call[name[parsing].find_template_variables, par... | keyword[def] identifier[_parse_template_vars] ( identifier[self] ):
literal[string]
identifier[template_vars] = identifier[set] ()
keyword[for] identifier[var] keyword[in] identifier[parsing] . identifier[find_template_variables] ( identifier[self] . identifier[_code] ):
id... | def _parse_template_vars(self):
""" find all template variables in self._code, excluding the
function name.
"""
template_vars = set()
for var in parsing.find_template_variables(self._code):
var = var.lstrip('$')
if var == self.name:
continue # depends on [contro... |
def list_tar (archive, compression, cmd, verbosity, interactive):
"""List a TAR archive with the tarfile Python module."""
try:
with tarfile.open(archive) as tfile:
tfile.list(verbose=verbosity>1)
except Exception as err:
msg = "error listing %s: %s" % (archive, err)
rais... | def function[list_tar, parameter[archive, compression, cmd, verbosity, interactive]]:
constant[List a TAR archive with the tarfile Python module.]
<ast.Try object at 0x7da1b0604d60>
return[constant[None]] | keyword[def] identifier[list_tar] ( identifier[archive] , identifier[compression] , identifier[cmd] , identifier[verbosity] , identifier[interactive] ):
literal[string]
keyword[try] :
keyword[with] identifier[tarfile] . identifier[open] ( identifier[archive] ) keyword[as] identifier[tfile] :
... | def list_tar(archive, compression, cmd, verbosity, interactive):
"""List a TAR archive with the tarfile Python module."""
try:
with tarfile.open(archive) as tfile:
tfile.list(verbose=verbosity > 1) # depends on [control=['with'], data=['tfile']] # depends on [control=['try'], data=[]]
... |
def create_git_commit(self, message, tree, parents, author=github.GithubObject.NotSet, committer=github.GithubObject.NotSet):
"""
:calls: `POST /repos/:owner/:repo/git/commits <http://developer.github.com/v3/git/commits>`_
:param message: string
:param tree: :class:`github.GitTree.GitTre... | def function[create_git_commit, parameter[self, message, tree, parents, author, committer]]:
constant[
:calls: `POST /repos/:owner/:repo/git/commits <http://developer.github.com/v3/git/commits>`_
:param message: string
:param tree: :class:`github.GitTree.GitTree`
:param parents: ... | keyword[def] identifier[create_git_commit] ( identifier[self] , identifier[message] , identifier[tree] , identifier[parents] , identifier[author] = identifier[github] . identifier[GithubObject] . identifier[NotSet] , identifier[committer] = identifier[github] . identifier[GithubObject] . identifier[NotSet] ):
... | def create_git_commit(self, message, tree, parents, author=github.GithubObject.NotSet, committer=github.GithubObject.NotSet):
"""
:calls: `POST /repos/:owner/:repo/git/commits <http://developer.github.com/v3/git/commits>`_
:param message: string
:param tree: :class:`github.GitTree.GitTree`
... |
def prob_t_compressed(self, seq_pair, multiplicity, t, return_log=False):
'''
Calculate the probability of observing a sequence pair at a distance t,
for compressed sequences
Parameters
----------
seq_pair : numpy array
:code:`np.array([(0,1), (2,2), ()..]... | def function[prob_t_compressed, parameter[self, seq_pair, multiplicity, t, return_log]]:
constant[
Calculate the probability of observing a sequence pair at a distance t,
for compressed sequences
Parameters
----------
seq_pair : numpy array
:code:`np.array... | keyword[def] identifier[prob_t_compressed] ( identifier[self] , identifier[seq_pair] , identifier[multiplicity] , identifier[t] , identifier[return_log] = keyword[False] ):
literal[string]
keyword[if] identifier[t] < literal[int] :
identifier[logP] =- identifier[ttconf] . identifier[B... | def prob_t_compressed(self, seq_pair, multiplicity, t, return_log=False):
"""
Calculate the probability of observing a sequence pair at a distance t,
for compressed sequences
Parameters
----------
seq_pair : numpy array
:code:`np.array([(0,1), (2,2), ()..])` a... |
def add_property(self,pid, label,term_span):
"""
Adds a new property to the property layer
@type pid: string
@param pid: property identifier
@type label: string
@param label: the label of the property
@type term_span: list
@param term_span: list of term id... | def function[add_property, parameter[self, pid, label, term_span]]:
constant[
Adds a new property to the property layer
@type pid: string
@param pid: property identifier
@type label: string
@param label: the label of the property
@type term_span: list
@par... | keyword[def] identifier[add_property] ( identifier[self] , identifier[pid] , identifier[label] , identifier[term_span] ):
literal[string]
identifier[new_property] = identifier[Cproperty] ( identifier[type] = identifier[self] . identifier[type] )
identifier[self] . identifier[node] . identi... | def add_property(self, pid, label, term_span):
"""
Adds a new property to the property layer
@type pid: string
@param pid: property identifier
@type label: string
@param label: the label of the property
@type term_span: list
@param term_span: list of term iden... |
def build_createbug(self,
product=None,
component=None,
version=None,
summary=None,
description=None,
comment_private=None,
blocks=None,
cc=None,
assigned_to=None,
keywords=None,
depends_on=None,
groups=None,
op_sys=... | def function[build_createbug, parameter[self, product, component, version, summary, description, comment_private, blocks, cc, assigned_to, keywords, depends_on, groups, op_sys, platform, priority, qa_contact, resolution, severity, status, target_milestone, target_release, url, sub_component, alias, comment_tags]]:
... | keyword[def] identifier[build_createbug] ( identifier[self] ,
identifier[product] = keyword[None] ,
identifier[component] = keyword[None] ,
identifier[version] = keyword[None] ,
identifier[summary] = keyword[None] ,
identifier[description] = keyword[None] ,
identifier[comment_private] = keyword[None] ,
identif... | def build_createbug(self, product=None, component=None, version=None, summary=None, description=None, comment_private=None, blocks=None, cc=None, assigned_to=None, keywords=None, depends_on=None, groups=None, op_sys=None, platform=None, priority=None, qa_contact=None, resolution=None, severity=None, status=None, target... |
def delete(self):
""" Delete this source """
r = self._client.request('DELETE', self.url)
logger.info("delete(): %s", r.status_code) | def function[delete, parameter[self]]:
constant[ Delete this source ]
variable[r] assign[=] call[name[self]._client.request, parameter[constant[DELETE], name[self].url]]
call[name[logger].info, parameter[constant[delete(): %s], name[r].status_code]] | keyword[def] identifier[delete] ( identifier[self] ):
literal[string]
identifier[r] = identifier[self] . identifier[_client] . identifier[request] ( literal[string] , identifier[self] . identifier[url] )
identifier[logger] . identifier[info] ( literal[string] , identifier[r] . identifier[s... | def delete(self):
""" Delete this source """
r = self._client.request('DELETE', self.url)
logger.info('delete(): %s', r.status_code) |
def add(self, pkgs):
"""Add blacklist packages if not exist
"""
blacklist = self.get_black()
pkgs = set(pkgs)
print("\nAdd packages in the blacklist:\n")
with open(self.blackfile, "a") as black_conf:
for pkg in pkgs:
if pkg not in blacklist:
... | def function[add, parameter[self, pkgs]]:
constant[Add blacklist packages if not exist
]
variable[blacklist] assign[=] call[name[self].get_black, parameter[]]
variable[pkgs] assign[=] call[name[set], parameter[name[pkgs]]]
call[name[print], parameter[constant[
Add packages in the... | keyword[def] identifier[add] ( identifier[self] , identifier[pkgs] ):
literal[string]
identifier[blacklist] = identifier[self] . identifier[get_black] ()
identifier[pkgs] = identifier[set] ( identifier[pkgs] )
identifier[print] ( literal[string] )
keyword[with] identifie... | def add(self, pkgs):
"""Add blacklist packages if not exist
"""
blacklist = self.get_black()
pkgs = set(pkgs)
print('\nAdd packages in the blacklist:\n')
with open(self.blackfile, 'a') as black_conf:
for pkg in pkgs:
if pkg not in blacklist:
print('{0}{1}{... |
def get_pfam(pdb_id):
"""Return PFAM annotations of given PDB_ID
Parameters
----------
pdb_id : string
A 4 character string giving a pdb entry of interest
Returns
-------
out : dict
A dictionary containing the PFAM annotations for the specified PDB ID
Examples
--... | def function[get_pfam, parameter[pdb_id]]:
constant[Return PFAM annotations of given PDB_ID
Parameters
----------
pdb_id : string
A 4 character string giving a pdb entry of interest
Returns
-------
out : dict
A dictionary containing the PFAM annotations for the specif... | keyword[def] identifier[get_pfam] ( identifier[pdb_id] ):
literal[string]
identifier[out] = identifier[get_info] ( identifier[pdb_id] , identifier[url_root] = literal[string] )
identifier[out] = identifier[to_dict] ( identifier[out] )
keyword[if] keyword[not] identifier[out] [ literal[string] ]... | def get_pfam(pdb_id):
"""Return PFAM annotations of given PDB_ID
Parameters
----------
pdb_id : string
A 4 character string giving a pdb entry of interest
Returns
-------
out : dict
A dictionary containing the PFAM annotations for the specified PDB ID
Examples
--... |
def watch(self, key, **kwargs):
"""Watch a key.
:param key: key to watch
:returns: tuple of ``events_iterator`` and ``cancel``.
Use ``events_iterator`` to get the events of key changes
and ``cancel`` to cancel the watch request
"""
event_queu... | def function[watch, parameter[self, key]]:
constant[Watch a key.
:param key: key to watch
:returns: tuple of ``events_iterator`` and ``cancel``.
Use ``events_iterator`` to get the events of key changes
and ``cancel`` to cancel the watch request
]
... | keyword[def] identifier[watch] ( identifier[self] , identifier[key] ,** identifier[kwargs] ):
literal[string]
identifier[event_queue] = identifier[queue] . identifier[Queue] ()
keyword[def] identifier[callback] ( identifier[event] ):
identifier[event_queue] . identifier[put]... | def watch(self, key, **kwargs):
"""Watch a key.
:param key: key to watch
:returns: tuple of ``events_iterator`` and ``cancel``.
Use ``events_iterator`` to get the events of key changes
and ``cancel`` to cancel the watch request
"""
event_queue = queu... |
def run_step(self, is_shell):
"""Run a command.
Runs a program or executable. If is_shell is True, executes the command
through the shell.
Args:
is_shell: bool. defaults False. Set to true to execute cmd through
the default shell.
"""
a... | def function[run_step, parameter[self, is_shell]]:
constant[Run a command.
Runs a program or executable. If is_shell is True, executes the command
through the shell.
Args:
is_shell: bool. defaults False. Set to true to execute cmd through
the default s... | keyword[def] identifier[run_step] ( identifier[self] , identifier[is_shell] ):
literal[string]
keyword[assert] identifier[is_shell] keyword[is] keyword[not] keyword[None] ,( literal[string] )
keyword[if] identifier[is_shell] :
identifier[args] = identif... | def run_step(self, is_shell):
"""Run a command.
Runs a program or executable. If is_shell is True, executes the command
through the shell.
Args:
is_shell: bool. defaults False. Set to true to execute cmd through
the default shell.
"""
assert is... |
def yesno(self, prompt, error='Please type either y or n', intro=None,
default=None):
""" Ask user for yes or no answer
The prompt will include a typical '(y/n):' at the end. Depending on
whether ``default`` was specified, this may also be '(Y/n):' or
'(y/N):'.
Th... | def function[yesno, parameter[self, prompt, error, intro, default]]:
constant[ Ask user for yes or no answer
The prompt will include a typical '(y/n):' at the end. Depending on
whether ``default`` was specified, this may also be '(Y/n):' or
'(y/N):'.
The ``default`` argument ca... | keyword[def] identifier[yesno] ( identifier[self] , identifier[prompt] , identifier[error] = literal[string] , identifier[intro] = keyword[None] ,
identifier[default] = keyword[None] ):
literal[string]
keyword[if] identifier[default] keyword[is] keyword[None] :
identifier[prompt] +... | def yesno(self, prompt, error='Please type either y or n', intro=None, default=None):
""" Ask user for yes or no answer
The prompt will include a typical '(y/n):' at the end. Depending on
whether ``default`` was specified, this may also be '(Y/n):' or
'(y/N):'.
The ``default`` argu... |
def salt_cloud():
'''
The main function for salt-cloud
'''
# Define 'salt' global so we may use it after ImportError. Otherwise,
# UnboundLocalError will be raised.
global salt # pylint: disable=W0602
try:
# Late-imports for CLI performance
import salt.cloud
import ... | def function[salt_cloud, parameter[]]:
constant[
The main function for salt-cloud
]
<ast.Global object at 0x7da2047e8ac0>
<ast.Try object at 0x7da2047e8490>
if compare[constant[] in name[sys].path] begin[:]
call[name[sys].path.remove, parameter[constant[]]]
variab... | keyword[def] identifier[salt_cloud] ():
literal[string]
keyword[global] identifier[salt]
keyword[try] :
keyword[import] identifier[salt] . identifier[cloud]
keyword[import] identifier[salt] . identifier[cloud] . identifier[cli]
keyword[except] identifier[I... | def salt_cloud():
"""
The main function for salt-cloud
"""
# Define 'salt' global so we may use it after ImportError. Otherwise,
# UnboundLocalError will be raised.
global salt # pylint: disable=W0602
try:
# Late-imports for CLI performance
import salt.cloud
import s... |
def finddirs(root):
"""Return a list of all the directories under `root`"""
retval = []
for root, dirs, files in os.walk(root):
for d in dirs:
retval.append(os.path.join(root, d))
return retval | def function[finddirs, parameter[root]]:
constant[Return a list of all the directories under `root`]
variable[retval] assign[=] list[[]]
for taget[tuple[[<ast.Name object at 0x7da1b0a4f640>, <ast.Name object at 0x7da1b0a4e9b0>, <ast.Name object at 0x7da1b0a4e710>]]] in starred[call[name[os].walk... | keyword[def] identifier[finddirs] ( identifier[root] ):
literal[string]
identifier[retval] =[]
keyword[for] identifier[root] , identifier[dirs] , identifier[files] keyword[in] identifier[os] . identifier[walk] ( identifier[root] ):
keyword[for] identifier[d] keyword[in] identifier[dirs]... | def finddirs(root):
"""Return a list of all the directories under `root`"""
retval = []
for (root, dirs, files) in os.walk(root):
for d in dirs:
retval.append(os.path.join(root, d)) # depends on [control=['for'], data=['d']] # depends on [control=['for'], data=[]]
return retval |
def dist_location(dist):
"""
Get the site-packages location of this distribution. Generally
this is dist.location, except in the case of develop-installed
packages, where dist.location is the source code location, and we
want to know where the egg-link file is.
"""
egg_link = egg_link_path(... | def function[dist_location, parameter[dist]]:
constant[
Get the site-packages location of this distribution. Generally
this is dist.location, except in the case of develop-installed
packages, where dist.location is the source code location, and we
want to know where the egg-link file is.
]
... | keyword[def] identifier[dist_location] ( identifier[dist] ):
literal[string]
identifier[egg_link] = identifier[egg_link_path] ( identifier[dist] )
keyword[if] identifier[os] . identifier[path] . identifier[exists] ( identifier[egg_link] ):
keyword[return] identifier[egg_link]
keyword[... | def dist_location(dist):
"""
Get the site-packages location of this distribution. Generally
this is dist.location, except in the case of develop-installed
packages, where dist.location is the source code location, and we
want to know where the egg-link file is.
"""
egg_link = egg_link_path(... |
def pack(self):
"""Pack the service code for transmission. Returns a 2 byte string."""
sn, sa = self.number, self.attribute
return pack("<H", (sn & 0x3ff) << 6 | (sa & 0x3f)) | def function[pack, parameter[self]]:
constant[Pack the service code for transmission. Returns a 2 byte string.]
<ast.Tuple object at 0x7da20cabe0b0> assign[=] tuple[[<ast.Attribute object at 0x7da20cabe170>, <ast.Attribute object at 0x7da20cabd7b0>]]
return[call[name[pack], parameter[constant[<H], b... | keyword[def] identifier[pack] ( identifier[self] ):
literal[string]
identifier[sn] , identifier[sa] = identifier[self] . identifier[number] , identifier[self] . identifier[attribute]
keyword[return] identifier[pack] ( literal[string] ,( identifier[sn] & literal[int] )<< literal[int] |( i... | def pack(self):
"""Pack the service code for transmission. Returns a 2 byte string."""
(sn, sa) = (self.number, self.attribute)
return pack('<H', (sn & 1023) << 6 | sa & 63) |
def _update_with_csrf_disabled(d=None):
"""Update the input dict with CSRF disabled depending on WTF-Form version.
From Flask-WTF 0.14.0, `csrf_enabled` param has been deprecated in favor of
`meta={csrf: True/False}`.
"""
if d is None:
d = {}
import flask_wtf
from pkg_resources imp... | def function[_update_with_csrf_disabled, parameter[d]]:
constant[Update the input dict with CSRF disabled depending on WTF-Form version.
From Flask-WTF 0.14.0, `csrf_enabled` param has been deprecated in favor of
`meta={csrf: True/False}`.
]
if compare[name[d] is constant[None]] begin[:]
... | keyword[def] identifier[_update_with_csrf_disabled] ( identifier[d] = keyword[None] ):
literal[string]
keyword[if] identifier[d] keyword[is] keyword[None] :
identifier[d] ={}
keyword[import] identifier[flask_wtf]
keyword[from] identifier[pkg_resources] keyword[import] identifier... | def _update_with_csrf_disabled(d=None):
"""Update the input dict with CSRF disabled depending on WTF-Form version.
From Flask-WTF 0.14.0, `csrf_enabled` param has been deprecated in favor of
`meta={csrf: True/False}`.
"""
if d is None:
d = {} # depends on [control=['if'], data=['d']]
i... |
def _check_intemediate(self, myntr, maxstate):
"""
For each state Apq which is a known terminal, this function
searches for rules Apr -> Apq Aqr and Arq -> Arp Apq where
Aqr is also a known terminal or Arp is also a known terminal.
It is mainly used as an optimization in order to... | def function[_check_intemediate, parameter[self, myntr, maxstate]]:
constant[
For each state Apq which is a known terminal, this function
searches for rules Apr -> Apq Aqr and Arq -> Arp Apq where
Aqr is also a known terminal or Arp is also a known terminal.
It is mainly used as ... | keyword[def] identifier[_check_intemediate] ( identifier[self] , identifier[myntr] , identifier[maxstate] ):
literal[string]
identifier[x_term] = identifier[myntr] . identifier[rfind] ( literal[string] )
identifier[y_term] = identifier[myntr] . identifier[rfind] ( literal[string] ... | def _check_intemediate(self, myntr, maxstate):
"""
For each state Apq which is a known terminal, this function
searches for rules Apr -> Apq Aqr and Arq -> Arp Apq where
Aqr is also a known terminal or Arp is also a known terminal.
It is mainly used as an optimization in order to avo... |
def important_dates(year):
"""Returns a dictionary of important dates"""
output = {}
data = mlbgame.data.get_important_dates(year)
important_dates = etree.parse(data).getroot().\
find('queryResults').find('row')
try:
for x in important_dates.attrib:
output[x] = important_... | def function[important_dates, parameter[year]]:
constant[Returns a dictionary of important dates]
variable[output] assign[=] dictionary[[], []]
variable[data] assign[=] call[name[mlbgame].data.get_important_dates, parameter[name[year]]]
variable[important_dates] assign[=] call[call[call[... | keyword[def] identifier[important_dates] ( identifier[year] ):
literal[string]
identifier[output] ={}
identifier[data] = identifier[mlbgame] . identifier[data] . identifier[get_important_dates] ( identifier[year] )
identifier[important_dates] = identifier[etree] . identifier[parse] ( identifier[d... | def important_dates(year):
"""Returns a dictionary of important dates"""
output = {}
data = mlbgame.data.get_important_dates(year)
important_dates = etree.parse(data).getroot().find('queryResults').find('row')
try:
for x in important_dates.attrib:
output[x] = important_dates.attr... |
def _load_modeling_extent(self):
"""
# Get extent from GSSHA Grid in LSM coordinates
# Determine range within LSM Grid
"""
####
# STEP 1: Get extent from GSSHA Grid in LSM coordinates
####
# reproject GSSHA grid and get bounds
min_x, max_x, min_y, ... | def function[_load_modeling_extent, parameter[self]]:
constant[
# Get extent from GSSHA Grid in LSM coordinates
# Determine range within LSM Grid
]
<ast.Tuple object at 0x7da20c6a8460> assign[=] call[name[self].gssha_grid.bounds, parameter[]]
call[name[self]._set_subset_i... | keyword[def] identifier[_load_modeling_extent] ( identifier[self] ):
literal[string]
identifier[min_x] , identifier[max_x] , identifier[min_y] , identifier[max_y] = identifier[self] . identifier[gssha_grid] . identifier[bounds] ( identifier[as_projection] = ident... | def _load_modeling_extent(self):
"""
# Get extent from GSSHA Grid in LSM coordinates
# Determine range within LSM Grid
"""
####
# STEP 1: Get extent from GSSHA Grid in LSM coordinates
####
# reproject GSSHA grid and get bounds
(min_x, max_x, min_y, max_y) = self.gssha_gri... |
def findSynonyms(self, word, num):
"""
Find "num" number of words closest in similarity to "word".
word can be a string or vector representation.
Returns a dataframe with two fields word and similarity (which
gives the cosine similarity).
"""
if not isinstance(wor... | def function[findSynonyms, parameter[self, word, num]]:
constant[
Find "num" number of words closest in similarity to "word".
word can be a string or vector representation.
Returns a dataframe with two fields word and similarity (which
gives the cosine similarity).
]
... | keyword[def] identifier[findSynonyms] ( identifier[self] , identifier[word] , identifier[num] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[word] , identifier[basestring] ):
identifier[word] = identifier[_convert_to_vector] ( identifier[word] )
... | def findSynonyms(self, word, num):
"""
Find "num" number of words closest in similarity to "word".
word can be a string or vector representation.
Returns a dataframe with two fields word and similarity (which
gives the cosine similarity).
"""
if not isinstance(word, bases... |
def flows(args):
"""
todo : add some example
:param args:
:return:
"""
def flow_if_not(fun):
# t = type(fun)
if isinstance(fun, iterator):
return fun
elif isinstance(fun, type) and 'itertools' in str(fun.__class__):
return fun
else:
... | def function[flows, parameter[args]]:
constant[
todo : add some example
:param args:
:return:
]
def function[flow_if_not, parameter[fun]]:
if call[name[isinstance], parameter[name[fun], name[iterator]]] begin[:]
return[name[fun]]
return[call[name[FlowList]... | keyword[def] identifier[flows] ( identifier[args] ):
literal[string]
keyword[def] identifier[flow_if_not] ( identifier[fun] ):
keyword[if] identifier[isinstance] ( identifier[fun] , identifier[iterator] ):
keyword[return] identifier[fun]
keyword[elif] identifier[is... | def flows(args):
"""
todo : add some example
:param args:
:return:
"""
def flow_if_not(fun):
# t = type(fun)
if isinstance(fun, iterator):
return fun # depends on [control=['if'], data=[]]
elif isinstance(fun, type) and 'itertools' in str(fun.__class__):
... |
def transform(self, X=None, t_max=100, plot_optimal_t=False, ax=None):
"""Computes the position of the cells in the embedding space
Parameters
----------
X : array, optional, shape=[n_samples, n_features]
input data with `n_samples` samples and `n_dimensions`
dim... | def function[transform, parameter[self, X, t_max, plot_optimal_t, ax]]:
constant[Computes the position of the cells in the embedding space
Parameters
----------
X : array, optional, shape=[n_samples, n_features]
input data with `n_samples` samples and `n_dimensions`
... | keyword[def] identifier[transform] ( identifier[self] , identifier[X] = keyword[None] , identifier[t_max] = literal[int] , identifier[plot_optimal_t] = keyword[False] , identifier[ax] = keyword[None] ):
literal[string]
keyword[if] identifier[self] . identifier[graph] keyword[is] keyword[None] :
... | def transform(self, X=None, t_max=100, plot_optimal_t=False, ax=None):
"""Computes the position of the cells in the embedding space
Parameters
----------
X : array, optional, shape=[n_samples, n_features]
input data with `n_samples` samples and `n_dimensions`
dimensi... |
def requirement_spec(package_name, *args):
"""Identifier used when specifying a requirement to pip or setuptools."""
if not args or args == (None,):
return package_name
version_specs = []
for version_spec in args:
if isinstance(version_spec, (list, tuple)):
operator, v... | def function[requirement_spec, parameter[package_name]]:
constant[Identifier used when specifying a requirement to pip or setuptools.]
if <ast.BoolOp object at 0x7da18f09c220> begin[:]
return[name[package_name]]
variable[version_specs] assign[=] list[[]]
for taget[name[version_sp... | keyword[def] identifier[requirement_spec] ( identifier[package_name] ,* identifier[args] ):
literal[string]
keyword[if] keyword[not] identifier[args] keyword[or] identifier[args] ==( keyword[None] ,):
keyword[return] identifier[package_name]
identifier[version_specs] =[]
keywo... | def requirement_spec(package_name, *args):
"""Identifier used when specifying a requirement to pip or setuptools."""
if not args or args == (None,):
return package_name # depends on [control=['if'], data=[]]
version_specs = []
for version_spec in args:
if isinstance(version_spec, (list,... |
def _rename(self, node, name):
'''
Rename an internal node of the tree. If an annotation is already
present, append the new annotation to the end of it. If a bootstrap
value is present, add annotations are added after a ":" as per standard
newick format.
Parameters
... | def function[_rename, parameter[self, node, name]]:
constant[
Rename an internal node of the tree. If an annotation is already
present, append the new annotation to the end of it. If a bootstrap
value is present, add annotations are added after a ":" as per standard
newick format... | keyword[def] identifier[_rename] ( identifier[self] , identifier[node] , identifier[name] ):
literal[string]
keyword[if] identifier[node] . identifier[label] :
keyword[try] :
identifier[float] ( identifier[node] . identifier[label] )
identifier[new_la... | def _rename(self, node, name):
"""
Rename an internal node of the tree. If an annotation is already
present, append the new annotation to the end of it. If a bootstrap
value is present, add annotations are added after a ":" as per standard
newick format.
Parameters
-... |
def _viewbox_set(self, viewbox):
""" Friend method of viewbox to register itself.
"""
self._viewbox = viewbox
# Connect
viewbox.events.mouse_press.connect(self.viewbox_mouse_event)
viewbox.events.mouse_release.connect(self.viewbox_mouse_event)
viewbox.events.mouse... | def function[_viewbox_set, parameter[self, viewbox]]:
constant[ Friend method of viewbox to register itself.
]
name[self]._viewbox assign[=] name[viewbox]
call[name[viewbox].events.mouse_press.connect, parameter[name[self].viewbox_mouse_event]]
call[name[viewbox].events.mouse_rel... | keyword[def] identifier[_viewbox_set] ( identifier[self] , identifier[viewbox] ):
literal[string]
identifier[self] . identifier[_viewbox] = identifier[viewbox]
identifier[viewbox] . identifier[events] . identifier[mouse_press] . identifier[connect] ( identifier[self] . identifier... | def _viewbox_set(self, viewbox):
""" Friend method of viewbox to register itself.
"""
self._viewbox = viewbox
# Connect
viewbox.events.mouse_press.connect(self.viewbox_mouse_event)
viewbox.events.mouse_release.connect(self.viewbox_mouse_event)
viewbox.events.mouse_move.connect(self.viewb... |
def parse_registry_uri(uri: str) -> RegistryURI:
"""
Validate and return (authority, pkg name, version) from a valid registry URI
"""
validate_registry_uri(uri)
parsed_uri = parse.urlparse(uri)
authority = parsed_uri.netloc
pkg_name = parsed_uri.path.strip("/")
pkg_version = parsed_uri.q... | def function[parse_registry_uri, parameter[uri]]:
constant[
Validate and return (authority, pkg name, version) from a valid registry URI
]
call[name[validate_registry_uri], parameter[name[uri]]]
variable[parsed_uri] assign[=] call[name[parse].urlparse, parameter[name[uri]]]
varia... | keyword[def] identifier[parse_registry_uri] ( identifier[uri] : identifier[str] )-> identifier[RegistryURI] :
literal[string]
identifier[validate_registry_uri] ( identifier[uri] )
identifier[parsed_uri] = identifier[parse] . identifier[urlparse] ( identifier[uri] )
identifier[authority] = identif... | def parse_registry_uri(uri: str) -> RegistryURI:
"""
Validate and return (authority, pkg name, version) from a valid registry URI
"""
validate_registry_uri(uri)
parsed_uri = parse.urlparse(uri)
authority = parsed_uri.netloc
pkg_name = parsed_uri.path.strip('/')
pkg_version = parsed_uri.q... |
def title(self, title, *args):
"""
Add a title to your chart
args are optional style params of the form <color>,<font size>
APIPARAMS: chtt,chts
"""
self['chtt'] = title
if args:
args = color_args(args, 0)
self['chts'] = ','.join(map(str,ar... | def function[title, parameter[self, title]]:
constant[
Add a title to your chart
args are optional style params of the form <color>,<font size>
APIPARAMS: chtt,chts
]
call[name[self]][constant[chtt]] assign[=] name[title]
if name[args] begin[:]
var... | keyword[def] identifier[title] ( identifier[self] , identifier[title] ,* identifier[args] ):
literal[string]
identifier[self] [ literal[string] ]= identifier[title]
keyword[if] identifier[args] :
identifier[args] = identifier[color_args] ( identifier[args] , literal[int] )
... | def title(self, title, *args):
"""
Add a title to your chart
args are optional style params of the form <color>,<font size>
APIPARAMS: chtt,chts
"""
self['chtt'] = title
if args:
args = color_args(args, 0)
self['chts'] = ','.join(map(str, args)) # depends on ... |
def leaves(self):
"Generator that returns the leaves of the tree"
for child in self.children:
for x in child.leaves():
yield x
if not self.children:
yield self | def function[leaves, parameter[self]]:
constant[Generator that returns the leaves of the tree]
for taget[name[child]] in starred[name[self].children] begin[:]
for taget[name[x]] in starred[call[name[child].leaves, parameter[]]] begin[:]
<ast.Yield object at 0x7da1... | keyword[def] identifier[leaves] ( identifier[self] ):
literal[string]
keyword[for] identifier[child] keyword[in] identifier[self] . identifier[children] :
keyword[for] identifier[x] keyword[in] identifier[child] . identifier[leaves] ():
keyword[yield] identifier... | def leaves(self):
"""Generator that returns the leaves of the tree"""
for child in self.children:
for x in child.leaves():
yield x # depends on [control=['for'], data=['x']] # depends on [control=['for'], data=['child']]
if not self.children:
yield self # depends on [control=[... |
def setup_gui(self):
"""Setup the main layout of the widget."""
layout = QGridLayout(self)
layout.setContentsMargins(0, 0, 0, 0)
layout.addWidget(self.canvas, 0, 1)
layout.addLayout(self.setup_toolbar(), 0, 3, 2, 1)
layout.setColumnStretch(0, 100)
layout.setColum... | def function[setup_gui, parameter[self]]:
constant[Setup the main layout of the widget.]
variable[layout] assign[=] call[name[QGridLayout], parameter[name[self]]]
call[name[layout].setContentsMargins, parameter[constant[0], constant[0], constant[0], constant[0]]]
call[name[layout].addWid... | keyword[def] identifier[setup_gui] ( identifier[self] ):
literal[string]
identifier[layout] = identifier[QGridLayout] ( identifier[self] )
identifier[layout] . identifier[setContentsMargins] ( literal[int] , literal[int] , literal[int] , literal[int] )
identifier[layout] . identif... | def setup_gui(self):
"""Setup the main layout of the widget."""
layout = QGridLayout(self)
layout.setContentsMargins(0, 0, 0, 0)
layout.addWidget(self.canvas, 0, 1)
layout.addLayout(self.setup_toolbar(), 0, 3, 2, 1)
layout.setColumnStretch(0, 100)
layout.setColumnStretch(2, 100)
layout.s... |
def _CalculateDOWDelta(self, wd, wkdy, offset, style, currentDayStyle):
"""
Based on the C{style} and C{currentDayStyle} determine what
day-of-week value is to be returned.
@type wd: integer
@param wd: day-of-week value for the current day
@typ... | def function[_CalculateDOWDelta, parameter[self, wd, wkdy, offset, style, currentDayStyle]]:
constant[
Based on the C{style} and C{currentDayStyle} determine what
day-of-week value is to be returned.
@type wd: integer
@param wd: day-of-week value for t... | keyword[def] identifier[_CalculateDOWDelta] ( identifier[self] , identifier[wd] , identifier[wkdy] , identifier[offset] , identifier[style] , identifier[currentDayStyle] ):
literal[string]
identifier[diffBase] = identifier[wkdy] - identifier[wd]
identifier[origOffset] = identifier[offset]... | def _CalculateDOWDelta(self, wd, wkdy, offset, style, currentDayStyle):
"""
Based on the C{style} and C{currentDayStyle} determine what
day-of-week value is to be returned.
@type wd: integer
@param wd: day-of-week value for the current day
@type w... |
def get_files(self, file_paths):
"""
returns a list of files faster by using threads
"""
results = []
def get_file_thunk(path, interface):
result = error = None
try:
result = interface.get_file(path)
except Exception as err:
error = err
# important to pr... | def function[get_files, parameter[self, file_paths]]:
constant[
returns a list of files faster by using threads
]
variable[results] assign[=] list[[]]
def function[get_file_thunk, parameter[path, interface]]:
variable[result] assign[=] constant[None]
<ast.Try obje... | keyword[def] identifier[get_files] ( identifier[self] , identifier[file_paths] ):
literal[string]
identifier[results] =[]
keyword[def] identifier[get_file_thunk] ( identifier[path] , identifier[interface] ):
identifier[result] = identifier[error] = keyword[None]
keyword[try] :
... | def get_files(self, file_paths):
"""
returns a list of files faster by using threads
"""
results = []
def get_file_thunk(path, interface):
result = error = None
try:
result = interface.get_file(path) # depends on [control=['try'], data=[]]
except Exception as er... |
def _check_symlink_ownership(path, user, group, win_owner):
'''
Check if the symlink ownership matches the specified user and group
'''
cur_user, cur_group = _get_symlink_ownership(path)
if salt.utils.platform.is_windows():
return win_owner == cur_user
else:
return (cur_user == u... | def function[_check_symlink_ownership, parameter[path, user, group, win_owner]]:
constant[
Check if the symlink ownership matches the specified user and group
]
<ast.Tuple object at 0x7da1b20ed990> assign[=] call[name[_get_symlink_ownership], parameter[name[path]]]
if call[name[salt].uti... | keyword[def] identifier[_check_symlink_ownership] ( identifier[path] , identifier[user] , identifier[group] , identifier[win_owner] ):
literal[string]
identifier[cur_user] , identifier[cur_group] = identifier[_get_symlink_ownership] ( identifier[path] )
keyword[if] identifier[salt] . identifier[utils... | def _check_symlink_ownership(path, user, group, win_owner):
"""
Check if the symlink ownership matches the specified user and group
"""
(cur_user, cur_group) = _get_symlink_ownership(path)
if salt.utils.platform.is_windows():
return win_owner == cur_user # depends on [control=['if'], data=[... |
def read_playlist_file(self, stationFile=''):
""" Read a csv file
Returns: number
x - number of stations or
-1 - playlist is malformed
-2 - playlist not found
"""
prev_file = self.stations_file
prev_format = self.new_... | def function[read_playlist_file, parameter[self, stationFile]]:
constant[ Read a csv file
Returns: number
x - number of stations or
-1 - playlist is malformed
-2 - playlist not found
]
variable[prev_file] assign[=] name[self]... | keyword[def] identifier[read_playlist_file] ( identifier[self] , identifier[stationFile] = literal[string] ):
literal[string]
identifier[prev_file] = identifier[self] . identifier[stations_file]
identifier[prev_format] = identifier[self] . identifier[new_format]
identifier[self]... | def read_playlist_file(self, stationFile=''):
""" Read a csv file
Returns: number
x - number of stations or
-1 - playlist is malformed
-2 - playlist not found
"""
prev_file = self.stations_file
prev_format = self.new_format
s... |
def plot_channel_sweep(proxy, start_channel):
'''
Parameters
----------
proxy : DMFControlBoard
start_channel : int
Channel number from which to start a channel sweep (should be a
multiple of 40, e.g., 0, 40, 80).
Returns
-------
pandas.DataFrame
See description ... | def function[plot_channel_sweep, parameter[proxy, start_channel]]:
constant[
Parameters
----------
proxy : DMFControlBoard
start_channel : int
Channel number from which to start a channel sweep (should be a
multiple of 40, e.g., 0, 40, 80).
Returns
-------
pandas.Dat... | keyword[def] identifier[plot_channel_sweep] ( identifier[proxy] , identifier[start_channel] ):
literal[string]
identifier[test_loads] = identifier[TEST_LOADS] . identifier[copy] ()
identifier[test_loads] . identifier[index] += identifier[start_channel]
identifier[results] = identifier[sweep_cha... | def plot_channel_sweep(proxy, start_channel):
"""
Parameters
----------
proxy : DMFControlBoard
start_channel : int
Channel number from which to start a channel sweep (should be a
multiple of 40, e.g., 0, 40, 80).
Returns
-------
pandas.DataFrame
See description ... |
def _organize_by_position(orig_file, cmp_file, chunk_size):
"""Read two CSV files of qualities, organizing values by position.
"""
with open(orig_file) as in_handle:
reader1 = csv.reader(in_handle)
positions = len(next(reader1)) - 1
for positions in _chunks(range(positions), chunk_size):... | def function[_organize_by_position, parameter[orig_file, cmp_file, chunk_size]]:
constant[Read two CSV files of qualities, organizing values by position.
]
with call[name[open], parameter[name[orig_file]]] begin[:]
variable[reader1] assign[=] call[name[csv].reader, parameter[name[in_... | keyword[def] identifier[_organize_by_position] ( identifier[orig_file] , identifier[cmp_file] , identifier[chunk_size] ):
literal[string]
keyword[with] identifier[open] ( identifier[orig_file] ) keyword[as] identifier[in_handle] :
identifier[reader1] = identifier[csv] . identifier[reader] ( iden... | def _organize_by_position(orig_file, cmp_file, chunk_size):
"""Read two CSV files of qualities, organizing values by position.
"""
with open(orig_file) as in_handle:
reader1 = csv.reader(in_handle)
positions = len(next(reader1)) - 1 # depends on [control=['with'], data=['in_handle']]
fo... |
def derivative(self, z, x, y, fase):
"""Wrapper derivative for custom derived properties
where x, y, z can be: P, T, v, u, h, s, g, a"""
return deriv_G(self, z, x, y, fase) | def function[derivative, parameter[self, z, x, y, fase]]:
constant[Wrapper derivative for custom derived properties
where x, y, z can be: P, T, v, u, h, s, g, a]
return[call[name[deriv_G], parameter[name[self], name[z], name[x], name[y], name[fase]]]] | keyword[def] identifier[derivative] ( identifier[self] , identifier[z] , identifier[x] , identifier[y] , identifier[fase] ):
literal[string]
keyword[return] identifier[deriv_G] ( identifier[self] , identifier[z] , identifier[x] , identifier[y] , identifier[fase] ) | def derivative(self, z, x, y, fase):
"""Wrapper derivative for custom derived properties
where x, y, z can be: P, T, v, u, h, s, g, a"""
return deriv_G(self, z, x, y, fase) |
def _run_pants_with_retry(self, pantsd_handle, retries=3):
"""Runs pants remotely with retry and recovery for nascent executions.
:param PantsDaemon.Handle pantsd_handle: A Handle for the daemon to connect to.
"""
attempt = 1
while 1:
logger.debug(
'connecting to pantsd on port {} (at... | def function[_run_pants_with_retry, parameter[self, pantsd_handle, retries]]:
constant[Runs pants remotely with retry and recovery for nascent executions.
:param PantsDaemon.Handle pantsd_handle: A Handle for the daemon to connect to.
]
variable[attempt] assign[=] constant[1]
while cons... | keyword[def] identifier[_run_pants_with_retry] ( identifier[self] , identifier[pantsd_handle] , identifier[retries] = literal[int] ):
literal[string]
identifier[attempt] = literal[int]
keyword[while] literal[int] :
identifier[logger] . identifier[debug] (
literal[string]
. ident... | def _run_pants_with_retry(self, pantsd_handle, retries=3):
"""Runs pants remotely with retry and recovery for nascent executions.
:param PantsDaemon.Handle pantsd_handle: A Handle for the daemon to connect to.
"""
attempt = 1
while 1:
logger.debug('connecting to pantsd on port {} (attempt {... |
def bam_to_fastq(self, bam_file, out_fastq_pre, paired_end):
"""
Build command to convert BAM file to FASTQ file(s) (R1/R2).
:param str bam_file: path to BAM file with sequencing reads
:param str out_fastq_pre: path prefix for output FASTQ file(s)
:param bool paired_end: whether... | def function[bam_to_fastq, parameter[self, bam_file, out_fastq_pre, paired_end]]:
constant[
Build command to convert BAM file to FASTQ file(s) (R1/R2).
:param str bam_file: path to BAM file with sequencing reads
:param str out_fastq_pre: path prefix for output FASTQ file(s)
:par... | keyword[def] identifier[bam_to_fastq] ( identifier[self] , identifier[bam_file] , identifier[out_fastq_pre] , identifier[paired_end] ):
literal[string]
identifier[self] . identifier[make_sure_path_exists] ( identifier[os] . identifier[path] . identifier[dirname] ( identifier[out_fastq_pre] ))
... | def bam_to_fastq(self, bam_file, out_fastq_pre, paired_end):
"""
Build command to convert BAM file to FASTQ file(s) (R1/R2).
:param str bam_file: path to BAM file with sequencing reads
:param str out_fastq_pre: path prefix for output FASTQ file(s)
:param bool paired_end: whether the... |
def parse_address(address, language=None, country=None):
"""
Parse address into components.
@param address: the address as either Unicode or a UTF-8 encoded string
@param language (optional): language code
@param country (optional): country code
"""
address = safe_decode(address, 'utf-8')
... | def function[parse_address, parameter[address, language, country]]:
constant[
Parse address into components.
@param address: the address as either Unicode or a UTF-8 encoded string
@param language (optional): language code
@param country (optional): country code
]
variable[address] ... | keyword[def] identifier[parse_address] ( identifier[address] , identifier[language] = keyword[None] , identifier[country] = keyword[None] ):
literal[string]
identifier[address] = identifier[safe_decode] ( identifier[address] , literal[string] )
keyword[return] identifier[_parser] . identifier[parse_a... | def parse_address(address, language=None, country=None):
"""
Parse address into components.
@param address: the address as either Unicode or a UTF-8 encoded string
@param language (optional): language code
@param country (optional): country code
"""
address = safe_decode(address, 'utf-8')
... |
def get_day_start_ut(self, date):
"""
Get day start time (as specified by GTFS) as unix time in seconds
Parameters
----------
date : str | unicode | datetime.datetime
something describing the date
Returns
-------
day_start_ut : int
... | def function[get_day_start_ut, parameter[self, date]]:
constant[
Get day start time (as specified by GTFS) as unix time in seconds
Parameters
----------
date : str | unicode | datetime.datetime
something describing the date
Returns
-------
da... | keyword[def] identifier[get_day_start_ut] ( identifier[self] , identifier[date] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[date] , identifier[string_types] ):
identifier[date] = identifier[datetime] . identifier[datetime] . identifier[strptime] ( identifier[dat... | def get_day_start_ut(self, date):
"""
Get day start time (as specified by GTFS) as unix time in seconds
Parameters
----------
date : str | unicode | datetime.datetime
something describing the date
Returns
-------
day_start_ut : int
st... |
def gemset_list(ruby='default', runas=None):
'''
List all gemsets for the given ruby.
ruby : default
The ruby version for which to list the gemsets
runas
The user under which to run rvm. If not specified, then rvm will be run
as the user under which Salt is running.
CLI Ex... | def function[gemset_list, parameter[ruby, runas]]:
constant[
List all gemsets for the given ruby.
ruby : default
The ruby version for which to list the gemsets
runas
The user under which to run rvm. If not specified, then rvm will be run
as the user under which Salt is runn... | keyword[def] identifier[gemset_list] ( identifier[ruby] = literal[string] , identifier[runas] = keyword[None] ):
literal[string]
identifier[gemsets] =[]
identifier[output] = identifier[_rvm_do] ( identifier[ruby] ,[ literal[string] , literal[string] , literal[string] ], identifier[runas] = identifier[... | def gemset_list(ruby='default', runas=None):
"""
List all gemsets for the given ruby.
ruby : default
The ruby version for which to list the gemsets
runas
The user under which to run rvm. If not specified, then rvm will be run
as the user under which Salt is running.
CLI Ex... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.