content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
from typing import Tuple
def _load_feature_metadata(feature_file: str, format_type: str, sep: str = "\t") -> Tuple[pd.DataFrame, str]:
""" Load feature information """
feature_metadata = pd.read_csv(feature_file, sep=sep, header=None)
if format_type == "HCA DCP":
# HCA DCP format genes.tsv.gz
... | c02599e0bac9fca6cadfafdd6835ce578b10dcb3 | 73,445 |
import warnings
def compute_err_score(true_positives, n_ref, n_est):
"""Compute error score metrics.
Parameters
----------
true_positives : np.ndarray
Array containing the number of true positives at each time point.
n_ref : np.ndarray
Array containing the number of reference freq... | b215fc28609bc6584912dc5d87172eb3b9c909cd | 73,446 |
def fibonacci_recursive(nth_nmb: int) -> int:
"""An recursive approach to find Fibonacci sequence value.
YOU MAY NOT MODIFY ANYTHING IN THIS FUNCTION!!"""
cache = {0: 0, 1: 1}
def fib(_n):
return _n if _n in cache else fib(_n - 1) + fib(_n - 2)
return fib(nth_nmb) | a6efe2a984e743d580d04a106a04463fa5d329c3 | 73,447 |
def api_core_myself():
"""自身のCcInfoのCRUD."""
if request.method == 'GET':
return _get_core_myself()
abort(405) | 4c983a5a2c27b7bc11c3ef16b21b1dce50a45252 | 73,448 |
def AC(obs, mod, axis=None):
""" Anomaly Correlation """
obs_bar = obs.mean(axis=axis)
if not axis is None:
obs_bar = np.expand_dims(obs_bar, axis=axis)
p1 = ((mod - obs_bar) * (obs - obs_bar)).sum(axis=axis)
p2 = (((mod - obs_bar) ** 2).sum(axis=axis) * ((obs - obs_bar) ** 2).sum(axis=axis)... | 07c6891769793729eafa6b72cfed281153a9c46e | 73,450 |
def table_to_data_frame(table):
"""Converts a vtkTable to a pandas DataFrame"""
if not isinstance(table, vtk.vtkTable):
raise _helpers.PVGeoError('Input is not a vtkTable')
if not isinstance(table, pv.Table):
table = pv.Table(table)
return table.to_pandas() | 0219cb28d766ea7ae3aaee27f83b672c4d2eae01 | 73,451 |
def ode_solutions(t,tsteps,M,S,gamma):
"""
Solve the differentials with an array of initial conditions and returns lists of positions and velocities.
Parameters
----------
t: float
The current time t[i].
tsteps: int
The number of times between [0,t] the solution is calculate... | aeb10534620852042f9dae0492976e358d444c2b | 73,452 |
import time
def test_main2():
"""Tests buckets containing multiple matches for traffic."""
b = [] # counting buckets
for i in range(0,2):
b.append(QueryTest())
time.sleep(0.2)
pol1 = match(srcip=ip1) >> b[0]
pol2 = match(srcip=ip2) >> b[1]
pol3 = match(srcip=ip3) >> b[0]
... | 61a43a7586aaa4ad548b97a0e6cbaa342aec37ea | 73,453 |
def recall_from_cfg(cfg):
""" Runs MCQ from julia based on the passed configuration
Params
cfg: Configuration (ConfigSpace.ConfigurationSpace.Configuration)
Configuration containing the parameters.
Configurations are indexable!
Returns:
scores: A crossvalidated mean score for the ... | 27ab71d4486d5bc084e2419546c6e64c03b22f46 | 73,454 |
import keyword
def is_valid_implicit_namespace_package_name(s):
"""
Checks whether provided string could represent implicit namespace package name.
:param s: string to check
:return: True if provided string could represent implicit namespace package name and False otherwise
"""
return isidenti... | 2ded9b0c20913d5a440169532d064b2691671a35 | 73,455 |
def get_maps_nested(models, cases, varList, from_time, to_time,
avg_over_lev=False,
pmin=None,
p_level=None,
pressure_adjust=True,
raw_data_path=get_input_datapath(),
recalculate=False,
... | f7f8960a6a455c5fa33ffd0555fef4c66a2fb5e8 | 73,457 |
async def login_post(request: Request, user: str = Form(...), db: Session = Depends(get_db)):
"""
POST route handler for the login page of the webapp
:param user: The form data for the user name to use to login.
:param db: Dependency for the db session.
:return: The response to the user based on the... | df97fffb0e9cc25fc681400edef29b19e0d7e6df | 73,458 |
import numpy
def _raw_fftnd(x, s, axes, direction, overwrite_x, work_function):
""" Internal auxiliary function for fftnd, ifftnd."""
if s is None:
if axes is None:
s = x.shape
else:
s = numpy.take(x.shape, axes)
s = tuple(s)
if axes is None:
noaxes = T... | 6341f5f49ef23fd773e285a845b39cf74332498f | 73,459 |
def check_apikey(name, query_type):
"""Verifies API Key."""
if not config.get(f"{name}", "api_key"):
print(f"Please add {name} api key to the '{settings.name}' file")
else:
api_key = config.get(f"{name}", "api_key")
name = query_type(api_key)
return name
return None | 38716627628b31094660b70b3da3e655f1150219 | 73,460 |
from typing import List
def motion_annotation(ephemerides: List[Ephemeris], wcs: WCS) -> GroupAnnotation:
"""Return an annotation showing the motion of an object on the sky.
If the motion is sufficiently large, it is shown as an arrow from the initial to the
final position. Labels for the initial and fin... | 39dcf46898b6c730ec1a1e452321c8f63c5620cf | 73,462 |
def select_k_best(points, scores, k, H=None, shape=None, margin=0):
""" Select the k best scoring points. If H and shape are defined,
additionally keep only the keypoints that once warped by H are
still inside shape within a given margin to the border. """
if H is None:
mask = np.ze... | 5072e9542acea5cdd65f9df29ef6e3e24d970243 | 73,463 |
def predict_linear_regression_labaled_features(fitted_model, dict_features):
"""
Calculates y ~ const + sum( parameter*value )
essentially the inner product
{ 'feature name' : value }
Does not assume you have all features present, so prediction may be off.
Assumes const parameter is not p... | b86fa00ff80e528080e473f849721a16e6f9f2a8 | 73,464 |
import json
def get_store_username():
""" 如果存储了用户名,就获取它 """
filename = 'username.json'
try:
with open(filename) as f_obj:
username = json.load(f_obj)
except FileNotFoundError:
return None
else:
return username | 68197999c12d0fdc5574dde45e92ef09f4a37d58 | 73,465 |
def group_documents_by_owner(documents):
"""Groups documents by owner."""
grouped = defaultdict(lambda: [])
for doc in documents:
grouped[doc.evergreen_owner].append(doc)
return grouped | e1b7bc9c571d3d376dea7811923f0e665120a37c | 73,466 |
def parse_time(text):
""" parse time of slurm output """
# check for days
tokens = text.split('-', 1)
if len(tokens) > 1:
days = int(tokens[0])
rest = tokens[1]
else:
days = 0
rest = tokens[0]
# check for time
tokens = rest.split(':')
return days*24*60 + ... | 91a07479f02a6d428a2c45fe6b701e009a9675cf | 73,467 |
def sigmaclip_inf(a, sigma_lower=3., sigma_upper=3.,
cenfunc='median', ddof=1, outfunc='median'):
""" Infinite loop sigma-clip.
copy from `scipy`_.
.. _scipy: https://github.com/scipy/scipy/blob/4c0fd79391e3b2ec2738bf85bb5dab366dcd12e4/scipy/stats/stats.py#L3159-L3225
"""
# bn.me... | 7ac94c1857f69c55c294e41f6a5a92c8b9fd94e3 | 73,468 |
def get_video_name(image_name):
""" Extracts the video name from an image filename.
Args:
image_name: The name of the image file.
Returns:
The name of the video that the image belongs to. """
video_name = image_name.split("_")[0:3]
video_name = "%s_%s_%s" % (video_name[0], video_name[1], video_name[2]... | d2e5254dfaa650455b346cec43273cd50004b335 | 73,470 |
def pretrain_model(albert_config,
seq_length,
max_predictions_per_seq,
initializer=None):
"""Returns model to be used for pre-training.
Args:
albert_config: Configuration that defines the core ALBERT model.
seq_length: Maximum sequence length of t... | 070e2b57487d130be823cee5924f522e2c48217a | 73,471 |
import keyword
def is_identifier(string):
"""Check if string could be a valid python identifier
:param string: string to be tested
:returns: True if string can be a python identifier, False otherwise
:rtype: bool
"""
val = PYTHON_IDENTIFIER_RE.match(string) and not keyword.iskeyword(string)
... | e0a2360909fb14a851711780051319c77cd27d22 | 73,472 |
def create_tf1_call_model_function(graph,
session,
y,
x,
conv_layer=None):
"""Creates a call_model_function which calls the TF1 model specified.
Args:
graph: The TensorFlo... | 041db914ece83ae0f58162bc625ebf213207d62a | 73,473 |
def check_orthogonality(modes, num_modes):
"""
Check orthogonality of modes.
:param np.ndarray modes: modes.
:param int num_modes: number of modes.
:return: True if orthogonality check passes.
:rtype: bool
"""
for m1 in range(num_modes):
for m2 in range(num_modes):
if m1 == m2:
s_ = np.sum(modes[:,m1... | 07c2fadf7ead843aee0a1e2f5048b84dd345a207 | 73,474 |
def Mce3(m, q, ξ, *, p=0):
"""
v = Mce3(m, q, ξ, *, p=0)
Compute the value of the even Radial Mathieu function of the third kind
Mce⁽³⁾ₘ(q, ξ).
Parameters
----------
m : array_like
interger order of the Mathieu function
q : array_like
positive parameter in the Mathieu d... | 349a3de477bb9c7913e18b3848db9ded040b776b | 73,475 |
from loopy.isl_helpers import static_max_of_pw_aff
from loopy.symbolic import pw_aff_to_expr
from loopy.kernel.data import VectorizeTag
from pymbolic import var
import six
def privatize_temporaries_with_inames(
kernel, privatizing_inames, only_var_names=None):
"""This function provides each loop iteration... | ef83a9b3fa00bfebcbeaf1c4dc2004e2e4ab5b60 | 73,477 |
def estimate_reasonable_max(df, x):
"""Estimate a reasonable maximum value for the plot y axis."""
# Use 1.5 IQR of the largest group.
group = df.groupby(x)
q1 = group.Time.quantile(0.25)
q3 = group.Time.quantile(0.75)
iqr = (q3 - q1).max()
return q3.max() + 1.5*iqr | a5fd4be194ca938c7cebd1ad31128ccffcfd44bd | 73,480 |
def multilabel_precision(y_true, y_pred):
"""
Macro-precision, with thresholds defined by by argmax F1
"""
values = list()
for i in range(y_true.get_shape()[1]):
pr, rec, thresholds = precision_recall_curve(y_true[:, i], y_pred[:, i])
f1 = 2.0 * pr * rec / (pr + rec)
values.a... | 25895da1a32085aa1f737d9afd13be3cbc6c06c6 | 73,481 |
def _add_members_to_obj(obj, data, columns):
"""Add members to obj.members
"""
i = 0
for member in obj.members:
name = 'member_' + str(i + 1)
data += ('\n'.join((f'{a}={v}' for a, v in member[i])),)
columns = columns + (name, )
i += 1
return data, columns | 6fd03824f3a17bb92fd7a42e16d3951222451cc2 | 73,482 |
def Compounds2Scaffolds(db,cids):
""" Return list of ScafIDs for selected compounds.
"""
cur=db.cursor()
sql='''\
SELECT DISTINCT
scaffold.id AS scafid
FROM
scaffold
JOIN
scafid2cid ON (scafid2cid.scaffold_id=scaffold.id)
JOIN
compound ON (compound.id=scafid2cid.compound_id)
WHERE
compound.id IN ( %(CIDS)s... | 7001628b0e9c4bc0ef569ae94857bafd02cfc430 | 73,483 |
def toggle_values_by_name(username=None, domain=None):
"""
Loads all toggles into a dictionary for use in JS
all toggles (including those not enabled) are included
"""
return {toggle_name: (toggle.enabled(username, NAMESPACE_USER) or
toggle.enabled(domain, NAMESPACE_DOMAIN... | a81efbccc5c0305a9d9bcd5b59bce9ac948cb151 | 73,484 |
import math
def get_exp(quantizer):
"""get max/min exp value for relu_po2 or quantized_po2."""
if quantizer.is_signed:
non_sign_bits = quantizer.bits - 1
else:
non_sign_bits = quantizer.bits
min_exp = -2 ** (non_sign_bits - 1)
max_exp_orig = 2 ** (non_sign_bits - 1) - 1
max_exp = max_exp_orig
... | b8a6e0f090c065e34350ee064f9b37bd09064b4b | 73,485 |
def scale_df_X_to_range(df_X, a, b):
"""
Given df_X (a pd.DataFrame containing just X values where each row is a
time series and each column is a voltage), scale each row to the range [a, b].
Take the min and max values for the sequence to be -40 and 40 (found by
inspecting all time series individu... | abe59ed3a7f17d4f74a5d74ab948e3abb2a77044 | 73,486 |
from typing import Type
def count_field(instance: Type[Model], field: str) -> int:
"""
Returns count of a related field. if `{field}_count`
exists in instance, then it's value will be returned
"""
count = getattr(instance, f'{field}_count', None)
if count is None:
count = getattr(insta... | 8c6723f725f37c27d3df9d604671244eebd7f16f | 73,487 |
def parse_number(value, locale=None):
"""Take localized number string and return a long integer.
Throws ValueError if bad format.
"""
return long(value.replace(get_group_format(locale), "")) | b30ee5ec347710a5a81e2ff78eb1885deef98294 | 73,488 |
import gzip
def load(filename):
"""Loads a compressed object from disk
"""
file = gzip.GzipFile(filename, 'rb')
object = cPickle.load(file)
file.close()
return object | c381d24517a73fc2aac08d29a340718bb442680c | 73,489 |
def _correct_background(v_raw_score, mat_ctrl_raw_score, v_var_ratio_c2t):
"""Cell-wise and gene-wise background correction
Args
----
v_raw_score (n_cell,n_ctrl) : np.ndarray
Trait raw score
mat_ctrl_raw_score (n_cell,n_ctrl) : np.ndarray
Control raw scores ... | 0ab76890f69bf6db1f8b05c6e462f82405330817 | 73,490 |
def get_points(file,img_shape,mirror=False):
"""
Read wp from a YOLO style file: each wp are the upper-left and the lower-right points of the bounding box
"""
points = []
img_shape = img_shape[:-1][::-1]
file = open(file).read().split('\n')[:-1]
for r in file:
r = r.split()
... | 9648edc2aa065aceadf2128c28b5ff71ded2cb92 | 73,491 |
def orjson_dumps(v, *, default):
"""
orjson.dumps returns bytes, to match standard json.dumps we need to decode.
orjson.dumps option arguments provide many options such as `option=orjson.OPT_SERIALIZE_UUID` to natively encode UUID instances.
"""
return orjson.dumps(v, default=default).decode() | 450473c8a4af546114aa453dcdead5530d7e6534 | 73,494 |
def definition():
"""
Cost information, for use in TT administration.
Seperate to v_c_cost for performance reasons - the other is used
for the curriculum model interface.
"""
acad_week_list = text_concat(
"acad_week", "x.acad_week FROM c_cost_week x WHERE x.cost_id = c.cost_id", ", ")
... | 3ae36d32a066b8280a409d44c7e51f62ddfc7e4f | 73,495 |
from typing import Optional
from typing import Union
from typing import Sequence
from typing import Dict
from pathlib import Path
def prepare_mtedx(
corpus_dir: Pathlike,
output_dir: Optional[Pathlike] = None,
languages: Optional[Union[str, Sequence[str]]] = "all",
num_jobs: int = 1,
) -> Dict[str, Di... | 0cc2790354ac008685061539de448468662eeb3d | 73,496 |
def get_label_mask(labelPath, params, mode):
"""
Loads the ground truth image (semantic or depth)
:param labelPath: Path to the ground truth file (CLS or AGL file)
:param params: input parameters from params.py
:param mode: either SEMANTIC_MODE or SINGLEVIEW_MODE from params (0 or 1)
:return: nu... | 049e9c0195f840c3a62e2db9e31eae75c67e02cd | 73,498 |
def _is_url(filename):
"""Check if the file is a url link.
Args:
filename (str): the file name or url link.
Returns:
bool: is url or not.
"""
prefixes = ['http://', 'https://']
for p in prefixes:
if filename.startswith(p):
return True
return False | cfffb3db75de4f613097c081f950d3feff079f63 | 73,499 |
import hmac
import hashlib
def acs_auth_sign(key, acs_action, acs_auth_data, path, optional_headers=None):
"""Creates X-Akamai-ACS-Auth-Sign value.
See also: https://control.akamai.com/dl/customers/NS/NS_http_api_FS.pdf
page 17
:param key str: (required) API key
:param acs_auth_data str: (re... | 570c5f56a7e8b6eb120c1034a7f5863c84c3640f | 73,502 |
def imperial_str_to_float(measure: str) -> float:
""" Convert an imperial measurement (possibly a fraction) to a float value """
if not is_safe(measure):
raise ValueError(f"{measure} is not a valid measurement")
# pylint: disable=eval-used
# Before eval() is called the string extracted from the ... | f47e97717407a65707820133d23c472d94ccc0a7 | 73,503 |
import six
import logging
def image2pulsetrain(img, implant, coding='amplitude', valrange=[0, 50],
max_contrast=False, const_val=20, invert=False,
tsample=0.005 / 1000, dur=0.5, pulsedur=0.5 / 1000.,
interphasedur=0.5 / 1000., pulsetype='cathodicfirst'):
... | 61ef9ed9f007eee3c3694b4f6a5494c600ec54f5 | 73,504 |
def _agg_weight(data, weight, method, drop_negative_weights):
"""Aggregate `data` by regions with weights, return indexed `pd.Series`"""
# only summation allowed with weights
if method not in ["sum", np.sum]:
raise ValueError("Only method 'np.sum' allowed for weighted average!")
weight = weigh... | 7e77d837ce0acb6f54eea943a1eeeb6143c527b2 | 73,505 |
def file2recarray(file, types=None, names=None, titles=None, delimiter='',
headerstring=None, ignorestring=None, skiplines=0,
datastring=None, buffer=False):
"""
creates a `numpy.recarray` from a file or buffer of consistent tabular data
of heterogeneous types, by guessin... | 64efffa21edca02b79681c59fe3a83a0e110f912 | 73,506 |
import hashlib
def _generate_orderless_cache_key(request, method, headerlist, key_prefix):
"""Returns a cache key from the headers given in the header list."""
ctx = hashlib.md5()
for header in headerlist:
value = request.META.get(header, None)
if value is not None:
ctx.update(... | 74cf07800cf1fc71c9c0954883e549944a41f6e0 | 73,507 |
from typing import List
def _mode_auto(total_frames: int, num_frames: int, fps: int, *args) -> List[int]:
"""The ``auto`` mode for frame extraction"""
return np.linspace(
0, total_frames, num_frames, endpoint=False, dtype=np.int
).tolist() | 04e28a1ff6768c1d4fdef4c3a3505e9f505dd972 | 73,508 |
def lookup_address(intersection, cached):
"""
Look up an intersection first in the cache, and if it
doesn't exist, geocode it
Args:
intersection: string
cached: dict
Returns:
tuple of original address, geocoded address, latitude, longitude
"""
if intersection in list... | a0046c0e195d0829610521f254a1cc3ee8013bcd | 73,509 |
def findgene_nmut(s, df):
"""Return the number equal bp of sequence compared to wt.
Looks for wildtype gene in given table whose sequence is most similar to
provided sequence. Then computes number of identical bases.
Parameters
----------
s : str
Sequence
df : Pandas.Dataf... | b54343fa2405ba6d9ef8cef1c67970701e2adb49 | 73,510 |
import types
def list_module_versions(glob, return_dict = False):
"""
Prints the versions of all loaded modules/packages in a script or notebook.
Parameters
----------
glob : dict
output of the globals() function call.
return_dict : bool, optional
Parameter to decide if funct... | 17a51568e5bf80f8eb8dac23f1996dc5dd609c50 | 73,511 |
def get_events(trace_collection, keys=None, syscall=True):
"""Return a generator of events. An event is a dict with the key the
arguement's name.
Args:
trace_collection (babeltrace.TraceCollection): Trace from which
to read the events.
keys (dict, optional): dict of the multiple... | abc6e99c1e3cc64b45671ab6e054bb4bffcf2032 | 73,512 |
def pass_draft(f):
"""Decorator to retrieve the draft using the record service."""
@wraps(f)
def view(**kwargs):
pid_value = kwargs.get("pid_value")
draft = service().read_draft(id_=pid_value, identity=g.identity)
kwargs["draft"] = draft
return f(**kwargs)
return view | e6d4af978fcee7978cb61088d0282abb46dc059e | 73,513 |
def getFeatures_Explore(catalog,dataH5_path,station,channel,fmin,fmax,fs,nfft,):
"""
Read waveforms from H5, calculate features prior to SpecUFEx
Return dataframe with features indexed by datetime
Parameters
----------
catalog : pandas Dataframe
Needed for event IDs; need columns called... | a236313bf6fd9a81c4f71591aaf36d76d425425b | 73,514 |
from typing import Optional
from typing import Dict
from typing import Any
def _get_schema_step_3(
hass: HomeAssistant,
user_input: Optional[Dict[str, Any]],
default_dict: Dict[str, Any],
plan_list: list,
entry_id: str = None,
) -> vol.Schema:
"""Gets a schema using the default_dict as a backu... | 3a8c555e4599ff18034e2aa5043be807498acdef | 73,515 |
from operator import add
def norm(x, ord=None, axis=None, keepdims=False):
"""
Matrix or vector norm.
This function is able to return one of eight different matrix norms,
or one of an infinite number of vector norms (described below), depending
on the value of the ``ord`` parameter.
Paramete... | 05aa8b2ea68ea90d631a6d494c8d73532b36391a | 73,516 |
import torch
def softplus_inverse(x: torch.Tensor) -> torch.Tensor:
"""
Inverse of the softplus function. This is useful for initialization of
parameters that are constrained to be positive (via softplus).
"""
if not isinstance(x, torch.Tensor):
x = torch.tensor(x)
return x + torch.log... | aa4649368b9e8372e7a22b4ab460bf8d26a38dad | 73,517 |
def leaky_relu(x, name=None):
"""Creates a leaky_relu.
This is an alternate non-linearity to relu. The leaky part of the relu may
prevent dead Neurons in a model since the gradient doesn't go completely to
0.
Args:
x: The input tensor.
name: Optional name for this op.
Returns:
x if x > 0 other... | 4dccc86b399d7e41b94fdbd993f0b5566928a968 | 73,518 |
import six
def get_prefix(table, name, allow_prefixes=True):
"""
Looks up an entry in a table where unique prefixes are allowed.
"""
result = table.get(name, _NONE)
if result is not _NONE:
return name, result
if allow_prefixes:
results = [(k, v) for (k, v) in six.iteritems(table) if k.startswith(... | cf037a693821cdfe20db27000a58f85a73a7c42e | 73,519 |
import time
def params(request):
"""Параметры передаваемые при каждом запросе по умолчанию"""
data = {
"owner_id": OPEN_OWNER_ID,
"type": TYPE_POST,
"access_token": ACCESS_TOKEN,
"v": API_VERSION,
"user_id": USER_ID
}
def fin():
"""Ограничение кол-ва за... | f5469bcebfd20d1fbc7e48e2b9079cfd1d065b6f | 73,520 |
def rosmac(y, t=0, r0=0.5, k=10, g0=0.4, h=2, l=0.15, e=0.6):
""" Rosenzweig-MacArthur predator prey model
"""
prey, cons = y
def r(x):
""" Growth rate """
return r0*(1 - x/k)
def g(x):
""" Grazing rate """
return g0/(x + h)
dydt = [r(prey)*prey -g(prey)*prey*c... | ec17e71cf5742b3db2b48123a63c14ae62101bee | 73,521 |
import re
def shorten(CSTAG: str) -> str:
"""Convert long format of cs tag into short format
Args:
CSTAG (str): cs tag in the **long** format
Return:
str: cs tag in the **short** format
Example:
>>> import cstag
>>> cs = "cs:Z:=ACGT*ag=CGT"
>>> cstag.shorten(cs)... | 653de1947a3cdf06103b01c1a7efc3dbc16ea4ab | 73,523 |
def calculate_average_metrics(model, test_data, metrics, progress_callback=None):
"""
Compute average value of metrics
:param model: Model used for evaluation
:param test_data: Data to evaluate on
:param metrics: List of evaluation metrics to compute
:param progress_callback: Callback called aft... | 13a6ad01b4df1b1889f7112ea16c67a562f132a5 | 73,524 |
def predict_outputs(sample_sheet=None,sample_sheet_file=None):
"""
Generate expected sample sheet output in human-readable form
Arguments:
sample_sheet (SampleSheet): if supplied then must be a
populated ``SampleSheet`` instance (if ``None`` then
data will be loaded from file specifie... | afed7201375c8d025a66716a8dfab66dfdee20ac | 73,525 |
def extended_unbinned_NLL(pdfs, integrals, n_obs, nsignals,
param_gauss=None, param_gauss_mean=None, param_gauss_sigma=None,
log_multi_gauss=None):
"""
Return unbinned negative log likelihood graph for a PDF
models : concatenated array of several PDF... | 2359a71fc2e90da8ba5d26e9a13447d46d7995f3 | 73,526 |
def model_with_buckets(encoder_inputs, decoder_inputs, targets, weights,
buckets, seq2seq, softmax_loss_function=None,
per_example_loss=False, name=None):
"""Create a sequence-to-sequence model with support for bucketing.
The seq2seq argument is a function that defines... | 1b928a26b2374a8537c7473f29d279c074227615 | 73,527 |
def make_cloud_mask(aa):
""" relevent points will be 1. paddings will be 0. """
mask = np.zeros(14)
if aa != "_":
n_atoms = 4 + len(SC_BUILD_INFO[aa]["atom-names"])
mask[:n_atoms] = 1
return mask | e9fdfce52bdef4c09233b44387837fc8c4b24eb7 | 73,528 |
def dbex_eval(db, expr):
"""Evaluate a database expression"""
return db.ex_eval(expr) | 9739e2dd85fadd4d1569ddec20c6db57379a2de9 | 73,529 |
import typing
import inspect
def get_class_fields(cls: type) -> typing.List[Field]:
"""Cache and return class's __init__ parameter names and type hint"""
if cls not in CLASS_SPECS_CACHE:
if hasattr(cls, '_field_types') and hasattr(cls, '_fields'):
# NamedTuple case
hints = cls... | e890f832be001a7ee6a5ba99530fe962dce29f29 | 73,531 |
def get_challenge_answer(challenge):
"""
Solve the math part of the challenge and get the result
"""
arr = list(challenge)
last_digit = int(arr[-1])
arr.sort()
min_digit = int(arr[0])
subvar1 = (2 * int(arr[2])) + int(arr[1])
subvar2 = str(2 * int(arr[2])) + arr[1]
power = ((int(... | dd36dc263e112e3720c57385c77e3f0742e4a323 | 73,532 |
def s(time):
"""CIO locator
"""
return sofa.vectorized_s06(time) | 640c92fc5fd4879eb4379d432406d6b4a5b4e249 | 73,533 |
def EmptyBitmapRGBA(width, height):
"""Create an empty bitmap with an alpha channel"""
if hasattr(wx, 'EmptyBitmapRGBA'):
bmp = wx.EmptyBitmapRGBA(width, height, alpha=0)
else:
bmp = wx.EmptyBitmap(width, height, -1)
if hasattr(bmp, 'UseAlpha'):
bmp.UseAlpha()
return ... | 1e74c7e96bdf7ecad705dfd8268fc70e9af9e259 | 73,534 |
def dme_ionization_ff(shell, e_er, q):
"""Return dark matter electron scattering ionization form factor
Outside the parametrized range, the form factor is assumed 0
to give conservative results.
:param shell: Name of atomic shell, e.g. '4p'
Note not all shells are included in the data.
:pa... | 13ac16420e32045c1c795632341aab8da4dbc426 | 73,535 |
def predict_by_tree(test_feature, tree_model):
"""
predict by gbdt model
"""
predict_list = tree_model.predict(xgb.DMatrix(test_feature))
return predict_list | 967126f9e9155d840bf29a88cea3c77389716cec | 73,536 |
import torch
def chain_predictor(theta_samples, nb_sample1, nb_sample2):
"""
Similar to the laplace sampler, we skip the step where we sample thetas from the unnormalised posterior
Then we use these to perform prediction via Monte Carlo integration
input:
theta_samples: samples obtai... | a50861290e99f2f50f27ca9e9fe03df6fea45c26 | 73,537 |
from typing import Iterable
def averageHourlyProduction(productions: Iterable[Production]) -> int:
"""Returns average production per hour."""
return int(sum([p.phour for p in productions]) / len(productions)) | 4efa2bfb55820afafd92700cf634072a75c125ea | 73,538 |
def _empty_invoke_bc(ivkbl, _stack, stack_ptr):
"""Write a warning to the screen"""
print(
"Warning: undefined primitive #%s called"
% ivkbl.get_signature().get_embedded_string()
)
return stack_ptr | 89b33c7b888560da6e8d49e432db9bc068bfaa66 | 73,539 |
def encode(mat):
"""Encode a 2x2 unitary matrix as a 1x8 vector, consiting of the real and imaginary
parts of each entry."""
flat_mat = np.array(mat.flat)
return np.concatenate((flat_mat.real, flat_mat.imag)) | cf752ab473635c8e9ea0caaf3b3162a106c3578a | 73,540 |
def _misc_err_msg(exception):
"""Returns page with an error message stating that cause of error was due
to various other things that could've gone wrong.
Args:
exception: Exception obj of varying type.
Returns:
(template): data that will be used to render webpage on client-side.
""... | 67d2388b8fa575523157d09fabb28532bc663041 | 73,541 |
def test_bccache(base_app, ext):
"""Test bytecode cache."""
app = base_app
app.jinja_options = dict(
app.jinja_options, cache_size=1000, bytecode_cache=BytecodeCache(app)
)
@app.route("/")
def view():
return render_template("template.html", msg="test")
with app.test_client(... | 0cd4d98351eb06ec69e76a7fbbd7f03230a235f0 | 73,542 |
import tqdm
import itertools
def play_tournament(game, agents, seed=1234, rounds=100):
"""Play a round robin tournament between multiple agents.
"""
rng = np.random.RandomState(seed)
# Load each team's agent
results = []
for _ in tqdm(range(rounds)):
for (agent1, agent2) in list(iterto... | b38c75875693181eae9b45531b4591ccc2d22af4 | 73,543 |
def delete_flavor(token, flavor_id):
"""
Asks OpenStack Nova to delete a flavor
"""
url = token.get_service_url(OPENSTACK_SERVICE.NOVA, strip_version=True)
if url is None:
raise ValueError("OpenStack Nova URL is invalid")
api_cmd = url + "/v2.1/%s/flavors/%s" % (token.get_tenant_id(), f... | 88c4b9e95bb1454b6fc1103484c62c3e167f3f97 | 73,544 |
def lemmatize(token, pos='n'):
""" lemmatize a token using a selected part of speech
args:
token: string
pos = parth_of_speech of the given token
returns
lemmatized_token: a lemmatized/reduced token
"""
lemmatized_token = lemmatizer.lemmatize(token, pos=pos)
return lemmat... | c4c734d0b74d3ba11c6ff46aa75f571cb4f10b6b | 73,546 |
def drainage_radius(area):
"""Returns the circular drainage radius (miles) given the drainage area (Acres)"""
return round(((area*43560)/(np.pi*5280**2))**0.5, 2) | 0a3fa7b63045c8c1f81df38d0983ee51da63d642 | 73,547 |
import math
def lognormal_stddev(m, stddev):
""" compute std. of log x with mean and std. of x
Args:
m: mean of x
stddev: standard deviation of x
Returns: std. of log x
"""
return math.sqrt(math.log((stddev * stddev) / (m * m) + 1)) | cb3abebc2225e3b2d33bdc1b6ff12c950437a594 | 73,548 |
def lex_braced_expr(string):
"""Lex a braced expression."""
tokenizer = lexer.make_tokenizer([
('lbrace', [r'{']),
('rbrace', [r'}']),
('content', [r'[^{}]+']),
])
return remove_whitespace_tokens(tokenizer(string)) | 95ab0dc6a6fb3cbd6a4f051c93848458786ae90a | 73,549 |
from typing import Optional
from typing import Any
def build_post_multi_param_groups_request(
*,
header_one: Optional[str] = None,
query_one: Optional[int] = 30,
header_two: Optional[str] = None,
query_two: Optional[int] = 30,
**kwargs: Any
) -> HttpRequest:
"""Post parameters from multipl... | a7e95609fdfeb537c54d8c6eba5bb3cbf46c1837 | 73,550 |
def dim(msg):
""" return dimmed msg """
return __apply_style(__format['dim'],msg) | 18bfb2805a1e97172ac0d92e8fa70eb0e1800c3e | 73,551 |
def ack(m, n):
"""Computes the Ackermann function A(m, n)
See http://en.wikipedia.org/wiki/Ackermann_function
n, m: non-negative integers
"""
if m == 0:
return n + 1
if n == 0:
return ack(m - 1, 1)
if (m, n) in know:
return know[(m, n)]
... | 2f7f816dc8a5d0b24b6f683ff11e6b843dbdcb72 | 73,552 |
def _setup(config):
"""Perform common setup tasks for the tests."""
if CONF_ADB_SERVER_IP not in config[DOMAIN]:
patch_key = "python"
else:
patch_key = "server"
if config[DOMAIN].get(CONF_DEVICE_CLASS) != "firetv":
entity_id = "media_player.android_tv"
else:
entity_i... | a1baf952003bda55c7f783096fdf85c9be08346e | 73,554 |
def resize(images: np.ndarray, size: tuple(int, int)) -> np.ndarray:
"""
Resize images with to size.
:param images: image data in numpy array
:shape: (n, h_init, w_init, c_init)
:param size : new size
:shape: (h_n, w_n)
:return: resized image data in numpy array
:sha... | 8bbc4cc5cd50827a4fe4360ceed84e8722b7a711 | 73,555 |
def sharedMemDictToNumpy(ShMem):
""" Get views (not copies) of all shared-mem arrays in dict.
Returns
-------
d : dict
"""
ArrDict = dict()
if ShMem is None:
return ArrDict
for key, ShArr in list(ShMem.items()):
ArrDict[key] = sharedMemToNumpyArray(ShArr)
return Arr... | c882ec36c84a2b1b389831466df03beea48969e4 | 73,556 |
import aiohttp
async def get_new_bangumi_json() -> dict:
"""
Get json data from bilibili
Args:
Examples:
data = await get_new_bangumi_json()
Return:
dict:data get from bilibili
"""
url = "https://bangumi.bilibili.com/web_api/timeline_global"
headers = {
"acce... | 02d39b7535a7db7b50dc81851725ffc67653cd17 | 73,557 |
def compare_math_formula(query, formula):
"""Compares two math tuples
Parameters:
query: the query math tuple (str)
formula: the formula math tuple (str)
Returns:
same: True if tuples are considered equal (boolean)
"""
if "'*'" in query:
# break on the wild card
... | 736e9f564e4c834270fd25af7ed8252873d4c07d | 73,558 |
def interpolate(df, key):
"""Interpolate subset of MulitIndex df."""
subset = df.xs(key, level=0, drop_level=False, axis=1)
return (subset.interpolate(axis=1)
.where(subset.fillna(method='bfill', axis=1).notnull())) | 0f5fec0b891871747337194bf56a0814ee015fc0 | 73,559 |
import re
def output_name_from_topic(topic: str, prefix: str, topic_type: str) -> str:
"""
Parses an MQTT topic and returns the name of the output that the message relates to.
"""
match = re.match(f"^{prefix}/{topic_type}/(.+?)/.+$", topic)
if match is None:
raise ValueError("Topic %r does... | ca6b3eb77815eee3f779bf16e8f706532dfe42e6 | 73,560 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.