content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def jwt_decode_token(token):
"""Register jwt decode handler
:param token:
"""
return jwt_lib.decode(token, current_app.config['JWT_SECRET_KEY'],
algorithms=current_app.config['JWT_ALGORITHMS']) | 274ebd03f6ca42436eeb8963a5d34777c68395f1 | 3,631,158 |
def renormalize_vector(a, scalar):
"""This function is used to renormalise a 3-vector quantity.
Parameters
----------
a: np.ndarray
The 3-vector to renormalise.
scalar: Union[float, int]
The desired length of the renormalised 3-vector.
Returns
-------
a: np.ndarray
... | 583c66621a0de2a2555104aed3a2dbb2e6302936 | 3,631,159 |
def load_data(path='affnist.npz'):
"""Loads the affnist dataset.
x_train: centered MNIST digits on a 40x40 black background
x_test: official affNIST test dataset (MNIST digits with random affine transformation)
# Arguments
path: path where to cache the dataset locally
(relative to ... | 474276570b0c05de09e397cb8d72d728de16a6f0 | 3,631,160 |
from re import T
def as_register_event_listener(
callback: EventCallback[RegisterEventEvent[T]]
) -> ListenerSetup[RegisterEventEvent[T]]:
"""A ListenerRegistraror type"""
return (EVENT_ID_REGISTER_EVENT, callback,) | 16017d437117462ddf60c1e98422379f37ee0303 | 3,631,161 |
def read_frame(frame_dir, model_name, scale_size=[480]):
"""
read a single frame & preprocess
"""
cv2_models = ['dino.vit', 'dino.conv', 'deit', 'mlp_mixer', 'resnet50', 'resnet152', 'resnet200', 'resnext', 'beit']
if model_name in cv2_models:
img = cv2.imread(frame_dir)
ori_h, ori_w, _ = img.shape
else:
... | a0ad77bcf0bf6b0c0118bd1cf83b8360d40df320 | 3,631,162 |
import collections
import random
def gen_undirected_graph(nodes = 1000, edge_factor = 2, costs = (1,1)):
"""
generates an undicrected graph with `nodes` nodes and around `edge_factor` edges per node
@param nodes amount of nodes
@param edge_factor approximate edges per node, might happen that som... | e46efd02805e82670703f456c979990a768af09f | 3,631,163 |
def compute_lpips(image1, image2, model):
"""Compute the LPIPS metric."""
# The LPIPS model expects a batch dimension.
return model(
tf.convert_to_tensor(image1[None, Ellipsis]),
tf.convert_to_tensor(image2[None, Ellipsis]))[0] | 3067a5ca312dead8308fa0b573e2853bbd590ab2 | 3,631,165 |
def int2bin(n, count=16):
"""
this method converts integer numbers to binary numbers
@param n: the number to be converted
@param count: the number of binary digits
"""
return "".join([str((n >> y) & 1) for y in range(count-1, -1, -1)]) | 70ce01844c8e32eb24750c4420812feda73a89dd | 3,631,166 |
def conv1x1(in_planes, out_planes, stride=1, groups=1, bias=False):
"""2D 1x1 convolution.
Args:
in_planes (int): number of input channels.
out_planes (int): number of output channels.
stride (int): stride of the operation.
groups (int): number of groups in the operation.
bias (boo... | 662ebdc7026b7324a749e7ee042f6aa2760a475d | 3,631,167 |
from typing import Tuple
def _get_preprocessing_functions(
train_client_spec: client_spec.ClientSpec,
eval_client_spec: client_spec.ClientSpec,
emnist_task: str) -> Tuple[_PreprocessFn, _PreprocessFn]:
"""Creates train and eval preprocessing functions for an EMNIST task."""
train_preprocess_fn = emnis... | 4d742f99001c84db89a67e2878efe020db819730 | 3,631,168 |
def intstr(num, numplaces=4):
"""A simple function to map an input number into a string padded with
zeros (default 4). Syntax is: out = intstr(6, numplaces=4) -->
0006
2008-05-27 17:12 IJC: Created"""
formatstr = "%(#)0"+str(numplaces)+"d"
return formatstr % {"#":int(num)} | 8637a1f6146d1ff8b399ae920cfbfaab83572f86 | 3,631,169 |
def vehiclesHistoryDF(
token="", version="stable", filter="", format="json", **timeseries_kwargs
):
"""Economic data
https://iexcloud.io/docs/api/#economic-data
Args:
token (str): Access token
version (str): API version
filter (str): filters: https://iexcloud.io/docs/api/#filte... | 097c259ed6017c95e180e9974f72f3421b55cfde | 3,631,170 |
def from_raw(raw_segment):
"""
Parse a new segment from a raw segment_changes response.
:param raw_segment: Segment parsed from segment changes response.
:type raw_segment: dict
:return: New segment model object
:rtype: splitio.models.segment.Segment
"""
keys = set(raw_segment['added']... | 2dc6cffc724a081be203c4c4e123555c522f839e | 3,631,172 |
def _max_mask_non_finite(x, axis=-1, keepdims=False, mask=0):
"""Returns `max` or `mask` if `max` is not finite."""
x = _convert_to_tensor(x)
m = np.max(x, axis=_astuple(axis), keepdims=keepdims)
needs_masking = ~np.isfinite(m)
if needs_masking.ndim > 0:
m = np.where(needs_masking, mask, m)
elif needs_m... | 2a70687891645d904552b660ee7c7c57104ffe01 | 3,631,173 |
def get_uniform_prototype(nlayer, opLibrary):
"""Creates a prototype over the uniform layer distribution (all
probabilities are equal).
Arguments
----------
nlayer: int
A number of layers in the prototype
opLibrary: list of layer classes
The layer library.
Returns
... | 37c4dca16ef0adf64483d338c142d112fa296d04 | 3,631,174 |
def make_batch_X(batch_X, n_steps_encode, dim_wordvec, word_vector):
"""Returns the world vector representation of the batch input by padding or truncating as may apply with a final dimension of [batch_size, n_steps_encode, word_vector] """
for i in range(len(batch_X)):
batch_X[i] = [word_vecto... | 3f0307c45f5a5644779147babdccbd6dc356cf14 | 3,631,175 |
def gap_fill(g, layer_qs, index, start_val, end_val, extrusion_rate, total_extruded, total_distance, n_fill_lines=None, gap=None):
"""Fill a polygon with a gap in between the lines that fill it.
The gap has a size of either `gap` or is evenly divided by `n_fill_lines`
"""
assert (n_fill_lines is not No... | bc01498a419df7444f9a2ea838a0ae2b8fe6923c | 3,631,176 |
def weekend_christmas(start_date=None, end_date=None, observance=None):
"""
If christmas day is Saturday Monday 27th is a holiday
If christmas day is sunday the Tuesday 27th is a holiday
"""
return Holiday(
"Weekend Christmas",
month=12,
day=27,
days_of_week=(MONDAY, ... | bda4ddf5d5dca18f061c5a6aa4391929aeef2033 | 3,631,177 |
from typing import List
def get_interface_packages() -> List[str]:
"""Get all packages that generate interfaces."""
return get_resources('rosidl_interfaces') | 4cfd473f939d43b51ab57339533b8ec265777981 | 3,631,178 |
def rgb2str(r, g=None, b=None):
"""
Given r,g,b values, this function returns the closest 'name'.
:Example:
.. doctest:: genutil_colors_rgb2str
>>> print rgb2str([0,0,0])
'black'
:param r: Either a list of size 3 with r, g, and b values, or an integer representing r v... | 0cf76c74fc9ad9d2e97c35f5baf59f646605e979 | 3,631,179 |
def calc_uvw(phase_centre, timestamps, antlist, ant1, ant2, ant_descriptions, refant_ind=0):
"""
Calculate uvw coordinates
Parameters
----------
phase_centre
katpoint target for phase centre position
timestamps
times, array of floats, shape(nrows)
antlist
list of ant... | b5adcfb507d1d1599e3d65fdd82e201a95afd135 | 3,631,180 |
def rename_duplicate_name(dfs, name):
"""Remove duplicates of *name* from the columns in each of *dfs*.
Args:
dfs (list of pandas DataFrames)
Returns: list of pandas DataFrames. Columns renamed
such that there are no duplicates of *name*.
"""
locations = []
for i, df i... | c816804a0ea9f42d473f99ddca470f4e527336f9 | 3,631,181 |
def test_accel_nb_1():
""" Use decorator """
accel.has_numba = True
@accel.try_jit
def fn():
return np.ones(100) * 5
assert isinstance(fn, jitd_class) | 7bc16046180c1973a6584150a1822bcd5da06d19 | 3,631,182 |
def checkH(board, intX, intY, newX, newY):
"""Check if the horse move is legal, returns true if legal"""
tmp=False
if abs(intX-newX)+abs(intY-newY)==3:
if intX!=newX and intY!=newY:
tmp=True
return tmp | f1ce66457a54dea4c587bebf9bd2dd0b56577dc4 | 3,631,183 |
def solarize_add(image, addition, threshold=None, name=None):
"""Adds `addition` intensity to each pixel and inverts the pixels
of an `image` above a certain `threshold`.
Args:
image: An int or float tensor of shape `[height, width, num_channels]`.
addition: A 0-D int / float tensor or int ... | 1a4b68abf1e64d0390d2bfa26aa0e70f4a0f5e87 | 3,631,184 |
def is_dirty2():
"""Function: is_dirty2
Description: Method stub holder for git.Repo.git.is_dirty().
Arguments:
"""
return False | 01ed2000d4ae6565760ed2efaa6624d75b005151 | 3,631,186 |
import re
def getTranslation(tbl, all_names, tsv_output):
"""get name translation for contig files from prokka
Args:
tbl (string): Path to the tbl file
all_names (list of string): All the name in the fasta in order
tsv_output (string): Path of the output tsv table with the prokka and ... | 301b41b87c0d84a8f36430f64f9cfae14b69d5bf | 3,631,187 |
def create(language, namespace, templatepath):
"""
Create a language by name.
"""
lang = None
if language == "Java":
lang = Java(namespace, templatepath)
elif language == "C++":
lang = CXX(namespace, templatepath)
else:
raise ModelProcessingError(
"Inval... | 8a6c04a1c8b6486d246cc7eff6bd5c20ccd2a0fd | 3,631,188 |
def dq2segs(channel, gps_start):
"""
This function takes a DQ CHANNEL (as returned by loaddata or getstrain) and
the GPS_START time of the channel and returns a segment
list. The DQ Channel is assumed to be a 1 Hz channel.
Returns of a list of segment GPS start and stop times.
"""
#-- Che... | 5c261431b73d3b0f6acc61dc04b4c41283e65e1d | 3,631,189 |
import re
def get_info(prefix, string):
"""
:param prefix: the regex to match the info you are trying to obtain
:param string: the string where the info is contained (can have new line character)
:return: the matches within the line
"""
info = None
# find and return the matches based on ... | ed41100910df8ec3e0060ecd1196fb8cc1060329 | 3,631,190 |
import calendar
def to_unix(dt):
"""Converts a datetime object to unixtime"""
return calendar.timegm(dt.utctimetuple()) | aefe370b3a812c258b83a389a136914398077b20 | 3,631,191 |
def count_circular_primes(ceiling):
"""
Counts the number of circular primes below ceiling.
A circular prime is a prime for which all rotations of the digits is also
prime.
"""
return len([
a for a in range(ceiling)
if is_prime(a) and all(is_prime(a) for a in gen_rotation_list(a)... | efab99e401b9afd799ab3d2e29c70adca90b875a | 3,631,192 |
def get_user_documents(user, documents=None):
"""
Return collections and documents for the user
"""
collections = get_user_collections(user)
if not documents:
documents = get_document_model().objects.all()
if not user.is_superuser:
documents = documents.filter(collection__in=coll... | 3b6992434477caffde10c0dba3e67830af333b43 | 3,631,193 |
from typing import Dict
async def hashtags(
db: DataBase = Depends(db_conn),
time_query: Dict = Depends(time_query),
party: str = Query(None, description="Abbreviated name of party", min_length=3),
):
"""Number of times a hashtag is used by supporters of a specific party.
A supporter of a party i... | 19ae9cea717faa9786c3a28f2f65b0df69baf7bd | 3,631,195 |
from typing import Optional
def calculate_inverse_propensity_weighted_confidence_from_df_cache(
df_cached_predictions: pd.DataFrame,
rule_head: PyloAtom,
pylo_context: PyloContext,
propensity_score_controller,
verbose: bool = False,
o_propensity_score_per_prediction: Op... | 30f1c9d9cc74c420c79fabeed828fa44eeca7886 | 3,631,196 |
from datetime import datetime
def _get_choices(ballot_type):
"""
Returns Q object that matches a ballot of the specified type that's
currently active, i.e. now() is between the vote_start and vote_end dates
"""
return Q(ballot__type=ballot_type) &\
Q(ballot__election__vote_start__lte=da... | efbc67a5542aac5bb87ebed28232c7c42fe0724e | 3,631,197 |
from typing import Any
def route(user_model: Any, request: prediction_pb2.SeldonMessage) -> prediction_pb2.SeldonMessage:
"""
Parameters
----------
user_model
A Seldon user model
request
A SelodonMessage proto
Returns
-------
"""
if hasattr(user_model, "route_rest")... | ed58df98da4d1de16de0fdfc9e8e1f56cddbd920 | 3,631,198 |
def find_percentile(array, percentile):
"""Find the value corresponding to the ``percentile``
percentile of ``array``.
Parameters
----------
array : numpy.ndarray
Array of values to be searched
percentile : float
Percentile to search for. For example, to find the 50th percentil... | 88651b16baec86b1181fef35d36be636b8a3e053 | 3,631,199 |
def mstep(X: np.ndarray, responsibilities: np.ndarray) -> GaussianMixture:
"""
M-step: Updates the gaussian mixture by maximizing the log-likelihood
of the weighted dataset
:param X: (n, d) array holding the data
:param responsibilities: (n, K) array holding the responsibilities for all components ... | 4b2c79d786fd613598248937a34e86bbc413e10b | 3,631,202 |
def gene_mode(reference, reads, compress, tab, keep):
"""For when inputs are in-frame genes"""
check_input(reference, reads)
tab = check_tab(tab)
ids = []
names = []
seqs = []
og_seqs = {}
err = []
for record in SeqIO.parse(reference, 'fasta'):
ids.append(record.id)
n... | 3b9406ac52f88855983942f0b406154c5aa08e00 | 3,631,203 |
def _acceptance_rule(fx: float, fn: float, temp: float) -> bool:
"""Metropolis acceptance rule"""
dfx = fn - fx
return (dfx < 0) or (
(dfx > 0) and (np.random.rand() <= np.exp(-(fn - fx) / temp))
) | d3c01d194cd23a1201326fd5f968b08df5d705e0 | 3,631,204 |
def listGenericServerEndpoints():
"""Return list of names of generic server endpoints"""
return getObjectNameList( 'GenericServerEndpoint' ) | c05256b4c9a6701eaf393ea0284e31eaddf42966 | 3,631,205 |
def fnCalculate_MaxUnamRangeRate(prf,centre_frequency):
"""
Calculate the maximum unambiguous range rate in the case of unknown direction
Date: 19 June 2017
"""
return AstCnst.c*prf/(4.*centre_frequency); | 7bb24520bf37313246e4335ec1f7c26c67552b94 | 3,631,206 |
from datetime import datetime
def convert_moz_time( moz_time_entry ):
""" Convert Mozilla timestamp-alike data entries to an ISO 8601-ish representation """
# [ https://developer.mozilla.org/en-US/docs/Mozilla/Projects/NSPR/Reference/PRTime ]
## result = datetime.fromtimestamp( moz_time_entry/1000000 ).s... | ba15a7ed86d9b608799384e9663d36c1cff36fae | 3,631,207 |
from pydantic import BaseModel # noqa: E0611
def generate_model_from_yaml(serialized,
tablename,
primary_key,
deserialize_function = None,
cls = BaseModel,
serialization_co... | 901f1223e9eb59ebd31eaa4420c8c06ce28d9b46 | 3,631,208 |
import signal
def stft_power(data, sf, window=2, step=.2, band=(1, 30), interp=True,
norm=False):
"""Compute the pointwise power via STFT and interpolation.
Parameters
----------
data : array_like
Single-channel data.
sf : float
Sampling frequency of the data.
w... | 25533d6bc9f353f12ef63a093d284ea4c81ffe17 | 3,631,209 |
from opf_python.universal import get_HNF_diagonals
def base_mono_29_30(n):
"""Finds the symmetry preserving HNFs for the base centered monoclinic
lattices with a determinant of n. Assuming for basis 29 A =
[[-0.666125, 1.16613 , 2.04852 ], [ 1. , 1. , 0. ], [ 1.61803 ,
-0.618034, 1. ]], for basis ... | a3ed438b9cf4c60523698838fe90d628f8dc4aac | 3,631,210 |
from ._common import connections
def _write_conne(parameters):
"""Write CONNE block data."""
# Reorder connections
if parameters["connections_order"] is not None:
order = parameters["connections_order"]
else:
order = parameters["connections"].keys()
# Format
label_length = le... | 2cdd27db72f98c7265273aa90ba1968102ff0e0f | 3,631,212 |
def objects_to_coordinate_arrays(posobjs,coords='auto',degrees=True):
"""
converts a sequence of position objects into an array of coordinates.
`coords` determines the order of the output coordinates - it can be a
comma-seperated list of coordinate names or if 'auto', it will be 'lat,long'
f... | 0b9e4a0bd2a253242e7c88a8119010f94d2294a5 | 3,631,213 |
def primset_var(*prims):
"""Create a variable that matches a Primitive node."""
return var(lambda node: is_constant(node) and node.value in prims) | d8ef25d456052326d338f7ca8ef9a6b55d070709 | 3,631,214 |
def flatten_basis_data(basis):
"""
Takes in a dictionary of basis set info and flattens
all primitive data into vectors.
"""
nshells = len(basis)
coeffs = []
exps = []
atoms = []
ams = []
indices = []
dims = []
# Smush primitive data together into vectors
nbf = 0
... | 83929bf7237caa1fca0db8e47f5674c2729ed8bc | 3,631,215 |
def generate_spherical_1D_filter(size):
"""
Generate a discrete circle-shaped 1D filter of odd size
Return a list of length size
Le filtre en forme de demi-cercle a été choisi car il présente une forme de plateau
"""
assert size%2==1
x = np.linspace(-1,1,num = size+2)[1:-1]
... | 551dbab78eb18297085e2835368b8618de0670e2 | 3,631,216 |
def send_email_with_rate_control(
user: User,
alert_type: str,
to_email: str,
subject,
plaintext,
html=None,
max_nb_alert=MAX_ALERT_24H,
nb_day=1,
) -> bool:
"""Same as send_email with rate control over alert_type.
Make sure no more than `max_nb_alert` emails are sent over the pe... | 94abf02d10bbf49ac59a8a0ebc1ac1f258911eef | 3,631,217 |
def equatorial_to_ecliptic(ra, dec):
""" translate from equatorial ra & dec to ecliptic ones """
sc = SkyCoord(ra, dec, unit='deg', frame='icrs', obstime='J2000') \
.transform_to('barycentrictrueecliptic')
return sc.lat.value, sc.lon.value | ba12d078e47aeefc3a6c3c7df0919bbf81e5e68b | 3,631,218 |
def get_decode_dir_name(ckpt_name):
"""Make a descriptive name for the decode dir, including the name of the checkpoint we use to decode. This is called in single_pass mode."""
if "train" in FLAGS.data_path: dataset = "train"
elif "val" in FLAGS.data_path: dataset = "val"
elif "test" in FLAGS.data_path: datase... | 8d0f7283ae4342dfd6e3d017c91d7a6a1bc1f11a | 3,631,219 |
from xone import calendar
def trade_day(dt, cal='US'):
"""
Latest trading day w.r.t given dt
Args:
dt: date of reference
cal: trading calendar
Returns:
pd.Timestamp: last trading day
Examples:
>>> trade_day('2018-12-25', cal='US').strftime('%Y-%m-%d')
'20... | bd9fc3e1262f6bff1d7945b140f64f5d7b369bbe | 3,631,220 |
def read_cclist(self):
"""
Read cross-correlation data from file 'cclist.dat'.
Parameters:
-----------
self (saes_core), an instance of the saes_core class.
Returns:
---------
evid1
evid2
sta_cc
cc_val
evdict
"""
evid1,evid2 = None,None
data = np.genfromtxt(... | 2a5c765b226fdc00c54df673a08c49be471a3828 | 3,631,221 |
def witchingHours(symbol="", **kwargs):
"""This is when option contracts and futures contracts expire on the exact same day.
https://iexcloud.io/docs/api/#witching-hours
Args:
symbol (str): symbol to use
"""
return _base(id="PREMIUM_WALLSTREETHORIZON_WITCHING_HOURS", symbol=symbol, **kwargs... | ae779cc2c9f000cb7a7e394cc7aa190079db4deb | 3,631,222 |
def create_write_buffer(context, host):
"""Shorthand for creating a write-only buffer on the GPU."""
return ocl.Buffer(context, ocl.mem_flags.WRITE_ONLY, host.nbytes) | 1efdcabb32dd12341bdc1a5b91ac851d9b77e20a | 3,631,224 |
import struct
import binascii
def packet_read(serial_connection):
"""Read a packet from given serial connection.
"""
header = serial_connection.read(3)
if len(header) != 3:
print('error: failed to read packet header')
return None, None
command_type, payload_size = struct.unpack... | 6396cb748d4b2c72525d16d8983450634f643635 | 3,631,225 |
def is_nonnegative_length(G, l):
""" Checks whether a length function, defined on the arcs, satisfies the non-negative condition.
Args:
G: An instance of Graph class.
l: A dictionary that defines a length function on the edge set.
Returns:
A boolean, True if the length function sat... | c99aaf07b65f9a192b6421b4b3ccf73c98917500 | 3,631,226 |
def prepare():
""" Configure environment for testing (like ansible playbook) """
tmt.steps.Prepare.enabled = True
return 'prepare' | f3ca8a5914a6e4747cb3ea46cfbe8115c0331245 | 3,631,227 |
def unflatten_tensor(input, feat_size, anchors):
"""
Un-flattens and un-permutes a tensor from size
[B x (W x H) x C] --> [B x C x W x H]
"""
bsize = input.shape[0]
if len(input.shape) >= 3: csize = input.shape[2]
else: csize = 1
input = input.view(bsize, feat_size[0] * anchors.shape[... | 9e7b603071312ea35fa214b3e5a6f586d652c760 | 3,631,229 |
def pct_change(df_or_series, periods=1, fill_method='pad',
limit=None, freq=None, **kwargs):
"""
Percentage change between the current and a prior element.
Computes the percentage change from the immediately previous row by
default. This is useful in comparing the percentage of change in... | e4bc49bdaa2fb5ebf0919a68d685eef612819864 | 3,631,230 |
def get_percentage_from_total(total_serie, fraction_serie):
"""
Get which percentage is each element of a serie from the same element
(same date) on another serie.
"""
return compute_time_series(
[fraction_serie, total_serie], utils.get_percent) | eb08c429da50c3408c6cdb90ea24c67d9f099680 | 3,631,231 |
def get_isotope_data(isotope_string: str) -> dict:
"""Get the isotope's intrinsinc properties from a JSON data file."""
formatted_isotope_string = format_isotope_string(isotope_string)
isotope_dict = dict(ISOTOPE_DATA[formatted_isotope_string])
isotope_dict.update({"isotope": formatted_isotope_string})
... | 08c5271e49db49f5cef45eb539797db8a2575eeb | 3,631,232 |
def resample_bins(xb, yb, min_bin=10, beta=0.5):
"""
Do a bootstrap resample within the len(xb) bins in the list yb.
Only resample if there are at least min_bin elements in a bin,
otherwise reject the entire bin with probability (1-beta).
"""
xb = np.asarray(xb)
bin_size = np.array(map(len,... | f9aa729266562332e5a5b67beb0e218a20b65733 | 3,631,233 |
from typing import Dict
from typing import Any
import logging
def _run_optimizers(
product_batch: Dict[str, Any],
language: str,
country: str,
currency: str,
cached_optimizers: optimizer_cache.OptimizerCache,
) -> (Dict[str, Any], Dict[str, optimization_result.OptimizationResult]):
"""Transforms... | e2346bd670099e86787d2b8690d7294a5da9f7d2 | 3,631,234 |
import curses
import math
def get_colour_depth():
"""
Returns the maximum number of possible values per color channel,
that can be used with the availible number of
colours and colour pairs in the terminal.
"""
nr_colours = curses.COLORS
return int(math.pow(nr_colours, 1. / 3.)) | 3bd47ee65a7db72d87ac7cc965a43e37724e148a | 3,631,235 |
def google_translate(request):
"""Get translation from Google machine translation service."""
try:
text = request.GET["text"]
locale_code = request.GET["locale"]
if not locale_code:
raise ValueError("Locale code is empty")
except (MultiValueDictKeyError, ValueError) as ... | 03d5746ac0eddb953d0f02fd78f6883c6c0809c9 | 3,631,237 |
from typing import Optional
import re
def get_genre_regexp(ctx: Context, actor: Actor) -> Optional[str]:
"""
Extract the genre from user request if present
Use adapter to insert as a condition or a processing function
"""
last_request = ctx.last_request
for key in GENRE_DICT.keys():
if... | 3d15c7babdb76be6ae63970df59366cbe4ebeaef | 3,631,239 |
def mapper(request_id, bucket, prefix):
"""Get instructions on how to process an input zarr store by chunk.
For a zarr store at s3://bucket/prefix, return a list of row boundaries
that correspond to chunks in the store. Assumes that the s3 path is
readable by an anonymous client.
"""
s3_path =... | e025a26521a53c8b9aec7410a63ae9c9875123c8 | 3,631,240 |
from typing import Optional
from typing import Union
def byteify(data: Optional[Union[str, bytes]], encoding='utf-8', if_none=None) -> bytes:
"""
Convert a piece of data into bytes if it isn't already::
>>> byteify("hello world")
b"hello world"
By default, if ``data`` is ``No... | aac62c4925ab204386d4fcfb927972fbc47c974b | 3,631,241 |
def vote_details(request, id):
"""
Details for a vote.
Parameters:
id -- the id of the `Vote`.
"""
vote = Vote.objects.filter(uid=id)
if not vote:
return {}
data = {
'id': vote.id,
'author_id': vote.author.id,
'author': vote.author.name,
'post_id... | f8066bc8f94308b2df2e0acc7d4703bd8937b48a | 3,631,242 |
def get_p_vals(location_median_results, author_gender_median_results, date_median_results):
"""
Takes results from **results_by_location(results, 'median')**, **results_by_author_gender**,
**results_by_date**.
ANOVA test for independence of:
- male vs female authors' median distance between female... | 8bd4f9ef60891f2767c79f28a9d51bcff72d2851 | 3,631,243 |
from shutil import copyfile
def copyfiles(filelist, dest, copy=False):
"""Copy or symlink files in ``filelist`` to ``dest`` directory.
Parameters
----------
filelist : list
List of files to copy.
dest : path/files
full path to destination. If it is a list of length greater
... | 1e05b1ff194babbe7f32ec59dfb0d426656caec4 | 3,631,244 |
def ancestors(repo, subset, x):
"""Changesets that are ancestors of changesets in set, including the
given changesets themselves.
If depth is specified, the result only includes changesets up to
the specified generation.
"""
# startdepth is for internal use only until we can decide the UI
a... | 06642e762d040a49600084db94ea36c6c1cec0e7 | 3,631,245 |
def mock_down_payment_time_with_raise_closure(option = 1):
"""
@fn mock_down_payment_time_with_raise_closure
"""
def mock_down_payment_time_with_raise_input(input_prompt):
if "annual salary" in input_prompt.lower():
return down_payment_time_with_raise_test_values(
option).annual_salary
if... | 669f7dc5b9945d0d153d908f63b6ea7c0d0ec332 | 3,631,246 |
def hist_intersection(histA, histB):
""" Calcuates the intersection of two histograms.
If two normalised histograms are the same then the sum of the intersection
will be one.
Assumes histograms are normalised.
Parameters
----------
histA: 1D numpy array
normalised array where the ... | 029c2d81a80d9ce89b5fd383fe1db1b8e40cf0ba | 3,631,247 |
import six
import traceback
def failure_format_traceback(fail):
"""
:param fail: must be an IFailedFuture
returns a string
"""
try:
f = six.StringIO()
traceback.print_exception(
fail._type,
fail.value,
fail._traceback,
file=f,
... | fdcbdf9f7617f401d511c9ce9b58420367419250 | 3,631,248 |
def ConvT3D(parent, filters, kernel_size, strides=[1, 1, 1], padding="same",
use_bias=True, groups=1, dilation_rate=[1, 1, 1], name=""):
"""\
3D Transposed convolution layer (sometimes called deconvolution).
The need for transposed convolutions generally arises from the desire to
use a tran... | e56980ec2a09c16d4392eca96ad0156e4c17fc1d | 3,631,249 |
def bytes_to_int(b: bytes) -> int:
"""
Convert bytes to a big-endian unsigned int.
:param b: The bytes to be converted.
:return: The int.
"""
return int.from_bytes(bytes=b, byteorder='big', signed=False) | eb08ae0b2663047557b8f102c6c6ed565aae8044 | 3,631,250 |
def train_step(sess, dataset, sequence_number, model, parameters):
"""
Train.
"""
# Perform one iteration
token_indices_sequence = dataset.token_indices['train'][sequence_number]
for i, token_index in enumerate(token_indices_sequence):
if token_index in dataset.infrequent_token_indices ... | bd5b1aef942b585d0ecaad3b1f90ad1b02a21fb4 | 3,631,252 |
import numpy
def cos_distance_numpy_vector(v1, v2):
"""get cos angle (similarity) between two vectors"""
d1 = numpy.sum(v1 * v1)
d1 = numpy.sqrt(d1) # magnitude of v1
d2 = numpy.sum(v2 * v2)
d2 = numpy.sqrt(d2) # magnitude of v2
n1 = v1 / d1
n2 = v2 / d2
return numpy.sum(n1 *... | fdbc02c5cba377c561843dd57e9ca13a2e9c6960 | 3,631,253 |
def list_all_submodules(package):
""" List all the modules in this package with their fully qualified names."""
root_modname = package.__name__
# if the module is not a package do nothing, we check this by the
# presence of the __path__ attribute which only packages have
if not hasattr(package, "_... | 81c22be084ebbba6bd300d95e52642b9b33954bc | 3,631,255 |
def int_greater_than(x, inclusive: bool = False):
"""Creates property that must be an int greater than (or equal to)
some value
Parameters:
x: Value that the property must be greater than
inclusive (bool): If set to True, includes x as a possibility.
Returns:
property
"""... | 8b8a74fe09590d90a77fda2d932a4b3b2905dbcc | 3,631,256 |
from typing import Optional
async def get_Sales_with_date_with_login(q: Query, start_date: Optional[str] = "", end_date: Optional[str] = ""):
"""
Get the sales of a particular day
"""
try:
tkit = Toolkit(shop_url=q.shop_url, api_secret=q.api_secret)
results = tkit.getSales(start_date,... | f83fc10fe5fbfaec6805c9a2079217b1e64c6c1e | 3,631,257 |
def cell_to_se2_batch(cell_idx, mapmin, mapres):
"""
Coversion for Batch input : cell_idx = [batch_size, 2]
OUTPUT: [batch_size, 2]
"""
return (cell_idx[:,0] + 0.5) * mapres[0] + mapmin[0], (cell_idx[:,1] + 0.5) * mapres[1] + mapmin[1] | 72a91b5b3a90014322ad8754848e5f85751d3b3a | 3,631,258 |
def merge(elems, field = None, **kwargs):
"""
merge the fields for all elements in a list return it as a single
element.
Parameters
-----------
elems : list. a list of element object
kwargs: dict. other properties of the new element.
Examples
----------
>>> bpm = getElements('... | 0801709d9af67963ab0223f502513bf9825e44f1 | 3,631,259 |
def add_answerset(m_json, mid=None, **kwargs):
"""Add answerset."""
if mid is None:
mid = str(uuid4())
with session_scope() as session:
aset = Answerset(m_json, id=mid, **kwargs)
session.add(aset)
return mid | 8bf0d9cc9ef0636a465af67eb26a9d0fe446f3ec | 3,631,260 |
def is_reserved(ips):
"""Indicates whether each address is reserved.
*** Addresses must be IPv4. IPv6 not yet supported. ***
"""
res = cudf.Series(rmm.device_array(len(ips), dtype="bool"))
ptr = res.data.mem.device_ctypes_pointer.value
reserved_ipv4_REGEX = r"^(2(4[0-9]|5[0-5]))\.([0-9]|[1-9][0-... | d40a0092268eee5c6a8d6b22e0b6de9b1ebd8132 | 3,631,261 |
def split_last_dimension(x, n):
"""Reshape x so that the last dimension becomes two dimensions.
The first of these two dimensions is n.
Parameters
----------
x
A Tensor with shape [..., m]
n: int
An integer.
Returns
-------
y
A Tensor with shape [..., n, m/... | 9909db0fda7cc5ee0666b910459c598741d5c6e3 | 3,631,262 |
from typing import Tuple
async def authenticate_user(
request: web.Request, for_password_modification=False
) -> Tuple[User, Claims]:
"""Multiple schemes authentication using request Authorization header.
Raises HTTPUnauthorized on failure.
"""
if not request.headers.get("Authorization"):
... | 72b0daa26f4b4c8e589223313c6fbba3e348decf | 3,631,263 |
def nest(collection, *properties):
"""This method is like :func:`group_by` except that it supports nested
grouping by multiple string `properties`. If only a single key is given, it
is like calling ``group_by(collection, prop)``.
Args:
collection (list|dict): Collection to iterate over.
... | ca66ca29c9a33674d8c8bb3dc1937cb1e6018a2d | 3,631,264 |
def pyav_decode_stream(
container, start_pts, end_pts, stream, stream_name, buffer_size=0
):
"""
Decode the video with PyAV decoder.
Args:
container (container): PyAV container.
start_pts (int): the starting Presentation TimeStamp to fetch the
video frames.
end_pts (i... | 5b012899c047dcd3ee90d793c68ebdd1d2f413c1 | 3,631,265 |
import sqlite3
def encode_data_for_sqlite(value):
"""Fix encoding bytes."""
try:
return value.decode()
except (UnicodeDecodeError, AttributeError):
return sqlite3.Binary(value) | fe59a2b0dde5ff7c41acc02c4de6724cc75553fb | 3,631,266 |
def inject_sync_poller(sender, caller, st_type, user, **kwargs):
"""Inject javascript code."""
condition = (
caller != "top" or
st_type != "js" or
not hasattr(user, "mailbox") or
not user.parameters.get_value("enable_carddav_sync")
)
if condition:
return ""
re... | 18479a46f02424e7b3e4a0a6e8d2543621ad1115 | 3,631,267 |
def parse_pointstamped(point_input):
"""
Parse point_input into PointStamped.
"""
try:
assert isinstance(point_input, PointStamped)
return point_input
except:
pass
try:
assert isinstance(point_input, Point)
point = PointStamped(point = point_input)
... | 0103abc2b73581daa73c8981d45ad87d77cfba78 | 3,631,269 |
def ext_binary_gcd_env(a, b):
"""Extended binary GCD.
Given input a, b the function returns
d, s, t such that gcd(a,b) = d = as + bt."""
u, v, s, t, r = 1, 0, 0, 1, 0
while (a & 1 == 0) and (b & 1 == 0):
a, b, r = a >> 1, b >> 1, r + 1
alpha, beta = a, b
#
# from here on we ma... | c189fbdd27dcff14bec9093924067f247ea38f88 | 3,631,270 |
import random
def gen_tasksets(
number_of_sets=100, number_of_task=15, util_req=0.5,
period_pdf=[0.03, 0.02, 0.02, 0.25, 0.40, 0.03, 0.2, 0.01, 0.04],
scalingFlag=True, threshold=0.1, cylinder=4, sumRunnable=True):
"""Main function to generate task sets with the WATERS benchmark.
Varia... | ac1f09df006d31dfc1b772c850906ec236d07f4d | 3,631,272 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.