code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def parse_args(self):
"""
Parse our arguments.
"""
# compile the parser
self._compile()
# clear the args
self.args = None
self._self_event('before_parse', 'parse', *sys.argv[1:], **{})
# list commands/subcommands in argv
cmds = [cmd for cmd... | Parse our arguments. |
def filter(self, criteria):
"""
Return a filtered version of this list following the given criteria,
which can be a string (take only courses where this attribute is
truthy) or a function which takes a course and return a boolean.
"""
if isinstance(criteria, str) or isins... | Return a filtered version of this list following the given criteria,
which can be a string (take only courses where this attribute is
truthy) or a function which takes a course and return a boolean. |
def state_args(id_, state, high):
'''
Return a set of the arguments passed to the named state
'''
args = set()
if id_ not in high:
return args
if state not in high[id_]:
return args
for item in high[id_][state]:
if not isinstance(item, dict):
continue
... | Return a set of the arguments passed to the named state |
def rewrite_elife_datasets_json(json_content, doi):
""" this does the work of rewriting elife datasets json """
# Add dates in bulk
elife_dataset_dates = []
elife_dataset_dates.append(("10.7554/eLife.00348", "used", "dataro17", u"2010"))
elife_dataset_dates.append(("10.7554/eLife.01179", "used", "d... | this does the work of rewriting elife datasets json |
def prepend(self, other, inplace=True, pad=None, gap=None, resize=True):
"""Connect another series onto the start of the current one.
Parameters
----------
other : `Series`
another series of the same type as this one
inplace : `bool`, optional
perform op... | Connect another series onto the start of the current one.
Parameters
----------
other : `Series`
another series of the same type as this one
inplace : `bool`, optional
perform operation in-place, modifying current series,
otherwise copy data and retu... |
def save_imgs(x, fname):
"""Helper method to save a grid of images to a PNG file.
Args:
x: A numpy array of shape [n_images, height, width].
fname: The filename to write to (including extension).
"""
n = x.shape[0]
fig = figure.Figure(figsize=(n, 1), frameon=False)
canvas = backend_agg.FigureCanvas... | Helper method to save a grid of images to a PNG file.
Args:
x: A numpy array of shape [n_images, height, width].
fname: The filename to write to (including extension). |
def pelix_infos(self):
"""
Basic information about the Pelix framework instance
"""
framework = self.__context.get_framework()
return {
"version": framework.get_version(),
"properties": framework.get_properties(),
} | Basic information about the Pelix framework instance |
def attribute_labels(self, attribute_id, params=None):
"""
Gets the security labels from a attribute
Yields: Security label json
"""
if params is None:
params = {}
if not self.can_update():
self._tcex.handle_error(910, [self.type])
for a... | Gets the security labels from a attribute
Yields: Security label json |
def object_merge(old, new, unique=False):
"""
Recursively merge two data structures.
:param unique: When set to True existing list items are not set.
"""
if isinstance(old, list) and isinstance(new, list):
if old == new:
return
for item in old[::-1]:
if uniqu... | Recursively merge two data structures.
:param unique: When set to True existing list items are not set. |
def _scan(positions):
"""get the region inside the vector with more expression"""
scores = []
for start in range(0, len(positions) - 17, 5):
end = start = 17
scores.add(_enrichment(positions[start:end], positions[:start], positions[end:])) | get the region inside the vector with more expression |
def square_root(n, epsilon=0.001):
"""Return square root of n, with maximum absolute error epsilon"""
guess = n / 2
while abs(guess * guess - n) > epsilon:
guess = (guess + (n / guess)) / 2
return guess | Return square root of n, with maximum absolute error epsilon |
def create_effect(self, label: str, name: str, *args, **kwargs) -> Effect:
"""
Create an effect instance adding it to the internal effects dictionary using the label as key.
Args:
label (str): The unique label for the effect instance
name (str): Name or full python... | Create an effect instance adding it to the internal effects dictionary using the label as key.
Args:
label (str): The unique label for the effect instance
name (str): Name or full python path to the effect class we want to instantiate
args: Positional arguments to the e... |
def recursively_register_child_states(self, state):
""" A function tha registers recursively all child states of a state
:param state:
:return:
"""
self.logger.info("Execution status observer add new state {}".format(state))
if isinstance(state, ContainerState):
... | A function tha registers recursively all child states of a state
:param state:
:return: |
def _send_packet(self, data):
"""
Send packet to client.
"""
if self._closed:
return
data = json.dumps(data)
def send():
try:
yield From(self.pipe_connection.write(data))
except BrokenPipeError:
self.de... | Send packet to client. |
def make_zigzag(points, num_cols):
""" Converts linear sequence of points into a zig-zag shape.
This function is designed to create input for the visualization software. It orders the points to draw a zig-zag
shape which enables generating properly connected lines without any scanlines. Please see the belo... | Converts linear sequence of points into a zig-zag shape.
This function is designed to create input for the visualization software. It orders the points to draw a zig-zag
shape which enables generating properly connected lines without any scanlines. Please see the below sketch on the
functionality of the ``... |
def TypeFactory(v):
"""Ensure `v` is a valid Type.
This function is used to convert user-specified types into
internal types for the verification engine. It allows Type
subclasses, Type subclass instances, Python type, and user-defined
classes to be passed. Returns an instance of the type of `v`.... | Ensure `v` is a valid Type.
This function is used to convert user-specified types into
internal types for the verification engine. It allows Type
subclasses, Type subclass instances, Python type, and user-defined
classes to be passed. Returns an instance of the type of `v`.
Users should never ac... |
def get_an_int(self, arg, msg_on_error, min_value=None, max_value=None):
"""Like cmdfns.get_an_int(), but if there's a stack frame use that
in evaluation."""
ret_value = self.get_int_noerr(arg)
if ret_value is None:
if msg_on_error:
self.errmsg(msg_on_error)
... | Like cmdfns.get_an_int(), but if there's a stack frame use that
in evaluation. |
def valid_project(self):
"""Handle an invalid active project."""
try:
path = self.projects.get_active_project_path()
except AttributeError:
return
if bool(path):
if not self.projects.is_valid_project(path):
if path:
... | Handle an invalid active project. |
def line_ball_intersection(start_points, end_points, center, radius):
"""
Compute the length of the intersection of a line segment with a ball.
Parameters
----------
start_points : (n,3) float, list of points in space
end_points : (n,3) float, list of points in space
center : (3,) f... | Compute the length of the intersection of a line segment with a ball.
Parameters
----------
start_points : (n,3) float, list of points in space
end_points : (n,3) float, list of points in space
center : (3,) float, the sphere center
radius : float, the sphere radius
Returns
... |
def functional(self):
"""All required enzymes for reaction are functional.
Returns
-------
bool
True if the gene-protein-reaction (GPR) rule is fulfilled for
this reaction, or if reaction is not associated to a model,
otherwise False.
"""
... | All required enzymes for reaction are functional.
Returns
-------
bool
True if the gene-protein-reaction (GPR) rule is fulfilled for
this reaction, or if reaction is not associated to a model,
otherwise False. |
def html_elem(e, ct, withtype=False):
"""
Format a result element as an HTML table cell.
@param e (list): a pair \c (value,type)
@param ct (str): cell type (th or td)
@param withtype (bool): add an additional cell with the element type
"""
# Header cell
if ct == 'th':
retur... | Format a result element as an HTML table cell.
@param e (list): a pair \c (value,type)
@param ct (str): cell type (th or td)
@param withtype (bool): add an additional cell with the element type |
def _new_extension(name, value, critical=0, issuer=None, _pyfree=1):
'''
Create new X509_Extension, This is required because M2Crypto
doesn't support getting the publickeyidentifier from the issuer
to create the authoritykeyidentifier extension.
'''
if name == 'subjectKeyIdentifier' and value.st... | Create new X509_Extension, This is required because M2Crypto
doesn't support getting the publickeyidentifier from the issuer
to create the authoritykeyidentifier extension. |
def _fw_policy_create(self, drvr_name, data, cache):
"""Firewall Policy create routine.
This function updates its local cache with policy parameters.
It checks if local cache has information about the rules
associated with the policy. If not, it means a restart has
happened. It ... | Firewall Policy create routine.
This function updates its local cache with policy parameters.
It checks if local cache has information about the rules
associated with the policy. If not, it means a restart has
happened. It retrieves the rules associated with the policy by
callin... |
def _call_command_in_repo(comm, repo, log, fail=False, log_flag=True):
"""Use `subprocess` to call a command in a certain (repo) directory.
Logs the output (both `stderr` and `stdout`) to the log, and checks the
return codes to make sure they're valid. Raises error if not.
Raises
------
excep... | Use `subprocess` to call a command in a certain (repo) directory.
Logs the output (both `stderr` and `stdout`) to the log, and checks the
return codes to make sure they're valid. Raises error if not.
Raises
------
exception `subprocess.CalledProcessError`: if the command fails |
def connect(self, dests=[], name=None, id='', props={}):
'''Connect this port to other ports.
After the connection has been made, a delayed reparse of the
connections for this and the destination port will be triggered.
@param dests A list of the destination Port objects. Must be provi... | Connect this port to other ports.
After the connection has been made, a delayed reparse of the
connections for this and the destination port will be triggered.
@param dests A list of the destination Port objects. Must be provided.
@param name The name of the connection. If None, a suit... |
def prefix_iter(self, ns_uri):
"""Gets an iterator over the prefixes for the given namespace."""
ni = self.__lookup_uri(ns_uri)
return iter(ni.prefixes) | Gets an iterator over the prefixes for the given namespace. |
def summary_df(df_in, **kwargs):
"""Make a panda data frame of the mean and std devs of an array of results,
including the uncertainties on the values.
This is similar to pandas.DataFrame.describe but also includes estimates of
the numerical uncertainties.
The output DataFrame has multiindex level... | Make a panda data frame of the mean and std devs of an array of results,
including the uncertainties on the values.
This is similar to pandas.DataFrame.describe but also includes estimates of
the numerical uncertainties.
The output DataFrame has multiindex levels:
'calculation type': mean and st... |
def is_out_of_range(brain_or_object, result=_marker):
"""Checks if the result for the analysis passed in is out of range and/or
out of shoulders range.
min max
warn min max warn
·········|----... | Checks if the result for the analysis passed in is out of range and/or
out of shoulders range.
min max
warn min max warn
·········|---------------|=====================|---------------|·········
... |
def _parallel_receive_loop(self, seconds_to_wait):
"""Run the receiving in parallel."""
sleep(seconds_to_wait)
with self._lock:
self._number_of_threads_receiving_messages += 1
try:
with self._lock:
if self.state.is_waiting_for_start():
... | Run the receiving in parallel. |
def notice(txt, color=False):
"print notice"
if color:
txt = config.Col.WARNING + txt + config.Col.ENDC
print(txt) | print notice |
def __generate_really (self, prop_set):
""" Generates the main target with the given property set
and returns a list which first element is property_set object
containing usage_requirements of generated target and with
generated virtual target in other elements. It's possible... | Generates the main target with the given property set
and returns a list which first element is property_set object
containing usage_requirements of generated target and with
generated virtual target in other elements. It's possible
that no targets are generated. |
def n_exec_stmt(self, node):
"""
exec_stmt ::= expr exprlist DUP_TOP EXEC_STMT
exec_stmt ::= expr exprlist EXEC_STMT
"""
self.write(self.indent, 'exec ')
self.preorder(node[0])
if not node[1][0].isNone():
sep = ' in '
for subnode in node[1]... | exec_stmt ::= expr exprlist DUP_TOP EXEC_STMT
exec_stmt ::= expr exprlist EXEC_STMT |
def assert_same(self, first, second):
"""
Compares two items for identity. The items can be either single
values or lists of values. When comparing lists, identity
obtains when the two lists have the same number of elements
and that the element at position in one list is identica... | Compares two items for identity. The items can be either single
values or lists of values. When comparing lists, identity
obtains when the two lists have the same number of elements
and that the element at position in one list is identical to
the element at the same position in the other... |
def disassemble(self, *, transforms=None) -> Iterator[Instruction]:
"""
Disassembles this method, yielding an iterable of
:class:`~jawa.util.bytecode.Instruction` objects.
"""
if transforms is None:
if self.cf.classloader:
transforms = self.cf.classloa... | Disassembles this method, yielding an iterable of
:class:`~jawa.util.bytecode.Instruction` objects. |
def do_execute(self):
"""
The actual execution of the actor.
:return: None if successful, otherwise error message
:rtype: str
"""
if isinstance(self.input.payload, Instances):
inst = None
data = self.input.payload
elif isinstance(self.inpu... | The actual execution of the actor.
:return: None if successful, otherwise error message
:rtype: str |
def serialize_artifact_json_blobs(artifacts):
"""
Ensure that JSON artifact blobs passed as dicts are converted to JSON
"""
for artifact in artifacts:
blob = artifact['blob']
if (artifact['type'].lower() == 'json' and
not isinstance(blob, str)):
artifact['blob... | Ensure that JSON artifact blobs passed as dicts are converted to JSON |
def calc_spectrum(signal, rate):
"""Return the spectrum and frequency indexes for real-valued input signal"""
npts = len(signal)
padto = 1 << (npts - 1).bit_length()
# print 'length of signal {}, pad to {}'.format(npts, padto)
npts = padto
sp = np.fft.rfft(signal, n=padto) / npts
# print('s... | Return the spectrum and frequency indexes for real-valued input signal |
def session_to_epoch(timestamp):
""" converts Synergy Timestamp for session to UTC zone seconds since epoch """
utc_timetuple = datetime.strptime(timestamp, SYNERGY_SESSION_PATTERN).replace(tzinfo=None).utctimetuple()
return calendar.timegm(utc_timetuple) | converts Synergy Timestamp for session to UTC zone seconds since epoch |
def predict(self, dataset, missing_value_action='auto'):
"""
Predict the target column of the given dataset.
The target column is provided during
:func:`~turicreate.random_forest_regression.create`. If the target column is in the
`dataset` it will be ignored.
Parameters... | Predict the target column of the given dataset.
The target column is provided during
:func:`~turicreate.random_forest_regression.create`. If the target column is in the
`dataset` it will be ignored.
Parameters
----------
dataset : SFrame
A dataset that has the... |
def preprocessor(dom):
"Removes unwanted parts of DOM."
options = {
"processing_instructions": False,
"remove_unknown_tags": False,
"safe_attrs_only": False,
"page_structure": False,
"annoying_tags": False,
"frames": False,
"meta": False,
"links": ... | Removes unwanted parts of DOM. |
def _timer(self, state_transition_event=None):
"""Timer loop used to keep track of the time while roasting or
cooling. If the time remaining reaches zero, the roaster will call the
supplied state transistion function or the roaster will be set to
the idle state."""
while not self... | Timer loop used to keep track of the time while roasting or
cooling. If the time remaining reaches zero, the roaster will call the
supplied state transistion function or the roaster will be set to
the idle state. |
def dmag_magic(in_file="measurements.txt", dir_path=".", input_dir_path="",
spec_file="specimens.txt", samp_file="samples.txt",
site_file="sites.txt", loc_file="locations.txt",
plot_by="loc", LT="AF", norm=True, XLP="",
save_plots=True, fmt="svg"):
"""
plots intensity decay ... | plots intensity decay curves for demagnetization experiments
Parameters
----------
in_file : str, default "measurements.txt"
dir_path : str
output directory, default "."
input_dir_path : str
input file directory (if different from dir_path), default ""
spec_file : str
in... |
def skus_get(self, product_id, session):
'''taobao.fenxiao.product.skus.get SKU查询接口
产品sku查询'''
request = TOPRequest('taobao.fenxiao.product.skus.get')
request['product_id'] = product_id
self.create(self.execute(request, session), fields=['skus','total_results'], models={... | taobao.fenxiao.product.skus.get SKU查询接口
产品sku查询 |
def info(self):
"""Supplemental description of the list, with length and type"""
itext = self.class_info
if self.prop.info:
itext += ' (each item is {})'.format(self.prop.info)
if self.max_length is None and self.min_length is None:
return itext
if self.ma... | Supplemental description of the list, with length and type |
def save_dict(self, key: str, my_dict: dict, hierarchical: bool = False):
"""Store the specified dictionary at the specified key."""
for _key, _value in my_dict.items():
if isinstance(_value, dict):
if not hierarchical:
self._db.hmset(key, {_key: json.dump... | Store the specified dictionary at the specified key. |
def main(argv=None):
"""Main function to run benchmarks.
@param argv: command-line arguments.
@return: exit code (0 is OK).
"""
import getopt
# default values
test_read = None
test_write = None
n = 3 # number of repeat
if argv is None:
argv = sys.argv[1:... | Main function to run benchmarks.
@param argv: command-line arguments.
@return: exit code (0 is OK). |
def create_record(self, dns_type, name, content, **kwargs):
"""
Create a dns record
:param dns_type:
:param name:
:param content:
:param kwargs:
:return:
"""
data = {
'type': dns_type,
'name': name,
'content': co... | Create a dns record
:param dns_type:
:param name:
:param content:
:param kwargs:
:return: |
def _get_distance_term(self, C, rrup, backarc):
"""
Returns the distance scaling term, which varies depending on whether
the site is in the forearc or the backarc
"""
# Geometric attenuation function
distance_scale = -np.log10(np.sqrt(rrup ** 2 + 3600.0))
# Anelas... | Returns the distance scaling term, which varies depending on whether
the site is in the forearc or the backarc |
def welch(timeseries, segmentlength, noverlap=None, scheme=None, **kwargs):
"""Calculate a PSD using Welch's method with a mean average
Parameters
----------
timeseries : `~gwpy.timeseries.TimeSeries`
input `TimeSeries` data.
segmentlength : `int`
number of samples in single averag... | Calculate a PSD using Welch's method with a mean average
Parameters
----------
timeseries : `~gwpy.timeseries.TimeSeries`
input `TimeSeries` data.
segmentlength : `int`
number of samples in single average.
noverlap : `int`
number of samples to overlap between segments, def... |
def mkdir(dirname, overwrite=False):
"""
Wraps around os.mkdir(), but checks for existence first.
"""
if op.isdir(dirname):
if overwrite:
shutil.rmtree(dirname)
os.mkdir(dirname)
logging.debug("Overwrite folder `{0}`.".format(dirname))
else:
... | Wraps around os.mkdir(), but checks for existence first. |
def posterior_to_xarray(self):
"""Extract posterior samples from fit."""
posterior = self.posterior
# filter posterior_predictive and log_likelihood
posterior_predictive = self.posterior_predictive
if posterior_predictive is None:
posterior_predictive = []
... | Extract posterior samples from fit. |
def get_logexp(a=1, b=0, a2=None, b2=None, backend=None):
""" Utility function for use with :func:symmetricsys.
Creates a pair of callbacks for logarithmic transformation
(including scaling and shifting): ``u = ln(a*x + b)``.
Parameters
----------
a : number
Scaling (forward).
b : ... | Utility function for use with :func:symmetricsys.
Creates a pair of callbacks for logarithmic transformation
(including scaling and shifting): ``u = ln(a*x + b)``.
Parameters
----------
a : number
Scaling (forward).
b : number
Shift (forward).
a2 : number
Scaling (b... |
def reset(self):
"""
Empties all internal storage containers
"""
super(MorseSmaleComplex, self).reset()
self.base_partitions = {}
self.merge_sequence = {}
self.persistences = []
self.min_indices = []
self.max_indices = []
# State pro... | Empties all internal storage containers |
def get_genes(
path_or_buffer, valid_biotypes,
chunksize=10000,
chromosome_pattern=None,
#chromosome_pattern=r'(?:\d\d?|MT|X|Y)$',
only_manual=False,
remove_duplicates=True,
sort_by='name'):
"""Get all genes of a specific a biotype from an Ensembl GTF file.
... | Get all genes of a specific a biotype from an Ensembl GTF file.
Parameters
----------
path_or_buffer : str or buffer
The GTF file (either the file path or a buffer).
valid_biotypes : set of str
The set of biotypes to include (e.g., "protein_coding").
chromosome_pattern : str, op... |
def get_internal_call_graph(fpath, with_doctests=False):
"""
CommandLine:
python -m utool.util_inspect get_internal_call_graph --show --modpath=~/code/ibeis/ibeis/init/main_helpers.py --show
python -m utool.util_inspect get_internal_call_graph --show --modpath=~/code/dtool/dtool/depcache_table.p... | CommandLine:
python -m utool.util_inspect get_internal_call_graph --show --modpath=~/code/ibeis/ibeis/init/main_helpers.py --show
python -m utool.util_inspect get_internal_call_graph --show --modpath=~/code/dtool/dtool/depcache_table.py --show
Example:
>>> # DISABLE_DOCTEST
>>> from... |
def run_preassembly_duplicate(preassembler, beliefengine, **kwargs):
"""Run deduplication stage of preassembly on a list of statements.
Parameters
----------
preassembler : indra.preassembler.Preassembler
A Preassembler instance
beliefengine : indra.belief.BeliefEngine
A BeliefEngin... | Run deduplication stage of preassembly on a list of statements.
Parameters
----------
preassembler : indra.preassembler.Preassembler
A Preassembler instance
beliefengine : indra.belief.BeliefEngine
A BeliefEngine instance.
save : Optional[str]
The name of a pickle file to sa... |
def task_done(self) -> None:
"""Indicate that a formerly enqueued task is complete.
Used by queue consumers. For each `.get` used to fetch a task, a
subsequent call to `.task_done` tells the queue that the processing
on the task is complete.
If a `.join` is blocking, it resumes... | Indicate that a formerly enqueued task is complete.
Used by queue consumers. For each `.get` used to fetch a task, a
subsequent call to `.task_done` tells the queue that the processing
on the task is complete.
If a `.join` is blocking, it resumes when all items have been
proces... |
def entity_to_bulk(entities, resource_type_parent):
"""Convert Single TC Entity to Bulk format.
.. Attention:: This method is subject to frequent changes
Args:
entities (dictionary): TC Entity to be converted to Bulk.
resource_type_parent (string): The resource parent t... | Convert Single TC Entity to Bulk format.
.. Attention:: This method is subject to frequent changes
Args:
entities (dictionary): TC Entity to be converted to Bulk.
resource_type_parent (string): The resource parent type of the tc_data provided.
Returns:
(dic... |
def get_default_config(self):
"""
Return the default config for the handler
"""
config = super(StatsdHandler, self).get_default_config()
config.update({
'host': '',
'port': 1234,
'batch': 1,
})
return config | Return the default config for the handler |
def getEmpTraitCorrCoef(self):
"""
Returns the empirical trait correlation matrix
"""
cov = self.getEmpTraitCovar()
stds=SP.sqrt(cov.diagonal())[:,SP.newaxis]
RV = cov/stds/stds.T
return RV | Returns the empirical trait correlation matrix |
def uniquetwig(self, ps=None):
"""
see also :meth:`twig`
Determine the shortest (more-or-less) twig which will point
to this single Parameter in a given parent :class:`ParameterSet`
:parameter ps: :class:`ParameterSet` in which the returned
uniquetwig will point to ... | see also :meth:`twig`
Determine the shortest (more-or-less) twig which will point
to this single Parameter in a given parent :class:`ParameterSet`
:parameter ps: :class:`ParameterSet` in which the returned
uniquetwig will point to this Parameter. If not provided
or Non... |
def VerifyStructure(self, parser_mediator, lines):
"""Verify that this file is a SkyDrive log file.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
lines (str): one or more lines from the text file.
Return... | Verify that this file is a SkyDrive log file.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
lines (str): one or more lines from the text file.
Returns:
bool: True if this is the correct parser, False o... |
def calculate_normals(vertices):
"""Return Nx3 normal array from Nx3 vertex array."""
verts = np.array(vertices, dtype=float)
normals = np.zeros_like(verts)
for start, end in pairwise(np.arange(0, verts.shape[0] + 1, 3)):
vecs = np.vstack((verts[start + 1] - verts[start], verts[start + 2] - vert... | Return Nx3 normal array from Nx3 vertex array. |
def filter_objects_by_section(self, rels, section):
"""Build a queryset containing all objects in the section subtree."""
subtree = section.get_descendants(include_self=True)
kwargs_list = [{'%s__in' % rel.field.name: subtree} for rel in rels]
q = Q(**kwargs_list[0])
for kwargs ... | Build a queryset containing all objects in the section subtree. |
def image_exists(self, image_name, tag='latest'):
"""
:param image_name:
:return: True the image_name location in docker.neg pos
"""
code, image = self.image_tags(image_name)
if code != httplib.OK:
return False
tag = tag.lower()
retu... | :param image_name:
:return: True the image_name location in docker.neg pos |
def _points(self, x_pos):
"""
Convert given data values into drawable points (x, y)
and interpolated points if interpolate option is specified
"""
for serie in self.all_series:
serie.points = [(x_pos[i], v) for i, v in enumerate(serie.values)]
if serie.poi... | Convert given data values into drawable points (x, y)
and interpolated points if interpolate option is specified |
def schema(self, shex: Optional[Union[str, ShExJ.Schema]]) -> None:
""" Set the schema to be used. Schema can either be a ShExC or ShExJ string or a pre-parsed schema.
:param shex: Schema
"""
self.pfx = None
if shex is not None:
if isinstance(shex, ShExJ.Schema):
... | Set the schema to be used. Schema can either be a ShExC or ShExJ string or a pre-parsed schema.
:param shex: Schema |
def _syscal_write_electrode_coords(fid, spacing, N):
"""helper function that writes out electrode positions to a file descriptor
Parameters
----------
fid: file descriptor
data is written here
spacing: float
spacing of electrodes
N: int
number of electrodes
"""
f... | helper function that writes out electrode positions to a file descriptor
Parameters
----------
fid: file descriptor
data is written here
spacing: float
spacing of electrodes
N: int
number of electrodes |
def add_named_metadata(self, name, element=None):
"""
Add a named metadata node to the module, if it doesn't exist,
or return the existing node.
If *element* is given, it will append a new element to
the named metadata node. If *element* is a sequence of values
(rather t... | Add a named metadata node to the module, if it doesn't exist,
or return the existing node.
If *element* is given, it will append a new element to
the named metadata node. If *element* is a sequence of values
(rather than a metadata value), a new unnamed node will first be
create... |
def getMugshot(self):
"""
Return the L{Mugshot} associated with this L{Person}, or an unstored
L{Mugshot} pointing at a placeholder mugshot image.
"""
mugshot = self.store.findUnique(
Mugshot, Mugshot.person == self, default=None)
if mugshot is not None:
... | Return the L{Mugshot} associated with this L{Person}, or an unstored
L{Mugshot} pointing at a placeholder mugshot image. |
def _dispatch_handler(args, cell, parser, handler, cell_required=False,
cell_prohibited=False):
""" Makes sure cell magics include cell and line magics don't, before
dispatching to handler.
Args:
args: the parsed arguments from the magic line.
cell: the contents of the cell, if an... | Makes sure cell magics include cell and line magics don't, before
dispatching to handler.
Args:
args: the parsed arguments from the magic line.
cell: the contents of the cell, if any.
parser: the argument parser for <cmd>; used for error message.
handler: the handler to call if the cell present/a... |
def validate(self, strict=True):
""" check if this Swagger API valid or not.
:param bool strict: when in strict mode, exception would be raised if not valid.
:return: validation errors
:rtype: list of tuple(where, type, msg).
"""
result = self._validate()
if str... | check if this Swagger API valid or not.
:param bool strict: when in strict mode, exception would be raised if not valid.
:return: validation errors
:rtype: list of tuple(where, type, msg). |
def level_grouper(text, getreffs, level=None, groupby=20):
""" Alternative to level_chunker: groups levels together at the latest level
:param text: Text object
:param getreffs: GetValidReff query callback
:param level: Level of citation to retrieve
:param groupby: Number of level to groupby
:r... | Alternative to level_chunker: groups levels together at the latest level
:param text: Text object
:param getreffs: GetValidReff query callback
:param level: Level of citation to retrieve
:param groupby: Number of level to groupby
:return: Automatically curated references |
def _write(self, session, openFile, replaceParamFile=None):
"""
ProjectFileEvent Write to File Method
"""
openFile.write(
text(
yaml.dump([evt.as_yml() for evt in
self.events.order_by(ProjectFileEvent.name,
... | ProjectFileEvent Write to File Method |
def forwards(apps, schema_editor):
"""
Create initial recurrence rules.
"""
RecurrenceRule = apps.get_model('icekit_events', 'RecurrenceRule')
for description, recurrence_rule in RULES:
RecurrenceRule.objects.get_or_create(
description=description,
defaults=dict(recur... | Create initial recurrence rules. |
def marker_tags(self, iid):
"""Generator for all the tags of a certain marker"""
tags = self._markers[iid]["tags"]
for tag in tags:
yield tag | Generator for all the tags of a certain marker |
def F_beta(self, beta):
"""
Calculate FBeta score.
:param beta: beta parameter
:type beta : float
:return: FBeta score for classes as dict
"""
try:
F_dict = {}
for i in self.TP.keys():
F_dict[i] = F_calc(
... | Calculate FBeta score.
:param beta: beta parameter
:type beta : float
:return: FBeta score for classes as dict |
def line(self, p1, p2, resolution=1):
"""Resolve the points to make a line between two points."""
xdiff = max(p1.x, p2.x) - min(p1.x, p2.x)
ydiff = max(p1.y, p2.y) - min(p1.y, p2.y)
xdir = [-1, 1][int(p1.x <= p2.x)]
ydir = [-1, 1][int(p1.y <= p2.y)]
r = int(round(max(xdif... | Resolve the points to make a line between two points. |
def is_terminal(self):
"""True if this result will stop the test."""
return (self.raised_exception or self.is_timeout or
self.phase_result == openhtf.PhaseResult.STOP) | True if this result will stop the test. |
def update_search_space(self, search_space):
"""
Update search space definition in tuner by search_space in parameters.
Will called when first setup experiemnt or update search space in WebUI.
Parameters
----------
search_space : dict
"""
self.json = sea... | Update search space definition in tuner by search_space in parameters.
Will called when first setup experiemnt or update search space in WebUI.
Parameters
----------
search_space : dict |
def bytes2str_in_dicts(inp # type: Union[MutableMapping[Text, Any], MutableSequence[Any], Any]
):
# type: (...) -> Union[Text, MutableSequence[Any], MutableMapping[Text, Any]]
"""
Convert any present byte string to unicode string, inplace.
input is a dict of nested dicts and lists... | Convert any present byte string to unicode string, inplace.
input is a dict of nested dicts and lists |
def _get_address_translations_table(address_translations):
"""Yields a formatted table to print address translations.
:param List[dict] address_translations: List of address translations.
:return Table: Formatted for address translation output.
"""
table = formatting.Table(['id',
... | Yields a formatted table to print address translations.
:param List[dict] address_translations: List of address translations.
:return Table: Formatted for address translation output. |
def replicate_directory_tree(input_dir, output_dir):
"""
_replicate_directory_tree_
clone dir structure under input_dir into output dir
All subdirs beneath input_dir will be created under
output_dir
:param input_dir: path to dir tree to be cloned
:param output_dir: path to new dir where dir... | _replicate_directory_tree_
clone dir structure under input_dir into output dir
All subdirs beneath input_dir will be created under
output_dir
:param input_dir: path to dir tree to be cloned
:param output_dir: path to new dir where dir structure will
be created |
def stream_url(self):
'''stream for this song - not re-encoded'''
path = '/Audio/{}/universal'.format(self.id)
return self.connector.get_url(path,
userId=self.connector.userid,
MaxStreamingBitrate=140000000,
Container='opus',
TranscodingContainer='opus... | stream for this song - not re-encoded |
def send(self, send_email=True):
"""Marks the invoice as sent in Holvi
If send_email is False then the invoice is *not* automatically emailed to the recipient
and your must take care of sending the invoice yourself.
"""
url = str(self.api.base_url + '{code}/status/').format(code... | Marks the invoice as sent in Holvi
If send_email is False then the invoice is *not* automatically emailed to the recipient
and your must take care of sending the invoice yourself. |
def get_body(self, msg):
""" Extracts and returns the decoded body from an EmailMessage object"""
body = ""
charset = ""
if msg.is_multipart():
for part in msg.walk():
ctype = part.get_content_type()
cdispo = str(part.get('Content-Disposition... | Extracts and returns the decoded body from an EmailMessage object |
def fetchall_sp(s,p):
"""
fetch all triples for a property
"""
query = """
SELECT * WHERE {{
<{s}> <{p}> ?x
}}
""".format(s=s, p=prefixmap[p])
bindings = run_sparql(query)
rows = [r['x']['value'] for r in bindings]
return rows | fetch all triples for a property |
def obj_to_grid(self, file_path=None, delim=None, tab=None,
quote_numbers=True, quote_empty_str=False):
"""
This will return a str of a grid table.
:param file_path: path to data file, defaults to
self's contents if left alone
:pa... | This will return a str of a grid table.
:param file_path: path to data file, defaults to
self's contents if left alone
:param delim: dict of deliminators, defaults to
obj_to_str's method:
:param tab: stri... |
def list_nodes_full(call=None):
'''
List devices, with all available information.
CLI Example:
.. code-block:: bash
salt-cloud -F
salt-cloud --full-query
salt-cloud -f list_nodes_full packet-provider
..
'''
if call == 'action':
raise SaltCloudException(
... | List devices, with all available information.
CLI Example:
.. code-block:: bash
salt-cloud -F
salt-cloud --full-query
salt-cloud -f list_nodes_full packet-provider
.. |
def validate_url(url):
"""
Auxiliary method to validate an urllib
:param url: An url to be validated
:type url: string
:returns: True if the url is valid
:rtype: bool
"""
scheme = url.split('://')[0].lower()
if scheme not in url_schemes:
return False
if not bool(url_rege... | Auxiliary method to validate an urllib
:param url: An url to be validated
:type url: string
:returns: True if the url is valid
:rtype: bool |
def _run_sbgenomics(args):
"""Run CWL on SevenBridges platform and Cancer Genomics Cloud.
"""
assert not args.no_container, "Seven Bridges runs require containers"
main_file, json_file, project_name = _get_main_and_json(args.directory)
flags = []
cmd = ["sbg-cwl-runner"] + flags + args.toolargs ... | Run CWL on SevenBridges platform and Cancer Genomics Cloud. |
def pcapname(dev):
"""Get the device pcap name by device name or Scapy NetworkInterface
"""
if isinstance(dev, NetworkInterface):
if dev.is_invalid():
return None
return dev.pcap_name
try:
return IFACES.dev_from_name(dev).pcap_name
except ValueError:
retu... | Get the device pcap name by device name or Scapy NetworkInterface |
def override_options(config: DictLike, selected_options: Tuple[Any, ...], set_of_possible_options: Tuple[enum.Enum, ...], config_containing_override: DictLike = None) -> DictLike:
""" Determine override options for a particular configuration.
The options are determined by searching following the order specifie... | Determine override options for a particular configuration.
The options are determined by searching following the order specified in selected_options.
For the example config,
.. code-block:: yaml
config:
value: 3
override:
2.76:
track:
... |
def get_phone_numbers(self):
"""
: returns: dict of type and phone number list
:rtype: dict(str, list(str))
"""
phone_dict = {}
for child in self.vcard.getChildren():
if child.name == "TEL":
# phone types
type = helpers.list_to_... | : returns: dict of type and phone number list
:rtype: dict(str, list(str)) |
def match_resource_id(self, resource_id, match):
"""Sets the resource ``Id`` for this query.
arg: resource_id (osid.id.Id): a resource ``Id``
arg: match (boolean): ``true`` if a positive match, ``false``
for a negative match
raise: NullArgument - ``resource_id`` i... | Sets the resource ``Id`` for this query.
arg: resource_id (osid.id.Id): a resource ``Id``
arg: match (boolean): ``true`` if a positive match, ``false``
for a negative match
raise: NullArgument - ``resource_id`` is ``null``
*compliance: mandatory -- This method mus... |
def delete_file(self, sass_filename, sass_fileurl):
"""
Delete a *.css file, but only if it has been generated through a SASS/SCSS file.
"""
if self.use_static_root:
destpath = os.path.join(self.static_root, os.path.splitext(sass_fileurl)[0] + '.css')
else:
... | Delete a *.css file, but only if it has been generated through a SASS/SCSS file. |
def deserialize_logical(self, node):
"""
Reads the logical tag from the given node, returns a Condition object.
node -- the xml node (xml.dom.minidom.Node)
"""
term1_attrib = node.getAttribute('left-field')
term1_value = node.getAttribute('left-value')
op = node.... | Reads the logical tag from the given node, returns a Condition object.
node -- the xml node (xml.dom.minidom.Node) |
def _create_model(model, ident, **params):
""" Create a model by cloning and then setting params """
with log_errors(pdb=True):
model = clone(model).set_params(**params)
return model, {"model_id": ident, "params": params, "partial_fit_calls": 0} | Create a model by cloning and then setting params |
def _set_mpls_traffic_lsps(self, v, load=False):
"""
Setter method for mpls_traffic_lsps, mapped from YANG variable /telemetry/profile/mpls_traffic_lsp/mpls_traffic_lsps (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_mpls_traffic_lsps is considered as a private
... | Setter method for mpls_traffic_lsps, mapped from YANG variable /telemetry/profile/mpls_traffic_lsp/mpls_traffic_lsps (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_mpls_traffic_lsps is considered as a private
method. Backends looking to populate this variable should
... |
def half_duration(self):
"""Half of the duration of the current interval."""
if self._interval is not None:
a, b = self._interval
return (b - a) * .5
else:
return self.interval_duration * .5 | Half of the duration of the current interval. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.