content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def get_groups_data():
"""
Get all groups, get all users for each group and sort groups by users
:return:
"""
groups = [group["name"] for group in jira.get_groups(limit=200)["groups"]]
groups_and_users = [get_all_users(group) for group in groups]
groups_and_users = [sort_users_in_group(group... | 9ec0d3772b438f10edde4a4bad591f249709de98 | 3,649,164 |
def hindu_lunar_holiday(l_month, l_day, g_year):
"""Return the list of fixed dates of occurrences of Hindu lunar
month, month, day, day, in Gregorian year, g_year."""
l_year = hindu_lunar_year(
hindu_lunar_from_fixed(gregorian_new_year(g_year)))
date1 = hindu_date_occur(l_month, l_day, l_year)
... | fa9bafead696b177a137c12b7544c8e71c4f2f43 | 3,649,166 |
import copy
def identify_all_failure_paths(network_df_in,edge_failure_set,flow_dataframe,path_criteria):
"""Identify all paths that contain an edge
Parameters
---------
network_df_in - Pandas DataFrame of network
edge_failure_set - List of string edge ID's
flow_dataframe - Pandas DataFrame of... | db2da6ad20a4ae547c309ac63b6e68a17c3874e7 | 3,649,167 |
def wikipedia_wtap_setup():
"""
A commander has 5 tanks, 2 aircraft and 1 sea vessel and is told to
engage 3 targets with values 5,10,20 ...
"""
tanks = ["tank-{}".format(i) for i in range(5)]
aircrafts = ["aircraft-{}".format(i) for i in range(2)]
ships = ["ship-{}".format(i) for i in range... | 828746bef74b88bde1a9c72a79338ec05591721a | 3,649,168 |
def allowed_file(filename: str) -> bool:
"""Determines whether filename is allowable
Parameters
----------
filename : str
a filename
Returns
-------
bool
True if allowed
"""
return "." in filename and filename.rsplit(".", 1)[1].lower() in ALLOWED_EXTENSIONS | fd05abc21025c9eb49f7e3426b4e183b178361c4 | 3,649,169 |
def update_bitweights(realization, asgn, tileids, tg_ids, tg_ids2idx, bitweights):
"""
Update bit weights for assigned science targets
"""
for tileid in tileids:
try: # Find which targets were assigned
adata = asgn.tile_location_target(tileid)
for loc, tgid in adata.items... | f1b7e085d43e36b025aa1c61ab1b7156ba1d3ed7 | 3,649,171 |
def load_from_input_flags(params, params_source, input_flags):
"""Update params dictionary with input flags.
Args:
params: Python dictionary of hyperparameters.
params_source: Python dictionary to record source of hyperparameters.
input_flags: All the flags with non-null value of overridden
hyper... | 7ec8662f03469f1ed03f29c9f7e9663c49aa7056 | 3,649,172 |
import hal
def hal(_module_patch):
"""Simulated hal module"""
return hal | 3ab217e0cbce54d6dab01217c829905dc61bf06c | 3,649,173 |
def elements(all_isotopes=True):
"""
Loads a DataFrame of all elements and isotopes.
Scraped from https://www.webelements.com/
Returns
-------
pandas DataFrame with columns (element, atomic_number, isotope, atomic_weight, percent)
"""
el = pd.read_pickle(pkgrs.resource_filename('latool... | d706ee5ffaa8c756c9e85f3e143876070f8f81e4 | 3,649,174 |
import typing
def create_steps_sequence(num_steps: Numeric, axis: str) -> typing.List[typing.Tuple[float, str]]:
"""
Returns a list of num_steps tuples: [float, str], with given string parameter, and
the floating-point parameter increasing lineairly from 0 to 1.
Example:
>>> create_steps_sequenc... | 3f7e2010a3360c90bec81a02228b1a7590686175 | 3,649,176 |
def disable_doze_light(ad):
"""Force the device not in doze light mode.
Args:
ad: android device object.
Returns:
True if device is not in doze light mode.
False otherwise.
"""
ad.adb.shell("dumpsys battery reset")
ad.adb.shell("cmd deviceidle disable light")
adb_sh... | d2054ae8f84a45b360ded839badfbd19fea83b11 | 3,649,177 |
def jobs():
""" List all jobs """
return jsonify(job.get_jobs()) | c7141011c59851586d327185892ea61d7a11ef58 | 3,649,178 |
def get_pipelines():
"""Get pipelines."""
return PIPELINES | 2d770a9fa189dd534528d26794f8887c638723f4 | 3,649,179 |
import re
def tokenize(s):
"""
Tokenize on parenthesis, punctuation, spaces and American units followed by a slash.
We sometimes give American units and metric units for baking recipes. For example:
* 2 tablespoons/30 mililiters milk or cream
* 2 1/2 cups/300 grams all-purpose flour
... | 04575ff78cb73515fafcda541177d53d330bd510 | 3,649,180 |
def makeColorMatrix(n, bg_color, bg_alpha, ix=None,
fg_color=[228/255.0, 26/255.0, 28/255.0], fg_alpha=1.0):
"""
Construct the RGBA color parameter for a matplotlib plot.
This function is intended to allow for a set of "foreground" points to be
colored according to integer labels (e.g. according to clustering ou... | 7ef7a7cfb6cd4a6bcb97086382e6b95e5340ce78 | 3,649,181 |
import itertools
def closest_pair(points):
"""
最近点対 O(N log N)
Verify: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_5_A&lang=ja
:param list of Point points:
:rtype: (float, (Point, Point))
:return: (距離, 点対)
"""
assert len(points) >= 2
def _rec(xsorted):
"""... | fbb189269b6d1fcbf214d8030d49bb0605b375c2 | 3,649,182 |
def less_equals(l,r):
"""
| Forms constraint :math:`l \leq r`.
:param l: number,
:ref:`scalar object<scalar_ref>` or
:ref:`multidimensional object<multi_ref>`.
:param r: number,
:ref:`scalar object<scalar_ref>` or
:ref:`multidimensional object<m... | ba37a090cbbf1d7db99411d67e9eda572c1f0153 | 3,649,183 |
def ensureImageMode(tex : Image, mode="RGBA") -> Image:
"""Ensure the passed image is in a given mode. If it is not, convert it.
https://pillow.readthedocs.io/en/stable/handbook/concepts.html#concept-modes
:param Image tex: The image whose mode to check
:param str mode: The mode to ensure and convert t... | 9b77763fbfea0f66b4b4d7151cdf595f2e2b8aa6 | 3,649,184 |
def code2name(code: int) -> str:
""" Convert prefecture code to name """
return __code2name[code] | d2ca1a3977915359afd8254337e14c6fd13db8b3 | 3,649,187 |
def newton(backward_differences, max_num_iters, newton_coefficient, ode_fn_vec,
order, step_size, time, tol, unitary, upper):
"""Runs Newton's method to solve the BDF equation."""
initial_guess = tf.reduce_sum(
tf1.where(
tf.range(MAX_ORDER + 1) <= order,
backward_differences[:M... | 9a5e6e45357d2d769153bf6854818e22df7639f3 | 3,649,188 |
import random
def input(channel):
"""
To read the value of a GPIO pin:
:param channel:
:return:
"""
return LOW if random.random() < 0.5 else HIGH | 838df044dc18c443e2f35f7f67a8e07b8276e1a3 | 3,649,190 |
def kml_start(params):
"""Define basic kml
header string"""
kmlstart = '''
<Document>
<name>%s</name>
<open>1</open>
<description>%s</description>
'''
return kmlstart % (params[0], params[1]) | c2fa4c1eeff086dfc3baa41ecd067634920b25b1 | 3,649,191 |
def add_item_to_do_list():
"""
Asks users to keep entering items to add to a new To Do list until they enter the word 'stop'
:return: to do list with new items
"""
### TO COMPLETE ###
return to_do_list | 4c133ea3c05024a51dda2fb9f01dcc30926f84f4 | 3,649,192 |
def parse(tokens):
"""Currently parse just supports fn, variable and constant definitions."""
context = Context()
context.tokens = tokens
while tokens:
parse_token(context)
if context.stack:
raise CompileError("after parsing, there are still words on the stack!!:\n{0}".format(
... | 89dce5a630dd0bd657963185ac533738bee7d6a5 | 3,649,193 |
def get_file_iterator(options):
"""
returns a sequence of files
raises IOError if problemmatic
raises ValueError if problemmatic
"""
# -------- BUILD FILE ITERATOR/GENERATOR --------
if options.f is not None:
files = options.f
elif options.l is not None:
try:
... | 53b16f49d14dc346e404a63415772dd2a1d10f50 | 3,649,195 |
def entropy_from_CT(SA, CT):
"""
Calculates specific entropy of seawater.
Parameters
----------
SA : array_like
Absolute salinity [g kg :sup:`-1`]
CT : array_like
Conservative Temperature [:math:`^\circ` C (ITS-90)]
Returns
-------
entropy : array_like
... | dfaaeef93ed924bc5e49fb02c30b6cc43ef824e0 | 3,649,196 |
def checking_log(input_pdb_path: str, output_log_path: str, properties: dict = None, **kwargs) -> int:
"""Create :class:`CheckingLog <model.checking_log.CheckingLog>` class and
execute the :meth:`launch() <model.checking_log.CheckingLog.launch>` method."""
return CheckingLog(input_pdb_path=input_pdb_path,
... | c6cb77585920609e12b90f5f783ceb73b58afb8b | 3,649,197 |
def get_registry_by_name(cli_ctx, registry_name, resource_group_name=None):
"""Returns a tuple of Registry object and resource group name.
:param str registry_name: The name of container registry
:param str resource_group_name: The name of resource group
"""
resource_group_name = get_resource_group_... | ca4bcee260f035a7921e772dffaace379e0ab115 | 3,649,199 |
def plot_karyotype_summary(haploid_coverage,
chromosomes,
chrom_length,
output_dir,
bed_filename,
bed_file_sep=',',
binsize=1000000,
... | 5234b2ac9e459cfe445be6820abb97821503f554 | 3,649,200 |
import torch
def probs_to_mu_sigma(probs):
"""Calculate mean and covariance matrix for each channel of probs
tensor of keypoint probabilites [N, C, H, W]
mean calculated on a grid of scale [-1, 1]
Parameters
----------
probs : torch.Tensor
tensor of shape [N, C, H, W] where each chann... | d0653e50d1f9ec4125e9b30c10a0e6cb78c6dc8e | 3,649,202 |
def fetch_biomart_genes_mm9():
"""Fetches mm9 genes from Ensembl via biomart."""
return _fetch_genes_biomart(
host='http://may2012.archive.ensembl.org',
gene_name_attr='external_gene_id') | f184608e87a2d390b47fd0f78d293dfd52064ad0 | 3,649,203 |
def tweet_words(tweet):
"""Return the words in a tweet."""
return extract_words(tweet_text(tweet)) | c207553fa1bd718083d26e57a9daea43c5629116 | 3,649,204 |
def meter_statistics(meter_id,api_endpoint,token,meter_list,web,**kwargs):
"""
Get the statistics for the specified meter.
Args:
meter_id(string): The meter name.
api_endpoint(string): The api endpoint for the ceilometer service.
token(string): X-Auth-token.
meter_list(list): T... | 33c717dee32027a1502a5a295b87c5cd67a2c054 | 3,649,205 |
from typing import Union
from typing import Tuple
def parse_image_size(image_size: Union[Text, int, Tuple[int, int]]):
"""Parse the image size and return (height, width).
Args:
image_size: A integer, a tuple (H, W), or a string with HxW format.
Returns:
A tuple of integer (height, width).
... | 12d8925780914672b1e7d976040596f3178e7e20 | 3,649,206 |
def find_last_match(view, what, start, end, flags=0):
"""Find last occurrence of `what` between `start`, `end`.
"""
match = view.find(what, start, flags)
new_match = None
while match:
new_match = view.find(what, match.end(), flags)
if new_match and new_match.end() <= end:
... | fc863cf00d05a1fb6302a34b5b1e891e3c9eb3d7 | 3,649,207 |
def convert_metrics_per_batch_to_per_sample(metrics, target_masks):
"""
Args:
metrics: list of len(num_batches), each element: list of len(num_metrics), each element: (num_active_in_batch,) metric per element
target_masks: list of len(num_batches), each element: (batch_size, seq_len, feat_dim) b... | 2ceae1402ac0efae841683d426f87a295f3695c8 | 3,649,208 |
import asyncio
async def get_series(database, series_id):
"""Get a series."""
series_query = """
select series.id, series.played, series_metadata.name, rounds.tournament_id, tournaments.id as tournament_id,
tournaments.name as tournament_name, events.id as event_id, events.name as event_name
... | f5e122052209c399c41afcd579f9b16e863c7a28 | 3,649,209 |
def n_mpjpe(predicted, target):
"""
Normalized MPJPE (scale only), adapted from:
https://github.com/hrhodin/UnsupervisedGeometryAwareRepresentationLearning/blob/master/losses/poses.py
"""
assert predicted.shape == target.shape
norm_predicted = np.mean(np.sum(predicted**2, axis=2, keepdims=T... | 68656aca6226db3a4cc7670ccc1972d666b11261 | 3,649,210 |
import math
def calc_distance(p1, p2):
""" calculates a distance on a 2d euclidean space, between two points"""
dist = math.sqrt((p2[0] - p1[0]) ** 2 + (p2[1] - p1[1]) ** 2)
return dist | d4005d44d5724c051860fb9aa2edeab1654157c6 | 3,649,211 |
def rgb2ycbcr(img, range=255., only_y=True):
"""same as matlab rgb2ycbcr, please use bgr2ycbcr when using cv2.imread
img: shape=[h, w, 3]
range: the data range
only_y: only return Y channel
"""
in_img_type = img.dtype
img.astype(np.float32)
range_scale = 255. / range
img *= range_sca... | e3dfd7b35faf437a936813afe537d1d4a41b2f6b | 3,649,212 |
def _create_xctest_bundle(name, actions, binary):
"""Creates an `.xctest` bundle that contains the given binary.
Args:
name: The name of the target being built, which will be used as the
basename of the bundle (followed by the .xctest bundle extension).
actions: The context's action... | cf6c64b73b7fcbd7df2a5e6bb60e0605b16a8f58 | 3,649,213 |
def doFile(path_, *args, **kwargs):
"""Execute a given file from path with arguments."""
result, reason = loadfile(path_)
if result:
data = result(*args, **kwargs)
if data:
return data[1]
error(data[1])
error(reason) | 15c6dd79872b479275717fb8a574a34f92381390 | 3,649,214 |
from pretty import pretty
from pprint import pformat
def pformat(obj, verbose=False):
"""
Prettyprint an object. Either use the `pretty` library or the
builtin `pprint`.
"""
try:
return pretty(obj, verbose=verbose)
except ImportError:
return pformat(obj) | 7522c9b64650a5056fb22d7fdd0c459ce87ca7c7 | 3,649,215 |
def reanalyze_function(*args):
"""
reanalyze_function(func_t pfn, ea_t ea1=0, ea_t ea2=BADADDR, bool analyze_parents=False)
reanalyze_function(func_t pfn, ea_t ea1=0, ea_t ea2=BADADDR)
reanalyze_function(func_t pfn, ea_t ea1=0)
reanalyze_function(func_t pfn)
"""
return _idaapi.reanalyze_function... | 52d248fbb82ebb41ff925c42b7cb6856c5cba927 | 3,649,216 |
def categorical_sample_logits(logits):
"""
Samples (symbolically) from categorical distribution, where logits is a NxK
matrix specifying N categorical distributions with K categories
specifically, exp(logits) / sum( exp(logits), axis=1 ) is the
probabilities of the different classes
Cleverly ... | c5bf8615fe3c25f392bc3fa27f965527f237ef3e | 3,649,217 |
def mass(d, r):
""" computes the right hand side of the differential equation of mass continuity
"""
return 4 * pi * d * r * r | 1924309951e35d36b51fe92389c3fa68fac3ebfa | 3,649,218 |
def bord(u):
"""
éxécution de bord("undébutuntructrucundébut")
i suffix estPréfixe
23 ndébutuntructrucundébut False
22 débutuntructrucundébut False
21 ébutuntructrucundébut False
20 butuntructrucundébut False
19 utuntructrucundébut False
18 tuntructrucundé... | 950eaac804a0788c9d2f845d594b7781d5ea9aa4 | 3,649,219 |
def is_unique_n_bit_vector(string: str) -> bool:
"""
Similiar to the dict solution, it just uses a bit vector instead of a dict or array.
"""
vector = 0
for letter in string:
if vector & 1 << ord(letter):
return False
vector |= 1 << ord(letter)
return True | d19609f1fb1e6a189a9adb11b37a96632c8d0958 | 3,649,220 |
def seq2msk(isq):
"""
Convert seqhis into mskhis
OpticksPhoton.h uses a mask but seq use the index for bit-bevity::
3 enum
4 {
5 CERENKOV = 0x1 << 0,
6 SCINTILLATION = 0x1 << 1,
7 MISS = 0x1 << 2,
8 BU... | 950dc8fe1fcc275f7a90e695816ea1777cc5164e | 3,649,221 |
def split(ich):
""" Split a multi-component InChI into InChIs for each of its components.
(fix this for /s [which should be removed in split/join operations]
and /m, which is joined as /m0110.. with no separators)
:param ich: InChI string
:type ich: str
:rtype: tuple(str)... | 0db3bee951e38f7db8cbcdb02a64ed28b9562e9d | 3,649,222 |
def crtb_cb(client, crtb):
"""Wait for the crtb to have the userId populated"""
def cb():
c = client.reload(crtb)
return c.userId is not None
return cb | eff248a877e195e59d2f6db812af2ff43955aee0 | 3,649,223 |
def create_network(network_input, n_alphabets):
""" create the structure of the neural network """
model = Sequential()
model.add(LSTM(512,input_shape=(network_input.shape[1], network_input.shape[2]),return_sequences=True))
model.add(Dropout(0.3))
model.add(Bidirectional(LSTM(512, return_sequences=T... | dd6610f0db02d0d20fb457d91346144494ad32e4 | 3,649,224 |
def create_derivative_graph(f, xrange, n):
"""Takes a function as an input with a specific interval xrange, then creates a list with the ouput
y-points for the nth derivative of f.
:param f: Input function that we wish to take the derivative of.
:type f: lambda
:param xrange: The interval on wh... | 782d26d22c93ae4b05d075fbf4075a8bba9d89b8 | 3,649,225 |
def _matching_not_matching(on, **kwargs):
"""
Change the text for matching/not matching
"""
text = "matching" if not on else "not matching"
classname = "colour-off" if not on else "colour-on"
return text, classname | aeefa7f16e3268ffe7af93db72490abe053370b2 | 3,649,226 |
def sample(model, x, steps, temperature=1.0, sample=False, top_k=None):
"""
take a conditioning sequence of indices in x (of shape (b,t)) and predict the next token in
the sequence, feeding the predictions back into the model each time. Clearly the sampling
has quadratic complexity unlike an RNN that is... | 532ad7e1af4c7b059bbd12a8584c469bcb5d079e | 3,649,228 |
def vstack(arg_list):
"""Wrapper on vstack to ensure list argument.
"""
return Vstack(*arg_list) | 95215c8277da6b86c21220021d667ae3dcc05440 | 3,649,229 |
import json
def metadata_to_list(metadata):
"""Transform a metadata dictionary retrieved from Cassandra to a list of
tuples. If metadata items are lists they are split into multiple pairs in
the result list
:param metadata: dict"""
res = []
for k, v in metadata.iteritems():
try:
... | 1044a93742a635e72e443d3a5c2e5805702d1602 | 3,649,230 |
from typing import Optional
from typing import Union
import torch
from pathlib import Path
import json
def load_separator(
model_str_or_path: str = "umxhq",
niter: int = 1,
residual: bool = False,
slicq_wiener: bool = False,
wiener_win_len: Optional[int] = 300,
device: Union[str, torch.device]... | 2cb2d951d669c7d08a3bf3cabc5c49a11ca717fc | 3,649,232 |
def IntermediateParticleConst_get_decorator_type_name():
"""IntermediateParticleConst_get_decorator_type_name() -> std::string"""
return _RMF.IntermediateParticleConst_get_decorator_type_name() | efb869aece5ad0f19e06f5d1a13e89998cde53a8 | 3,649,233 |
def multiply_add_plain_with_delta(ct, pt, context_data):
"""Add plaintext to ciphertext.
Args:
ct (Ciphertext): ct is pre-computed carrier polynomial where we can add pt data.
pt (Plaintext): A plaintext representation of integer data to be encrypted.
context (Context): Context for extr... | 4f004cc443d183f25cf35bc691c9797b4a8a5875 | 3,649,234 |
import json
from datetime import datetime
def retrieve_form_data(form, submission_type="solution"):
"""Quick utility function that groups together the processing of request data. Allows for easier handling of exceptions
Takes request object as argument
On Success, returns hashmap of processed data...other... | 4ab635ac226ebb7811baf2d0e3d71c8cfc25b1da | 3,649,236 |
def keep_english_for_spacy_nn(df):
"""This function takes the DataFrame for songs
and keep songs with english as main language
for english version of spacy neural network for word processing"""
#Keep only english for spacy NN English preprocessing words
#Network for other languages like fre... | e24402fa91ee0444c86867c98777fbd3cb7c9894 | 3,649,238 |
def make_dealer_cards_more_fun(deck, dealer):
"""
to make dealercards more fun to make dealer win this game more.
:param dealercards: dealercards
:return: none
maybe has a lot of memory work will arise.
"""
dealercards = card_sorting_dealer(dealer)
count = 0
if jokbo(dealercards) =... | 5adf8fbeeb53124c75ec43a13492d7aef1ebdc7e | 3,649,239 |
def data(request):
"""Returns available albums from the database. Can be optionally filtered by year.
This is called from templates/albums/album/index.html when the year input is changed.
"""
year = request.GET.get('year')
if year:
try:
year = int(year)
except (ValueErro... | 8390bcc6fd2bcc109930cb34b3269b450c12a87c | 3,649,241 |
from typing import Tuple
def yaw_to_quaternion3d(yaw: float) -> Tuple[float,float,float,float]:
"""
Args:
- yaw: rotation about the z-axis
Returns:
- qx,qy,qz,qw: quaternion coefficients
"""
qx,qy,qz,qw = Rotation.from_euler('z', yaw).as_quat()
return qx,qy,qz,qw | 263a0b12e0c165f929c5004cdb67b8133f117140 | 3,649,242 |
def parse_coap_response_code(response_code):
"""
Parse the binary code from CoAP response and return the response code as a float.
See also https://tools.ietf.org/html/rfc7252#section-5.9 for response code definitions.
:rtype float
"""
response_code_class = response_code // 32
response_code... | 9a8165f205ec2f6fe8576e18a831498f82834a10 | 3,649,243 |
from functools import reduce
def modified_partial_sum_product(
sum_op, prod_op, factors, eliminate=frozenset(), plate_to_step=dict()
):
"""
Generalization of the tensor variable elimination algorithm of
:func:`funsor.sum_product.partial_sum_product` to handle markov dimensions
in addition to plate... | 24d5f529d03eeb3a332cc861fdabff3a0d613d37 | 3,649,244 |
def load_scicar_cell_lines(test=False):
"""Download sci-CAR cell lines data from GEO."""
if test:
adata = load_scicar_cell_lines(test=False)
adata = subset_joint_data(adata)
return adata
return load_scicar(
rna_url,
rna_cells_url,
rna_genes_url,
atac_u... | 4760b41e2a29125ba9eaf597c555b1b40e338612 | 3,649,245 |
def binary_search(sorted_list, item):
"""
Implements a Binary Search, O(log n).
If item is is list, returns amount of steps.
If item not in list, returns None.
"""
steps = 0
start = 0
end = len(sorted_list)
while start < end:
steps += 1
mid = (start + end) // 2
... | 30b1bba330752455d932b4c6cf1ad4dab5969db3 | 3,649,246 |
def _scale_by(number, should_fail=False):
"""
A helper function that creates a scaling policy and scales by the given
number, if the number is not zero. Otherwise, just triggers convergence.
:param int number: The number to scale by.
:param bool should_fail: Whether or not the policy execution sho... | 046dcaf120d4c04578e9562b23f76f1cb8f98690 | 3,649,248 |
import traceback
def selectgender(value):
"""格式化为是/否
:param value:M/F,
:return: 男/女
"""
absent = {"M": u'男', "F": u'女'}
try:
if value:
return absent[value]
return ""
except:
traceback.print_exc() | 7b6b0b41b5ea8d3eaab5574881b40f5c00da73cd | 3,649,249 |
def Clifford_twirl_channel_one_qubit(K, rho, sys=1, dim=[2]):
"""
Twirls the given channel with Kraus operators in K by the one-qubit
Clifford group on the given subsystem (specified by sys).
"""
n = int(np.log2(np.sum([d for d in dim])))
C1 = eye(2**n)
C2 = Rx_i(sys, np.pi, n)
C3 = Rx... | 1225c8689641e245d7666c75f9e31d862f1efe56 | 3,649,250 |
def unpack_batch(batch, use_cuda=False):
""" Unpack a batch from the data loader. """
input_ids = batch[0]
input_mask = batch[1]
segment_ids = batch[2]
boundary_ids = batch[3]
pos_ids = batch[4]
rel_ids = batch[5]
knowledge_feature = batch[6]
bio_ids = batch[1]
# knowledge_adjoin... | 6bc8bc9b3c8a9e2b40ac08e67c9fbcf84914e2eb | 3,649,251 |
def truncate(text: str, length: int = 255, end: str = "...") -> str:
"""Truncate text.
Parameters
---------
text : str
length : int, default 255
Max text length.
end : str, default "..."
The characters that come at the end of the text.
Returns
-------
truncated text... | f14605542418ca95e4752be7ec2fea189b9454ce | 3,649,252 |
def gaussian_slice(x, sigma, mu):
"""
return a slice of x in which the gaussian is significant
exp(-0.5 * ((x - mu) / sigma) ** 2) < given_threshold
"""
r = sigma * sp.sqrt(-2.0 * sp.log(small_thr))
x_lo = bisect_left(x, mu - r)
x_hi = bisect_right(x, mu + r)
return slice(x_lo, x_hi) | 25ed1bf4423e8d86baaebec54e4478b58b58365c | 3,649,254 |
def preview(delivery_id):
"""
打印预览
:param delivery_id:
:return:
"""
delivery_info = get_delivery_row_by_id(delivery_id)
# 检查资源是否存在
if not delivery_info:
abort(404)
# 检查资源是否删除
if delivery_info.status_delete == STATUS_DEL_OK:
abort(410)
delivery_print_date = ti... | d57acf49d7692fe4da02607695ad71fdad1758e5 | 3,649,255 |
import requests
def request_with_json(json_payload):
"""
Load interpolations from the interp service into the DB
"""
test_response = requests.post(INTERP_URL, json=json_payload)
test_response_json = test_response.json()
return test_response_json | 5222060788ce321d258fa23309f5894640a70589 | 3,649,256 |
def correlation(df, rowvar=False):
"""
Calculate column-wise Pearson correlations using ``numpy.ma.corrcoef``
Input data is masked to ignore NaNs when calculating correlations. Data is returned as
a Pandas ``DataFrame`` of column_n x column_n dimensions, with column index copied to
both axes.
... | b64ab2f5f08191c9536f6d08b8132b3ecc100698 | 3,649,257 |
def cost_zpk_fit(zpk_args, f, x,
error_func=kontrol.core.math.log_mse,
error_func_kwargs={}):
"""The cost function for fitting a frequency series with zero-pole-gain.
Parameters
----------
zpk_args: array
A 1-D list of zeros, poles, and gain.
Zeros and ... | fb18cfae20a279e0b65a03b37a10c33e6a17c6db | 3,649,258 |
def getTrainPredictions(img,subImgSize,model):
"""Makes a prediction for an image.
Takes an input of any size, crops it to specified size, makes
predictions for each cropped window, and stitches output together.
Parameters
----------
img : np.array (n x m x 3)
Image to be transformed
... | e81ee8d6839fa07753ac379520c60d7b2d5be175 | 3,649,259 |
def use_bcbio_variation_recall(algs):
"""Processing uses bcbio-variation-recall. Avoids core requirement if not used.
"""
for alg in algs:
jointcaller = alg.get("jointcaller", [])
if not isinstance(jointcaller, (tuple, list)):
jointcaller = [jointcaller]
for caller in joi... | c833f9a2dd9523f78cf294a1822b251b6940a1cd | 3,649,260 |
from typing import Mapping
def _sa_model_info(Model: type, types: AttributeType) -> Mapping[str, AttributeInfo]:
""" Get the full information about the model
This function gets a full, cachable, information about the model's `types` attributes, once.
sa_model_info() can then filter it the way it likes, w... | 8886427a4722bb1fb37664fa7382f61922d89b69 | 3,649,261 |
def bll6_models(estimators, cv_search={}, transform_search={}):
"""
Provides good defaults for transform_search to models()
Args:
estimators: list of estimators as accepted by models()
transform_search: optional LeadTransform arguments to override the defaults
"""
cvd = dict(
... | c69d17c1f5c6625ef6382959910b23d44459c158 | 3,649,262 |
def bgColor(col):
""" Return a background color for a given column title """
# Auto-generated columns
if col in ColumnList._COLUMNS_GEN:
return BG_GEN
# KiCad protected columns
elif col in ColumnList._COLUMNS_PROTECTED:
return BG_KICAD
# Additional user columns
else:
... | ae6a44c61807f513a679ccad0f4c39622efa768e | 3,649,263 |
def merge_hedge_positions(df, hedge):
"""
将一个表中的多条记录进行合并,然后对冲
:param self:
:param df:
:return:
"""
# 临时使用,主要是因为i1709.与i1709一类在分组时会出问题,i1709.是由api中查询得到
if df.empty:
return df
df['Symbol'] = df['InstrumentID']
# 合并
df = df.groupby(by=['Symbol', 'InstrumentID', 'HedgeFla... | 4bcaa8b160186c6c5e6e3382017d0db3ee9d6c6e | 3,649,264 |
import numpy
def BackwardSubTri(U,y):
"""
usage: x = BackwardSubTri(U,y)
Row-oriented backward substitution to solve the upper-triangular, 'tridiagonal'
linear system
U x = y
This function does not ensure that U has the correct nonzero structure. It does,
however, attempt to catch ... | 5b7c2c636eac0912aa26bc8a236f1c870b95c48b | 3,649,265 |
def discrete_model(parents, lookup_table):
"""
Create CausalAssignmentModel based on a lookup table.
Lookup_table maps inputs values to weigths of the output values
The actual output values are sampled from a discrete distribution
of integers with probability proportional to the weights.
Looku... | a0eee81439b5997b91941181b8c7978d7f3581c9 | 3,649,266 |
import base64
import json
import tempfile
import traceback
def retrieve(datafile, provider):
"""
Retrieve a file from the remote provider
:param datafile:
:param provider:
:return: the path to a temporary file containing the data, or None
"""
r = _connect(provider)
try:
data =... | fca0595df40b1743e5cdb73c8a20b0ddc6a2611f | 3,649,267 |
def edf_parse_message(EDFFILE):
"""Return message info."""
message = edf_get_event_data(EDFFILE).contents
time = message.sttime
message = string_at(byref(message.message[0]), message.message.contents.len + 1)[2:]
message = message.decode('UTF-8')
return (time, message) | 3d29db28b7d110e9fcdf6e8309c027cb4254c647 | 3,649,268 |
from typing import Dict
import logging
def read_abbrevs_and_add_to_db(abbrevs_path: str,
db: Connection) -> Dict[str, int]:
"""Add abbreviations from `abbrevs_path` to `idx` and `defns`."""
with open(abbrevs_path, 'rt') as ab:
abbrevs = read_abbrevs(ab)
abbrev_nid = ... | 6c937fd15352d8b7e3dcf607bbf2a5b66f105ffb | 3,649,269 |
def is_encrypted(input_file: str) -> bool:
"""Checks if the inputted file is encrypted using PyPDF4 library"""
with open(input_file, 'rb') as pdf_file:
pdf_reader = PdfFileReader(pdf_file, strict=False)
return pdf_reader.isEncrypted | be03d2843f35e21d7881c17f086f33ffbee5e8fa | 3,649,270 |
def get_parameter_by_name(device, name):
""" Find the given device's parameter that belongs to the given name """
for i in device.parameters:
if i.original_name == name:
return i
return | 9669262a9bcac8b4c054e07b2c04b780b5f84f87 | 3,649,271 |
from typing import Optional
import requests
def LogPrint(email: str, fileName: str, materialType: str, printWeight: float, printPurpose: str, msdNumber: Optional[str], paymentOwed: bool) -> bool:
"""Logs a print. Returns if the task was successful.
:param email: Email of the user exporting the print.
:pa... | eb8c629d4eacdf24988cd6d33d4b4733bb90caac | 3,649,272 |
def is_requirement(line):
"""
Return True if the requirement line is a package requirement;
that is, it is not blank, a comment, or editable.
"""
# Remove whitespace at the start/end of the line
line = line.strip()
# Skip blank lines, comments, and editable installs
return not (
... | db30ff6bb2421d2b31939a20e708bf1c923a353e | 3,649,273 |
def read_pose_txt(pose_txt):
"""
Read the pose txt file and return a 4x4 rigid transformation.
"""
with open(pose_txt, "r") as f:
lines = f.readlines()
pose = np.zeros((4, 4))
for line_idx, line in enumerate(lines):
items = line.split(" ")
for i in range(4... | 250cc4c793a3bba948aeac2ca547c6680937a6e7 | 3,649,274 |
def get_futures(race_ids=list(range(1, 13000))):
"""Get Futures for all BikeReg race pages with given race_ids."""
session = FuturesSession(max_workers=8)
return [session.get(f'https://results.bikereg.com/race/{race_id}')
for race_id in race_ids if race_id not in BAD_IDS] | 1992c7b2fee93eecb75fd6e0c7a625181073609f | 3,649,275 |
def sum_of_proper_divisors(number: int):
"""
Let d(n) be defined as the sum of proper divisors of n
(numbers less than n which divide evenly into n).
:param number:
:return:
"""
divisors = []
for n in range(1, number):
if number % n == 0:
divisors.append(n)
retu... | 9015dd3809f90d328b0b4a6b51f6fcb145f0241d | 3,649,276 |
def coddington_meridional(p, q, theta):
""" return radius of curvature """
f = p * q / (p + q)
R = 2 * f / np.sin(theta)
return R | ef4964f08af065b2da6cbe5b156e4e976406a879 | 3,649,277 |
def read_analysis_file(timestamp=None, filepath=None, data_dict=None,
file_id=None, ana_file=None, close_file=True, mode='r'):
"""
Creates a data_dict from an AnalysisResults file as generated by analysis_v3
:param timestamp: str with a measurement timestamp
:param filepath: (str)... | 5e0d1797f45f18665f3ae5eaa6bac987fe94f926 | 3,649,278 |
def get_player_macro_econ_df(rpl: sc2reader.resources.Replay,
pid: int) -> pd.DataFrame:
"""This function organises the records of a player's major
macroeconomic performance indicators.
The function uses a player's PlayerStatsEvents contained in a Replay
object to compose a... | 4a0123ce4fe7f704f83c39a8c78e29c9347b1e1a | 3,649,279 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.