content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def _f1_score(guess, answers):
"""Return the max F1 score between the guess and *any* answer."""
if guess is None or answers is None:
return 0
g_tokens = normalize_answer(guess).split()
scores = [
_prec_recall_f1_score(g_tokens, normalize_answer(a).split())for a in answers
]
retu... | e265f3bd8764f81f000ee28713664a9a087f9b81 | 3,619,500 |
def handle_post_sleep_notification(msg):
"""Process an internal pre sleep notification message."""
if not msg.gateway.is_sensor(msg.node_id):
return None
handle_smartsleep(msg)
handle_wakeup(msg)
return None | 5551994d2939607262deffde2cb6df9e1fe97cdd | 3,619,501 |
def pozice_od_hrace():
"""Fuknce pozice od hrace se zeptá uživatele kam chce umístít svůj znak,
ověří, že se jedná o číslo a pozici vrátí"""
while True:
try:
cisloPolickaHrace = int(input("Na kolikáté místo v herním poli chceš umístit tvůj znak \"x\"? "))-1
except ValueError:
... | 4faede9c2e3357070eb0ab218e970a1788610dbb | 3,619,502 |
def plaintext(msg):
""" Parse a SNS message and relay it on to pusher.com """
return msg | 6832f4ccad66d025b3023b9839c90bbbb41bebb6 | 3,619,503 |
def multihead_attention(
queries,
keys,
num_units=None,
num_heads=8,
dropout_rate=0,
is_training=True,
causality=False,
scope="multihead_attention",
reuse=None,
with_qk=False,
):
"""Applies multihead attention.
Args:
queries: A 3d tensor with shape of [N, T_q, C_q]... | feab0edde0b707da5dd5126f57441c0d8eb6739b | 3,619,504 |
from typing import Dict
from typing import Any
def conn_record_to_message_repr(conn: ConnectionRecord) -> Dict[str, Any]:
"""Map ConnectionRecord onto Connection."""
def _state_map(state: str) -> str:
if state in ('active', 'response'):
return 'active'
if state == 'error':
... | 98ef66eecbfaa6ed73bc0524f9c68e0a4575dbac | 3,619,505 |
def strategy_connected_sequential_bfs(G, colors):
"""Returns an iterable over nodes in ``G`` in the order given by a
breadth-first traversal.
The generated sequence has the property that for each node except
the first, at least one neighbor appeared earlier in the sequence.
``G`` is a NetworkX gra... | fd53629b90417860dc861a445f27286f656fbf03 | 3,619,506 |
def provider_borad(request):
"""show the provider board"""
page_index = request.POST.get('page_index')
page_size = request.POST.get('page_size')
sort_type = request.POST.get('sort_type')
page_size = interface.handle_page(page_size, 5)
page_index = interface.handle_page(page_index, 1)
msg_dat... | b3bc0c760b15606403b994de04ed6093f3d8aa53 | 3,619,507 |
def generate_common_invalid_structure_schemas():
"""
Generate schemas that make schema request cannot be submitted to ledger.
:return: schema and ids.
"""
data = list()
ids = list()
ids.append("schema_build_schema_req_fails_with_missing_schema_version")
data.append({'data': schema()})... | b0a893260942ca104efa9831836f67c40473a5e0 | 3,619,508 |
import logging
import string
def auto_log(logger_name):
"""
A decorator that wraps the passed in function, logs entering and exiting the function,
and logs exceptions should one occur. Exceptions are reraised.
Tag each method or function with @auto_log(__name__) to automatically log calls.
Logs th... | 8d9813ba49b4cd76aff2b1f4ce55850f00b1985c | 3,619,509 |
def _is_extern_seg(seg):
"""Returns `True` if `seg` refers to a segment with external variable or
function declarations."""
if not seg:
return False
seg_type = idc.get_segm_attr(seg.start_ea, idc.SEGATTR_TYPE)
return seg_type == idc.SEG_XTRN | 3e7fb296999347f0cc43c92c0fc9cdd21294d9fe | 3,619,510 |
import os
def _fixpath(p):
"""Apply tilde expansion and absolutization to a path."""
return os.path.abspath(os.path.expanduser(p)) | 662eaea19625d11e0d88b486133ead928ee57c48 | 3,619,511 |
from typing import List
def get_indices_remain_type_zero(p: np.ndarray) -> List[int]:
"""p is assumed to be a probability distribution with type-0."""
indices = list(range(len(p)))
indices_removed = get_indices_removed_type_zero(p)
for i in indices_removed:
indices.remove(i)
return indices | b54f3b79e44d03da0f5654d5e46e0286812fc84a | 3,619,512 |
def get_indicators_mv(df_mv):
"""Compute indicators about missing values. Used for plotting figures."""
# 1: Statistics on the full database
n_rows, n_cols = df_mv.shape
n_values = n_rows*n_cols
df_mv1 = df_mv == 1
df_mv2 = df_mv == 2
df_mv_bool = df_mv != 0
# Number of missing values i... | 6780165fe904f2764cf2de4392bd28cae30532f6 | 3,619,513 |
def fitness(pop):
""" Applies _fitness to every chromossome in the population."""
pop_size = pop.shape[0]
fitvec = np.zeros(pop_size, np.float64)
for i in range(pop_size):
fitvec[i] = _fitness(pop[i])
return fitvec | d0cede2668cb75b6c7d70b123f4381fe6e9d80e2 | 3,619,514 |
from typing import Union
from typing import List
from typing import Tuple
from typing import Optional
def trim_t_results(
results: OdeResult,
t_span: Union[List, Tuple, Array],
t_eval: Optional[Union[List, Tuple, Array]] = None,
) -> OdeResult:
"""Trim ``OdeResult`` object based on value of ``t_span``... | f06fd34f421597bfacc218eb3eaabe43ec547f52 | 3,619,515 |
import types
def itk_image_type(medipy_image):
""" Return the ITK image type corresponding to the given ``medipy.base.Image``
"""
if medipy_image.data_type == "scalar" :
itk_type = types.dtype_to_itk[medipy_image.dtype.type]
image_type = itk.Image[itk_type, medipy_image.ndim]
elif... | 39c455cf0efc8bea42553b784c100c069e594a95 | 3,619,516 |
def load_gt_boxes(path):
"""
Don't care about what shit it is. whatever, this function
returns many ground truth boxes with the shape of [-1, 4].
xmin, ymin, xmax, ymax
"""
bbs = open(path).readlines()[1:]
roi = np.zeros([len(bbs), 4])
for iter_, bb in zip(range(len(bbs)), bbs):
... | f680fa1e8ed12d26ae870f64cca820461cdaba80 | 3,619,517 |
import json
def pushbullet(ALERTID=None, TOKEN=None):
"""
Send a `link` notification to all devices on pushbullet with a link back to the alert's query.
If `TOKEN` is not passed, requires `PUSHBULLETTOKEN` defined, see https://www.pushbullet.com/#settings/account
"""
#if not PUSHBULLETURL:
... | 8017179e97968168871726aa89b2afd6be781165 | 3,619,518 |
def get_cost(outputs, targets):
"""Return the cost/error rate at the output."""
cost_per_sample = []
cost = []
if(np.array(outputs).ndim == 2):
for idx, outputs_per_epoch in enumerate(outputs):
cost_per_sample.append(list(np.array(outputs_per_epoch) - np.array(targets)))
... | 057dc663173c37c48111a30e98b2e66b23c32ae5 | 3,619,519 |
def calculate_truhlar_scaling_factors(zpe_dict, level_of_theory):
"""
Calculate the scaling factors using Truhlar's method:
FREQ: A PROGRAM FOR OPTIMIZING SCALE FACTORS (Version 1)
written by Haoyu S. Yu, Lucas J. Fiedler, I.M. Alecu, and Donald G. Truhlar
Department of Chemistry and Supercomputing... | f948d525ceaaafba25d556734cffd89d10702875 | 3,619,520 |
def pairwise_intersection(boxlist1, boxlist2):
"""Compute pairwise intersection areas between boxes.
Args:
boxlist1: Nx1x4 floatbox
boxlist2: NxDx4
Returns:
"""
x_min1, y_min1, x_max1, y_max1 = tf.split(boxlist1, 4, axis=2) # NxDx1
x_min2, y_min2, x_max2, y_max2 = tf.split(boxl... | 5600c68ac51891bc514a3da9476f778f4d2ecd80 | 3,619,521 |
def _parse_sha1_thumbprint_openssl(output):
# type: (str) -> str
"""Get SHA1 thumbprint from buffer
:param str buffer: buffer to parse
:rtype: str
:return: sha1 thumbprint of buffer
"""
# return just thumbprint (without colons) from the above openssl command
# in lowercase. Expected open... | 30668ade806b5207c85359e10110e191506d8321 | 3,619,522 |
def people_preferences_get(search=None) -> ApiOptions: # noqa: E501
"""List of People Preference options
List of People Preference options # noqa: E501
:param search: search term applied
:type search: str
:rtype: ApiOptions
"""
try:
if search:
data = [tag for tag in P... | 831a1944ec37e4d8232abc7cdb2df31a5818b618 | 3,619,523 |
def encode_name(name):
"""
Encode a unicode value as utf-8 and then URL encode that
string. Use for entity titles in URLs.
"""
return quote(name.encode('utf-8'), safe=".!~*'()") | 42c795849399a6ae1176a8e1b17e0f5f498586ec | 3,619,524 |
def reduce(braid, (p, q)):
"""
Applies one step of the alphabetical homomorphism on the given handle.
Returns a new reduced braid.
"""
new_handle = []
j = abs(braid.generators[p])
e = j/braid.generators[p]
for letter in braid.generators[p:q+1]:
exp = abs(letter)/letter
i... | 185768a534f3d2d7756fa8a8c584aed830df44a4 | 3,619,525 |
def MAEMetric(key):
"""Create max absolute error metric on key."""
return DictMetric(key, MaximumAbsoluteError()) | 4ce96e41b7a58ab5827cc6f93189df6fccf5f6b9 | 3,619,526 |
def get_data(group: h5py.Group, name: str) -> np.ndarray:
"""
Gets data in array form. This is mostly so that I can change the way I get data later
# TODO: Maybe make this only get data that isn't marked as bad or something in the future?
Args:
group (): Group that data is in
name (): N... | 332b66fc6dcb5fee47cf749930b30bfec080b9c0 | 3,619,527 |
import json
def generate_json_config(jsonnet_config_path, values):
"""Generate json config from jsonnet config and values.yaml.
Jsonnet code is used to load jsonnet config and merge it with values.
Args:
jsonnet_config_path (str): Path to jsonnet (libsonnet) config file.
values (dict): V... | da18bf32cfb77938cbc74b5f21ea58406948ab4d | 3,619,528 |
def convert_to_scitype(obj, to_scitype, from_scitype=None, store=None):
"""Convert single-series or single-panel between mtypes.
Assumes input is conformant with one of the mtypes
for one of the scitypes Series, Panel, Hierarchical.
This method does not perform full mtype checks, use mtype or check... | 9c48b8282ef91de533cf6f7b92f05b0314699e47 | 3,619,529 |
import os
import shutil
def main() -> int:
"""Script entry point."""
args = parse_args()
# Clear out any existing docs for the target.
if os.path.exists(args.sphinx_build_dir):
shutil.rmtree(args.sphinx_build_dir)
# TODO(pwbug/164): Printing the header causes unicode problems on Windows... | 916190e8feb3b27e178ac67a954aa641a247556c | 3,619,530 |
def add(config_or_file, default=False):
"""
Add an endpoint to the registry.
``config_or_file`` can be the path to a yaml definition file or a dictionary of arguments to pass to
``endpoints.api``. See also Google's documentation on `endpoints.api <https://cloud.google.com/appengine/docs/python/endpoint... | c6268ee46cacdc481e680f8e50a16db737e765aa | 3,619,531 |
import math
def find_dice_medial(dice):
"""Средний бросок кости в формате навроде 1d6, 2d6, 1d12.
"""
dice_list = dice.split('d')
medial_number = math.floor(int(dice_list[0]) * (int(dice_list[1]) / 2))
return medial_number | 22af27cb4d3a06fe9b1c6af345f4deb4df46af23 | 3,619,532 |
def remove_out_of_bounds_bins(df, chromosome_size):
# type: (pd.DataFrame, int) -> pd.DataFrame
"""Remove all reads that were shifted outside of the genome endpoints."""
# The dataframe is empty and contains no bins out of bounds
if "Bin" not in df:
return df
df = df.drop(df[df.Bin > chrom... | 6d13bdb4df1c955567343d72ee3c64ba1554a4e0 | 3,619,533 |
def delete_order_condition(context: SagaContext) -> bool:
"""For testing purposes."""
return "b" in context | 4790f974bf12c2d655baf28287c1a6f99ae0d7af | 3,619,534 |
def shorten_url(url_long) -> str:
"""Can be used to shorten a long url with tiny-url
:param url_long: The URL that shoul be shortened
:return: Shortened URL as string
"""
url = "http://tinyurl.com/api-create.php" + "?" \
+ parse.urlencode({"url": url_long})
res = get(url)
return res... | 415d021de27ee5fe39a8ca35fdfa279ca3450618 | 3,619,535 |
import argparse
def build_parser(args):
""" This method allows us to test the args.
>>> args = build_parser(['--verbose'])
>>> print(args.verbose)
True
"""
parser = argparse.ArgumentParser(usage='$ python parser.py',
description='Parse the M... | 69954cb6705fac7f5b9b29a22b9e6e85a3b3b2af | 3,619,536 |
def encode_string_list(x):
"""
:Summary: Take a list of strings x and encode its values to a list of integers.
:param x: list of strings
:return y: list of integers that are codes for x. x is sorted before being encoded.
:Example:
x = ['cat', 'dog', 'book', 'pencil', 'dog', 'book']
... | ee1e12c2949362bde977b64191784030d516b744 | 3,619,537 |
def mean_specobj(dat, inds=slice(None), *args, **kwargs):
"""
A specobj constructor, that returns an average over the *inds*.
See also:
ind_specobj
"""
a = ind_specobj(dat, inds, *args, **kwargs)
out = a.mean()
del a
return out | 2a8987d6f60f5e8d576c24d6d2ef1578b12a5524 | 3,619,538 |
def two_traits(uni):
"""Get two table traitlets."""
if not hasattr(uni, "atom_two"):
raise AttributeError("for the catcher")
if "frame" not in uni.atom_two.columns:
uni.atom_two['frame'] = uni.atom_two['atom0'].map(uni.atom['frame'])
lbls = uni.atom.get_atom_labels()
df = uni.atom_tw... | 85f2ecef68f1ae5739ce71dbcc02d83673d99389 | 3,619,539 |
import eli5
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.ensemble import RandomForestRegressor
from eli5.sklearn import PermutationImportance
def randomforest_feature_importance(X_train, y_train, classification):
"""
Trains a RandomFores... | 448fdb1351cf2208fc4317d07253647a1d8c6a1a | 3,619,540 |
import os
def wmt_zhen_tokens(model_hparams, wrong_vocab_size):
"""Chinese to English translation benchmark."""
p = default_problem_hparams()
# This vocab file must be present within the data directory.
if model_hparams.shared_embedding_and_softmax_weights == 1:
model_hparams.shared_embedding_and_softmax_... | bc7150a24b73a18f1430c1559ef8d7dca8a91f74 | 3,619,541 |
from typing import Union
from typing import List
def _alter_pipe(alter: schemas.PipeAlter, name: str, version: Union[str, int], db: Session):
"""
The implementation of the update_pipe route with logic here so other functions can call it
:param alter: The pipe to alter
:param name: The pipe name
:p... | 812059f4d3ebd93fcae634181833062d4232c887 | 3,619,542 |
def get_docker_container_image(docker_client):
"""
Returns a dictionary containing the image each existing container.
"""
containers = docker_client.containers(all=True)
images = dict()
for container in containers:
names = container['Names']
image = container['Image']
f... | 8af97f7ec763b55c83d82b76fd02895864d1c3c4 | 3,619,543 |
def path_leaf(path):
"""
:param path:
:return:
"""
"""
Extract path and filename
:param path: Entire filepath
:return: Return a tuple that contains the (path, filename)
"""
head, tail = _split(path)
return (head, tail or _basename(head)) | ea8ca40411fdf30edf0a2bc6623fa014a15b2853 | 3,619,544 |
def writeXML(ofile, polylist, withHeader=False):
"""
Write a readable representation of the Polygons in polylist to a XML file.
A simple header can be added to make the file parsable.
:Arguments:
- ofile: see above
- polylist: sequence of Polygons
- optional withHeader: bool
... | 645a198e352f1e3497faa7df42264fbf8d125c16 | 3,619,545 |
def Calc_Cold_Pixels_Veg(NDVI,NDVI_max,NDVI_std,QC_Map,ts_dem,Image_Type, Cold_Pixel_Constant):
"""
Function to calculates the the cold pixels based on vegetation
"""
cold_pixels_vegetation = np.copy(ts_dem)
cold_pixels_vegetation[np.logical_and(NDVI <= (NDVI_max-0.1*NDVI_std),QC_Map != 0.0)] = 0... | 41866a10813e64270b2d809fac85e7a6305ef155 | 3,619,546 |
async def post(service, workspace_id, utterance, sem):
""" Single post restrained by semaphore
"""
counter = 0
async with sem:
while True:
try:
res = await message(service, workspace_id, utterance)
return res
except Exception as e:
... | 3ad16d7033043d3893d36ae6b001cc38cab1a040 | 3,619,547 |
def largest_number(seq_seq):
"""
Returns the largest number in the subsequences of the given
sequence of sequences. Returns None if there are NO numbers
in the subsequences.
For example, if the given argument is:
[(3, 1, 4),
(13, 10, 11, 7, 10),
[1, 2, 3, 4]]
then thi... | 5a2418e1f8ee0413e8306a04d3ee17a909b7b0c3 | 3,619,548 |
def ScanSingleParameter(script_name, parameter_name, values):
"""
Generic function to run a MOTMaster script (script_name - note you don't need the path or .cs suffix)
repeatedly, whilst scanning a single parameter (parameter_name) over a list of values. Can be used
directly or with one of convenience functions d... | f05a239fc559efc4005927e8307b21dd4acd55d5 | 3,619,549 |
def merge_line_list(mod_text, vanilla_text, gen_text):
"""Merges sequences of lines.
Params:
mod_text
The lines of the mod file being added to the merge.
vanilla_text
The lines of the corresponding vanilla file.
gen_text
The lines of the previously me... | b6edc7c5897fe244a9196dbb5934b3ce85fd629a | 3,619,550 |
import os
import yaml
def get(key=None):
"""
Returns the value of a configuration key.
:param str key: Configuration key. If key
is None, then returns entire dictionary.
:return value:
:Raises KeyError: Key not present
"""
if os.path.isfile(cn.CONFIG_FILE_PATH):
with open(cn.CONFIG_FILE_PATH, 'r... | 8f442b323f7670c4660e834751edb7ea63dd6298 | 3,619,551 |
import tqdm
def covid_deconvolve(Cdiff, Fdiff, kp, t = None, mode='C', alpha=1, BS=1000, TSPAN=200, data_poisson=True, kernel_syst=True):
"""
COVID time-series deconvolution.
Args:
Cdiff: observed daily cases array
Fdiff: observed daily fatalities array
kp: ... | 9f6b31da3d67f9fc908f0cab39c28a2171d18371 | 3,619,552 |
def get_usc_release_text(
release_vers, short_title, section_number
) -> USCSectionContentList: # noqa: E501
"""Your GET endpoint
Get the text for a specific section # noqa: E501
:param release_vers:
:type release_vers: str
:param short_tile:
:type short_tile: str
:param section_numbe... | 5480a2ece316eba68aec634c82914659e1fe8bb8 | 3,619,553 |
import xml.etree.ElementTree as ET
import zipfile
from datetime import datetime
import os
def get_work_history_file(cfolder, filename, nyears):
"""
Generates a vector of works found in a lattes CV.
Args:
cfolder: folder containing the researcher Lattes CV file.
filename: name of the file c... | 23cc3e11185674676713076c91b854b3395ba0e6 | 3,619,554 |
import argparse
import sys
import os
def _parse_args(cmdl):
"""Parse command line arguments."""
parser = argparse.ArgumentParser(
description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter
)
parser.add_argument(
"--inbam",
"-i",
help="input BAM (/dev/stdi... | dd83c05c56041082df6794592216b88e77333440 | 3,619,555 |
def jacobi_iteration(A, b, tol=1e-9, Max_iter=5000):
""" Solve linear equations by Jacobi iteration method.
Args:
A: ndarray, coefficients matrix
b: ndarray, constant vector
tol: double, iteration accuracy
Max_iter: int, maximum iteration number
Returns:
y: ndarray,... | 815e36c6bea242b8daeca5eac7410126130cf7d5 | 3,619,556 |
def load_3dlut_3dl_format(filename):
"""
3DL形式の3DLUTデータをファイルから読み込む。
Parameters
----------
filename : str
file name.
Returns
-------
lut : array_like
3DLUT data with 3dl format.
grid_num : int
grid number.
title : str
title of the 3dlut.
"""
... | 0dba8c4f888526deb6078e7b78f38bd6250f2463 | 3,619,557 |
def split_model(model, xi_kern=None):
"""
Take a model where the output has multiple columns (channels) and split it
so that each model only deals with a single column.
:param model:
:return: (list of models)
"""
yt = model.Y.value.copy().T
print("Split model ({} channels)...".format(yt.... | 2ba637b3c8a713161706234472d4cc5c2a525f3f | 3,619,558 |
def betaPDF(mean, var, centers, eps=1e-6):
"""
Calculate beta PDF
:param mean: mean
:type mean: float
:param var: variance
:type var: float
:param centers: bin centers
:type centers: array
:param eps: smallness threshold
:type eps: float
:return: pdf
:rtype: array
""... | 70267a4f5820fa5348ebc4801b1cb1a1a913a92e | 3,619,559 |
def classify(parameters, data):
""" tests the algorithm """
global count
x_data, y_data = parameters
data = from_data_to_haar(data)
distances = ((x_data-data)**2).sum(axis=1)
# nearest = sorted(zip(distances, y_data), key=itemgetter(0))[:K_CONSTANT]
item_indexes = np.argsort(distances)[:K_CO... | f1136e9cc2aae5c4d858b285612fb6c439b369af | 3,619,560 |
from typing import Optional
import ast
import json
def format_list_to_dataframe(json_string: str) -> Optional[str]:
"""
:param json_string: Takes in input json in form of a string value
:return: Formatted tabular output of the json sent
"""
val = ast.literal_eval(json_string)
val1 = json.loads... | 7624258425149310054235b66b265ce65dd80cfe | 3,619,561 |
def __unwrap_nonsense_request(request):
"""
Unwrap the given "estimate nonsense" request into a string.
Args:
request: A JSON-like dict describing an "estimate nonsense" request
(as described on https://clusterdocs.azurewebsites.net/)
Returns: A string that represents the sentence of w... | 793b5b352db1edd31e537e39bd7ac0c3f62e0fc0 | 3,619,562 |
from typing import List
def available_agents() -> List[str]:
"""Returns a list of all available agent names.
Returns:
A list of strings indicating the agents that are available.
"""
return list(_mapping.keys()) | 93daa151260b3ce28d395622851962c74fc0b42a | 3,619,563 |
def parseDefault(eInfo):
"""Return None for each element; use as a catch-all
"""
assert (isinstance(eInfo, pd.Series))
eInfo.loc[:] = None
return eInfo | f8fb6412300f5e19b11d9778ba1a53234e9fc791 | 3,619,564 |
import time
import socket
def wait_for_cluster(api, expected_nodes, timeout=1800):
"""
Wait up to half an hour for cluster to form correctly
api: datera sdk object used to interface with the cluster
expected_nodes (list of str): IPs of nodes that should be in the cluster
timeout (int): number of ... | aa8d5d61e2a4ba59e20383c6a76146a02155a556 | 3,619,565 |
def set_reverse(flag):
"""Action to reverse color palette colors"""
return {"kind": SET_PALETTE, "payload": {"reverse": flag}} | 02af0c8227c44362e7d700e927eb2746239728d5 | 3,619,566 |
def _clean(target_str: str, is_cellref: bool = False) -> str:
"""Rids a string of its most common problems: spacing, capitalisation,etc."""
try:
output_str = target_str.lstrip().rstrip()
except AttributeError:
raise AttributeError("Cannot clean value other than a string here.")
if is_cel... | 778658332059679356c399c7bb5b0c66383650d3 | 3,619,567 |
def _gen_testcase_with_post(testcase_method, epilogues):
"""
Attach an epilogue to a testcase method
:param testcase_method: a testcase method
:param epilogue: a callable with a compatible signature
:return: testcase with epilogue attached
"""
@wraps(testcase_method)
def testcase_with_... | 4ee4efbfd17580feac1963fb39c89b8414adec38 | 3,619,568 |
import re
def read_peaks(path, arr=False):
"""
read peak list in the form of
prot peaks selected cmplx name
output hash cmplx name prot => peaks selected
"""
header = []
HoA = makehash()
temp = {}
for line in open(path, "r"):
line = line.rstrip("\n")
if line.starts... | 98475a4984ff53ef35db08d072b884b41fffe9c2 | 3,619,569 |
def get_values(record, tag):
"""Gets values that matches |tag| from |record|."""
keys = [key for key in record.keys() if key[0] == tag]
return [record[k] for k in sorted(keys)] | 7b75e300cbdb5c1840681c78af9adc4dc1f21838 | 3,619,570 |
from typing import List
def expected_value(values: List[float]) -> float:
"""Return the expected value of the input list
>>> expected_value([1, 2, 3])
2.0
"""
return sum(values) / len(values) | b856157d21bd8a82813bfb8ae39c4c5a1f3aef53 | 3,619,571 |
def has_partition(collection_name, partition_name, using="default"):
"""
Checks if a specified partition exists in a collection.
:param collection_name: The collection name of partition to check
:type collection_name: str
:param partition_name: The name of partition to check.
:type partition... | 9bdc7b3c689f54ecc200bc8d3c613dd9b8868cf7 | 3,619,572 |
from typing import Any
import importlib
from typing import cast
def import_file(full_name: str, path: str) -> Any:
"""Import a python module from a path"""
spec = importlib.util.spec_from_file_location(full_name, path)
mod = importlib.util.module_from_spec(spec)
# We assume this is not None and has ... | 2460ca2fe4c85edeab183fabcdd3f7db6b435acc | 3,619,573 |
def calculate_stats(num_observations, time_list):
"""Calculate mean and standard deviation of a list"""
time_array = np.array(time_list)
median = np.median(time_array)
mean = np.mean(time_array)
std_dev = np.std(time_array)
max_time = np.amax(time_array)
min_time = np.amin(time_array)
q... | 8da9c39c00f50b765f0e350f31ee8cc01ceb5ba1 | 3,619,574 |
def getOutputDeviceNames():
"""Obtain the names of all audio output devices on the system.
@return: The names of all output devices on the system.
@rtype: [str, ...]
@note: Depending on number of devices being fetched, this may take some time (~3ms)
"""
return [name for ID, name in _getOutputDevices()] | 172b4cd6177da02bd918092f050ce327b23e26fc | 3,619,575 |
import sklearn
import pandas as pd
def did_info(Y, treated_units, control_units, T0):
""" Return Difference-in-Difference information on setup
:param Y: Matrix of outcomes
:param treated_units:
:param control_units:
:param T0:
:returns: (Synthetic controls Y, R2 for controls post-treatment)
... | c512fafae22e7ee01692575573e2d1da7e02cb90 | 3,619,576 |
def help():
"""
Shows this help information.
"""
return __salt__["sys.doc"]("minionutil") | fd0aa66a9a9e3b376185ddef6e11c7d8e1872d8f | 3,619,577 |
def _get_integration_times(start_year: int, end_year: int, time_step: int):
"""
Get a list of timesteps from start_year to end_year, spaced by time_step.
"""
n_iter = int(round((end_year - start_year) / time_step)) + 1
return np.linspace(start_year, end_year, n_iter).tolist() | fe567a4fe566956758e04cdca5d5d96b68f65353 | 3,619,578 |
def add_layers_to_end_of_conn_mat(conn_mat, num_add_layers):
""" Adds layers with no edges and returns. """
new_num_layers = conn_mat.shape[0] + num_add_layers
conn_mat.resize((new_num_layers, new_num_layers))
return conn_mat | 4fb327f5b63b6c38ed0efa77d5247ae81113c7d3 | 3,619,579 |
def read_url(url, headers):
"""
Reads the url, processes it and returns a StringIO object to aid reading
:Parameters:
url: str
the url to request and read from
headers: dict
The right set of headers for requesting from http://nseindia.com
:returns: _io.StringIO object of the resp... | e1fcb43b6afe8903322d253584b823c546ffff5b | 3,619,580 |
def getVaultPath():
"""
Returns the vault location (either default or user defined)
"""
global args, vaultPathDefault
if args.vault_location:
return args.vault_location
return vaultPathDefault | 981260a17abe3187553bb3dc984e55dc2cadef43 | 3,619,581 |
def verify(token, access_token=None):
"""Verify a cognito JWT"""
# get the key id from the header, locate it in the cognito keys
# and verify the key
header = jwt.get_unverified_header(token)
key = [k for k in JWKS if k["kid"] == header['kid']][0]
id_token = jwt.decode(token, key, audience=conf[... | 63dfecb4557148156ba04b41d17ff1ffa067c322 | 3,619,582 |
from numpy import where,array,zeros,ones,ndarray,float64
from pylab import errorbar, semilogy,semilogx,loglog
def logerrplot(x,y,xerr=None,yerr=None,logaxes='y',boundscale=.5,**kwargs):
"""
fixes log plots to be upper bounds in the event of zero-data or errorbars
that go below zero
logaxes can be 'x'... | f1298884bd6dcff2f834dda3c74220d071fc92a2 | 3,619,583 |
def recount_correlations_removing_station(
cd, station, remove_station, days_apart=60
):
"""
Method to recount the number of correlations of each station and each
correlation period after removing a station.
Parameters
----------
station_code: TYPE
DESCRIPTION.
Returns
----... | a84ba89e1446d7e22c09174b866d515b835e9ff6 | 3,619,584 |
def index_append(graf_list) -> None:
"""
adds indexes to the list to be searched
:param graf_list: list of tasks to add
:return: None
"""
for task in graf_list:
indexs_to_check.append(task)
return None | 62a1e24ab2bcfdac1a42b872d61ef9c3d3165ca3 | 3,619,585 |
import os
def retrieve_noaa_folder_path():
"""
Helper function to retrieve the path to the NOAA folder in PydroXL
Returns
-------
str
folder path to the NOAA folder as string
"""
folder_path = path_to_NOAA()
if not os.path.exists(folder_path):
raise RuntimeError("the ... | a2473a0b0f3b6e38560ae00acb549c91027c4a9b | 3,619,586 |
import select
import sys
def is_input():
"""
Utility to check if there is input available.
Returns
-------
is_input: ``bool``
``True`` if there is data in sys.stdin
"""
return select.select([sys.stdin], [], [], 1) == ([sys.stdin], [], []) | 0d0194f72686bd839181a74eaa76d3baacbbd9ba | 3,619,587 |
import torch
def assemble_convection_parts(domain: Domain):
"""Compute the convection inner products of trial and test function for each pair of
cell vertices.
"""
parts = []
for i in range(domain.dim):
@skfem.BilinearForm
def convection_component(u, v, w, i=i):
retur... | 1b5c021c2c8c74bf9360aca5665e0dca8aa65ea5 | 3,619,588 |
from pathlib import Path
def create_app():
"""
Flask application factory.
"""
app = Flask(__name__)
app.config.update(
SECRET_KEY=config.ODP.UI.DAP.FLASK_KEY,
SESSION_COOKIE_SECURE=True,
SESSION_COOKIE_SAMESITE='Lax',
CLIENT_ID=config.ODP.UI.DAP.CLIENT_ID,
C... | 9a66a38a6d4a0770aaeca32170baef8c3d872901 | 3,619,589 |
import sys
def parse_genomecov(filename):
"""Parse median genome coverage from covmed output.
Assumes median coverage is the top left value in the text file."""
sample_id = get_sample(filename)
try:
mediancov = pd.read_table(filename, delim_whitespace = True, header = None).iloc[0,0]
e... | dc047378c22d62c320b4b14814976a0a4342b47c | 3,619,590 |
def make_t0(df):
"""
Make "timepoint 0" data for each condition by copying the group of uninfected cells from the lowest
moi and timepoint, for each moi and strain,
Receive and return dataframe.
"""
# get the minimal timepoint and moi in the experiment
timepoints = sorted(df['timepoint'].uni... | 0b31f295f5053c211f296a5e865d14f6f32d4a5a | 3,619,591 |
def data_zero(max_number, pieces_per_player):
"""
Force player0 to have at least half of his pieces of zero number, including double zero.
Randomly distribute pieces among the other players.
Valid pieces are all integer tuples of the form:
(i, j) 0 <= i <= j <= max_number
Each player will ha... | ff29885d7f9f3b46dc1d6fbf25cc1c7b9b1e97a0 | 3,619,592 |
import requests
def getAddressByAmp(lnglat):
"""
逆地理编码,通过高德地图api
:param lnglat:
:return:
"""
key = "efe4e9291a4a665ff691c55e3a3b871d"
url = "https://restapi.amap.com/v3/geocode/regeo?"
params = {
"key": key,
"location": lnglat
}
headers = {
"Content-typ... | c25d70d34b69890780a7514791919c2fb78c21b5 | 3,619,593 |
def style_loss(feats, style_layers, style_targets, style_weights):
"""
Computes the style loss at a set of layers.
Inputs:
- feats: list of the features at every layer of the current image, as produced by
the extract_features function.
- style_layers: List of layer indices into feats giving t... | 9cc79cc62beb291a6ed35c2571e18d6dfa8fbd0e | 3,619,594 |
import subprocess
def cobbler_delete_server(serverid):
"""Delete a server from cobbler
.. :quickref: Cobbler; Delete a server by server id
**Example Request**:
.. sourcecode:: http
DELETE /api/v2/cobbler/servers/<serverid> HTTP/1.1
Content-Type: application/json
... | 3b030cab290a8719e7994e7c28e6cc2369e3cbf2 | 3,619,595 |
def get_download_clientpack(
api_client, name=None, fileformat=None, fileFormat=None, **kwargs
): # noqa: E501
"""get_download_clientpack # noqa: E501
Returns clientpack file. Clientpacks are files with the necessary information and credentials for an overlay client to be connected to the VNS3 topology ... | f810a138113255a30ee633317df8c9810ca5fd7e | 3,619,596 |
def color_name(data, bits):
"""Color names in #RRGGBB format, given the number of bits for each component."""
ret = ["#"]
for i in range(3):
ret.append("%02X" % (data[i] << (8 - bits[i])))
return ''.join(ret) | 623ba9759f3dec88c60db2b120cdf151008e55b6 | 3,619,597 |
def is_valid_gadget(gadget, bad_chars):
"""Determine if a gadget is valid (i.e., contains no bad characters).
Args:
gadget (Gadget): A namedtuple-like object with `shellcode` and `asm`
fields.
bad_chars (bytearray): The bad characters not allowed to be present.
Returns:
... | 00189e08120e377ec873aa4267f3240d72943966 | 3,619,598 |
def month(dt):
""" For a given datetime, return the matching first-day-of-month date. """
return dt.date().replace(day=1) | 480fcdfd7a69f95aa071e2061efc4740802d72d6 | 3,619,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.