content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def search_by_pattern(pattern, limit=20):
"""Perform a search for pattern."""
pattern_ = normalize_pattern(pattern)
db = get_db()
results = db.execute(
"""
SELECT json FROM places
WHERE document MATCH ?
ORDER BY rank DESC
LIMIT ?;
""",
(fts_pattern... | 5,345,200 |
def gcd(a, b):
"""Greatest common divisor"""
return _gcd_internal(abs(a), abs(b)) | 5,345,201 |
def exp_create_database(db_name, demo, lang, user_password='admin', login='admin', country_code=None, phone=None):
""" Similar to exp_create but blocking."""
_logger.info('Create database `%s`.', db_name)
_create_empty_database(db_name)
_initialize_db(id, db_name, demo, lang, user_password, login, count... | 5,345,202 |
def fix_cr(data):
"""Cosmic ray fixing function.
Args:
data (:class:`numpy.ndarray`): Input image data.
Returns:
:class:`numpy.dtype`: Fixed image data.
"""
m = data.mean(dtype=np.float64)
s = data.std(dtype=np.float64)
_mask = data > m + 3.*s
if _mask.sum()>0:
... | 5,345,203 |
def update_user_edit_config_file(new_config_items):
"""
Update the settings to the user editable config file
"""
config = configparser.RawConfigParser()
# start with the current config settings
config_items = read_user_edit_config_file()
# update with the new config items
... | 5,345,204 |
def iou(box1, box2, iouType='segm'):
"""Compute the Intersection-Over-Union of two given boxes.
or the Intersection-Over box2.
Args:
box1: array of 4 elements [cx, cy, width, height].
box2: same as above
iouType: The kind of intersection it will compute.
'keypoints' is for intersectio... | 5,345,205 |
def transform_color(color1, color2, skipR=1, skipG=1, skipB=1):
"""
transform_color(color1, color2, skipR=1, skipG=1, skipB=1)
This function takes 2 color1 and color2 RGB color arguments, and then returns a
list of colors in-between the color1 and color2
eg- tj.transform_color([0,0,0],[10,10,20]) returns a list:... | 5,345,206 |
def sandwich(func):
"""Write a decorator that prints UPPER_SLICE and
LOWE_SLICE before and after calling the function (func)
that is passed in (@wraps is to preserve the original
func's docstring)
"""
@wraps(func)
def wrapped(*args, **kwargs):
print(UPPER_SLICE)
fun... | 5,345,207 |
def as_dict(bdb_path, compact=True):
"""Get the state of a minter BerkeleyDB as a dict. Only the fields used by EZID are
included.
"""
with nog.bdb_wrapper.BdbWrapper(bdb_path, dry_run=False) as w:
return w.as_dict(compact) | 5,345,208 |
def _ecg_findpeaks_ssf(signal, sampling_rate=1000, threshold=20, before=0.03, after=0.01):
"""From https://github.com/PIA-
Group/BioSPPy/blob/e65da30f6379852ecb98f8e2e0c9b4b5175416c3/biosppy/signals/ecg.py#L448.
- W. Zong, T. Heldt, G.B. Moody, and R.G. Mark. An open-source algorithm to detect onset of art... | 5,345,209 |
def main() -> int:
"""
Builds/updates aircraft.json codes
"""
craft = {}
for line in AIRCRAFT_PATH.open().readlines():
code, _, name = line.strip().split("\t")
if code not in craft:
craft[code] = name
json.dump(craft, OUTPUT_PATH.open("w"))
return 0 | 5,345,210 |
def reflect_static_member(structured_cls, name):
"""Provide the type of 'name' which is a member of 'structured_cls'.
Arguments:
associative_cls: The type of the structured object (like a dict).
name: The name to be reflected. Must be a member of 'structured_cls'.
Returns:
The typ... | 5,345,211 |
def bootstrap_mean(x, alpha=0.05, b=1000):
"""
Calculate bootstrap 1-alpha percentile CI of the mean from a sample x
Parameters
----------
x : 1d array
alpha : float
Confidence interval is defined as the
b : int
The number of bootstrap samples
Returns
-------
lb... | 5,345,212 |
def greet_users(names): # names is used as a python parameter
"""Greet a list of users"""
for name in names:
greeting = "Hello, " + name.title() + "!"
print(greeting) | 5,345,213 |
def test_marginal_covs(with_tf_random_seed, ssm_setup):
""" Test that we generate the correct marginal means and covariances. """
ssm, array_dict = ssm_setup
transitions = ssm.num_transitions
marginal_covs = ssm.marginal_covariances
covs = [array_dict["P_0"]]
for i in range(transitions):
... | 5,345,214 |
def _penalize_token(log_probs, token_id, penalty=-1e7):
"""Penalize token probabilities."""
depth = log_probs.shape[-1]
penalty = tf.one_hot([token_id], depth, on_value=tf.cast(penalty, log_probs.dtype))
return log_probs + penalty | 5,345,215 |
def get_data_home(data_home=None):
"""
Returns
-------
path: str
`data_home` if it is not None, otherwise a path to a directory into the
user HOME path.
"""
if data_home is None:
user_home = os.path.expanduser('~')
if user_home is None:
raise Runtime... | 5,345,216 |
def load_win32com(finder, module):
"""the win32com package manipulates its search path at runtime to include
the sibling directory called win32comext; simulate that by changing the
search path in a similar fashion here."""
baseDir = os.path.dirname(os.path.dirname(module.file))
module.path.app... | 5,345,217 |
def _clear_mpi_env_vars():
"""
from mpi4py import MPI will call MPI_Init by default. If we spawn a child process that also calls MPI_Init and
has MPI environment variables defined, MPI will think that the child process is an MPI process just like the
parent and do bad things such as hang or crash.
... | 5,345,218 |
def AddSourceArg(parser):
"""Adds argument for specifying source for the workflow."""
parser.add_argument(
'--source',
help='Location of a workflow source code to deploy. Required on first '
'deployment. Location needs to be defined as a path to a local file '
'with the source code.') | 5,345,219 |
def plot_donut(df):
"""Generates a donut plot with the counts of 3 categories.
Parameters
----------
df : pandas.DataFrame
The DataFrame to be plotted.
"""
# We will only need 3 categories and 3 values.
labels = ["Positivo", "Negativo", "Neutro"]
positive = len(df[df["score"]... | 5,345,220 |
def test_write_state(traj_path, dyn_path, discretizer, num_states):
"""Testing the writing function of the MDanalysis script
Args:
traj_path ([type]): [description]
dyn_path ([type]): [description]
discretizer ([type]): [description]
num_states ([type]): [description]
"""
... | 5,345,221 |
def minimize(function,
vs,
explicit=True,
num_correction_pairs=10,
tolerance=1e-05,
x_tolerance=0,
f_relative_tolerance=1e7,
initial_inverse_hessian_estimate=None,
max_iterations=1000,
parallel_iteration... | 5,345,222 |
def variation_reliability(flow, gamma=1):
""" Calculates the flow variation reliability
Parameters
----------
flow: numpy array
flow values
gamma: float, optional
soft threshold
Returns
-------
variation reliability map (0 less reliable, 1 reliable)
"""
#comput... | 5,345,223 |
def create_experiment_dirs(exp_dir):
"""
Create Directories of a regular tensorflow experiment directory
:param exp_dir:
:return summary_dir, checkpoint_dir:
"""
experiment_dir = os.path.realpath(os.path.join(os.path.dirname(__file__))) + "/experiments/" + exp_dir + "/"
summary_dir = experim... | 5,345,224 |
def sutherland_hodgman_polygon_clipping(subject_polygon, clip_polygon):
"""Sutherland-Hodgman polygon clipping.
.. note
This algorithm works in regular Cartesian plane, not in inverted y-axis image plane,
so make sure that polygons sent in are ordered clockwise in regular Cartesian sense!
... | 5,345,225 |
def main() -> None:
"""数当てゲームのメイン
"""
args = get_parser()
min_ans = int(args.min_ans)
max_ans = int(args.max_ans)
max_stage = int(args.max_stage)
mode = args.mode
if args.ans is not None:
ans = int(args.ans)
runner = number_guess3.NumberGuess(
min_ans=min_ans... | 5,345,226 |
def countHitscore(evt, hitscore, hitscoreThreshold=200, outkey="predef: "):
"""A simple hitfinder that performs a limit test against an already defined hitscore
and adds the result to ``evt["analysis"][outkey + "isHit"]``, and
the hitscore to ``evt["analysis"][outkey + "hitscore"]``.
Args:
:ev... | 5,345,227 |
def get_means(df: pd.DataFrame, *, matching_sides: bool,
matching_roots: bool) -> pd.Series:
"""
Calculates mean conditional probabilities from a given co-occurrence table
with filters restricting for matching sides and roots.
Args:
df: The co-occurrences.
matching_sides: ... | 5,345,228 |
def main(
pathname: str,
sheetname: str='Sheet1',
min_row: int=None,
max_row: int=None,
min_col: int=None,
max_col: int=None,
openpyxl_kwargs: Dict=None
):
"""
main is the main function. It accepts details about a excel sheet and returns an HTML table matching it.
Arguments:
... | 5,345,229 |
def get_go_module_path(package):
"""assumption: package name starts with <host>/org/repo"""
return "/".join(package.split("/")[3:]) | 5,345,230 |
def labelbooklets(
labels,
pagecount,
booklets="booklets.pdf",
output="labeled_booklets.pdf",
colfname="fname",
collname="lname",
colid="netID",
):
"""
Outputs a PDF containing labeled exams given a data frame of labels,
a PDF of unlabeled booklets, and the number of pages in eac... | 5,345,231 |
def test_adjust_axial_sz_px():
"""Test adjust_axial_sz_px."""
assert adjust_axial_sz_px(1, 16) == 16
assert adjust_axial_sz_px(2, 16) == 16
assert adjust_axial_sz_px(16, 16) == 16
assert adjust_axial_sz_px(17, 16) == 32
assert adjust_axial_sz_px(32, 16) == 32 | 5,345,232 |
def get_hports(obj, *args, **kwargs):
"""
get_hports(obj, ...)
Get hierarchical references to ports *within* an object.
Parameters
----------
obj : object, Iterable - required
The object or objects associated with this query. Queries return a collection of objects associated with the
... | 5,345,233 |
def _command_from_cli() -> Command:
"""
Parse CLI arguments as a command.
:return: parsed command.
"""
parser = argparse.ArgumentParser(prog="curl")
parser.add_argument("url", help="Gemini URL to fetch")
parser.add_argument(
"-v", "--verbosity", action="count", default=0, help="Incr... | 5,345,234 |
def binary_cross_entropy(preds, targets, name=None):
"""Computes binary cross entropy given `preds`.
For brevity, let `x = `, `z = targets`. The logistic loss is
loss(x, z) = - sum_i (x[i] * log(z[i]) + (1 - x[i]) * log(1 - z[i]))
Args:
preds: A `Tensor` of type `float32` or `float64`.
... | 5,345,235 |
def setup(app: Sphinx):
"""
:param app:
Passed by Sphinx.
"""
app.add_html_theme(
"piccolo_theme", os.path.abspath(os.path.dirname(__file__))
) | 5,345,236 |
def get_organization(name: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetOrganizationResult:
"""
Use this data source to retrieve basic information about a GitHub Organization.
## Example Usage
```python
import pulumi
import pulumi_githu... | 5,345,237 |
def numerator_LGG(mfld_dim: int,
ambient_dim: array,
vol: array,
epsilon: array,
prob: float) -> array: # our theory
"""
Theoretical M * epsilon^2 / K, our formula
Parameters
----------
mfld_dim
K, dimensionality of ma... | 5,345,238 |
def group_nodes(node_list, tree_height):
"""
Groups a list of nodes.
"""
dict = OrderedDict()
for node in node_list:
nodelist = _make_node_list(GroupNode(node), tree_height)
if nodelist.get_name() not in dict:
dict[nodelist.get_name()] = nodelist
else:
... | 5,345,239 |
def power_over_line_rule_pos_rule(m, i, j, t):
"""
If decision variable m.var_x[i, j, t] is set to TRUE, the positive power over the line var_power_over_line is
limited by power_line_limit
:param m: complete pyomo model
:type m: pyomo model
:param i: startnode index of set_edge
:type i: int... | 5,345,240 |
def join_tiles(tiles):
"""Reconstructs the image from tiles."""
return np.concatenate(np.concatenate(tiles, 1), 1) | 5,345,241 |
def parallel_imap(func, args, pool: Union[Pool, DumbPool]) -> List[T]:
"""@TODO: Docs. Contribution is welcome."""
result = list(pool.imap_unordered(func, args))
return result | 5,345,242 |
async def test_setup_component(hass):
"""Test setup component."""
config = {tts.DOMAIN: {"platform": "yandextts", "api_key": "1234567xx"}}
with assert_setup_component(1, tts.DOMAIN):
await async_setup_component(hass, tts.DOMAIN, config)
await hass.async_block_till_done() | 5,345,243 |
def solve2(lines, max_total):
"""Solve the problem for Part 2."""
points = parse_points(lines)
xmin = min([p[0] for p in points])
xmax = max([p[0] for p in points])
ymin = min([p[1] for p in points])
ymax = max([p[1] for p in points])
size = 0
for x in range(xmin, xmax+1):
for y ... | 5,345,244 |
def main():
"""
関数の実行を行う関数。
Return:
"""
import random
def shuffle_dict(d):
"""
辞書(のキー)の順番をランダムにする
Args:
d: 順番をランダムにしたい辞書。
Return:
dの順番をランダムにしたもの
"""
keys = list(d.keys())
random.shuffle(keys)
return dict(... | 5,345,245 |
def register(cli, email, password, name, hint):
"""register a new account on server."""
log.debug("registering as:%s", email)
cli.client.register(email, password, name, hint)
del password | 5,345,246 |
def test_keyword_exception(options, topology):
"""Tests if exceptions are thrown when keywords are missing"""
with pytest.raises(KeyError):
GeneralOptimizerPSO(5, 2, options, topology) | 5,345,247 |
def scheme_load(*args):
"""Load a Scheme source file. ARGS should be of the form (SYM, ENV) or (SYM,
QUIET, ENV). The file named SYM is loaded in environment ENV, with verbosity
determined by QUIET (default true)."""
if not (2 <= len(args) <= 3):
expressions = args[:-1]
raise SchemeError... | 5,345,248 |
def drawVertexList_textured(vertex_list, tvertex_list):
"""Dibuja una lista de puntos point2/point3 con una lista Point2 de aristas
para modelos texturados"""
if len(vertex_list) >= 1:
if vertex_list[0].get_type() == POINT_2:
for vertex in range(len(vertex_list)):
glTexCo... | 5,345,249 |
def test_contrast():
"""
Feature: Test image contrast.
Description: Adjust image contrast.
Expectation: success.
"""
context.set_context(mode=context.GRAPH_MODE, device_target="CPU")
image = np.random.random((32, 32, 3))
trans = Contrast(alpha=0.3, beta=0)
dst = trans(image)
prin... | 5,345,250 |
def mask2idx(
mask: torch.Tensor,
max_length: Optional[int] = None,
padding_value: int = 0,
) -> Tuple[torch.Tensor, torch.Tensor]:
"""
E.g. input a tensor [[T T F F], [T T T F], [F F F T]] with padding value -1,
return [[0, 1, -1], [0, 1, 2], [3, -1, -1]]
:param mask: Mask tenso... | 5,345,251 |
def generate_paths(data, path=''):
"""Iterate the json schema file and generate a list of all of the
XPath-like expression for each primitive value. An asterisk * represents
an array of items."""
paths = []
if isinstance(data, dict):
if len(data) == 0:
paths.append(f'{path}')
... | 5,345,252 |
def parseCommandArgs(argv):
"""
Parse command line arguments
argv argument list from command line
Returns a pair consisting of options specified as returned by
OptionParser, and any remaining unparsed arguments.
"""
# create a parser for the command line options
parser = arg... | 5,345,253 |
def run_hybrid_endpoint_overlap(topology_proposal, current_positions, new_positions):
"""
Test that the variance of the perturbation from lambda={0,1} to the corresponding nonalchemical endpoint is not
too large.
Parameters
----------
topology_proposal : perses.rjmc.TopologyProposal
To... | 5,345,254 |
def _node_list(rawtext, text, inliner):
"""
Return a singleton node list or an empty list if source is unknown.
"""
source = inliner.document.attributes['source'].replace(os.path.sep, '/')
relsource = source.split('/docs/', 1)
if len(relsource) == 1:
return []
if text in rcParams:
... | 5,345,255 |
def enable_heater_shaker_python_api() -> bool:
"""Get whether to use the Heater-Shaker python API."""
return advs.get_setting_with_env_overload("enableHeaterShakerPAPI") | 5,345,256 |
def main(args):
"""
This script will change some items TensorFlow Object Detection API training config file base on adaptive learning
config.ini
"""
pipeline_config = pipeline_pb2.TrainEvalPipelineConfig()
with tf.gfile.GFile(args.pipeline, "r") as f:
proto_str = f.read()
text_f... | 5,345,257 |
def solidityKeccak(abi_types, values):
"""
Executes keccak256 exactly as Solidity does.
Takes list of abi_types as inputs -- `[uint24, int8[], bool]`
and list of corresponding values -- `[20, [-1, 5, 0], True]`
"""
if len(abi_types) != len(values):
raise ValueError(
"Length ... | 5,345,258 |
def extract_frames(path_out, frame_rate=1, time_limit=10):
"""
Parameters
----------
path_out: str,
path to save the frames
time_limit: float, optional
time to record in seconds, default 10
frame_rate: int or float, optional
Extract the frame every ... | 5,345,259 |
def check_segment_end(segment, duration):
"""
not all segments have an end set...
helper to check for that without concern
duration should be passed in to handle no segment end
"""
end = duration
#TODO: What about no end on segment?
# get end of content (total length)
if segment.end... | 5,345,260 |
def set_status(new_status: str):
"""
Sets the status for the bot
:param new_status: String to use for the status
"""
global status, raw_settings
status = raw_settings["status"] = new_status
save_json(os.path.join("config", "settings.json"), raw_settings) | 5,345,261 |
def run_fib_recursive_mathy_cached(n):
"""Return Fibonacci sequence with length "n" using "fib_recursive_mathy_cached".
Args:
n: The length of the sequence to return.
Returns:
A list containing the Fibonacci sequence.
"""
return [fib_recursive_mathy_cached(i + 1) for i in range... | 5,345,262 |
async def test_metakg_500(client):
"""Test that when a KP gives a bad response to /meta_knowledge_graph,
we add a message to the log but continue running.
"""
QGRAPH = query_graph_from_string(
"""
n0(( ids[] CHEBI:6801 ))
n0(( categories[] biolink:ChemicalSubstance ))
n1(... | 5,345,263 |
def test_ngram_regex_field_resolve(dataset_num_files_1, reader_factory):
"""Tests ngram.resolve_regex_field_names function
"""
fields = {
-1: ["^id.*", "sensor_name", TestSchema.partition_key],
0: ["^id.*", "sensor_name", TestSchema.partition_key],
1: ["^id.*", "sensor_name", TestSch... | 5,345,264 |
def binning(LLRs_per_window,info,num_of_bins):
""" Genomic windows are distributed into bins. The LLRs in a genomic windows
are regarded as samples of a random variable. Within each bin, we calculate
the mean and population standard deviation of the mean of random variables.
The boundaries of the bins ... | 5,345,265 |
def conj(node: BaseNode,
name: Optional[Text] = None,
axis_names: Optional[List[Text]] = None) -> BaseNode:
"""Conjugate a `node`.
Args:
node: A `BaseNode`.
name: Optional name to give the new node.
axis_names: Optional list of names for the axis.
Returns:
A new node. The compl... | 5,345,266 |
def f1(
predictions: Union[list, np.array, torch.Tensor],
labels: Union[list, np.array, torch.Tensor],
):
"""Calculate F1 score for binary classification."""
return f1_score(y_true=labels, y_pred=predictions) | 5,345,267 |
def length(v, squared=False, out=None, dtype=None):
"""Get the length of a vector.
Parameters
----------
v : array_like
Vector to normalize, can be Nx2, Nx3, or Nx4. If a 2D array is
specified, rows are treated as separate vectors.
squared : bool, optional
If ``True`` the sq... | 5,345,268 |
def generateUniqueId():
"""
Generates a unique ID each time it is invoked.
Returns
-------
string
uniqueId
Examples
--------
>>> from arch.api import session
>>> session.generateUniqueId()
"""
return RuntimeInstance.SESSION.generateUniqueId() | 5,345,269 |
def order_rep(dumper, data):
""" YAML Dumper to represent OrderedDict """
return dumper.represent_mapping(u'tag:yaml.org,2002:map', data.items(),
flow_style=False) | 5,345,270 |
def match_format(
format_this: spec.BinaryInteger,
like_this: spec.BinaryInteger,
match_pad: bool = False,
) -> spec.BinaryInteger:
"""
will only match left pads, because pad size cannot be reliably determined
"""
output_format = get_binary_format(like_this)
output = convert(data=forma... | 5,345,271 |
def parse_nonterm_6_elems(expr_list, idx):
"""
Try to parse a non-terminal node from six elements of {expr_list}, starting
from {idx}.
Return the new expression list on success, None on error.
"""
(it_a, it_b, it_c, it_d, it_e, it_f) = expr_list[idx : idx + 6]
# Match against and_n.
if ... | 5,345,272 |
def make1d(u, v, num_cols=224):
"""Make a 2D image index linear.
"""
return (u * num_cols + v).astype("int") | 5,345,273 |
def xkcd(scale=1, length=100, randomness=2):
"""
Turn on `xkcd <https://xkcd.com/>`_ sketch-style drawing mode. This will
only have effect on things drawn after this function is called.
For best results, the "Humor Sans" font should be installed: it is
not included with Matplotlib.
Parameters... | 5,345,274 |
def team_size(data):
"""
Computes team size of each paper by taking the number of authors in 'authors'
Input:
- df: dataframe (dataset); or just the 'authors' column [pandas dataframe]
Output:
- team: vector of team_size for each paper of the given... | 5,345,275 |
def header_to_date(header):
""" return the initial date based on the header of an ascii file"""
try:
starttime = datetime.strptime(header[2], '%Y%m%d_%H%M')
except ValueError:
try:
starttime = datetime.strptime(
header[2] + '_' + header[3], '%Y%m%d_%H'
... | 5,345,276 |
def PhenylAlanineCenterNormal(residue):
""" Phenylalanine """
PHE_ATOMS = ["CG", "CD1", "CD2", "CE1", "CE2", "CZ"]
return RingCenterNormal(residue, PHE_ATOMS) | 5,345,277 |
def test_is_character_at_index_not_with_character_at_end():
"""
Make sure that a string with one of the characters at the index is handled properly.
"""
# Arrange
input_string = "this is a test!"
start_index = len(input_string) - 1
valid_character = "!"
expected_output = False
# Ac... | 5,345,278 |
def _check_source(src, paths, vshape):
"""Checks (non exaustive) on the validity of a stochasticity source."""
# check compliance with the source protocol
if callable(src) and hasattr(src, 'paths') and hasattr(src, 'vshape'):
# check paths and vshape
paths_ok = (src.paths == paths)
t... | 5,345,279 |
def test_emnist_exception():
"""
Test error cases for EMnistDataset
"""
logger.info("Test error cases for EMnistDataset")
error_msg_1 = "sampler and shuffle cannot be specified at the same time"
with pytest.raises(RuntimeError, match=error_msg_1):
ds.EMnistDataset(DATA_DIR, "byclass", "t... | 5,345,280 |
def get_labels(input_dir):
"""Get a list of labels from preprocessed output dir."""
data_dir = _get_latest_data_dir(input_dir)
labels_file = os.path.join(data_dir, 'labels')
with file_io.FileIO(labels_file, 'r') as f:
labels = f.read().rstrip().split('\n')
return labels | 5,345,281 |
def documents_concordance(response: Response,
request: Request=Query(None, title=opasConfig.TITLE_REQUEST, description=opasConfig.DESCRIPTION_REQUEST),
paralangid: str=Query(None, title=opasConfig.TITLE_DOCUMENT_CONCORDANCE_ID, description=opasConfig.DESCRIPTION_DOCUM... | 5,345,282 |
def query_yes_no(question, default=True):
"""Ask a yes/no question via intput() and return their answer.
"question" is a string that is presented to the user.
"default" is the default return value True or False
The "answer" return value is True for "yes" or False for "no".
https://stackoverflow.c... | 5,345,283 |
def diamBiasK(diam, B, Kexcess, RshellRstar=2.5):
"""
diameter bias (>1) due to the presence of a shell
only works for scalar diam, B and Kexcess
validity: Kexcess>0 and Kexcess<0.1 and B*diam <~ 500
return 1 if Kexcess <= 0
"""
global __biasData, KLUDGE
d = np.abs(__biasData['Rshell/... | 5,345,284 |
def interpolate_poses_from_samples(time_stamped_poses, samples):
"""
Interpolate time stamped poses at the time stamps provided in samples.
The poses are expected in the following format:
[timestamp [s], x [m], y [m], z [m], qx, qy, qz, qw]
We apply linear interpolation to the position and use SLERP for
... | 5,345,285 |
def test_add_client(case, client_name, client=None, client_id=None, duplicate_client=None, check_errors=False,
log_checker=None):
"""
UC MEMBER_47 main test method. Tries to add a new client to a security server and check logs if
ssh_host is set.
:param case: MainController object
... | 5,345,286 |
def get_data_unit_labels(data_unit: DataUnit) -> List[Attributes]:
"""
Extract important information from data_unit. That is, get only bounding_boxes and
associated classifications.
Args:
data_unit: The data unit to extract information from.
Returns: list of pairs of objects and associated ... | 5,345,287 |
def mock_folder_contributions():
"""Mock all action functions and ensure they raise an error if they are called."""
with mock.patch(
"forester.folder_contributions.print_folder_contributions"
) as mock_contrib, mock.patch("forester.tree_info.print_tree_info") as mock_info:
mock_info.side_eff... | 5,345,288 |
def calc_4points_bezier_path(svec, syaw, spitch, evec, eyaw, epitch, offset, n_points=100):
"""
Compute control points and path given start and end position.
:param sx: (float) x-coordinate of the starting point
:param sy: (float) y-coordinate of the starting point
:param syaw: (float) yaw angle at... | 5,345,289 |
def permutationwithparity(n):
"""Returns a list of all permutation of n integers, with its first element being the parity"""
if (n == 1):
result = [[1,1]]
return result
else:
result = permutationwithparity(n-1)
newresult = []
for shorterpermutation in result:
for position... | 5,345,290 |
def _train_model(model: BertForValueExtraction, optimizer, scheduler, train_data_loader, val_data_loader) -> List[int]:
"""
Main method to train & evaluate model.
:param model: BertForValueExtraction object
:param optimizer: optimizer
:param scheduler: scheduler
:param train_data_loader: traini... | 5,345,291 |
def mass_at_two_by_counting_mod_power(self, k):
"""
Computes the local mass at `p=2` assuming that it's stable `(mod 2^k)`.
Note: This is **way** too slow to be useful, even when k=1!!!
TO DO: Remove this routine, or try to compile it!
INPUT:
k -- an integer >= 1
OUTPUT:
a r... | 5,345,292 |
async def async_setup_entry(
hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback
) -> None:
"""Set up Hive thermostat based on a config entry."""
hive = hass.data[DOMAIN][entry.entry_id]
devices = hive.session.deviceList.get("sensor")
entities = []
if devices:
... | 5,345,293 |
def get_paginiation_data(first_pagination_url, family, cazy_home, args, session):
"""Parse the first paginiation page and retrieve URLs to all pagination page for the Family.
:param first_pagination_url: str, URL to the fist page of the family
:param family: Family class instance, represents a unique CAZy ... | 5,345,294 |
def task(ctx, config):
"""
Loop a sequential group of tasks
example:
- loop:
count: 10
body:
- tasktest:
- tasktest:
:param ctx: Context
:param config: Configuration
"""
for i in range(config.get('count', 1)):
stack = []
try:
... | 5,345,295 |
def gravitationalPotentialEnergy(mass, gravity, y):
"""1 J = 1 N*m = 1 Kg*m**2/s**2
Variables: m=mass g=gravity constant y=height
Usage: Energy stored by springs"""
U = mass*gravity*y
return U | 5,345,296 |
def subset_by_supported(input_file, get_coords, calls_by_name, work_dir, data,
headers=("#",)):
"""Limit CNVkit input to calls with support from another caller.
get_coords is a function that return chrom, start, end from a line of the
input_file, allowing handling of multiple input ... | 5,345,297 |
def to_list(obj):
"""List Converter
Takes any object and converts it to a `list`.
If the object is already a `list` it is just returned,
If the object is None an empty `list` is returned,
Else a `list` is created with the object as it's first element.
Args:
obj (any object): the object... | 5,345,298 |
def remove(molecular_system, selection=None, frame_indices=None, to_form=None, syntaxis='MolSysMT'):
"""remove(item, selection=None, frame_indices=None, syntaxis='MolSysMT')
Remove atoms or frames from the molecular model.
Paragraph with detailed explanation.
Parameters
----------
item: mol... | 5,345,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.