content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def get_template_module(template_name_or_list, **context):
"""Return the python module of a template.
This allows you to call e.g. macros inside it from Python code."""
current_app.update_template_context(context)
tpl = current_app.jinja_env.get_or_select_template(template_name_or_list)
return tpl.... | e8326fe836331b1f715159e20e1a4df2dc00a278 | 3,618,900 |
def get_user_agents(config):
"""Loads user-agent from data file to local memory"""
user_agent_file = config["USER_AGET_DATA_FILE"]
user_agents = config["USER_AGET_DATA"] if "USER_AGET_DATA" in config else None
if not user_agents:
logger.info("Processing user agent data from file %s", user_agent... | 0f4d4950fc7d7dcd9b073a97ef14215f3ec3c3ef | 3,618,901 |
def writeArk(filename, features, uttids, append=False):
"""
Takes a list of feature matrices and a list of utterance IDs,
and writes them to a Kaldi ark file.
Returns a list of strings in the format "filename:offset",
which can be used to write a Kaldi script file.
"""
pointers = []
... | 0c8c25cdcec2f95983fd1c42afa9ede7e24f6c78 | 3,618,902 |
import os
def graph_to_string(graph: nx.MultiDiGraph, starting_node, level=0):
"""
String representation of `graph` for debugging purposes.
A class name is wrapped in brackets []. A function name is wrapped in parens ().
For example, a graph 'g' representing Python module 'main.py' that defines
f... | ef849a26f863216b47eb5dc05a1996ae91acc8d1 | 3,618,903 |
from datetime import datetime
def current_datetime_str(fmt="%Y%m%d_%H%M%S", ms=False, ms_prefix="_"):
"""Get the current datetime with second precision with default format ``YYYYMMDD_HHMMSS``"""
dt = datetime.datetime.now()
dt_str = dt.strftime(fmt)
if ms:
dt_str = dt_str + ms_prefix + str(dat... | 5637518e0bf4c3d446662cc354ec51b690f8473b | 3,618,904 |
def getRetiredPages(device, retiredType):
""" Return the retired pages for the specified type
Parameters:
device -- DRM device identifier
retiredType - Type of retired page to return (retired, pending, unreservable, all)
"""
returnPages = ''
pages = getSysfsValue(device, 'bad_pages')
if... | 0e08cfd8b80deb4903b1e99939549e8c4c7f5ed4 | 3,618,905 |
import random
def get_opening_sentences(season, day = None):
"""given a season (text), returns a dictionary with 'text' and 'verse"""
#TODO: special case for Ascension day: it should be using Easter opening sentences
if season in opening_sentences:
season_list = opening_sentences[season]
else:... | e048a0cca92471dee781f6a0d4bd2ca1bf2b2f17 | 3,618,906 |
import pathlib
import torch
from typing import Tuple
import logging
import re
def load_model_checkpoint(
load_checkpoint_dir: pathlib.Path,
model: torch.nn.Module,
optimizer: torch.optim.Optimizer,
) -> Tuple[int, torch.nn.Module, torch.optim.Optimizer]:
"""Loads the optimizer state dict and model sta... | d9d5dbfb93587c874821043ca0add5bee4d25b14 | 3,618,907 |
import tqdm
import random
def get_rand_patches_rand_cond(img, mask, n_patches=16000, sz=160, nclasses=6,
nodata_ascloud=True, method='rand'
) -> np.array:
"""
Generate training data.
:param images: ndarray in the format (w,h,c).
:param mask... | 15a82484e5ff87c9b1d4a4cf82742b39e2d5d214 | 3,618,908 |
def decode_example(example):
"""Decode a serialized example."""
example = tf.io.parse_single_example(
example,
{
"image": tf.io.FixedLenFeature([], tf.string),
"mask": tf.io.FixedLenFeature([], tf.string),
},
)
image = tf.image.decode_png(example["image"])... | d3381194361a627a1cc97c674c14ae223f3d0a8f | 3,618,909 |
def apply_dynamic_cleaning(image, signal_pixels, threshold, fraction):
"""
Application of the dynamic cleaning
Parameters
----------
image: `np.ndarray`
Pixel charges
signal_pixels
threshold: `float`
Minimum average charge in the 3 brightest pixels to apply
the dyn... | a64e907bafc477fb6d4e01ef7b275e7575035ba4 | 3,618,910 |
def select(con, id):
""" 指定したキーのデータをSELECTする """
cur = con.execute(
'select id, title_en, title_ja, description_en, description_ja, author, created from suggestions where id=?',
(id,))
return cur.fetchone() | 64f7f96c04dc533446835f6b6d06f7cc4530285e | 3,618,911 |
def save_params(net, best_metric, current_metric, epoch, save_interval, prefix):
"""Logic for if/when to save/checkpoint model parameters"""
if current_metric < best_metric:
best_metric = current_metric
net.save_parameters('{:s}_best.params'.format(prefix, epoch, current_metric))
with op... | 9af251965a4facc598c9a3d833f967511cc7b0ec | 3,618,912 |
def resize(data, number_rows=None, number_columns=None, lower=None, upper=None, categories=None, weights=None, distribution=None, shift=None, scale=None, sample_proportion=None, minimum_rows=None, **kwargs):
"""
Resize Component
Resizes the data in question to be consistent with a provided sample size,... | 458d6fd940655058622e4e6acbb38395036837ac | 3,618,913 |
def svn_uri_dirname(*args):
"""svn_uri_dirname(char const * uri, apr_pool_t result_pool) -> char *"""
return _core.svn_uri_dirname(*args) | b06fa82c95206bf0de6a53b37286752e962f53b1 | 3,618,914 |
from typing import Optional
def create_test_dl(df:pd.DataFrame, b:Optional[np.array]=None,
t_scaler:MaxAbsScaler=None, x_scaler:StandardScaler=None,
bs:int=128, only_x:bool=False) -> DataLoader:
"""
Take dataframe and return a pytorch dataloader.
parameters:
- df:... | 384de2ac68547e48be1a86cbee5293178f8d885a | 3,618,915 |
import math
def initialize_bot_settings(settings: Config) -> Config:
"""
Initialises the settings that are used within the bot to manage the contextual reminders
"""
settings.define_section("ctxreminders", ContextualRemindersSection)
settings.ctxreminders.configure_setting(
"persistence_... | 15ac9073e8cafdb2a604072014a8a9ae12ba260e | 3,618,916 |
from mturk.models import Experiment
from mturk.cubam import update_votes_cubam
from photos.tasks import update_photos_num_intrinsic
def update_votes_cubam(show_progress=False):
""" This function is automatically called by
mturk.tasks.mturk_update_votes_cubam_task """
# responses that we will consider
... | 00d2c20f56f9cc82f5c8f5c0f8a01dc8858c6c69 | 3,618,917 |
from models.yolo import Detect
import torch
def from_pretrained(chkpt, model_dir=None, force_reload=False, **kwargs):
"""
Kwargs:
bucket(str): S3 bucket name
key(str): path in an S3 bucket
"""
stem, suffix = chkpt.split('.')
tag = kwargs.get('tag', 'v6.0')
s3 = kwargs.get('s3'... | 811a0a0f57e03ca30f84c512d3b1252b8bcb25b3 | 3,618,918 |
def generate_multilabel_ensemble_classification_outputs(classifiers, n_classes, n_samples, continuous_out=False,
parallelize=True):
"""
Generate random multilabel crisp classification outputs (assignments) for the given ensemble of classifiers with
th... | cfae74cb5185c98370da81666c0fc65be21d04fb | 3,618,919 |
from ActiveLearning import prepare_for_inference
from io import StringIO
def test_prepare_for_inference(monkeypatch):
"""
There are only 2 records in the input.manifest and they both are sent to batch transform.
"""
def mock_copy(*args, **kwargs):
source = args[0]
dest = args[1]
... | d05f95232b0e86a23c14371562d2b8a63007f6b4 | 3,618,920 |
def nvisitsM5Maps(colmap=None, runName='opsim',
extraSql=None, extraMetadata=None,
nside=64, runLength=10.,
ditherStacker=None, ditherkwargs=None):
"""Generate number of visits and Coadded depth per RA/Dec point in all and per filters.
Parameters
------... | 2122caded6dacb8ff8cef4b5ed07070f4130f066 | 3,618,921 |
import os
import json
def load_map(indexing_dir):
"""获得1.栏目id到内容视频的idx序列, 2.视频id到idx 的映射"""
res = []
file_list = ["cid2vidx.json", "vid2idx.json"]
for file in file_list:
file_path = os.path.join(indexing_dir, file)
with open(file_path, "r", encoding="utf8") as fp:
res.appe... | ec9eb9fc379e35c76d175567ad3408f8b0d893fc | 3,618,922 |
def create_3d_trap(radius, height, delta):
"""Creates a 3D surface plot showing the trap and the beach.
Args:
radius: the radius of the trap
height: the height of the trap
delta: how far along the beach the center of radius r circle the semicircular trap could be in
returns:
... | 10d7001fbb04c151f28aa94096411e93501a0527 | 3,618,923 |
import logging
def get_logger(name, log_file=None, log_level=logging.INFO):
"""Initialize and get a logger by name.
If the logger has not been initialized, this method will initialize the
logger by adding one or two handlers, otherwise the initialized logger will
be directly returned. During initializ... | 15d38780c68b4a8d667b7bbfb2cc9b1085a7b637 | 3,618,924 |
def convert_pyte_buffer_to_colormap(buffer, lines):
"""
Convert a pyte buffer to a simple colors
"""
color_map = {}
for line_index in lines:
# There may be lines outside the buffer after terminal was resized.
# These are considered blank.
if line_index > len(buffer) - 1:
... | d16e8aeeb327bfa75af3ba76d339c0a2538dcfa7 | 3,618,925 |
def find_offsets_local_direction(
centered_patches: tf.Tensor, delta: float
) -> tf.Tensor:
"""Computes subpixel offsets from the direction of the pixels around the peak.
This function finds the delta-offset from the center pixel of peak-centered patches
by finding the direction of the gradient around ... | 6f9ddcbb1ef799d0a51631057bf0b731fedccc78 | 3,618,926 |
def to_device(data, device):
"""Move tensor (s) to chosen device"""
if isinstance(data, (list, tuple)):
return [to_device(x, device) for x in data]
return data.to(device, non_blocking=True) | 15f8af4512bf110fa5c8364a7d223725a8c00ce5 | 3,618,927 |
def push_branch_set_upstream(git_dir, branch_name):
""" Push new branch to remote.
"""
try:
# this will ask username/password
git('-C', git_dir, 'push', '--set-upstream', 'origin', branch_name)
except ErrorReturnCode as e:
return failed_util_call_results(e)
else:
retu... | 3ab68134a1d326f752a65b2bc161dc6c6ffa918a | 3,618,928 |
import array
def interpolate_g(xi,yi,zi,xx,yy,knots=10, error=False,mask=None):
"""Create a grid of zi values interpolating the values from xi,yi,zi
xi,yi,zi 1D Lists or arrays containing the values to use as base for the interpolation
xx,yy 1D vectors or lists containing the output coordinates... | 2c14aa5dfd7b968480fe58fb25c69fdaf37b7890 | 3,618,929 |
def knownTypes():
"""
Returns known types.
@ In, None
@ Out, __knownTypes, list, list of known types
"""
return __knownTypes | 19f327ec8167d5390986cf669d2609b0b0c78d57 | 3,618,930 |
def histogram_reads(bam_file, windowsize, chromosomes='all', exclude_chroms=['chrM', 'chrY', 'chrX'],
skip_qc_fail=True):
"""Histogram the counts along bam_file, resulting in a vector.
This will concatenate all chromosomes, together, so to get the
counts for a particular chromosome, pas... | 04838104e02d577285061d150e689d8b975cbfd4 | 3,618,931 |
def single_load(input_, ac_parser=None, ac_template=False,
ac_context=None, **options):
"""
Load single configuration file.
.. note::
:func:`load` is a preferable alternative and this API should be used
only if there is a need to emphasize given input `input_` is single one.
... | d77a3001c0c522571488f5b189f2ef616087f84b | 3,618,932 |
from typing import IO
from typing import List
def read_abbrevs(abbrevs: IO[str]) -> List[Abbrev]:
"""Parse the XML from `abbrevs` into a list of `Abbrev` objects."""
root = ET.parse(abbrevs).getroot()
r = [] # type: List[Abbrev]
for node in root.findall('source'):
spellouts = [
no... | c4db816b311157910bac1fa1924ea833e0a6df1d | 3,618,933 |
def deleteTemplate(**kargs):
""" Delete Template (OS Image) of Your VM
* Args:
- zone(String, Required) : [KR-CA, KR-CB, KR-M, KR-M2]
- id(String, Required) : Template ID
* Examples : print(server.deleteSnapshot(zone='KR-M', id='6a59215f-df8b-4633-9a55-c42ac41b3467'))
"""
my_apik... | 6c05397b612121afda5ebadf1f6f449a69a62bd8 | 3,618,934 |
def create_session(checkpoint_path, target_device):
"""Create ONNX runtime session"""
if target_device == 'GPU':
providers = ['CUDAExecutionProvider']
elif target_device == 'CPU':
providers = ['CPUExecutionProvider']
else:
raise ValueError(
f'Unsupported target device... | cec11aeca9c3c5ca974e2d290bf2652cf7f1c6eb | 3,618,935 |
def support_vector_regressor(x_train: list, x_test: list, train_user: list) -> float:
"""
Third method: Support vector regressor
svr is quite the same with svm(support vector machine)
it uses the same principles as the SVM for classification,
with only a few minor differences and the only different ... | d820aa66a1a63a1974d1ab9bb0aa2d43a4c917d1 | 3,618,936 |
def _get_default_session():
"""
Get the default session, creating one if needed.
:rtype: :py:class:`~boto3.session.Session`
:return: The default session
"""
if DEFAULT_SESSION is None:
setup_default_session()
_warn_deprecated_python()
return DEFAULT_SESSION | 33fd60704fba9cbc03aa8be1ee18d5dc29c047e6 | 3,618,937 |
import random
def read_meminfo():
"""
Mocks read_meminfo as this is a Linux-specific operation.
"""
return {
"MemTotal": random.randint(0, 999999999),
"MemFree": random.randint(0, 999999999),
"MemAvailable": random.randint(0, 999999999),
"HugePages_Total": random.randin... | 6bdf66ded424748736875d70eae4b54d4a820c28 | 3,618,938 |
def irfft(x, axes):
"""
like np.fft.irfft
"""
return core.Result(core.IRFFT(axes),[x]) | 1b178a85b63562fbefea5b19bd9e512205f7df9d | 3,618,939 |
def set_tmin(ndvar, tmin=0.):
"""Change the time axis of an :class:`NDVar`
Parameters
----------
tmin : scalar
New ``tmin`` value (default 0).
Returns
-------
out_ndvar : NDVar
Shallow copy of ``ndvar`` with updated time axis.
"""
axis = ndvar.get_axis('time')
o... | 9c7e6423c8362d98f1bfa0f0e9abbad4c4e54dcd | 3,618,940 |
import requests
import logging
def place_by_name(place, key, FIND_PLACE=FIND_PLACE):
"""Finds a Google Place ID by searching with its name.
Args:
place (str): Name of the place. It can be a restaurant, bar, monument,
whatever you would normally search in Google Maps.
key (str): Ke... | 5b645b50f9401a42b0a08f20ab7d1e18df4322e2 | 3,618,941 |
import torch
def spearmanr(pred, target, eps=1e-6):
"""
Spearman correlation between target and prediction.
Implement in PyTorch, but non-diffierentiable. (validation metric only)
Parameters:
pred (Tensor): prediction of shape :math: `(N,)`
target (Tensor): target of shape :math: `(N,... | 683810c611288bd4d6c0fa08b8da8005f7ef10ce | 3,618,942 |
def kappa_adj_err_fn(speed, a, b):
"""
:param a: the slope parameter of the adjustment function
:param b: the bias parameter of the adjustment function
"""
global good_a
global good_b
simulator = SingleCue(cue="wind")
rel_model = ReliabilityModel()
iterations = 100
r_averages =... | 56fa4681fe41e826809f5a66944a097ea243d476 | 3,618,943 |
def do_request(cur, method="GET"):
"""
GET API should provide a json with the following fields:
state: str - can be:
"idle" - before anything is done, or after camera is stopped (to be implemented with push button)
"ready" - camera is initialized
"capture" - camera is capturing
r... | 7eed2b9096c7b8c9fc93386915e27a44f54b1a88 | 3,618,944 |
def reconnect_on_remote_close(f):
"""
lockdownd's _socket_select will close the connection after 60 seconds of "radio-silent" (no data has been
transmitted). When this happens, we'll attempt to reconnect.
"""
def _reconnect_on_remote_close(*args, **kwargs):
try:
return f(*args, ... | 1cf8729f39e85333cf05ae3154b76476a02c1ab7 | 3,618,945 |
def showstack(ui, repo, displayer):
"""current line of work"""
wdirctx = repo[b'.']
if wdirctx.rev() == nullrev:
raise error.Abort(
_(
b'stack view only available when there is a '
b'working directory'
)
)
if wdirctx.phase() == pha... | 3adde49f9b97f501437401b5e6119b9c6c4dded0 | 3,618,946 |
import bisect
import numpy
import traceback
import pdb
def matchTimes(primary_dt,dt,tol_s=1,tol_us=4e5,fail_on_duplicates=True,allow_duplicates=False,warn_no_match=False):
"""
Finds a matching timestamp in primary_dt
within tolerance tol_us (given in microseconds)
for every value in dt.
Inputs:
-------
dt - ... | 1245e1a24e4c521eb9d56319bf3889b99ba99c72 | 3,618,947 |
import tokenize
import warnings
def build_model():
"""
- Build model with GridSearch
Returns:
Trained model with GridSearch
"""
pipeline = Pipeline([
('features', FeatureUnion([
('text_pipeline', Pipeline([
('vect', CountVectorizer(tokenizer=tokenize)),
... | e2017e5c99b0d2629393e045e0b50cf48f0bf5e9 | 3,618,948 |
import attr
def _get_field_default(field: attr.ib):
"""
Return a marshmallow default value given a dataclass default value
>>> @dataclass
... class A:
... x: int = attr.ib()
>>> _get_field_default(attr.fields(A).x)
<marshmallow.missing>
"""
if isinstance(field.default, attr.Fa... | 13ab7ac7edaa020b3bc32024def093d20e8f5d6e | 3,618,949 |
def str_to_vec(sequences):
"""converts nucleotide strings into vectors using a 2-bit encoding scheme."""
vecs = []
nuc2bit = {"A": (0, 0),
"C": (0, 1),
"T": (1, 0),
"G": (1, 1)}
for seq in sequences:
vec = []
for nuc in seq:
vec.ap... | 952e35253c275ef4424410b024338da1a11b20e7 | 3,618,950 |
import operator
def vector_add(a, b):
"""Component-wise addition of two vectors.
>>> vector_add((0, 1), (8, 9))
(8, 10)
"""
return tuple(map(operator.add, a, b)) | 2144a02128ffa8712cfb998045ede1ca9308650f | 3,618,951 |
def gen_fill_suffix_row(row, name_to_suffix_dict,
street_name_col, street_suffix_col,
suggested_name_col=None, suggested_suffix_col=None):
""" Returns a callable that suggests suffix based on row information
Args:
row: a row in DataFrame
name_to_su... | 388a801a88d8067a94dd9e8354a792713dad36df | 3,618,952 |
def classify_fragmentation_for_mitochondria(label_mask, skeletons):
"""
Performs mitochondria fragmentation based off the labels mask and skeletons mask
:param label_mask:
:param skeletons:
:return:
"""
# what if no mitochondria currently found?
# what if we want to compare the surface ... | 05e23703b274cdd50867b341586bf5d8040d6f91 | 3,618,953 |
def from_angle(theta: float) -> Vector2:
"""
Create a unit vector from an angle relative to the positive x-axis.
"""
return Vector2(cos(theta), sin(theta)) | 35f510f4cdcaa05500ee27f7defc0c12d97d131a | 3,618,954 |
def neg(left):
"""
Negative of a distribution.
Args:
dist (Dist) : distribution.
"""
if not isinstance(left, Dist):
return -left
return Neg(left) | 5543ae8d3367fa9f92f3daba8855ae053dfdf234 | 3,618,955 |
import configparser
def initialize_from_tar(tar_path, is_full=False, clean_up=False):
"""Initialize from a remote TAR"""
# Step 1 is to unpack our TAR. Let's delete what was there first.
utils.delete_tree(dtfglobals.DTF_INCLUDED_DIR)
__unpack_included(tar_path)
# Next, we do the the auto config... | a0c8637a49212b4263bff905a7ba4b47a8896076 | 3,618,956 |
import json
def get_aws_key_and_secret(aws_creds_file_path):
""" Given a filename containing AWS credentials (see README.md),
return a 2-tuple (access key, secret key).
"""
with open(aws_creds_file_path, 'r') as f:
creds_dict = json.load(f)
return creds_dict['accessKeyId'], creds_dict[... | b3eae6ee0283a7245d37f92b5a5f4ef1102e248d | 3,618,957 |
def group_service(app):
"""Group service."""
return current_groups_service | cb484b9664bd21ca5706a085ba8e9cc2e002b72c | 3,618,958 |
import copy
def iterate(q, A_unrestrained, B, resp_a, resp_b, ihfree, symbols, toler, maxit, num_conformers):
"""Iterates the RESP fitting procedure
Parameters
----------
q : ndarray
array of initial charges
A_unrestrained : ndarray
array of unrestrained A matrix
B : ndarray
... | 3b477be0bdb0e8bcfd17404342f46f27a45839d2 | 3,618,959 |
import email
def get_filename(part):
"""
Find the filename of a mail part. Many MUA send attachments with the
filename in the I{name} parameter of the I{Content-type} header instead
of in the I{filename} parameter of the I{Content-Disposition} header.
@type part: inherit from email.mime.bas... | 638690299167e6025826372bdccfb207acdd788c | 3,618,960 |
def next_frame_stochastic_emily():
"""Emily's model."""
hparams = next_frame_stochastic()
hparams.latent_loss_multiplier = 1e-4
hparams.learning_rate_constant = 0.002
hparams.add_hparam("z_dim", 10)
hparams.add_hparam("g_dim", 128)
hparams.add_hparam("rnn_size", 256)
hparams.add_hparam("posterior_rnn_la... | 35cf839326ebfa5be3c0f6ef84d15537640441f4 | 3,618,961 |
import json
def test_get_vim_info(get_vim_info_keys):
"""Tests API call to get the information about individual vim"""
osm_admin = OSMClient.Admin(HOST_URL)
osm_auth = OSMClient.Auth(HOST_URL)
_token = json.loads(osm_auth.auth(username=USERNAME, password=PASSWORD))
_token = json.loads(_token["data... | 075eab419e614ec640a495f50d0ffc87abdb8b70 | 3,618,962 |
def twix2DCMOrientation(mapVBVDHdr, force_svs=False, verbose=False):
""" Convert twix orientation information to DICOM equivalent.
Convert orientation to DICOM imageOrientationPatient, imagePositionPatient,
pixelSpacing and sliceThickness field values.
Args:
mapVBVDHdr (dict): Header info inte... | b3346b399b8ed0b1f4066eaf8a3d71ca6c4991a7 | 3,618,963 |
def axial_mixture_unidir(x, config, is_training=True, causal=True):
"""Full attention matrix with axial pattern as local and mixture for global summary."""
del is_training
assert causal
bsize = x.shape[0]
query, key, value = attention.get_qkv(x, x, x, hidden_size=config.model_size,
... | 9ce028def7dc4e48585764333554ba7cb2cd55b9 | 3,618,964 |
def get_git_hash():
""" Return the current git hash """
repo = git.Repo(search_parent_directories=True)
return repo.head.object.hexsha | 7483ae16acb43dab1774c5b5a505f7ce95b4a9d1 | 3,618,965 |
import pickle
def _eval_once(session_creator, ops_dict, summary_writer, merged_summary,
global_step, num_examples, input_data, labels, unique_groups, fair_margin_over_epochs, FLAGS, config):
"""Runs evaluation on the full data and saves results.
Args:
session_creator: session creator.
ops_... | 4e60d450e4a11bf1e9ceb370c4d247c59709916b | 3,618,966 |
def project_ABA(A, B):
"""
Project matrix of K vectors, a_k, onto Hermitian matrix B
Projects each of K vectors, a_k, in matrix, A, of dimension K x M
onto a Hermitian matrix, B, of dimension M x M producing a
vector of scalars, c, of length K
Parameters
----------
... | 3ef84870ce3ac2a1a7cc62eccfc14024da585af1 | 3,618,967 |
def plcc_loss(x, y):
"""Loss version of `plcc_tf`"""
return (1. - plcc(x, y)) / 2. | f457389775d6d46ef55eeae97282c6c5c026458a | 3,618,968 |
def replicas_to_qps(num_replicas, processing_time, max_qp_replica=1, target_utilization=0.7):
"""Provide a rough estimate of the queries per second supported by a number of replicas
Args:
num_replicas (int): number of replicas
processing_time (float): the estimated amount of time (in secon... | a944ca4b6bbc60279c18360f396f2660be23f599 | 3,618,969 |
async def retrieve_address_by_id(
address_id: int, db: MSSQLConnection = Depends(get_db)
) -> AddressResponse:
"""
**Retrieves an address with the id from the `address_id` path parameter.**
"""
address = await AddressService(db).get(address_id)
if address is None:
raise HTTPException(sta... | 2c6d75ea860bfb67bcbec5e65af81e942104a661 | 3,618,970 |
from typing import Optional
def sqrt(x: VariableLike, *, out: Optional[VariableLike] = None) -> VariableLike:
"""Element-wise square-root.
:param x: Input data.
:param out: Optional output buffer.
:raises: If the dtype has no square-root, e.g., if it is a string.
:return: The square-root values o... | 216085ed06420f71cd7aaaff2db7d5272534920d | 3,618,971 |
def filter_tree(tree: pd.DataFrame, filterids: list or str or None = None,
root: str = "1", ignoreinvalid: bool = True, sep: str = None, indx: int = 0) -> pd.DataFrame:
"""
Filters an existing pandas DataFrame based on a List of TaxIDs.
:param tree: pandas DataFrame
:param filterids: li... | dfc542fbcc49dd75ecae6d35bf9f2462f2923ebd | 3,618,972 |
def multinomial_coeffs_of_power_of_nd_linear_monomial(num_vars, degree):
""" Compute the multinomial coefficients of the individual terms
obtained when taking the power of a linear polynomial
(without constant term).
Given a linear multivariate polynomial e.g.
e.g. (x1+x2+x3)**2 = x1**2+2*x1*x2+2*... | 05b402488616452c72445505aa07bae2bbf973ec | 3,618,973 |
def _get_split_rows(input_array, num_of_sections):
""" Split array by the number of valid cells (not NaNs) on each rows
input_array : an array with some NaNs
num_of_sections : (int) number of sections that the array to be splited
return split_rows : a list of row subscripts to split the array
Split ... | 1efe71bb83f97365fb0a6d5e09df726d0b0d2bcb | 3,618,974 |
def probability(df, features):
"""
Calculates the occurence probability of all the categories for every feature.
Parameters
----------
df : panda dataframe
the dataset of the population
features : dictionary
a dictionary of features with keys as feature name and val... | 7f46f2ec0fa69b22fea0a2b4a0e9ffc691630b1d | 3,618,975 |
from typing import Deque
import collections
import fractions
from typing import cast
def clip_to_timecodes(src_clip: vs.VideoNode) -> Deque[float]:
"""
Cached function to return a list of timecodes for vfr clips.
The first call to this function can be `very` expensive depending on the `src_clip`
leng... | b331e6de49a1fb768775c6559d1b18a3169d12b0 | 3,618,976 |
def numeric_map(lookup, numeric_stops, default=0.0):
"""Return a number value interpolated from given numeric_stops
"""
# if no numeric_stops, use default
if len(numeric_stops) == 0:
return default
# dictionary to lookup value from match-type numeric_stops
match_map = dict((x, y) fo... | 0f9868fb8e0e1036cd9581cbf3babe0f8ec86b43 | 3,618,977 |
import logging
def index():
"""
code and variables for when the page refreshes
"""
logging.info("Loading updated Website")
#calls the function which calls the functions which are needed to perform the tasks which the user specifies
manage_url()
#runs the scheduler
s.run(blo... | 2b3667b302f3e70467da7263ee3f78f5d4dfda84 | 3,618,978 |
def greedy_remove(text_before, guesses_before, n_keep):
"""Remove words from the question while trying to keep the original
predictions
Args:
text_before: the text before removal
guesses_before: a dictionary of scores of guesses as the starting point
n_keep: number of words to ke... | eef589ec7793c00473ff180574b809ce1df81eb8 | 3,618,979 |
import os
import json
def get_all_logins():
"""Get the login details from the encrypted text store."""
cipher_suite = Fernet(FERNET_KEY)
if os.path.exists("src/bga_keys"):
with open("src/bga_keys", "rb") as f:
encrypted_text = f.read()
text = cipher_suite.decrypt(encrypted_... | b7ac4e9d208baf3338e29c113b06c17d3839c46e | 3,618,980 |
def get_msa_site(pro_id, seq, site, res, verbose=True):
"""TODO: Please check the surrounding residues
"""
cnt = -1
msa_site = -1
for i in range(len(seq)):
if seq[i] != "-": # and seq[i] != "?" # and seq[i] != "X"
cnt += 1
if cnt == site:
msa_site = i
... | 1a84e2c3c8dfdfc896c8e94a8b108cef8382b998 | 3,618,981 |
def freq_id_to_stream_id(f_id):
""" Convert a frequency ID to a stream ID. """
pre_encode = (0, (f_id % 16), (f_id // 16), (f_id // 256))
stream_id = (
(pre_encode[0] & 0xF)
+ ((pre_encode[1] & 0xF) << 4)
+ ((pre_encode[2] & 0xF) << 8)
+ ((pre_encode[3] & 0xF) << 12)
)
... | f89d52adf4390f665e069c2b5f4f5accc22709b8 | 3,618,982 |
def paypal_cancel(request):
""" Render paypal_cancel.html template when the user click cancel during a purchase process in PayPal."""
args = {'post': request.POST, 'get': request.GET}
return render(request, 'paypal/paypal_cancel.html', args) | 869a011f3e58385dfd1dc78b5319e63df3e0a940 | 3,618,983 |
def contourf(x, y, z, xlabel='x', ylabel='y', xlim=None, ylim=None,
legend=None, **kwargs):
"""Plots a filled countour plot of z vs. x and y in a single frame."""
fig, ax = plt.subplots()
lvls = np.linspace(np.min(z), np.max(z), 150)
l1 = ax.contourf(x, y, z, levels=lvls, zorder=-9, **kwarg... | 52f300cf044bb170d9a20f36d512f9d8e01e7875 | 3,618,984 |
def convolve2d(imagee, kernell):
"""
This function which takes an image and a kernel and returns the convolution of them.
:param image: a numpy array of size [image_height, image_width].
:param kernel: a numpy array of size [kernel_height, kernel_width].
:return: a numpy array of size [image_heigh... | c24fd944d19336ebb2ac6094ac6123e5c416eb5a | 3,618,985 |
def text_format(text: str, text_size: int, text_color: tuple, text_font_location: str = font):
"""Template for creating text in pygame. Reformation of the size and color
Parameters:
text (str): The input text to be formatted
text_size (int): The text size of the formatted text
text_colo... | 7ffd56953967304f42925d37317a1b30bb5ef907 | 3,618,986 |
import math
def _weight_fn(x, weight=None, inverse=False):
"""
Implement the polynomial weight function described in the paper.
Y = X^weight and
Y = X^(1 / weight) as the inverse.
>>> _weight_fn(2)
2.2973967099940698
>>> _weight_fn(2, weight=2)
4.0
>>> _weight_fn(2, weight=2, inv... | 36b342e209b7805c164b0d9a6f450b70c807bfc6 | 3,618,987 |
from typing import Counter
def id_to_name(transcription, mapping={}, composed=False):
"""Takes transcription annotated with entities and updates/outputs a dict mapping
entity identifier and counted proper names
"""
for i, token in enumerate(transcription):
# keep only proper names
if p... | 125b0c1aaeb251023d4e0a7c438aee7842ba0b46 | 3,618,988 |
import os
def get_all_folders(path):
"""
:param path:
:return:
"""
return [path + '/' + i for i in os.listdir(path)] | ba944c8d2bec3450fdf4fb1fc7b60e7675ddce7a | 3,618,989 |
def cgtransformation_to_rgtransform(cgT):
# type: (compas.geometry.Transformation) -> Rhino.Geometry.Transform
"""Convert :class:`compas.geometry.Transformation` to :class:`Rhino.Geometry.Transform`.""" # noqa: E501
_ensure_rhino()
M = cgT.matrix
return matrix_to_rgtransform(M) | 6000f87064030ccbe35c7ea74509c63af4bfb745 | 3,618,990 |
def fadein(clip, duration, initial_color=None):
"""
Makes the clip progressively appear from some color (black by default),
over ``duration`` seconds at the beginning of the clip. Can be used for
masks too, where the initial color must be a number between 0 and 1.
For cross-fading (progressive appea... | 3b17b1090a7fa1bab789d6da7d9ac862d099e88a | 3,618,991 |
import pickle
import time
def evaluate(weight_file_path, data_dir, output_dir, prob_thresh=0.5, nms_thresh=0.1, lw=3, display=False):
"""Detect faces in images.
Args:
prob_thresh:
The threshold of detection confidence.
nms_thresh:
The overlap threshold of non maximum suppression
weight... | c2a5596cec7f2eefcde51771ce49edc08baedf50 | 3,618,992 |
def count_occupied_fields(window, player):
"""" Count number of occupied fields by 'player' in 'window'. """
count = np.count_nonzero(window == player)
return 0 if count is None else count | 68d6a7216292638d919a7c121821050cadf8c610 | 3,618,993 |
def covariance(x):
"""Compute array covariance matrix.
:param x: narrowband complex timeseries data for multiple sensors (row per sensor)
"""
cov_mtx = _np.zeros((x.shape[0], x.shape[0]), dtype=_np.complex)
for j in range(x.shape[1]):
cov_mtx += _np.outer(x[:,j], x[:,j].conj())
cov_mtx ... | 9a91875f694dba23c2f06341b878991f1a2528eb | 3,618,994 |
def fix_trimap(trimap, lower_threshold=0.1, upper_threshold=0.9):
"""Fixes broken trimap :math:`T` by thresholding the values
.. math::
T^{\\text{fixed}}_{ij}=
\\begin{cases}
0,&\\text{if } T_{ij}<\\text{lower_threshold}\\\\
1,&\\text{if }T_{ij}>\\text{upper_threshold}\\... | 2d6ab770d9bedc1cb9ba5cc6fe2b51ce0bcff28d | 3,618,995 |
import random
def get_hash_tags(sentence, be_class_verb, subj_obj_list, seed=0, max_outputs=1, nlp=None):
"""method for appending hashtags to sentence"""
verb, hashtag_list = extract_hashtags(sentence, nlp, be_class_verb, subj_obj_list)
transformation_list = []
for _ in range(max_outputs):
ran... | f39f8041b7693a451f8aefb1aa65f72154413cb2 | 3,618,996 |
def get_tune(tune):
"""
Convert a tune value to a frequency.
"""
if isinstance(tune,str):
try:
tune = _TUNE_A * 2.**(_NOTES[tune]/12.)
except KeyError as e:
raise ValueError("If `tune` is provided as a string, it has to be any of "+str(list(_NOTES.keys())))
... | f78b4fecb7ce90a8288931466ecd66f1f7583f1c | 3,618,997 |
def aspheric_surface_equation(r, d, k, radius_of_curvature):
"""
Representation of the aspheric surface function.
"""
l = np.sqrt((radius_of_curvature * radius_of_curvature) - ((1 + k) * np.multiply(r, r)))
num = np.multiply(r, r)
den = radius_of_curvature + l
z = num / den + d
return ... | 5f598f7c45a994c0d29ce4c4be58aa3a2fd11fc5 | 3,618,998 |
import doctest
from crds.core import utils
def test():
"""Run doctests."""
return doctest.testmod(utils) | 09409cae8aa5708907b177a455a66df6a94c6c77 | 3,618,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.