content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import torch
import tqdm
def validate(model, valset, iteration, batch_size, n_gpus,
collate_fn, logger, distributed_run, rank):
"""Handles all the validation scoring and printing"""
model.eval()
with torch.no_grad():
val_sampler = DistributedSampler(valset) if distributed_run else Non... | 6db04182aa04abb2059ffdfc9a9fb1414b3c3ec8 | 3,605,500 |
import sys
def _get_captcha(reddit_session, captcha_id):
"""Prompt user for captcha solution and return a prepared result."""
url = urljoin(reddit_session.config['captcha'],
captcha_id + '.png')
sys.stdout.write('Captcha URL: {0}\nCaptcha: '.format(url))
sys.stdout.flush()
raw = ... | 9da9901aa5d1120cb7f79ba7c57f155951d7f1e0 | 3,605,501 |
def klucbPoisson(x, d, precision=1e-6):
""" KL-UCB index computation for Poisson distributions, using :func:`klucb`.
- Influence of x:
>>> klucbPoisson(0.1, 0.2) # doctest: +ELLIPSIS
0.450523...
>>> klucbPoisson(0.5, 0.2) # doctest: +ELLIPSIS
1.089376...
>>> klucbPoisson(0.9, 0.2) # doc... | 12c681cbca8aad17d0362ac8991bb0507ecff03a | 3,605,502 |
import json
def api_download_version(request, preprocess_id, version):
"""Download preprocess info by version"""
if version:
# use this param for the query
version_decimal = Decimal(str(version))
else:
# Default to version 1.0
version_decimal = Decimal('1.0')
# Return... | 78af91ddf91503d1ff5bf58019b320b439903417 | 3,605,503 |
def get_confusion_matrix_elements(groundtruth_list, predicted_list):
"""
Return confusion matrix elements covering edge cases
:param groundtruth_list list of groundtruth elements
:param predicted_list list of predicted elements
:return returns confusion matrix elements i.e TN, FP, FN, TP in that or... | da7232d7c1123c706bbd280311692db1f1debc40 | 3,605,504 |
def densityice(airf=None,temp=None,pres=None,entr=None,dhum=None,
chkvals=False,chktol=_CHKTOL,airf0=None,temp0=None,pres0=None,
dhum0=None,chkbnd=False,mathargs=None):
"""Calculate icy air ice density.
Calculate the density of ice in icy air.
:arg airf: Dry air mass fraction in kg/kg. If ... | d53319867ef449f89788bacc308459a4ad86868a | 3,605,505 |
def convert_mutation_list_to_df(mutations_list, count_label):
""" Take in a list of mutations and count how many of there in a dataframe
The number of counts appears in the count_label column
This works for both single and double mutations
"""
df = pd.Series(mutations_list)
unique_counts... | b83a9b92c883c84c1fdde30122bdcdb44c5c5598 | 3,605,506 |
def r2(y_true, y_pred):
"""
R2 score
$$ 1 - \frac{MSE}{TSS}, \quad TSS= \sum\limits_{i}^{N} (y_i - \bar{y})^2) $$
$$ \bar{y} = \frac{1}{N} sum\limits_{i}^{N} y_i $$
"""
return 1. - K.mean(K.sum(K.square(y_true - y_pred))) / K.sum(K.square(y_true - K.mean(K.identity(y_true)))) | 988db482da7c094276eb8d0819193c201242533b | 3,605,507 |
def predict_map(map, predict, window_h, window_w, stride, batch_size, **kwargs):
"""Creates a probability map of predictions of the high resolution input
image `map` using a sliding window approach.
Arguments:
map: Array. Input image with dimensions of (height, width, 6).
predict: Fu... | 7c5d4da5c2d6a862cdda5c44511c19586892472e | 3,605,508 |
def genome_distance(**kwargs):
"""
Protocol:
Concatenate alignments based on genomic distance
Parameters
----------
Mandatory kwargs arguments:
See list below in code where calling check_required
Returns
-------
outcfg : dict
Output configuration of the pipeline, i... | e96aa72584eab1d14faeb77e350527ebd4a16949 | 3,605,509 |
import torch
def create_tau( fval, gradf, d1x, d2x, smoothing_operator=None ):
"""
tau = create_tau( fval, gradf, d1x, d2x )
In:
fval: torch.FloatTensor
of shape B
gradf: torch.FloatTensor
of shape B*C*H*W
d1x: torch.FloatTensor
of shape B*C*H*W
d2x: torch.FloatTen... | 5e086908e432fbc6a34e1ce72bee84a1f467823e | 3,605,510 |
def balance(atomic_data_table, title=None):
"""
Plot the derived abundances as a function of excitation potential and line
strength, as typically done in classical analysis approaches.
:param atomic_data_table:
A record array table containing the wavelength, species, lower excitation
po... | a0e709909ad81a7f68a04430263417008d878fc1 | 3,605,511 |
def drmaa_singlejob(cmd, jobtemplate, session, waitforever, lock):
"""
:param cmd:
:param jobtemplate:
:param session:
:param waitforever:
:return:
"""
out, err = '', ''
try:
with lock:
outpath = jobtemplate.outputPath
errpath = jobtemplate.errorPath
... | 71e5c3b0d2f1c596f3bfb08a50bd25dceb1f5f3a | 3,605,512 |
from datetime import datetime
def date_from_epoch(epoch, in_ms=None):
"""
Args:
epoch (int | float): Unix epoch in seconds or milliseconds, utc or local
in_ms (bool | None): In milliseconds if True, auto-determined if None
Returns:
(datetime.date): Corresponding datetime object
... | cb96189e82f2bd4a82e3b5b53a38cb785e35707c | 3,605,513 |
import torch
def adjust_m4i_data(source_data):
"""
Input: (iteration, segment, sample, channel)
"""
print("Begin reshaping ... {}".format(source_data.shape))
# Remove channel (last index) and cute data shape to fit into model
# model currenly has a window of 128, need to make adjustable
... | d9d44504992f0232ccf7d42dc9babca0aae60ee1 | 3,605,514 |
import json
def run_extract(config):
"""
run_extract(config)
Main function that gets configuration to run a given extract:
2 - M-extract
3 - P-Extract
3 or 4 - R-Extract
"""
category = int(config.get('category'))
if category == 2:
# Extrac... | 07ea0ce6998b1a5815be094eb32dfbfc73ac3e51 | 3,605,515 |
def format_seconds(delta):
"""
Given a time delta object, calculate the total number of seconds and return
it as a string.
"""
def _total_seconds(td):
return (td.microseconds + (td.seconds + td.days * 24 * 3600) * 10 ** 6) / 10 ** 6
return '%s' % (_total_seconds(delta)) | 60248f96a64b04be6480e27aa134c943461a6daa | 3,605,516 |
import os
def create_module(module, target):
""" Create a module directory structure into the target directory. """
module_x = module.split('.')
cur_path = ''
for path in module_x:
cur_path = os.path.join(cur_path, path)
if not os.path.isdir(os.path.join(target, cur_path)):
... | 2aa686dbc381f863a7860d2e75dacde941297761 | 3,605,517 |
from tqdm import tqdm
from typing import List
import concurrent
def tiles_urllib(tile_metas: List[HipsTileMeta], hips_survey: HipsSurveyProperties,
progress_bar: bool, n_parallel, timeout: float) -> List[HipsTile]:
"""Generator function to fetch HiPS tiles from a remote URL."""
with concurren... | c8803a085e1bbdde8c1ae640b9c77409cd971d9c | 3,605,518 |
def defineShapePerimeter():
"""Define the perimeter and radius of each shape for different sizes"""
allowedRadius = {
"circle" : {
"small" : [16,25], "medium" : [32,40], "large" : [45,58]
},
"quadrilateral" : {
"small" : [16,32], "medium" : [40,48], "large" : [56,72]
},
"triangle" : {
"small" : [2... | 92ad63dcfe4f93fc8910bdb41d52f80169a91c1c | 3,605,519 |
def ldns_key_keytag(*args):
"""LDNS buffer."""
return _ldns.ldns_key_keytag(*args) | 4d2c91c111a3d81b6f46980a06e776ada69899a7 | 3,605,520 |
def setup_module(module):
"""Setup fixtures for module."""
class SubClassUnitTest(PotentialSampler, key="unittest"):
def __call__(self, n, *, random=None, **kwargs):
representation_type = self.representation_type # can be None
if random is None:
random = np.rand... | a57fc5624126a693c125712a1e8b527788448efc | 3,605,521 |
def ols(y, X, const=True):
"""Performs an OLS regression"""
y = np.array([y]).transpose()
ones = np.ones(y.shape)
X = np.array(X).transpose()
X = np.hstack([X, ones])
Xp = X.transpose()
beta = np.linalg.inv(Xp.dot(X)).dot(Xp).dot(y)
yp = X.dot(beta)
u = y - yp
return beta, yp, ... | f3b7076f1294ec77354fd990d011e63753ad70fe | 3,605,522 |
def write_atoms(fp, elem, pos, pseudized_charge, atomic_number_map={'H': 1, 'Li': 3, 'C': 6}):
""" create and fill the /atoms group
!!!! QMCPACK does NOT check valence_charge, pseudized_charge matters?
Args:
fp (h5py.File): hdf5 file object
elem (np.array): array of atom names
pos (np.array): array o... | 5441cf2b2bc2a22ac35e700f9b5b53339f532ab9 | 3,605,523 |
def clpool():
"""clpool()"""
return _cspyce0.clpool() | b2ef48500759fe89db1f42f95584aaa65b8bac7a | 3,605,524 |
def reset_db(ctx, with_testdb):
"""
Init and seed automatically.
:param with_testdb: Create a test database
:return: None
"""
ctx.invoke(init, with_testdb=with_testdb)
ctx.invoke(seed)
return None | a35a6cc53653edb7aeee3087871a4969d52b6882 | 3,605,525 |
def dataset_detail(request, dataset_id):
"""Renders individual dataset detail page."""
active_dataset = get_object_or_404(Dataset, pk=dataset_id)
datadict_id = active_dataset.data_dictionary_id
datadict = DataDictionaryField.objects.filter(
parent_dict=datadict_id
).order_by('columnIndex')
... | dd033c8264120753642692837f6c3076d845a648 | 3,605,526 |
def scanner_position(n, t):
"""Return positin of scanner of range n at time t."""
n1 = n - 1
return n1 - abs(t % (2*n1) - n1) | 3651f5997b370e703e09ff1f97c1d7d249cf286c | 3,605,527 |
from datetime import datetime
def get_rolling_average(date, df, column):
"""Calculate rolling average from a column.
We apply mean for each values of a specific column
within the range of last week date and date itself
"""
lowestDate = datetime.strftime(
datetime.strptime(date, "%Y-%m-%d"... | 5deff4293d72f272569f228dc66b9686405e7982 | 3,605,528 |
import numba
import functools
def compile_function(
_func: callable = None,
*,
compilation_mode: str = None,
**decorator_kwargs,
) -> callable:
"""A decorator to compile a given function.
Numba functions are by default set to use `nogil=True` and `nopython=True`,
unless explicitly defined... | 261147323278fa9eefaf8537aec6b5886f3a10e3 | 3,605,529 |
from re import T
def create_php(idx, ar, rip='0x????????', pc=None):
"""Collect metadata for a PHP frame.
All arguments are expected to be gdb.Values, except `idx'.
"""
func = ar['m_func']
shared = rawptr(func['m_shared'])
# Pull the function name.
if not shared['m_isClosureBody']:
... | 7b28d16349031bcd97593ab496ee092d85109a69 | 3,605,530 |
def equal_images(img1, img2):
"""Adapted from Nicolas Hahn:
https://github.com/nicolashahn/diffimg/blob/master/diffimg/__init__.py
"""
if img1.mode != img2.mode or img1.size != img2.size or img1.getbands() != img2.getbands():
return False
diff_img = ImageChops.difference(img1, img2)
sta... | 811e993c4c3fc0225f4917039ac4df320dd0429f | 3,605,531 |
import socket
import struct
def discover(service, timeout=2, retries=1):
"""discover pilight servers"""
group = ("239.255.255.250", 1900)
message = "\r\n".join([
'M-SEARCH * HTTP/1.1',
'HOST: {0}:{1}'.format(*group),
'MAN: "ssdp:discover"',
'ST: {st}', 'MX: 3', '', ''])
... | 6e220b66de64b00d18d71883791dd2d1ad5d9a96 | 3,605,532 |
def valid_date_version(s: str) -> bool:
"""Check that the string is a valid date versions string."""
return _validate_date_fmt(s, DATE_VERSION_FMT) | 4b81a9ddaa6dd072c9f29e0a287eb7d4ed759cf5 | 3,605,533 |
import argparse
def load_arguments():
"""
Parse the arguments for the cli_env_autoinstall.py module.
"""
# cur_path = os.path.dirname(os.path.realpath(__file__))
# config_file = os.path.join(cur_path, "config.toml")
p = argparse.ArgumentParser(
description="Create a new conda environ... | f9e0b2b3bed71bb149478e86729e60cc9fe15af7 | 3,605,534 |
def calc_pq(hmm_annotation, fs, p_states=P_STATES, q_state=Q_STATE, r_state=R_STATE):
""" Calculate PQ based on HMM prediction.
Parameters
----------
hmm_annotation : numpy.array
Annotation for the signal from hmm_annotation model.
fs : float
Sampling rate of the signal.
p_state... | e78b3257b7af6d3c08f46936b922a5ecafb15b00 | 3,605,535 |
import json
def zp3111_state_fixture():
"""Load the zp3111 4-in-1 sensor node state fixture data."""
return json.loads(load_fixture("zwave_js/zp3111-5_state.json")) | c24dd3ae6f26d4a4f346c32cbcb970fc2e03cc05 | 3,605,536 |
from typing import TypeVar
from typing import Callable
def literal_substitute(t, type_map):
"""Make substitutions in t according to type_map, returning resulting type."""
if isinstance(t, TypeVar) and t.__name__ in type_map:
return type_map[t.__name__]
elif isinstance(t, TuplePlus):
subbed... | 4b44e42093800f3d0e8e2cdea7f85fa2b2c7a0e3 | 3,605,537 |
def get_18(input_shape, num_classes, unit_cls=ResidualUnit):
"""As described in [1]"""
_validate_non_bottleneck_unit(unit_cls)
return get(input_shape, num_classes, unit_cls, [2, 2, 2, 2]) | 1da78467bd96184e6379ca0978d05647660794e9 | 3,605,538 |
def generate_values(TR,P=101325):
""" Starting with T,R as inputs, generate all other values """
T,R = TR
psi_w = CP.HAPropsSI('psi_w','T',T,'R',R,'P',P)
other_output_keys = ['T_wb','T_dp','Hda','Sda','Vda','Omega']
outputs = {'psi_w':psi_w,'T':T,'P':P,'R':R}
for k in other_output_keys:
... | 5e557b1ef8943d2848874474a204da5c34125e4b | 3,605,539 |
def _query_comcat(start_time, end_time, min_magnitude=2.50,
min_latitude=31.50, max_latitude=43.00,
min_longitude=-125.40, max_longitude=-113.10, extra_comcat_params=None):
"""
Return eventlist from ComCat web service.
Args:
start_time (datetime.datetime): start ti... | f85dc83bfff42bdbb35df1d63cd484a348cdebf7 | 3,605,540 |
from functools import reduce
def reduce_2array(A, B, fun, axis=-1, initializer=0.0, keepDims=False):
"""
Compute the dot product along the given axis.
a and b must have exactly the same shape, as the axis dimension will be reduced by element-wise multiplication and summation along that dimension.
Args:
- a, ... | 0875c00fb71808a926b41d771ea260692d8a5a10 | 3,605,541 |
def get_advice_tab_context(case, caseworker, queue_id):
"""Get contextual information for the advice tab such as the tab's URL and
button visibility, based off the case, the current user and current user's queue.
"""
team_alias = caseworker["team"]["alias"]
queue_alias = next((item["alias"] for item... | ff3164724d0a9e4aecf5f9e9a27ce909553fd7f4 | 3,605,542 |
def find_tree_root(tree, key):
"""Find a root in a tree by it's key
:param dict tree: the pkg dependency tree obtained by calling
`construct_tree` function
:param str key: key of the root node to find
:returns: a root node if found else None
:rtype: mixed
"""
result = ... | 372bf64f3230fe01d4369ae79bd61edc503b0fd6 | 3,605,543 |
def get_initializer(initializer_config, seed=None):
"""Get variable initializer.
Args:
- initializer_config: Configuration for initializer.
Returns:
initializer: Instantiated variable initializer.
"""
if 'type' not in initializer_config:
raise ValueError('Initializer missi... | 7eb8f1d8bd21cc7b4d004e4034b2987a4da71765 | 3,605,544 |
import os
def run_with_context(function):
"""Context Decorator"""
def wrapper(*args, **kwargs):
db_uri = os.environ.get('LOD_DATABASE_URL', None)
if not db_uri:
log.error("Please, specify 'LOD_DATABASE_URL' variable.")
return
context = app_lod().app_context()... | aa4c8fffc039327bf171db70143affafa08e8da0 | 3,605,545 |
def einsum2(*args, **kwargs):
"""
einsum2(subscripts_str, arr0, arr1)
or,
einsum2(op0, subscript_list0, arr1, subscript_list1,
output_subscript_list)
This function is similar to einsum, except it only operates
on two input arrays, does not allow diagonal operations
(repeated sub... | 749c9f9a66a26dd0595a1c0a37ba02ccc2516557 | 3,605,546 |
def convert_str_to_list(sequence: str, is_ordered_sequence: bool = True, is_first_term_seq_name: bool = True):
"""
sequence: A string that contains a comma seperated numbers
is_first_term_seq_name: True to drop the first term (i.e. A01255,1,3,5, ...)
return: A list of integers in a list (String ---> Lis... | f73213ae3484e00824920722eb58368bb116886b | 3,605,547 |
def get_rotation_matrix(zone, verbose=False):
"""Calculates the rotation matrix to rotate the zone axis parallel to the cartasian z-axis.
We use spherical coordinates to first rotate around the z-axis and then around the y-axis.
This makes it easier to apply additional tilts, than to use the cross produc... | 87655da0deeceef16f241ed4038d53c9727167f1 | 3,605,548 |
def create_user(db: Session, user: schemas.UserCreate):
"""
Function to create user to `users` table and
password to `users_hashes` table.
Uses schemas.User to add to models.User
models.User attributes:
- user_id: int, non-nullable, unique
- username: str, non-nullable, unique
... | 884acde0899c8e88df45d6fa43e01c93c9873da8 | 3,605,549 |
def _terms_match(t1, t2):
"""check that all the fields in the first term t1 are in t2 and
have the same values
"""
for k, val in t1.items():
if k not in t2:
if val:
return False
else:
if k == 'parents' or k == 'slim_terms' or k == 'source_ontol... | 476a03057953d648d9097c9c2c920eaf0f5d44ed | 3,605,550 |
def get_obs_lsstSim_camera(log_level=lsstLog.WARN):
"""
Get the obs_lsstSim CameraMapper object, setting the default
log-level at WARN in order to silence the INFO message about
"Loading Posix exposure registry from .". Note that this only
affects the 'CameraMapper' logging level. The logging level... | 8cfda186f667cb88b4cbfd805dd04bfc735e0a34 | 3,605,551 |
from datetime import datetime
from dateutil import tz
import sys
def format_date(
dt: datetime.datetime, format: str = "%Y-%m-%d %H:%M:%S"
) -> str:
"""Format a date into a string.
Args:
dt: Datetime object to be formatted.
format: The format in string you want the datetime formatted to.
... | e3d3ac5134bf65c7fcfa3f4a6890767a6e2e08f8 | 3,605,552 |
def volume_down(y: np.ndarray, db: float):
"""
Low level API for decreasing the volume
Parameters
----------
y: numpy.ndarray
stereo / monaural input audio
db: float
how much decibel to decrease
Returns
-------
applied: numpy.ndarray
audio with decreased volum... | ac1d47681e25b4550f9c44d25e36ded9918e3b6c | 3,605,553 |
def get_random_idx(dataset, n_samples, seed=10):
"""Take random n images from target for comparison"""
n = n_samples
if len(dataset) < n:
n = len(dataset)
idx = list(range(len(dataset))) # Set pseudo idx list
currRandom = Random(seed)
r_idx = currRandom.sample(idx, n) # Sample idx
... | 930ad883c48d09f9657eb7c0bd6bf10037b77c47 | 3,605,554 |
def now():
"""<p>Get the current temperature, humidity and dewpoint for the
requested OMEGA iServer(s).</p>
<h3>Parameters</h3>
<ul>
<li>
<b>serial</b> : string (optional)
<p>The serial number(s) of the OMEGA iServer(s) to get the data from.
If requesting data from multipl... | 0c828aab44c124cc6f295e66c498eaa8a37ac874 | 3,605,555 |
def test_mixin_mi():
"""Does comparable mixin works w/ MI (other __new__'s get called)"""
class TestMixin(object):
def __new__(cls, *a, **ka):
newcls = super(TestMixin, cls).__new__(cls, *a, **ka)
newcls.foo = 'bar'
return newcls
class TestClass(TestMixin, Compara... | 40c0637107323e874724af863a98c2c435b14dfd | 3,605,556 |
def get_enrollment_attributes(user_id, course_id):
"""Retrieve enrollment attribute array"""
return _ENROLLMENT_ATTRIBUTES | 398f1a55287fa25af33e743629228801679d63b8 | 3,605,557 |
from pathlib import Path
import venv
def _create_new_venv() -> Path:
"""Create a new venv.
Returns:
path to created venv
"""
# Create venv
venv_dir = _create_tmp_dir()
venv.main([str(venv_dir)])
return venv_dir | f7874f4607476f98ba8defb8d5eee3298788dbfb | 3,605,558 |
def predict(features, weights):
"""
Given the input data features and the weight calls forward propogation and returns the index of value
the neural network is most confident in.
:param features: Numpy matrix of input data used to make prediction.
Each row is a training example an... | d4819903bdd481d3dacffb46d98521484eeffa3d | 3,605,559 |
from typing import Collection
def get_user_xp_rank(uid: int):
"""
Returns the xp rank of a user.
@param uid: int - The unique identifier of the user.
@return: rank: int
"""
try:
users: Collection = _db[config.mongodb_users]
xp = get_user(uid).xp
rank = users.count_docu... | 40ed043af2d57c87f6b051ea539c10924be56a54 | 3,605,560 |
def file2matrix(filename):
"""
Desc:
导入训练数据
parameters:
filename: 数据文件路径
return:
数据矩阵 returnMat 和对应的类别 classLabelVector
"""
fr = open(filename)
# 获得文件中的数据行的行数
numberOfLines = len(fr.readlines())
# 生成对应的空矩阵
# 例如:zeros(2,3)就是生成一个 2*3的矩阵,各个位置上全是 0
returnMat = zeros((... | 7ddc35998fcaea8e3f1877eec561ef710d2946fe | 3,605,561 |
import os
def extract_SENTINEL_date(sen_directory):
"""
extracts the acquisition date of SENTINEL scenes sorted earlier on into a new list
:return:
"""
SENTINEL_date_list = []
for filename in os.listdir(sen_directory):
timestamp = filename[8:18]
SENTINEL_date_list.append(os.pa... | 1688953656cbb48a088b5ed89159847cf66a17f7 | 3,605,562 |
def toFile(chant, filepath=None, showOptions=True, showSections=False,
showWords=False, showSyllables=False, showNeumes=False,
showMetadata=False, showMisalignments=True):
"""Export a Chant to an HTML file.
Args:
chant (chant21.Chant): A chant object
filepath (string, optional): If... | a83b0c94920c97daa2721e486ffeb3c56dc1444a | 3,605,563 |
from typing import Optional
import time
import random
import shutil
import warnings
def run_script(
script: Optional[str],
show_progress: bool = False,
produce: int = 40,
generate: int = 1000000,
seed: int = None,
verbose: bool = False,
swapping: int = 0,
outformat: str = "plain",
outfile: Optional[str] = N... | 7cccab89eebf6bc9a2491d28b4b2109c2d139293 | 3,605,564 |
import requests
import sys
import re
from bs4 import BeautifulSoup
def souper(url):
"""Turns a given URL into a BeautifulSoup object."""
try:
html = requests.get(url)
except requests.exceptions.RequestException:
print('''Dope was unable to fetch Stack Overflow results.
... | 4701c096b19a093eb16d169270368b7be6fe0344 | 3,605,565 |
from sys import path
def get_data(is_train_data=True, data_path=None):
"""
读取数据的函数,
:return: dic由 'ids','contents','characters','emotions' ,'merged_sentences'作为key
调用时可用 merged_sentences中的句子 句子形式 content + '[MASK]角色' + character
新增 key ‘link_content’ 向前拼接的句子 'link_content_merged' 句... | c5cdd3a5411a52b0ce2a332c34e5c94c8aa5891e | 3,605,566 |
import torch
def cbf_qp_filter(x, u_ref, relaxation_penalty):
"""Use the CBF QP to filter a provided reference control signal
args:
x: an N x 6 numpy array of states (x, y, z, vx, vy, vz)
u_ref: an N x 3 numpy array of controls (fx, fy, fz)
relaxation_penalty: the penalty to use for C... | 1c2cef18ed14c19d26c65803605cc32f4b6e65e8 | 3,605,567 |
def filter_chants_without_notes(chants, logger=None):
"""Exclude all chants without notes"""
notes_pattern = r'[89abcdefghjklmnopqrs\(\)ABCDEFGHJKLMNOPQRS]+'
contains_notes = chants.volpiano.str.contains(notes_pattern) == True
return chants[contains_notes] | 98324a2b9c17d975ebfc7860ad9ca38e65db481e | 3,605,568 |
def correct_eval_poly(d):
"""This function evaluates the polynomial poly at point x.
Poly is a list of floats containing the coeficients
of the polynomial
poly[i] -> coeficient of degree i
Parameters
----------
poly: [float]
Coefficients of the polynomial,
where poly[i... | 5a0042c0fb28a5fa4891f86b8b8fa70516fbed34 | 3,605,569 |
def parse_args_and_kwargs(parser, bits):
"""
Parses template tag arguments and keyword arguments
Returns a tuple ``args, kwargs``.
Usage::
@register.tag
def custom(parser, token):
return CustomNode(*parse_args_and_kwargs(parser,
token.split_contents()[1:]))... | 4075a1189ec1d2fbb331b6481f6599446d024d1d | 3,605,570 |
def stim_circuit_to_cirq_circuit(circuit: stim.Circuit) -> cirq.Circuit:
"""Converts a stim circuit into an equivalent cirq circuit.
Qubit indices are turned into cirq.LineQubit instances. Measurements are
keyed by their ordering (e.g. the first measurement is keyed "0", the second
is keyed "1", etc).
... | 82459bf32cc22ea2f4d0b9860ff485c24691a5aa | 3,605,571 |
import os
def start_replica_cmd(builddir, replica_id, view_change_timeout_milli="10000"):
"""
Return a command that starts an skvbc replica when passed to
subprocess.Popen.
Note each arguments is an element in a list.
"""
statusTimerMilli = "500"
path = os.path.join(builddir, "tests", "sim... | 729f38be646243a9e739668dfba6d2d1072cb3e5 | 3,605,572 |
def admit_dir(file):
""" create the admit directory name from a filename
This filename can be a FITS file (usually with a .fits extension
or a directory, which would be assumed to be a CASA image or
a MIRIAD image
"""
loc = file.rfind('.')
ext = '.admit'
if loc < 0:
return file ... | 12cf941054cdd1783f83095aa2e0bf1f3a9d980d | 3,605,573 |
import torch
def zeros(shape, dtype=None, device = None):
"""
Creates a tensor with all elements set to zero.
Parameters
----------
shape : A list of integers
a tuple of integers, or a 1-D Tensor of type int32.
dtype : tensor
The DType of an element in the resulting Tensor
... | e8e7b18a1f0d2999152504536709388440c56f1a | 3,605,574 |
import sys
def substr_count(space, haystack, needle, num_args, offset=0,
length=sys.maxint):
"""Count the number of substring occurrences."""
if len(needle) == 0:
space.ec.warn('substr_count(): Empty substring')
return space.w_False
if offset < 0:
space.ec.warn('su... | 6ce65931abaf56d1a55f00d85cdafdbb89929590 | 3,605,575 |
import os
def metrics(wildcards):
"""Get JSON output for each metric for a specific task, method and dataset."""
task = getattr(openproblems.tasks, wildcards.task)
return [
os.path.join(
TEMPDIR,
wildcards.task,
wildcards.dataset,
wildcards.method,
... | 3e15e467efc5f2efdfc49fdd4335718ca26543ab | 3,605,576 |
def _convert_timedelta_to_auto_off(full_time: timedelta) -> str:
"""Convert timedelta object for auto-shutdown to hexadecimal.
Args:
full_time: timedelta object represnting the auto-shutdown time.
Return:
Hexadecimal represntation of the full_time argument.
Raises:
aioswitcher.erros... | 987fd0fca7acf1e108ecafd1c1cb29cb814f3434 | 3,605,577 |
import functools
def output_validates_with_args(**kwargs_validators):
"""Decorator to validate output.
The validator can take the arguments of the decorated
function as its arguments.
"""
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
obj = f... | b948f6e3a470e037ccf4aff97f793ee357dd36c1 | 3,605,578 |
def seed_target_indices(seeds, targets):
"""Generate indices parameter for seed based connectivity analysis.
Parameters
----------
seeds : array of int | int
Seed indices.
targets : array of int | int
Indices of signals for which to compute connectivity.
Returns
-------
... | 22eb5527d7dd769a67fc299d84de2457af5d938b | 3,605,579 |
import sys
def start_persistent(address, callable, *args, **kw):
"""
Create a new process which shall be reachable using the given 'address' and
which will start running in the given 'callable'. Additional arguments to
the 'callable' can be given as additional arguments to this function.
Return ... | fa9fe960f991e2c0f3cef2a12e7e09d830e0814f | 3,605,580 |
import random
def chapter_uid_generator() -> str:
"""Random number generator for Mastroka chapter UIDs."""
return str(random.choice(range(int(1E18), int(1E19)))) | 024ea43a93d3e94576324364375542338b859d13 | 3,605,581 |
import os
import requests
import json
def Geocoding(long, lat):
"""
经纬度获取街道信息
:param long: 经度
:param lat: 维度
:return: 地址,json信息
"""
baidu_key = os.environ.get('baidu', '')
url = "http://api.map.baidu.com/geocoder/v2/?location=%s,%s&output=json&pois=1&ak=%s"\
%(lat, long, baidu_... | 01cf7f8bde7a365f70e67a5ef1cc6d2af74d00e5 | 3,605,582 |
def _send_tiddler_revisions(environ, start_response, tiddler):
"""
Push the list of tiddler revisions out the network.
"""
store = environ['tiddlyweb.store']
tmp_bag = Bag('tmp', tmpbag=True, revbag=True)
try:
for revision in store.list_tiddler_revisions(tiddler):
tmp_tiddle... | d78b5a6e3a466b7c722dba5e2d09ca744888c53f | 3,605,583 |
def get_path_cost(slice: np.ndarray = None, offset: int = 0, p1: float = 10, p2: float = 120) -> np.ndarray:
"""
Find the minimum costs in a D x M slice where M represents the number of pixels in the given direction.
:param slice: M x D array from cost volume
:param offset: ignore pixels at border
... | 3fb6510324d055e706aedcb8f2c3a25cf0d52d76 | 3,605,584 |
import tempfile
import json
def _get_run_command(wandb_run: wandb.apis.public.Run) -> str:
"""Return python run command for input wandb_run."""
with tempfile.TemporaryDirectory() as tmp_dirname:
wandb_file = wandb_run.file("wandb-metadata.json")
with wandb_file.download(root=tmp_dirname, repla... | e7f0f23e5f4c463043bda246e20aa2ee9b52cfa5 | 3,605,585 |
def Triangle_right (color, long, short = None, include_base = False, ** kwargs) :
"""Rule for a CSS triangle pointing right with `color`."""
if short is None :
short = long
rkw = dict \
( kwargs
, border_color = C_TRBL0 (l = color)
, border_width = TRBL (short, 0, short, l... | 208c5db32db496a8376bd496a0fe6392ef28a959 | 3,605,586 |
import os
from datetime import datetime
import math
def create_activity_widget(repo_name):
"""Creates a widget displaying the repository activity over the last 24 hours
:param repo_name: the repository to create the widget for
:type repo_name: str
:returns: a widget representing the activity data
... | e713638ed5b5e53795254539f3fa2f5f822b1a07 | 3,605,587 |
from datetime import datetime
def generate_header(header: str = "") -> str:
"""
Generates a file header.
Args:
header: A custom header to insert.
Returns:
str: The generated header of a file.
"""
syntax = " Warning generated file ".center(90, "-")
date = datetime.now().is... | 0821aef1f5f77dcd7b9fb1bcbcbca74749c3ed4a | 3,605,588 |
from typing import OrderedDict
def sort_precomputed(precomputed, all_pre_comp):
"""Sorts the precomputed equations in the given dictionary as per the
dependencies of the symbols and returns an ordered dict.
Note that this will not deal with finding any precomputed symbols that
are dependent on other ... | 79c24236566ea2726eb6cb228750f195fd778a11 | 3,605,589 |
def _mbits(num_bytes, duration_ms) -> float:
"""Return Mbit/s."""
mbits = (num_bytes * 8) / (1024 * 1024)
seconds = duration_ms / 1000
if seconds == 0:
return 0
return mbits / seconds | 8e4a1157ddb5f4d0361a553081aa8c6c3b0d62a6 | 3,605,590 |
def configure(**kwargs):
"""
Convenience function to merge multiple settings into the default global
config.
Example:
>>> import conjur
>>> conjur.configure(appliance_url='https://conjur.example.com/api',
... account='example',
... cert_path='/... | f200d89c76107569bd00367fb26bb10d0695412b | 3,605,591 |
def run_prb(path):
"""Execute the .prb probe file and import resulting locals return results as dict.
Args:
path: file path to probe file with layout as per klusta probe file specs.
Returns: Dictionary of channel groups with channel list, geometry and connectivity graph.
"""
if path is None... | 605bc61aa730d056ce5d8b07ad4753ea076eea89 | 3,605,592 |
def goto_definitions(script):
"""Get definitions for thing under cursor."""
return script.goto_definitions() | b614c72080b51e7c91100359cd863f9a8deae228 | 3,605,593 |
def get_main_path():
"""
Returns the working directory.
:return: A string containing the working directory path.
"""
return getcwd() | c86b233bb7fab1bbee695c551eacf468b3ed2eeb | 3,605,594 |
def hasActiveManifest(service):
"""
return the name of the active manifest under a specific __service
@param __service: name of __service
@return: existence of active manifest
"""
activePath = activeManifestPath(service)
return activePath is not None and activePath != '' | 42d908c1c8a931fd85ff8e0a332fc95c6944790e | 3,605,595 |
import argparse
def nstr(value):
"""String converter that checks for contents"""
value = value.strip()
if not value:
raise argparse.ArgumentTypeError("a non-empty, non-whitespace string is expected")
return value | 7b395e2384cc90956c5938a5d0717a8789eb8337 | 3,605,596 |
def constrain_mdl_obs_time(mdls, obs):
"""
This constrains all the models to the temporal range of the observations
"""
years = obs.coord('year').points
for cube in mdls:
years = np.intersect1d(years, cube.coord('year').points)
con = iris.Constraint(year=years)
out_mdls = []
fo... | 303528a3fcaf3bfe374e6486a772f5ce58833b95 | 3,605,597 |
def get_adgroup_df(ads_df, num_days=90):
"""
Adgroups - Look at the effectiveness of different ad groups in bounce and close rate.
* time windowed - look at the last 1, 7, 14, 28, and 90 days. Look for major changes in 1-7 and 7-28
"""
adgroups = ads_df.groupby('adgroup')
adgroup_df = adgroups.... | 1723064da39554cdc6ddea50d69a07ffc65c08b1 | 3,605,598 |
import torch
def pad_atomic_properties(atomic_properties, padding_values=defaultdict(lambda: 0.0, species=-1)):
"""Put a sequence of atomic properties together into single tensor.
Inputs are `[{'species': ..., ...}, {'species': ..., ...}, ...]` and the outputs
are `{'species': padded_tensor, ...}`
A... | e346a6f2111fe417d92ab702aaf7a104398654fa | 3,605,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.