content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import json
def readJsonTextarea2(request):
"""JSONでの応答練習"""
template = loader.get_template('practice/json-textarea2.html')
# ----------------------------
# 1
# 1. host1/webapp1/templates/practice/json-textarea2.html を取ってきます
# ... | df428a65fbd0e29801e4aeb2f11226ae251a2928 | 3,611,700 |
def _smart_fusion_strategy(ents):
"""This strategy adds the entities scores if one entity occurs multiple times with the same tag, and afterwards
applies the fusion strategy."""
deduplicated_ents = []
for idx, ent in enumerate(ents):
next_ent = ents[idx + 1] if idx + 1 < len(ents) else None
... | 7b1fd80fe7a7feec69502fc240c045bca9f722cf | 3,611,701 |
def bayesian_regret(voters, winner):
"""
Calculate bayesian regret
voters : array (a, n)
Voter preferences; n-dimensional voter cardinal preferences for n issues.
winner : array shape (n)
Winner preferences for winner and `n`-dimensional issues.
"""
voters =... | faf1d9e4b16c410665be4179bceeeca7339f6fba | 3,611,702 |
def run(process_class, *args, **inputs):
"""
Synchronously (i.e. blocking) run a workfunction or process.
:param process_class: The process class or workfunction
:param _attributes: Optional attributes (only for process)
:param args: Positional arguments for a workfunction
:param inputs: The li... | 44dc23b378b51bb30b3bba74558df909083a60e8 | 3,611,703 |
def pointing_str2tuple(beamctldirarg):
"""
Convert a beamctl direction string into direction tuple
Inverse of pointing_tuple2str().
Parameters
----------
beamctldirarg : str
String with format 'angle1,angle2,refsys'
Returns
-------
dirtuple : tuple or None
Directio... | a277365ad7e9173a5dfc9316479593f2f228216d | 3,611,704 |
from datetime import datetime
def plotter(fdict):
""" Go """
pgconn = get_dbconn('coop')
ctx = get_autoplot_context(fdict, get_description())
station = ctx['station']
t1 = ctx['t1']
t2 = ctx['t2']
table = "alldata_%s" % (station[:2],)
nt = NetworkTable("%sCLIMATE" % (station[:2],))
... | 8313ed7cb5da0a607f194b874ad23aa3a7de606c | 3,611,705 |
def for_each_package_specs(ns, pkg_specs, info, func,
repoid=None, just_on_installed=True):
"""
Iterate over package specification strings, find them on remote host,
make them into ``LMI_SoftwareIdentity``, and pass them to given function.
:param list pkg_specs: Package specification strings.
... | ad00a007ee7698e94bc11af2b9abfc2be989d358 | 3,611,706 |
def cu_projection(param: str, date: date, cu_projections) -> int:
"""
Get the Columbia model's prediction
of the param for the date
"""
scenario = cu_model_scenario(tuple([s for s in cu_projections.keys()]))
quantile = cu_model_quantile()
# Extract quantiles of the model distribution
xs... | 16e240e1553b52c2fdd60e46fe55b3c18b4b7b71 | 3,611,707 |
def dicthash(d:dict)->Hash:
""" Calculate hashsum of a Python dict. Top-level fields starting from '_' are ignored """
string="_".join(str(k)+"="+str(v) for k,v in sorted(d.items()) if len(k)>0 and k[0]!='_')
return md5(string.encode('utf-8')).hexdigest() | 39adff8a7cec0ec70695013332db9eed5b03b0ab | 3,611,708 |
def _urlparse_qs(url):
"""
Parse a URL query string and return the components as a dictionary.
Based on the cgi.parse_qs method.This is a utility function provided
with urlparse so that users need not use cgi module for
parsing the url query string.
Arguments:
:type url: str
:param ur... | 3516b35f814d5bf9a549540858d632cfb0a99e17 | 3,611,709 |
def erfc_inverse(x):
""" erfc-1(x) = - 1/sqrt(2) * normal_quantile( 0.5 * x)"""
return -0.70710678118654752440 * normal_quantile(0.5 * x) | f1994c8fdee5ae94624562210fe4621594636204 | 3,611,710 |
def extract_8_statistical_features(data):
"""
Extract 8 statistical features: mean, standard deviation, length,
minimum val, first quartile, second quartile,
third quartile, maximum val
:parameter data: pandas DataFrame of the data who... | 9aae0c143fd0eb1183fa77e7cb86d3806d73cd99 | 3,611,711 |
import array
def bin_stats(x, y, xbins, stat='average'):
"""Given the variable y=f(x), and
the bins limits xbins, return the
corresponding statistics, e.g. <y(xbins)>
Options are rms, median y average
"""
nbins = len(xbins)
if stat == 'average' or stat == 'mean': func = mean
elif sta... | ea97d56cde01bfa4ebd7eaf4d0c53a5f2d48c4c8 | 3,611,712 |
from typing import Sequence
def all_unique(lst):
"""Returns True if all elements of Sequence `lst` are unique.
False otherwise.
"""
assert isinstance(lst, Sequence)
return bool(len(set(lst)) == len(lst)) | 546d4254d5ca287952eec6af2bda048e60bb6b89 | 3,611,713 |
def ingredient_fractions_predictor() -> IngredientFractionsPredictor:
"""Build a Ingredient Fractions predictor for testing."""
return IngredientFractionsPredictor(
name='Ingredient fractions predictor',
description='Computes total ingredient fractions',
input_descriptor=formulation,
... | 934ab59171ceb3bd2227092ab3e5eea300884d95 | 3,611,714 |
def record_fuzz_target(engine, binary_name, job_type):
"""Record existence of fuzz target."""
if not binary_name:
logs.log_error('Expected binary_name.')
return None
project = data_handler.get_project_name(job_type)
key_name = data_types.fuzz_target_fully_qualified_name(
engine, project, binary_n... | 5b88599944eeb74c2da43d395e9877d4e9d7eba9 | 3,611,715 |
def svm_loss(x: NPArray, y: NPIntArray) -> tuple[float, NPArray]:
"""
Computes the loss and gradient using for multiclass SVM classification.
Inputs:
- x: Input data, of shape (N, C) where x[i, j] is the score for the jth class
for the ith input.
- y: Vector of labels, of shape (N,) where y[i... | e5d8709d3323e9a8dacc3ed7344c6208fdbcfefc | 3,611,716 |
def make_constellation(config):
"""Builds the constellation model."""
n_caps = 3
encoder = SetTransformer(
n_layers=4,
n_heads=4,
n_dims=128,
n_output_dims=32,
n_outputs=n_caps,
layer_norm=True,
dropout_rate=0.,
)
decoder = ConstellationCapsule(
n_caps=n_caps... | a250df9a70be5637eee079e1471e3a4baa2f3ba9 | 3,611,717 |
import os.path
import shutil
import ssl
from urllib.error import URLError
from urllib.request import Request, urlopen
from clinica.utils.stream import cprint
import _sha256
def fetch_file(remote, dirname=None):
"""Download a specific file and save it into the resources folder of the package.
Args:
re... | cb489a6605385b0dd1a61f4246e0cc4b44e6f93c | 3,611,718 |
def scale_matrix(
factor: float,
origin: np.ndarray = None,
direction: np.ndarray = None
) -> np.ndarray:
"""
Return matrix to scale by factor around origin in direction.
Use factor -1 for point symmetry.
"""
if direction is None:
# uniform scaling
M = np.array(
... | 92b000567245b4cf7732ee66ffd32e389fbf365c | 3,611,719 |
def plot_h(data, cols, wspace=.1, plot_kw=None, **kwargs):
"""
Plot horizontally
Args:
data: DataFrame of data
cols: columns to be plotted
wspace: spacing between plots
plot_kw: kwargs for each plot
**kwargs: kwargs for the whole plot
Returns:
axes for p... | dc3f62442da33f3bc45df70ec0e6ee41cab658ab | 3,611,720 |
def generate_average_csv(fname, fields, trait_list):
""" Generate CSV called fname with fields and trait_list """
csv = open(fname, 'w')
csv.write(','.join(map(str, fields)) + '\n')
csv.write(','.join(map(str, trait_list)) + '\n')
csv.close()
return fname | 43195ea054ea537a4860c07c03c96efc263c472f | 3,611,721 |
import sys
def skip_if_no_xpu(func):
""" oneCCL xpu tests require at least 1 XPU. Skip if this is not met"""
@wraps(func)
def wrapper(*args, **kwargs):
if not xpu_is_avaliable:
sys.exit(TEST_SKIPS["no_cuda"].exit_code)
# if torch.xpu.device_count() < int(os.environ["WORLD_SIZE"... | d1aa2e9405a6da3010811204aac383ee5b6f509a | 3,611,722 |
from typing import Set
def get_s2_patches_with_no_19_class_target() -> Set[str]:
"""
List all patches from the BigEarthNet-S2 dataset that
have _no_ defined classes with the 19-class nomenclature.
Note: This set still includes patches with snow, clouds, or shadows.
To re-build the file, it is ne... | 9132457f706df6dfe2f538a25210c936d528d565 | 3,611,723 |
import torch
from typing import Tuple
from typing import List
def winnow_model(model: torch.nn.Module, input_shape: Tuple,
list_of_modules_to_winnow: List[Tuple[torch.nn.Module, List]] = None,
reshape=True, in_place=False, verbose=False):
""" This API is used to winnow a model w... | 41643e9bb832669293220693282d2232b7ae321a | 3,611,724 |
import tqdm
def get_expr_dict(input_tuple):
"""Returns the quantification results as a dict of dicts."""
bamfname, contig, start, stop, length, worker_ind = input_tuple
if worker_ind == None: worker_ind = 0
if contig is None:
desc_str='all_reads'
else:
desc_str='chr_'+contig
region = dict(
... | 036f8f683e32c189ca64be0e2b8a7a2b4564bfd2 | 3,611,725 |
def arg_parsing(req):
"""
:type req: class 'ow_lander.srv._Grind.GrindRequest'
"""
if req.use_defaults :
# Default trenching values
x_start = 1.65
y_start = 0.0
depth = 0.05
length = 0.6
parallel = True
ground_position = constants.DEFAULT_GROUND_HEIGHT
else :
x_start = req... | 981d0faca672fe5d508dde24cef24500f0885ca5 | 3,611,726 |
def adjacency_lattice_square(sidelength, num_cells, search_radius, periodic_bc=False):
"""
periodic_bc: wrap around boundary condition (False default)
"""
assert num_cells == sidelength ** 2
adjacency_arr_uptri = np.zeros((num_cells, num_cells))
# build only upper diagonal part of A
for a in... | 4fedf6dffc6b9fe92bf164d8a2ae8a176126f026 | 3,611,727 |
import math
def determine_aha_part(seg_sa, affine_sa, three_slices=False):
""" Determine the AHA part for each slice. """
# Label class in the segmentation
label = {'BG': 0, 'LV': 1, 'Myo': 2, 'RV': 3}
# Sort the z-axis positions of the slices with both endo and epicardium
# segmentations
X, ... | 0fe5f26f172a9fc77fcfb98b562b583760982949 | 3,611,728 |
def swap_scientific_notation_float(line: deque, precision: int) -> deque:
"""
Returns a deque representing 'pycode_as_deque' with any python floats that
will get "cut-off" by the 'precision' arg when they are rounded as being
rendered as strings in python's "e format" scientific notation.
A float ... | 8ddc47cff96a98309f6c646769116e26e6c693db | 3,611,729 |
import math
def exponential(max_iteration=1.0, min_transition=1.0, initial_radius=1.0):
"""
Return an exponential radius neighborhood function.
f(iteration) = initial_radius * (min_transition / initial_radius)^(iteration / max_iteration)
Keyword arguments:
max_iteration -- maximum count of itera... | 8f3a8789547ddb93cb884da04c92ecfef9daf5ed | 3,611,730 |
def cal_newpath(dis_mat, path_new, cityNum):
"""
计算所有路径对应的距离
:param dis_mat: 城市距离矩阵 ndarray
:param path_new: 路径矩阵 ndarray
:param cityNum: 城市数量 int
:return: 动态规划最优路径 list
"""
dis_list = []
for each in path_new:
dis = 0
for j in range(cityNum - 1):
dis = dis_mat[each[j]][each[j + 1]] + dis... | 2a4d733e9633a44da3d66d74d54b75efc165d8bf | 3,611,731 |
def load_input(source):
"""load the input"""
if isinstance(source, str): # pragma: no cover
with open(source, 'r', encoding='utf8') as stream:
return stream.read()
else:
data = source.read()
if isinstance(data, bytes):
return data.decode("utf8")
retur... | fa0a9aac1854af59f400bf2344638c8fb4bee96d | 3,611,732 |
def init_sqlite_db(connection=None):
"""
Initializes SQLite database.
:param connection: Database connection object
:return: Database connection object
"""
if connection is None:
raise AttributeError("Provide connection as parameter")
sql_query = '''CREATE TABLE api_keys (
... | 44d6d787be2a905bd26d230b251b76a305a37ead | 3,611,733 |
def _compute_dci(x_recon, x):
"""Computes score based on both training and testing codes and factors."""
scores = {}
importance_matrix, train_err = compute_importance_gbt(
x_recon, x)
assert importance_matrix.shape[0] == x_recon.shape[0]
assert importance_matrix.shape[1] == x.shape[0]
informativeness_... | 047745df93d73e26578c1d7b7b0bb5e4165a1434 | 3,611,734 |
from typing import Dict
from typing import Any
def sample_sac_params(trial: optuna.Trial,
octree_observations: bool = True,
octree_depth: int = 4,
octree_full_depth: int = 2,
octree_channels_in: int = 7,
octr... | 63d57c7a8de0eb12f01b410ed33ba5b5beb4a725 | 3,611,735 |
import random
def split_vertex_labels(num_vertices, proportion_censored, rng=None):
""" Adapts tensorflow dataset to produce another element in the labels dictionary
corresponding to whether the vertex is in the training or testing set.
Parameters
----------
num_vertices: The number of vertices i... | 63a3419ca171ef006041e12f3cb61b9c368262af | 3,611,736 |
def table():
"""Display base and representative InChI."""
if request.method == "POST" and request.form.get("nmr-inchi-table-data"):
nmr_experiment_type = request.form.get("select-nmr-experiment")
generate_nmr(
nmr_experiment_type=nmr_experiment_type, records=RECORDS
)
... | 29d5552418f98b79036df37446ae940f85873ed6 | 3,611,737 |
def PSO(
directed = False, preprocess = "auto", load_nodes = True, load_node_types = True,
load_edge_weights = True, auto_enable_tradeoffs = True,
sort_tmp_dir = None, verbose = 2, cache = True, cache_path = None,
cache_sys_var = "GRAPH_CACHE_DIR", version = "2020-05-19", **kwargs
) -> Graph:
"""Ret... | 02d9f25998aba2154e8d921ce4667c8803f286df | 3,611,738 |
def se_resnet152(num_classes):
"""Constructs a ResNet-152 model.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
"""
model = ResNet(SEBottleneck, [3, 8, 36, 3], num_classes=num_classes)
model.avgpool = nn.AdaptiveAvgPool2d(1)
return model | 95984b592f695e9423263f8c3cf0edb7fb07e541 | 3,611,739 |
def is_integer(mark_string):
"""Function to check if a supposed pk is an integer."""
try:
mark_id = int(mark_string)
except ValueError:
return False
return mark_id | 1df4842906452cf5672584e5781e0e8a2d3b367d | 3,611,740 |
def getCoordsAndSearchRadius(inputString):
"""getCoordsAndSearchRadius.
Args:
inputString:
"""
coords = {}
ra = None
dec = None
radius = None
sex = COORDS_SEX_REGEX_COMPILED.search(inputString)
decimal = COORDS_DEC_REGEX_COMPILED.search(inputString)
if decimal:
... | 289e6153908ec0553c4560b18d8afd4e57aeebbc | 3,611,741 |
def _extract_command_with_args(cmd):
"""Parse input command with arguments.
Parses the input command in such a way that the user may
provide additional argument to the command. The format used is this:
command=arg1,arg2,arg3,...
all the additional arguments are passed as arguments to the target
... | 3db8aebab04e32f292e2956412bd81e7a07a471e | 3,611,742 |
def filtered_secondary_files(unfiltered_secondary_files: dict) -> list:
"""
Remove unprocessed secondary files.
Interpolated strings and optional inputs in secondary files were added to
CWL in version 1.1.
The CWL libraries we call do successfully resolve the interpolated strings,
but add the ... | 89c0906984ca634b8afc3dd4bdf2e9ccbbad504c | 3,611,743 |
def get_P_rtd_hs(q_rtd_hs, e_rtd):
"""定格消費電力 (4)
Args:
q_rtd_hs(float): 温水暖房用熱源機の定格能力 (W)
e_rtd(float): 当該給湯機の効率
Returns:
float: 定格消費電力
"""
return q_rtd_hs / e_rtd | 61d4a7c2f26b979891936efd6db0195ca3b083b0 | 3,611,744 |
def registration_success(request):
"""
This view is called when the registration succeeded
"""
rcontext = RequestContext(request, {})
return render_to_response('auth/registration_success.haml', rcontext) | 6fe87ed1559b7d0a54a380d543eeab1a6a4fc63b | 3,611,745 |
def match_attr( src1, src2, attrlist=None ):
"""
extension: check that attributes listed are the same for each src
input: string <OR> dict, string <OR> dict, list
output: bool
notes: input sources can be either paths to netcdf files
or dicts {attr_name : attr_val}.
if attrlist is None t... | 4a6eb511dc90c85bc38fa2bd0caef1a85e1c2446 | 3,611,746 |
def slash_validator(
epochs_ctx: EpochsContext,
state: BeaconState,
slashed_index: ValidatorIndex,
config: Eth2Config,
whistleblower_index: ValidatorIndex = None,
) -> BeaconState:
"""
Slash the validator with index ``slashed_index``.
"""
epoch = epochs_ctx.current_shuffling.epoch
... | da36f061397c3909427abc47a30b68e56ac819de | 3,611,747 |
import sys
import csv
def read_csv_file(filename):
"""Read csv file into a numpy array
"""
header_info = {}
# Make this Py2.x and Py3.x compatible
if sys.version_info[0] < 3:
infile = open(filename, 'rb')
else:
infile = open(filename, 'r', newline='', encoding='utf8')
with... | 7994b35afca23029a931253bb577c875f1bc0417 | 3,611,748 |
def biot_savart(loop_list, fov_min, fov_max, fov_n, points=None):
"""
Creates coil profiles for arbitrary loops, for use in multichannel shim examples that do not match spherical
harmonics
Args:
centers (list): List of 3D float center points for each loop in mm
normals (list): List of 3D... | 1a116e3299131911bc1a6c19106518c56427efe4 | 3,611,749 |
def heatmap(data, row_labels, col_labels, ax=None, cbar_kw={}, cbarlabel="", **kwargs):
"""
Create a heatmap from a numpy array and two lists of labels.
Arguments:
data : A 2D numpy array of shape (N,M)
row_labels : A list or array of length N with the labels
for ... | 5465a92df4edbc94e194a140b0a81b105be68953 | 3,611,750 |
import json
import logging
def writeTimeSeriesData(assetId,aspectName,dataList):
""" URL = /timeseries/{entityId}/{propertySetName}
Body needs to be a list of dictionaries:
[
{
"_time": "2019-02-10T23:01:00Z",
"exampleproperty0": "examplepropertyValue",
"exampleproperty... | bcd8aa2994d51ef6777b9459b3a0e693dd0de843 | 3,611,751 |
def check_availability(nova_connection: NovaConnection, snapshot_image_uuid: str):
"""
Check the availability of snapshot_image_uuid
:param nova_connection: NovaConnection object
:param snapshot_image_uuid: str snapshot uuid to find
:return: bool True if is found else False
:raise: ValueError ... | d9fe9023ca719fe2f8af10a24cad74271acac697 | 3,611,752 |
def get_request():
"""Get the current request from anywhere."""
request = request_accessor.send(None)
if request:
return request[0][1]
return None | 92853938db8d7f90551c6ce4febbfedbaccfa6db | 3,611,753 |
def get_aligned_face_and_landmarks(
im, face_cache, aligned_face_size=256, padding=(0, 0)
):
"""
get all aligned faces and landmarks of all images
:param imgs: origin images
:param fa: face_alignment package
:return:
"""
aligned_cur_shapes = []
aligned_cur_im = []
for mat, point... | cdb0989a377c609945058e2903fbec15b94c64ce | 3,611,754 |
def items_per_cart(customers, orders, data):
"""Return customers dataframe with an extra column containing
the average of items_per_cart for each customer."""
mapper = customers_mapper(data)
customers = customers.copy()
orders = orders.copy()
orders['customer_unique_id'] = orders['customer_id'].... | 8fdbdba3bfaaeaeaf89cafcaee0597cf626856d6 | 3,611,755 |
def getParameterDefinitions():
"""Return ParameterDefinitionCollections for each appropriate ArmiObject."""
return {Block: _getBlockParams()} | 502c909754b80c4e0bf40dd74a77e6b2c2df55e1 | 3,611,756 |
def check_fake_image_dataset(method):
"""A wrapper that wraps a parameter checker around the original Dataset(FakeImageDataset)."""
@wraps(method)
def new_method(self, *args, **kwargs):
_, param_dict = parse_user_args(method, *args, **kwargs)
nreq_param_int = ['num_images', 'num_classes', ... | 11b140ca35b5f3f232c1d410671010c9351dd220 | 3,611,757 |
async def validation_exception_handler(request: Request, exc: RequestValidationError):
"""
Handling error in validating requests
"""
return JSONResponse(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
content=get_error_response(request, exc)
) | a05629d0853b9aadceebda568450373718bd5912 | 3,611,758 |
def update(hostname, ip, ttl=None):
"""
Create or update desired DNS record.
Returns Synology-friendly status strings:
https://community.synology.com/enu/forum/17/post/57640?reply=213305
"""
log.debug("Updating {} to {}".format(hostname, ip))
# get zone name correctly (from hostname)
zo... | 9382ebf8c5958e755c980b11e4d8d30780a09783 | 3,611,759 |
def cpo(total_cost, total_transactions):
"""Return the CPT (Cost per Order).
Args:
total_cost (float): Total cost of marketing.
total_transactions (int): Total number of transactions.
Returns:
cpt (float) as total cost per order
"""
return total_cost / total_transactions | aaaaf5a96fcbef65e59591954bded1afa13f8c47 | 3,611,760 |
def convert_seq2seq_golds(indices, lengths, rlut, subword_fix=lambda x: x):
"""Convert indices to words and format like a bleu reference corpus.
:param indices: The indices of the gold sentence. Should be in the shape
`[B, T]`. Iterating though axis=1 should yield ints.
:param lengths: The length o... | 152385efd2354486d2e069c9ac80f27032672c70 | 3,611,761 |
import sys
def brew(args, source, cwd=None, callback=None):
"""
Compile command
"""
if sys.platform == "win32":
args.append("-s")
else:
args.append("-e")
return run("coffee", args=args, source=source.encode('utf-8'), callback=callback) | 826cccb72bf5cf008f7beb6f0307f678985ea49e | 3,611,762 |
import math
import sys
def compare_tokens(ref,dat,tol,feps,ieps):
"""
Compare two tokens taking a potential tolerance into account.
The number returned is the number of characters that are the same.
"""
tmp = str(tol)
(tr,dr,lnr,tnr) = ref
(td,dd,lnd,tnd) = dat
#result = -2*math.log10(... | 89a4d4f5354fd85ebba8f71118fdca5933c509a1 | 3,611,763 |
def advanced_raster_scan(ny=10, nx=10, fast_axis=1, mirror=[1, 1], theta=0, dy=1, dx=1):
"""
Generates as raster scan.
Parameters
----------
ny, nx : int
Number of steps in *y* (vertical) and *x* (horizontal) direction
*x* is the fast axis
dy, dx : float
Step size (grid... | f3c54a605956c4373654fb466e6b0493048160a0 | 3,611,764 |
def command(func):
"""Decorator to register a fn as an available command."""
if func.__name__ not in COMMANDS:
COMMANDS.append(func.__name__)
return func | 5ed35f6fe82751c95969cd43e5ef2fe3f6fc3dcf | 3,611,765 |
def dendrogram(
df, method='average', filter=None, n=0, p=0, orientation=None, figsize=None, fontsize=16,
label_rotation=45, ax=None
):
"""
Fits a `scipy` hierarchical clustering algorithm to the given DataFrame's variables and visualizes the results as
a `scipy` dendrogram.
The default vertica... | f2f8838547df8c0112e65ff1f6bfb0687f86730b | 3,611,766 |
def intervalrecordlookup(table, start='start', stop='stop', include_stop=False):
"""
As :func:`petl.transform.intervals.intervallookup` but return records
instead of tuples.
"""
tree = recordtree(table, start=start, stop=stop)
return IntervalTreeLookup(tree, include_stop=include_stop) | cc1941e96a0affabcebabb2e39b34b65aa12cb10 | 3,611,767 |
def Convert2targetSeqView(
sampleName,
sampleBamName,
sampleSplitBamName,
vcfFile,
outputDir,
outputFileName):
"""This ``converts`` the Delly Vcf file having tumor normal, to tab-delimited format for input to targetSeqView
:param str sampleName: str for the name... | c2d13107f0e142a17fb10d1933bbed17e17e24ea | 3,611,768 |
def max_valued_dose_dependent_assertion_to_jtms(ev, s, a, ac):
""" convert this continous valued DIKB assertion to a JTMS assertion that includes the dose used in the study/experiment
@param ev:an instance of EvidenceBase containing Assertions instances
@param s:string - representation of the assertion ty... | 6e8312112fa9022d966aca0da6808df7393fa173 | 3,611,769 |
import re
def create_user():
"""注册新用户"""
data = request.get_json()
if not data:
return bad_request('Please post json data.')
message = {}
if 'username' not in data or not data['username']:
message['username'] = 'Please provide a valid username.'
pattern = '^(([^<>()\[\]\\.,;:\... | 97629ef053c298a679dd46f820f76ba49056620f | 3,611,770 |
def rebin_1darray(a, shape, function='sum'):
"""Rebin an array into a new shape by making the sum or mean
"""
sh = shape,a.shape[0]//shape
if function == 'mean':
return a.reshape(sh).mean(-1)
elif function == 'sum':
return a.reshape(sh).sum(-1)
else:
print("WARNING: doing... | 66de60326e081c27aae471281c79c5e86f5180e3 | 3,611,771 |
def affine(src, dst, rcond=1e-6):
"""Estimate the best affine matrix by least-squares in target space.
The implementation is specific to 3-dimensional source and target spaces,
but could be generalized easily.
"""
assert src.shape[1] == dst.shape[1] == 3
flat_dst = dst.flatten(order="C") # ord... | a9d59339813fd0e37e51262a8f13e7af7e4a7918 | 3,611,772 |
def get_ground_truth(obj, image, question):
"""
Get the ground truth value for the image/question combination in reader
study obj.
"""
ground_truths = obj.statistics["ground_truths"]
return ground_truths[image][question] | 522b5550344891e0985bacb9c763c4c52686cb67 | 3,611,773 |
import os
def get_workspace(strOrigPath, strType_='flatten', strSuff_=''):
""" Return TDIS working (flatten) path given TDIS path. """
if os.path.split(strOrigPath)[1].startswith('TDISm__'):
strScene = strOrigPath.split(os.sep)[-4].split('_')[0]
p, f = os.path.split(strOrigPath)
strWor... | adb28fe59a436a85329c7f7e88412835e6486a38 | 3,611,774 |
def remove_dist_img():
"""Remove image from dist measure
1. find dist measure by id, if not found return error msg
2. remove image url from DB
3. return the removed image url as response
"""
# Extract dut_id and img_url from request
dut_id = request.json["dut_id"]
img_url = request.json... | a30dcd1bee89d1c316973ce1e336548a1ab93b29 | 3,611,775 |
def eval_math(math, compiled_math, workspace):
""" Compile a mathematical expression
Args:
math (:obj:`str`): mathematical expression
compiled_math (:obj:`_ast.Expression`): compiled expression
workspace (:obj:`dict`): values to use for the symbols in the expression
Returns:
... | deeaefa52a048bf218874614062f8e6e43b9e389 | 3,611,776 |
def LF_CD_PARENTHETICAL_DESC(c):
"""
This label function looks for mentions that are in paranthesis.
Some of the gene mentions are abbreviations rather than names of a gene.
"""
if ")" in c[1].get_span() and "(" in list(get_left_tokens(c[1], window=1)):
if LF_CD_DISTANCE_SHORT(c):
... | d4cf44b27cf8ee2139173096a39328c2d841dd96 | 3,611,777 |
def _declare_clang_library_target_files(
ctx,
target,
build_config_path,
clang_custom_info):
"""Declares the outputs for a clang module and returns a struct value describing the clang module.
Args:
ctx: A `ctx` instance.
target: A target `dict` from the package d... | faf39325495eadc5cb775c4ed97f28e871ac8598 | 3,611,778 |
def is_pandas_df(obj):
"""Check if an object is a Pandas dataframe
The benefit here is that Pandas doesn't have to be included
in the dependencies for pydeck
The drawback of course is that the Pandas API might change and break this function
"""
return obj.__class__.__module__ == 'pandas.core.f... | aa226f86d8640903fef4e51121e285ba9c594a3c | 3,611,779 |
import glob
import os
def dynamic_range_input():
"""
Input: list of all consensus peak files
Method: Loop through each consensus file. Define method,condition,mark.
Method: Use method,condition,mark to glob relevant bam file pairs.
Output: One consensus file with one BAM file. Their condition,mark... | 5fef6c4136717622e6049e152fbe11c1f4128475 | 3,611,780 |
import logging
def collect_vcard_names(vcard):
""" Collect all vcard possible names in fields 'fn', 'n' and 'email' """
if not isinstance(vcard, Component):
raise TypeError("parameter 'vcard' must be a vobject.base.Component (type: '" + str(type(vcard)) + "')")
# collect names
logging.debug("... | adbb3c82f53aa501c468472a24382e5eb4398a28 | 3,611,781 |
def time(days=0, seconds=0, minutes=0, hours=0, **kwargs):
""" Returns a Time that can be added to a Date object.
Other parameters: microseconds, milliseconds, weeks, months, years.
"""
return Time(days=days, seconds=seconds, minutes=minutes, hours=hours, **kwargs) | 3e39559a4f9d9a2da9bc97489a4c1a8582533883 | 3,611,782 |
def accuracy(output, target, topk=(1,)):
"""Computes the precision@k for the specified values of k"""
maxk = max(topk)
batch_size = target.size(0)
# output: [B, d]
_, pred = output.topk(maxk, 1, True, True)
pred = pred.t()
# pred: [B, len(topk)] -> [len(topk), B]
# target.reshape(1, -1)... | f8dd618922056eafb7aa1e856137c6a0ea7a3c6e | 3,611,783 |
def password_login(request):
"""
客户端用户使用密码登录
:param request:
:return:
"""
print('api:password_login')
if request.session.get(USER_SESSION_KEY):
print("###api:password_login request.session.session_key已经存在: ", request.session.session_key)
return fail(ResultCode.COMMONERR, "失败:... | f2e794d188d485385170d2e0ae8c5a192a384896 | 3,611,784 |
import os
def article_image(instance, file_name):
"""
Fonction pour générer le chemin des images des articles
Récupère l'instance et affecte la valeur à une variable avec la propriété "pk" et "title" de l'instance si elle
est disponible, sinon affecte un UUID généré, puis retourne la vari... | 25305d903c64b72e3187f8dcb24f83ac1c64dd14 | 3,611,785 |
def gen_node_color_map(table_column,
palette = {'d': palette_color_brewer_q_Set2(),
'c': (palette_color_brewer_s_GnBu(), palette_color_brewer_d_RdYlBu())},
mapping_type='c',
default_color=None,
... | 08fe825e3901cb21c39ea7c32ea6c023b9e50a0f | 3,611,786 |
def unpack_qubit(qubit):
"""
Get a qubit from an object.
:param qubit: An int or Qubit.
:return: A Qubit instance
"""
if isinstance(qubit, integer_types):
return Qubit(qubit)
elif isinstance(qubit, Qubit):
return qubit
elif isinstance(qubit, QubitPlaceholder):
re... | 27f6dd2598bf2cc052849bbf032f4d1cdf545058 | 3,611,787 |
def solve(f, x0):
"""
Solve the equation f(x) = x using a fixed point iteration. x0 is the start value.
"""
x = x0
for n in range(10000): # at most 10000 iterations
oldX = x;
x = f(x);
if abs(x - oldX) < 1.0e-15:
return x; | d5f5409d689c842c1a8c70b95c621360c9ae7c8c | 3,611,788 |
import time
import json
def save(filename, data):
"""Saves the result data to the given a json file.
Overwrites the file if it already exists.
Args:
filename: The name of the output file.
data: An instance of `Result`.
"""
log.debug(f'Saving data to {filename}', data)
def co... | f07895429c660364b3c04c852fc9d573daa9b3e0 | 3,611,789 |
import datasets
def mi_estimate(y_real, gen, enc, masks, k, batch_size, z_dim, s_dim,
z_trans = None):
"""Estimates the MI of the encoder.
Args:
y_real: s_I
gen: generator, (z -> x^)
enc: encoder, (x^ -> dist(z^))
masks: for sampling z_\I from the prior
k: number o... | 68e0d902145ba1eec6d02b195a56413f9feebe4e | 3,611,790 |
from application.plotlydash.dashboard import create_dashboard
from application.assets import compile_assets
import sqlite3
def create_app():
"""Construct core Flask application with embedded Dash app."""
app = Flask(__name__, instance_relative_config=False)
app.config.from_object('config.Config')
wit... | fb1cd994477f7cddd1852edad3d28b685cc69892 | 3,611,791 |
def _transformer_configs(c: Configs):
"""
### Transformer configurations
"""
# We use our
# [configurable transformer implementation](../configs.html#TransformerConfigs)
conf = TransformerConfigs()
# Set the vocabulary sizes for embeddings and generating logits
conf.n_src_vocab = c.n_to... | 6cc7d72cef9a1f607b6f0e712f0a3792247892c2 | 3,611,792 |
def te_diff_template(ruletype):
"""
This is a template for the type_* diff functions.
Parameters:
ruletype The rule type, e.g. "type_transition".
"""
def diff(self):
"""Generate the difference in rules between the policies."""
self.log.info(
"Generating {0} dif... | d2f5b2eca127be8c991ac0c49027bce9c01ee3a2 | 3,611,793 |
def normalize(v1, Rmin=1.0e-8, Rmax=1.0e15):
"""
Do not normalize in place. Not supported in autograd
"""
n = norm(v1)
if n < Rmin or n > Rmax:
print('vector:', v1)
print('norm:', n)
raise Exception("Could not normalize vector. Vector norm beyond tolerance")
else:
... | dddc57693472e5a72ab3caed5e592fd859a4b64e | 3,611,794 |
import sys
import os
import stat
import subprocess
def run(*args):
"""Load given `envfile` and run `command` with `params`"""
if not args:
args = sys.argv[1:]
if len(args) < 2:
print('Usage: runenv <envfile> <command> <params>')
sys.exit(0)
os.environ.update(create_env(args[0... | 662afec597b45d2db21444b06b626912a103b061 | 3,611,795 |
import re
def find_version() -> str:
"""Only define version in one place."""
version_file = read_file("__init__.py")
version_match = re.search(r'^__version__ = ["\']([^"\']*)["\']', version_file, re.M)
if version_match:
return version_match.group(1)
raise RuntimeError("Unable to find versi... | 8bbd0c331eef2a1918f0fcf0ce63127396e40681 | 3,611,796 |
def p2_allocateByScore(CCA, nameCat, quota, rank, scorelist, final_dic, CCA_dic):
"""
Allocates students to cca where applicants exceed quota
Returns the final dictionaries
"""
cat = ""
for key, value in nameCat.items(): #theoretically it will all be the same anyway
cat = value
quot... | de0ec96eadf396319a7dfbb3942a6917afc6c84c | 3,611,797 |
def _total_solves(color_info):
"""
Return total number of linear solves required based on the given coloring info.
Parameters
----------
color_info : dict
dict['fwd'] = (col_lists, row_maps)
col_lists is a list of column lists, the first being a list of uncolored columns.
... | 32031f2ba834f7d6ed310b0a71ab43884b424459 | 3,611,798 |
def generat_int_pop(n_particles,n_vars,low_bounds,up_bounds):
"""
Generate initial population function.
Here, random values between the lower and the higer bounds are defined for the initial population:
x1^j = rand[xlb^j, xub^j]
Parameters:
n_particles: int
Number of partic... | 27afd97b45b74135633d133ee7ff1163898bf1b8 | 3,611,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.