content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def get_alt(ref, var_size, var_type):
"""
Generate alternative allele from SNV and INS but not DEL.
:param var_type: SNV or INS
:return: A string of nucleotides
"""
if var_type == 'SNV':
nucleotides = [x for x in dna if x != ref]
return choice(nucleotides)
elif var_type == '... | 34a1316a2fe6fcea55faefb3d2debe530b19d0c5 | 42,836 |
def interpolate_volume(ref, resize):
"""Intperolate a 3D volume
"""
assert len(ref.shape) == 3, "3D data only"
(sx, sy, sz) = ref.shape
assert sx == sy, "Only cubic data allowed"
assert sx == sz, "Only cubic data allowed"
# 2D interpolation along first two axes
twodintp = np.zeros((sx, ... | 6052c33eb7d4bc34b2e548815fc6540b01493559 | 42,838 |
def mock_run_controller(decoy: Decoy) -> RunController:
"""Get a fake RunController dependency."""
return decoy.mock(cls=RunController) | d33174c6d1a1bf543632a6d0c4dd7584e746adc5 | 42,839 |
def detectorEff(E):
"""Function to describe the detector efficiency. It is based on a fit of
Serpent2 results.
Parameters
----------
E : float or list
Energy in MeV
Returns
-------
Eps : float or list
Detector efficiency at energy/energies E
"""
E=E*100... | e52a4f398782396ed2922f7d949528935d704fc1 | 42,840 |
from typing import Dict
def retrieve_monthly_average_scores(database_connection: mysql.connector.connect
) -> Dict:
"""Retrieve average panelist scores grouped by month
for every available year"""
cursor = database_connection.cursor(dictionary=True)
query = ("SELECT... | 0a4ec2471e3129d64f2dfefd0b59b007e501e4a0 | 42,844 |
def Float(*args, **kwargs):
"""Create a validator that checks that the value is a valid float
according to the `spec`
:param spec: The specification to check the float against.
Can be either
None
Anything that is a float passes. e.g. 1.2 and "1.2" ar... | 29ecd23e7b5ee407fc037afa706524fd2cf19798 | 42,845 |
def CV_IS_SEQ_POLYGON(*args):
"""CV_IS_SEQ_POLYGON(CvSeq seq) -> int"""
return _cv.CV_IS_SEQ_POLYGON(*args) | 46548bebfb9881c0cfb04d730165efec75e05a8d | 42,846 |
def fetch_fork_result_list(pipe_ids):
"""
Read the output pipe of the children, used after forking to perform work
and after forking to entry.writeStats()
@type pipe_ids: dict
@param pipe_ids: Dictinary of pipe and pid
@rtype: dict
@return: Dictionary of fork_results
"""
out = {}
... | 71f5249463cdb6797f13cbbc524ce406300156f6 | 42,848 |
from typing import Mapping
from typing import Iterable
def is_drf_friendly_errors_dict(val) -> bool:
"""Check if val is in format drf-friendly-errors."""
try:
return (
isinstance(val, Mapping)
and val.get('code', None) is not None
and is_integer_value(val.get('code'... | 68201684822c502b2311737ce8e8dfa079bccd3a | 42,849 |
def home():
"""Will render React once compiled."""
return render_template("index.html") | 7fecae256d71773be739faf9d13c4b6a3cbffc08 | 42,850 |
def del_flowspec_local(flowspec_family, route_dist, rules):
"""Deletes/withdraws Flow Specification route from VRF identified
by *route_dist*.
"""
try:
tm = CORE_MANAGER.get_core_service().table_manager
tm.update_flowspec_vrf_table(
flowspec_family=flowspec_family, route_dist... | 1139bd366dfdef51f757b8737d82dac9d2b28de2 | 42,851 |
from typing import Sequence
from typing import Tuple
def logical_slice_assign_op(x, update, slice_tup_list: Sequence[Tuple[int, int, int]]):
"""Update a slice of tensor `x`(in-place). Like `x[start:stop:step] = update`.
Args:
x: A `Tensor`, whose slice will be updated.
update: A `Tensor`, in... | f87dd0691bb8df1d498fc713de5e40b47722726f | 42,852 |
def standardize(X, scale_dict = None, reverse = False):
"""Facilitates standardizing data by subtracting the mean and dividing by
the standard deviation. Set reverse to True to perform the inverse
operation.
Parameters
----------
X : numpy ndarray, or pandas.DataFrame
Data for whic... | f10afa7f1bd64ba1d4b223c99fb81dbef1b9c204 | 42,853 |
def draw_landmarks_edges(image,
keypoint_locs,
keypoint_edges,
edge_colors,
keypoint_color=(0, 255, 0)):
"""Draw landmarks and edges on the input image and return it."""
for landmark in keypoint_locs:
landmark_x ... | 991b60c7d833afdb85b5cca7fcda982425bdc5a5 | 42,854 |
import torch
def psnr(img_batch, ref_batch, batched=False, factor=1.0):
"""Standard PSNR."""
def get_psnr(img_in, img_ref):
mse = ((img_in - img_ref)**2).mean()
# if mse > 0 and torch.isfinite(mse):
# return (10 * torch.log10(factor**2 / mse))
# elif not torch.isfinite(mse)... | aff37f49ea558ac97bb6e2197a0a58d37ad5b73d | 42,855 |
def current_loss(model_loss):
"""
Returns the minimum validation loss from the
trained model
"""
losses_list = []
[losses_list.append(x) for x in model_loss]
return np.min(np.array(losses_list)) | 278090761133cb01610ce53965c1d6c0f51da0dd | 42,856 |
def explicit_impute(
adata: AnnData,
replacement: (str | int) | (dict[str, str | int]),
impute_empty_strings: bool = True,
copy: bool = False,
) -> AnnData:
"""Replaces all missing values in all or the specified columns with the passed value
There are two scenarios to cover:
1. Replace all ... | 23af91ee58852e34105145f35a82706a4baafc12 | 42,857 |
def jacobi_solver(L,dp_dx,mu,u_i,tol):
"""
simple jacobi solver for testing purposes
"""
Ny = np.size(u_i)
u_even = np.copy(u_i)
u_odd = np.copy(u_i)
h = L/(float(Ny) - 1.)
rhs = (h**2)*(1./mu)*dp_dx
maxIter = 1000000
KEEP_GOING = True
nIter = 0
exit_code = 0
wh... | 97815c9f231cee4a710c1b828a881d62c9f7b773 | 42,859 |
import ast
def default_for_unknown(word):
"""Provide a default definition for words that are not in the lexicon."""
proper_noun = ast.SentenceNode(word, ast.Var(word.lower()), ast.TYPE_ENTITY)
single_place = ast.SentenceNode(
word,
ast.Lambda("x", ast.Call(ast.Var(word.title()), ast.Var("x... | 4a81b696c0531a1fec6dfb0e841afacde838191b | 42,860 |
def add_basic_head(model, blob_in, dim_in, pool_stride, out_spatial_dim,
suffix, lfb_infer_only, test_mode):
"""Add an output head for models predicting "clip-level outputs"."""
# -> (B, 2048, 1, 1, 1)
pooled = model.AveragePool(
blob_in, blob_in + '_pooled',
kernels=[pool_stri... | 7771d33c3a8fbb839f1901dcc19d45bc723bd38d | 42,861 |
def connect(app: Application) -> NetworkState:
"""
Estabilish a connection to the server.
"""
client = nm.get_client()
assert app.current_network_uuid is not None
nm.activate_connection(
client,
app.current_network_uuid,
partial(on_any_update_callback, app),
)
ret... | 2ab2fae74941de765c6244dee636b08cd445b1f6 | 42,862 |
import random
from datetime import datetime
def gen_malicious(num_per_dga=10000):
"""Generates num_per_dga of each DGA"""
domains = []
labels = []
# We use some arbitrary seeds to create domains with banjori
banjori_seeds = ['somestring', 'firetruck', 'bulldozer', 'airplane', 'racecar',
... | 05ce47c5ec739f14b81c1efc4c2c05f4d5087a34 | 42,863 |
def rnd_date_array(size, start=date(1970, 1, 1), end=date.today()):
"""
Array or Matrix of random date generator.
"""
start = parser.parse_date(start)
end = parser.parse_date(end)
_assert_correct_start_end(start, end)
return _randn(size, _rnd_date, start, end) | c1495729f9ef03f5a1c5c9164eba4295e51e1aaa | 42,864 |
import builtins
def createResolutionCallbackFromClosure(fn):
"""
Create a resolutionCallback by introspecting the function instead of
looking up the stack for the enclosing scope
"""
closure = get_closure(fn)
def env(key):
if key in closure:
return closure[key]
eli... | 7ab59b1d38919005e096b65865fd7be47dbdafcc | 42,865 |
def move(locations):
"""
Provide an interface to the user facilitating their movement between
locations.
Arguments
---------
locations : list
A list of locations they can move to.
Returns
-------
str
The location the user enters to move to.
"""
move... | 9792bc56b7b0961619864df6d582a71dd14f37ce | 42,866 |
def split_loops_into_anchors(file_name):
"""
Split loops into anchors.
"""
left = []
right = []
run = file_name.split('.')[0]
i = -1
with open(file_name, 'r') as f:
for line in f:
if '#' in line:
# Skip header
continue
... | c5040b4c2a675d7250d0658a4e60fddd064d933a | 42,868 |
from pathlib import Path
import tqdm
def read_challenge17_data(db_dir, verbose=False):
"""
Read the PhysioNet Challenge 2017 data set.
@param db_dir: Database directory.
@param verbose: Whether to show a progress bar.
@return: Tuple of: (array of wfdb records, DataFrame with record ids as index ... | 8a4c51fd7c6728d98a88d42c0ce3abd118d5804c | 42,869 |
def create_population(number_of_individual, data_file_name, intervals_min, intervals_max):
"""
-> Create a population of random initialized individuals
"""
pack = dichotomization.extract_matrix_from(data_file_name)
variable_to_position = pack[1]
population = []
for x in range(0, number_of_individual):
individ... | e424842172f4dafb5d4d8a9c3cd3012e9768221c | 42,870 |
def AdjointOperator(model, geometry, space_order=4,
**kwargs):
"""
Construct an adjoint modelling operator in an tti media.
Parameters
----------
model : Model
Object containing the physical parameters.
geometry : AcquisitionGeometry
Geometry object that cont... | 6b6362110e0da85460b16cca29c2d6460dadf981 | 42,871 |
def get_vdi_url(request, compute_id, vname):
"""
:param request:
:param vname:
:return:
"""
compute = get_object_or_404(Compute, pk=compute_id)
try:
conn = wvmInstance(compute.hostname, compute.login, compute.password, compute.type, vname)
fqdn = get_hostname_by_ip(compute.... | 02af96867090b9703b99a19c52275f843aea8c9a | 42,872 |
def munsell_colour_to_xyY(munsell_colour: StrOrArrayLike) -> NDArray:
"""
Convert given *Munsell* colour to *CIE xyY* colourspace.
Parameters
----------
munsell_colour
*Munsell* colour.
Returns
-------
:class:`numpy.ndarray`
*CIE xyY* colourspace array.
Notes
-... | a2c7d4df68a1c9f9e6cdc79fafd4f06501ea60e5 | 42,873 |
def get_filter_meta_table():
"""Generate a table with meta information about HELP filters
This function generates an astropy.table.Table containing the information
about the filters used in HELP, except their transmission profile.
Returns
-------
astropy.table.Table
"""
# List of fil... | d81f0d848651c6f52bba1f9f556c86027d3740b5 | 42,874 |
def corner_subpix(image, corners, window_size=11, alpha=0.99):
"""Determine subpixel position of corners.
Parameters
----------
image : ndarray
Input image.
corners : (N, 2) ndarray
Corner coordinates `(row, col)`.
window_size : int, optional
Search window size for subpi... | a0e93691833e4d66aeb0f2cbbd9302972cd511c3 | 42,875 |
import torch
def adaptive_attack_pgd(model, X, y, c_head_model, scripted_transforms, criterion, epsilon, alpha, attack_iters, restarts,
norm, early_stop=False,
mixup=False, y_a=None, y_b=None, lam=None, n_views=2, lambda_S=1):
"""Defense Aware Attack, where the attacker optimizes to ... | 3cf61686d42dde18dff7fee614b4d4a5424a1cff | 42,876 |
def login_view(request):
"""
View that allow us to login a user
"""
context = {}
user = request.user
if user.is_authenticated:
return redirect("mainpage")
if request.method == "POST":
form = AccountAuthenticationForm(request.POST)
if form.is_valid():
email... | 0100394ec069ad9f82648b6f31b61dbe3b6b3903 | 42,877 |
def rearrange(da, out_dims, in_dims=None, **kwargs):
"""Wrap `einops.rearrange <https://einops.rocks/api/rearrange/>`_.
Parameters
----------
da : xarray.DataArray
Input DataArray to be rearranged
out_dims : list of str, list or dict
The output pattern for the dimensions.
Th... | 198bd91b132ff08d0432e5086ee2bcd879f7b161 | 42,878 |
def first(*objects):
"""
Return the first non-None object in objects.
"""
for obj in objects:
if obj is not None:
return obj | 4d33225eb0348aa9b7fefa875070eb5527e67135 | 42,879 |
def example_interaction_with_policy(policy="random"):
"""Example usage of Interaction that uses a random policy
or user interaction to decide which candidate to expand.
"""
assert policy in ("random", "user")
def random_policy(state):
"""Choose a random candidate to expand"""
from h... | 0a6a964878b0f70d50026390bfd54883f03b913a | 42,880 |
def add_gallery_media_pic():
"""
POST endpoint that adds a new gallery picture to the club with an image upload and a caption.
"""
user = get_current_user()
json = g.clean_json
gallery_pic_file = request.files.get('photo', None)
if gallery_pic_file is not None:
gallery_pic_url, pi... | 20114a3fffef909a38d1dce1235a3ec01af5dd3e | 42,881 |
from typing import Optional
import torch
import functools
from typing import OrderedDict
import tqdm
def volume_render(
rays_o,
rays_d,
model: NeuS,
obj_bounding_radius=1.0,
batched = False,
batched_info = {},
# render algorithm config
calc_normal = False,
use_view_dirs... | e63ed820080e25f2debfe67baec60230ae40598b | 42,882 |
def ball_tree(dataset, profondeur):
"""
Compartimente dataset selon l'algorithme BallTree.
Parameters
----------
dataset : list
Liste de points à séparer.
profondeur : int
Nombre de fois que la liste de départ est séparé.
Returns
-------
listes : list
liste ... | 2ad96667834c8eec63a95d65c8cbf5f26bfe2c06 | 42,883 |
def init_list_with_values(list_length: int, init_value):
"""Return a pre-initialized list.
Returns a list of length list_length with each element equal to
init_value. init_value must be immutable (e.g. an int is okay; a
dictionary is not), or the resulting list will be a list of
references to same object (e.g. re... | 85d5aa5f575b6aec54658ca6d398ded5f48f7188 | 42,885 |
import math
def get_ab_test_ci(
conversions_control: int,
conversions_treatment: int,
total_users_control: int,
total_users_treatment: int,
confidence_level: float = 0.05,
) -> str:
"""
Conducts an A/B test on the two sided hypothesis:
- H_0: Probability of conversion in treatment ... | a3cdc23941c1eec956a0d9eb631300c62f07a402 | 42,886 |
def euler_to_quaternion(euler_angles, rotation_order=DEFAULT_ROTATION_ORDER,filter_values=True):
"""Convert euler angles to quaternion vector [qw, qx, qy, qz]
Parameters
----------
* euler_angles: list of floats
\tA list of ordered euler angles in degress
* rotation_order: Iteratable
\t a li... | 4259e96658f46a99d8c056e5b98aa3a63cd9aed2 | 42,887 |
from tqdm import tqdm as t
def tqdm(iterable=None, desc=None, total=None, leave=True, **kwargs):
"""ascii=Trueでncols=100なtqdm。"""
return t(iterable, desc, total, leave, ascii=True, ncols=100, **kwargs) | 7e4bd94ac0a94318b16b3f16d920665106c62361 | 42,888 |
def get_largest_mol(mol_list):
"""
Given a list of rdkit mol objects, returns mol object containing the
largest num of atoms. If multiple containing largest num of atoms,
picks the first one.
Args:
mol_list(list): a list of rdkit mol object.
Returns:
the largest mol.
"""
... | c30b2bb55af911f72fa29b800ef0081ad7c1830b | 42,889 |
import re
def decode_sigma(ds,sigma_v):
"""
ds: Dataset
sigma_v: sigma coordinate variable.
return DataArray of z coordinate implied by sigma_v
"""
formula_terms=sigma_v.attrs['formula_terms']
terms={}
for hit in re.findall(r'\s*(\w+)\s*:\s*(\w+)', formula_terms):
terms[hit[0]]... | 3ea233f2b3acb0012166e8e002d6824845a7c043 | 42,890 |
def is_territory(element: inkex.BaseElement) -> bool:
"""
Checks if the given element is a territory
:param element:
:return:
"""
return Warzone.TERRITORY_IDENTIFIER in element.get_id() | e2a00e223884f0704a8b03524079e6aecf302d19 | 42,891 |
def lowfirst(string):
"""
Make the first letter of a string lowercase (counterpart of :func:`~django.utils.text.capfirst`, see also
:templatefilter:`capfirst`).
:param string: The input text
:type string: str
:return: The lowercase text
:rtype: str
"""
return string and str(string)... | f877129f9225e84989fc70d096b01715a2287373 | 42,892 |
import requests
def get_snapchat_access_token(snap_credentials):
"""Generate short-lived snapchat access token"""
access_url = 'https://accounts.snapchat.com/login/oauth2/access_token'
access_params = {
'client_id': snap_credentials['client_id'],
'client_secret': snap_credentials['client_s... | 3681afbc82fabef6d34e5b671bd51d1bae1eb591 | 42,893 |
def FindSat(ephem, times, gpsweek):
# Satloc contains both positions and velocities.
"""
# Original in ECE456_orbitutils.py. #NOTE: Ask Ashwin for original source
# Function to coarse calculate satellite positions given the GPS almanac.
# The calculation can be performed for multiple satellites with... | 254ad7af7895024d07adda590746c64e9d9a10f1 | 42,894 |
def output_xml(data, code, headers=None):
"""Makes a Flask response with a XML encoded body"""
xml = dumps(data)
# simplexml lacks ability to insert encoding and standalone,
# so this is a hack
xml_with_headers = "%s%s%s" % (xml[0:20],
'encoding="utf-8" standalone=... | 40a26b0f23aea40a95ff6d940c84155afeff29d3 | 42,895 |
def plot_box(points_horizon, img_obj):
"""
Based on the crosspoints to extract the grids
:param points_horizon: horizon crosspoints
:param img_obj: the class of img
:return:
"""
#################################################################################################################... | 90a18f9a14ecb30b7c38b580152d201ba12654c7 | 42,896 |
def priority(profile):
""" function : to set priority level based on certain age group
input : id, age, infection_status (0 means not infected , 1 means infected) , coordinates, residency
output : priority level : local_high(6), local_medium(5) , local_low (4), foreign(3), foreign(2) ,foreign(1)... | dae951efb11f8988cb32910e708bb4f69d8a3ed0 | 42,897 |
from typing import Sequence
def _compile1_next_statement_with_mods(statements: Sequence[Statement]) -> (IFElement, int):
"""Returns the IFElements and the number of statements read"""
main_statement = statements[0]
if main_statement.matches_pattern(TEXT_PATTERN):
ifelement = IFText(main_statement... | 01aaebeecd3b305f3ac4c26ebeb9a06427ccd67b | 42,898 |
def build_selection(stage_name, config, weights=[]):
"""Creates event selectors based on the configuration.
Parameters:
stage_name: Used to help in error messages.
config: The event selection configuration.
weights: How to weight events, used to produce the resulting cut
eff... | 300f88c2544da9cf0313ec431b8944f062d1e91c | 42,899 |
def seqlib_type(cfg):
"""
Get the type of :py:class:`~enrich2.seqlib.SeqLib` derived object
specified by the configuration object.
Args:
cfg (dict): decoded JSON object
Returns:
str: The class name of the :py:class:`~seqlib.seqlib.SeqLib` derived
object specified by `cfg`... | e48661f00eb6d0cb707fbb96d77b3a9ee3e798d6 | 42,900 |
def ids(probabilities):
"""Turn a 1-hot encoding or a probability distribution over the possible
characters back into its (most likely) character representation."""
return [str(c) for c in np.argmax(probabilities, 1)] | c51b64311c298f48219e35c67bbd50db43778ad2 | 42,902 |
import logging
def scrape(start=None, end=None, silent=False):
"""Returns a pandas DataFrame of school information extracted from the
website CollegeData.com, with each row corresponding to a successfully
scraped schoolId in the range [start, stop], inclusive, with each column
corresponding to labeled... | 3dc93b5c043715aa6ef1f6833146e002205ca1a2 | 42,903 |
def clean_pdb(traj,neighbour_cutoff=5.0,Nsigma=1):
""" pdb_clean
"""
print("Initial number of atoms ",traj.n_atoms)
traj.superpose(traj, 0)
atom_indices = pdb_clean_get_atom_indices(traj,neighbour_cutoff=neighbour_cutoff,Nsigma=Nsigma)
traj.atom_slice(atom_indices,inplace=True)
traj.superpos... | 2931996bbf71af0fb31c534f2f5e722d93ff4fb3 | 42,904 |
from . import palette_tools
from typing import Iterable
from typing import Optional
from typing import Literal
def modules(
adata: AnnData,
root_milestone: str,
milestones: Iterable,
layer: Optional[str] = None,
module: Literal["early", "late", "all"] = "all",
):
"""\
Extract mean expressi... | 33bfbed8d816d4c3eb7085ba227480b1e1131c6f | 42,905 |
def largest_pandigital_multiples():
"""
This function returns the largest pandigital number
which is a multiple of an integer and a sequence of integer
(1,2,3,..n)
"""
largest_number = 0
for i in range(1, 50000):
j = 1
number = i*j
while len(str(number)) < 9:
... | 844ab07aca7d7d44805f893f849f5d63018797f4 | 42,907 |
import torch
def train(unimodal_files, rep_size, classes, sub_sizes, train_data, valid_data, surrogate, max_labels,
batch_size=32, epochs=3,
search_iter=3, num_samples=15, epoch_surrogate=50,
eta_max=0.001, eta_min=0.000001, Ti=1, Tm=2,
temperature_init=10.0, temperature_final=... | 51ee41222ee72f8afaad9f2a6ba20b0927219e40 | 42,908 |
def plot_kdeplot(data, ylabel, title, log_scaling=True):
"""
Args:
data: Dict of list of numbers.
"""
fig, ax = plt.subplots(1, 1, figsize=(8, 6), dpi=300)
plt.xticks(rotation=90)
d = []
for k, v in data.items():
for i in v:
d.append((k, i))
df = pd.DataFrame... | b41bb8283354f66d53feeecbd406dd3ad4ce11bb | 42,910 |
import requests
from bs4 import BeautifulSoup
def get_sector_symbol_name_url():
"""
获取期货所对应板块的 URL
:return: dict
{'能源': '/commodities/energy',
'金属': '/commodities/metals',
'农业': '/commodities/softs',
'商品指数': '/indices/commodities-indices'}
"""
url = "https://cn.investing.com/commod... | e9cec1bc28cdcc2b90fea5f25b326ad613284470 | 42,911 |
def visualize(mesh, vector_field, colors=None, params=None):
"""
Visualize a mesh and a vector field over it
:param mesh: a mesh with n points
:param vector_field: (n,3) array
:param colors: (n,3) array
:param params: params[0] is the length of the quivers
:return:
"""
n = mesh.verti... | 672f665563ece4b0356f880df18b573720865a79 | 42,912 |
def log__OperationsEvent(
ctx,
event_type_id,
event_payload_dict=None,
dbOperationsEvent_child_of=None,
timestamp_event=None,
):
"""
creates a OperationsEvent instance
if needed, registers it into the ctx
"""
# defaults
# timestamp overwrite?
timestamp_event = timestamp_e... | fed5d85d1ea009b79391f4a74ff6326649119995 | 42,913 |
def bare_rate_theta(k, kp, Ntheta, N_z):
""" Calculate phonon scattering rate matrix element (scattering rate without thermal factors NQ of NQ+1)
vs scattering angle theta ***for a given pair*** of k and k'.
k magnitude of initial vector
kp magnitude of scattering vector k'
Ntheta number ... | 1bbc2b4af2ccdb99fd1c6461f000ccd395cd93a2 | 42,914 |
def ingest_data(args):
"""
Ingest and wrangle data from BLS
"""
conf = get_config()
opts = dict(vars(args))
del opts['func']
opts['startyear'] = opts.pop('start_year') or conf.STARTYEAR
opts['endyear'] = opts.pop('end_year') or conf.ENDYEAR
record = ingest(**opts)
return (
... | 93edf5593262526a92be6ea8d4207d6e4454bd92 | 42,915 |
import torch
def decode(loc, priors, variances=[0.1, 0.2]):
"""Decode locations from predictions using priors to undo
the encoding we did for offset regression at train time.
Args:
loc (tensor): location predictions for loc layers,
Shape: [num_priors,4]
priors (tensor): Prior b... | 3394fb7d3e2a7874047689f2211bab6b618b43c2 | 42,916 |
def form(title='', text='', cancel_text='Cancel', inputs=[], buttons=[], style=None, async_=False):
"""
Display a text input box.
Return the given text, or None when cancelled.
"""
#def accept():
# get_app().layout.focus(ok_button)
input_objects = []
button_objects = []
def creat... | 5f190323a16e533e20baa13a78301581d083fda1 | 42,918 |
def process_file(filepath):
""" decides to either call process_openxml or process_ole """
if olefile.isOleFile(filepath):
return process_ole(filepath)
else:
return process_openxml(filepath) | 2d434135b42213a92083b6b1cd1bca40c2e6e93d | 42,919 |
def run(*args):
"""
Create admin using this command. If the email already is registered, just return the email and no need to create new users.
"""
if args and "email" in args[0]:
email = args[0].split("=")[1]
admin = User.objects.get_user(email=email)
if admin:
prin... | 8e8b370cf21a8cc51d9ba92a7be26bf05c11b6b7 | 42,920 |
import csv
def read_data(data_path):
"""Read real-world trial data from given folder
Arguments:
data_path (string): path to folder containing measurements.csv and
transforms.csv files to be read in
Returns:
(tuple of arrays): measurements array and transforms array populated with
... | 572cdebd0034813ae11b5c8789e1816dd5fe49f9 | 42,921 |
def get_rms(y):
"""
Compute the root mean square of an array, usually a Y array.
Parameters
----------
y (vector array): Array of values where the variance needs to be computes.
Returns
-------
RMS (value): The RMS value.
"""
return np.sqrt(np.mean(y ** 2.0)) | 7bd1bd827e1329011c9588818b6e72f3541a6fa6 | 42,922 |
def symmetric_phase_corr(I1, I2):
""" match two imagery through symmetric phase only correlation (SPOF)
also known as Smoothed Coherence Transform (SCOT)
Parameters
----------
I1 : numpy.array, size=(m,n), ndim={2,3}
array with intensities
I2 : numpy.array, size=(m,n), ndim={2,3}
... | 6df7f7dd5a5424d2bb7843151af3f8d370c15144 | 42,923 |
def saturated_oxygen(t,s,gsw=False):
"""Compute oxygen saturation from temperature and salinity
Oxygen saturation value is the volume of oxygen gas absorbed from humidity-saturated
air at a total pressure of one atmosphere, per unit volume of the liquid at the temperature
of measurement (ml/l)
"""
... | 195b5beb6077e8ede563da188ab37384e1a1136e | 42,925 |
def get_cpe_version(cpe):
"""
Determine if the given CPE name is following
version 2.2 or 2.3 of the standard.
:param cpe: CPE name.
:type cpe: str
:returns: CPE standard version ("2.2" or "2.3").
:rtype: str
"""
if not isinstance(cpe, basestring):
raise TypeError("Expected... | c92299bcbf672ebf9140de663160853c77d9111e | 42,926 |
def PaddingMask(pad=0):
"""Returns a layer that maps integer sequences to padding masks.
The layer expects as input a batch of integer sequences. The layer output is
a tensor that marks for each sequence position whether the integer (e.g., a
token ID) in that position represents padding -- value `pad` -- versu... | d6f538042e260d38f2d62c4535e36e78cf032f7f | 42,927 |
def parseXML(user, fname):
"""
Read 1 XML file via remote client and parse the content.
"""
data = localFs.read_user_file(user, fname)
try:
return etree.fromstring(data)
except Exception as e:
logError('Error parsing file `{}`, for user `{}`: `{}`!'.format(fname, user, e))
... | 46550b9c2f4b294ad8dbc9a819533f18caa64fd5 | 42,929 |
def rfactorial(n: int) -> int:
"""Recursive factorial function
:param n:
.. docstring::python
>>> from math import factorial
>>> rfactorial(1) == factorial(1)
True
>>> rfactorial(2) == factorial(2)
True
>>> rfactorial(3) == factorial(3)
True
... | c8455ce7d0e7e781c0c745287c2aef3c9a776a48 | 42,931 |
import time
def vassign(configuration, threads = 0):
"""
Loads network configuration (user characteristics, network capacity, representations, etc. from a scenario file and solves the ILP.
"""
# num users
N = len(configuration["users"])
# Capacity in terms of pRBs
capacity = configuration["nprb"]
# ... | dac335283ccb24788baa634fdd7cfa2ff7c5b596 | 42,932 |
import re
def extract_port_vlan(strValue):
"""处理show port vlan得到的数据
Args:
strValue (str): show port vlan得到的数据
Returns:
list: 元组列表。形式如,[(startVlan, endVlan, "U"), [(startVlan, endVlan, "T"),...]。
"""
# port 9:2,
# vlan(optin):
# 1000(U) .
# 1251 ~ 1254(T).
# 3049 ... | e2aefb9dd5225410637904e6efb67010606243a2 | 42,933 |
def augment_dim(x3: Array, w: Array) -> Array:
"""(x,y,z) -> (x,y,z,w)"""
d4 = np.expand_dims(w, axis=-1)
x4 = np.concatenate((x3, d4), axis=1)
assert len(x4) == len(x3)
assert x4.shape[1] == 4
return x4 | a0b7ff372e2e1698040dde11d60c5c05851d9580 | 42,935 |
def shorten_reference_string(reference_string):
"""Shorten a reference string
Returns the minimum necessary string to unambigiously
list references: E.g. `Genesis 1, Genesis 2` -> `Genesis 1, 2`
"""
range_list = parse_reference_string(reference_string)
if len(range_list) == 0:
return ""... | ad8564e3409b025fd1909d53d38ed291381d793a | 42,936 |
def many2many_dicts(m2mlist):
"""
Maps objects from one list to the other list and vice versa.
Args:
m2mlist: list of 2lists [list1i, list2i] where list1i, list2i represent
a many to many mapping
Returns:
(one2two, two2one) : one2two, two2one
dictionaries from elements o... | edce4101213941dc08d2b32f4c4624ece02bf79c | 42,937 |
def can_read_members(user: QfcUser, organization: Organization) -> bool:
"""Return True if the `user` can list members (incl. teams) of `organization`.
Return False otherwise."""
if not organization.is_organization:
return False
return True | d754de80cd242431c57cfaa598a3da2485a0d261 | 42,938 |
def total_variation_loss(x, img_size):
"""
This function computes the total variation loss as an additional loss to the content and style loss from the paper "A Neural Algorithm of Artistic Style".
Args:
x [numpy.ndarray] generated image with index axis as first dimension.
Returns:
tota... | f8a46b183f4a09768100190c396dee0b973377aa | 42,939 |
def test_get_annotations_data_returned(
pandas_series, coordination_args, monkeypatch
):
"""Test coordination of annotation retrieval for a given protein."""
def mock_get_anno(*args, **kwargs):
annotations = [["NA", "NA", "NA", "NA", "NA"]]
return annotations
monkeypatch.setattr(get_ge... | b0dab14bc6d2598a72b9f8b62c0a442f4aa3256c | 42,940 |
def args_readfactors(lst):
"""Parse the factor arguments."""
factors = dict()
if lst:
for s in lst:
res = s.partition('=')
if not res[0]:
raise CGBadArg("Factor has no key.")
if not res[2]:
raise CGBadArg("Factor has no value.")
factors[res[0]] = float(res[2])
return factors | abb5e9eee08963bc7971c96cbfc8e7ad2304ccc1 | 42,942 |
def Adimensional_to_Asquare(SII,Z_jct,Te):
"""
Converts a SII with no unit to A**2/Hz
"""
return (2.0*_kb*Te)*SII/Z_jct | cebed8d98e434b33f2f092b762946c4bb4682d81 | 42,943 |
def coordinate_search(mni_coordinates, img_shape, inverse_affine, store_path):
"""
Return a list of patients whose masks have damage at the specified location.
Parameters
----------
coordinates : tuple
MNI coordinates (x,y,z)
img_shape : tuple
Voxel dimensions of the 3D MNI-... | 4085d5d093f2d388bd4e056fc12898e4aa8d29ea | 42,944 |
def array_relative_error(a1, a2):
"""Return the elementwise absolute difference between the inputs,
scaled by the maximum value that occurs in the input."""
denom = max(np.amax(np.absolute(a1)), np.amax(np.absolute(a2)))
difference = np.amax(np.absolute(a1 - a2))
if denom < 1e-15:
# Both input a... | 523460101774f7667c0b0557bbb71133555c75be | 42,946 |
import math
def calculate_inverse_log_density(cluster):
"""Calculate the log of inverse of Density of a cluster.
inverse of density-log = log-volume - ln(size)
Args:
cluster ():
Returns:
float: inverse of density-log
-inf if log-volume = -inf
"""
inverse_log_... | e6d6a77d078b080cd01d9fce47f9715562132864 | 42,947 |
def reload_api_v1_integrator(func):
""" Reload a model for each quest """
@wraps(func)
def wrapper(*args, **kwargs):
global COVID_API_V1, dt, ts
COVID_API_V1 = CovidAPIv1()
dt, ts = COVID_API_V1.datetime_raw, COVID_API_V1.timestamp
return func(*args, **kwargs)
return wrap... | 7ad7072174c4201adda47ea3d9269006f653a404 | 42,948 |
def _prepare_errcheck():
"""
This function sets the errcheck attribute of all ctypes wrapped functions
to evaluate the _exc_info_from_callback global variable and re-raise any
exceptions that might have been raised in callbacks.
It also modifies all callback types to automatically wrap the function
... | 8b707f3f400354853e53c885018522bf7b98e1e6 | 42,949 |
def _es_primo(n: int) -> bool:
"""
>>> _es_primo(7)
True
>>> _es_primo(8)
False
"""
for i in range(2, n):
if n % i == 0:
return False
return True | 11a45986b68a3e05250a549356f536680ca282d1 | 42,950 |
import tarfile
import time
from contextlib import closing
from io import BytesIO
from base64 import b64encode
def tarball64_factory():
"""Provides a factor for creating base64 encoded contents of a tarball.
"""
def tarball_(input_dir):
"""Creates a base64 encoded tarball fro input_dir.
... | b9e2a8a1dd526afc597053c7b9d09fb08e89c6ac | 42,951 |
from typing import List
def study_with_records(
complete_study: castor_study.CastorStudy, records: List[castor_record.CastorRecord]
) -> castor_study.CastorStudy:
"""Creates a CastorStudy with linked records for use in tests."""
return link_study_with_records(complete_study, records) | e1e5ba241b13f036d56425933b84bac47d52da8f | 42,953 |
def expires(plugin):
"""
Returns the number of seconds after which to expire a pending plugin task
Args:
plugin (PanoptesPluginInfo): The plugin for which to return the expiry time
Returns:
int: The number of seconds after which to consider the task expired
"""
assert isinstanc... | 5b004fe6c03cf93f5a25c000f37c29853e0bfa27 | 42,954 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.