content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import torch
def sampler(value, percentile):
"""Score based on sampling task model output distribution
Args:
value: The output of the task model
percentile: the (sorted) index of the sample we use
Returns:
The percentile largest distance from the mean of the samples.
"""
s... | 905665d5219df7737adaf2c7fd435cef3f3c7f1d | 3,656,800 |
def gists_by(username, number=-1, etag=None):
"""Iterate over gists created by the provided username.
.. deprecated:: 1.2.0
Use :meth:`github3.github.GitHub.gists_by` instead.
:param str username: (required), if provided, get the gists for this user
instead of the authenticated user.
... | b98f478dbac25c0334296da5055952a776af9d39 | 3,656,801 |
import pyspark
def needs_spark(test_item):
"""
Use as a decorator before test classes or methods to only run them if Spark is usable.
"""
test_item = _mark_test('spark', test_item)
try:
# noinspection PyUnresolvedReferences
except ImportError:
return unittest.skip("Skipping te... | f4d40b7119f753162ed5f6377ebef3b42d2bf549 | 3,656,802 |
from typing import Generator
def get_school_years_from_db() -> Generator:
"""Get all school years from the database.
:return: iterable with all availabe school years
"""
session: db.orm.session.Session = Session()
return (e[0] for e in set(session.query(Holiday.school_year).all())) | 48651fab2364e03a2d18224c7a798d8754cca911 | 3,656,803 |
def get_api(context=None):
"""
This function tries to detect if the app is running on a K8S cluster or locally
and returns the corresponding API object to be used to query the API server.
"""
if app.config.get("MODE") == "KUBECONFIG":
return client.CustomObjectsApi(config.new_client_from_con... | 89808a80c3ad4ae1260ffbb9611543b6e33298ee | 3,656,804 |
def is_variant(title) -> bool:
"""
Check if an issue is variant cover.
"""
return "variant" in title.lower() | 5e0bab3030c069d7726bbc8c9909f561ed139cb8 | 3,656,805 |
def _decode_common(hparams):
"""Common graph for decoding."""
features = get_input(hparams, FLAGS.data_files)
decode_features = {}
for key in features:
if key.endswith("_refs"):
continue
decode_features[key] = features[key]
_, _, _, references = seq2act_model.compute_logits(
features, hpar... | a9eac81d9fe5e0480c679e41a61699b9e281fdd5 | 3,656,806 |
from typing import Tuple
def _lex_single_line_comment(header: str) -> Tuple[str, str]:
"""
>>> _lex_single_line_comment("a=10")
('', 'a=10')
>>> _lex_single_line_comment("//comment\\nb=20")
('', 'b=20')
"""
if header[:2] != "//":
return "", header
line_end_pos = header.find("\n... | 4d562557db11c7279042e439a56cc7864fa259ef | 3,656,807 |
from thelper.data.loaders import LoaderFactory as LoaderFactory
import os
import logging
import sys
import pprint
import json
def create_loaders(config, save_dir=None):
"""Prepares the task and data loaders for a model trainer based on a provided data configuration.
This function will parse a configuration d... | 41a40951dc0f5848120cc88ac6abc34ea0367b04 | 3,656,808 |
def in_box(X, box):
"""Get a boolean array indicating whether points X are within a given box
:param X: n_pts x n_dims array of points
:param box: 2 x n_dims box specs (box[0, :] is the min point and box[1, :] is the max point)
:return: n_pts boolean array r where r[idx] is True iff X[idx, :] is within... | 8ee516937b3a19a27fed81cfee0ca19356cb5249 | 3,656,809 |
def test_partial_field_square():
"""Fields that do not extend over the whole wall"""
field = np.zeros((40, 40))
field[:10, 0] = 1
fields = {kw_field_map: field}
walls = "L"
assert func(fields, "s", walls=walls) == 0.25
field[:20, 0] = 1
assert func(fields, "s", walls=walls) == 0.5
fi... | 94af1cf9e500ddddd16c9fea61eeb43874589b68 | 3,656,810 |
import sys
from sys import path
def get_countries():
"""
The function to generate a dictionary containing ISO_3166-1 country codes
to names.
Returns:
Dictionary: A dictionary with the country codes as the keys and the
country names as the values.
"""
#Initialize the count... | 4491097e1b3f0a5cd4034b4745a7597688a952fd | 3,656,811 |
def get_empty_faceid(current_groupid, uuid, embedding,
img_style, number_people, img_objid, forecast_result):
"""
当softmax无结果时(无模型/预测置信度低)调用遍历数据库识别
:param current_groupid:
:param uuid:
:param embedding:
:param img_style:
:param number_people:
:param img_objid:
:retu... | 265250564de0ac160c5f0110293fc52693edaeda | 3,656,812 |
def dz_and_top_to_phis(
top_height: xr.DataArray, dz: xr.DataArray, dim: str = COORD_Z_CENTER
) -> xr.DataArray:
""" Compute surface geopotential from model top height and layer thicknesses"""
return _GRAVITY * (top_height + dz.sum(dim=dim)) | 14e19781cdac7a743d26db7d29317ea33ae94517 | 3,656,813 |
import scipy
def altPDF(peaks,mu,sigma=None,exc=None,method="RFT"):
"""
altPDF: Returns probability density using a truncated normal
distribution that we define as the distribution of local maxima in a
GRF under the alternative hypothesis of activation
parameters
----------
peaks: float or list of floats
lis... | 0346d1efcad2a3f8e1548857c980fb6c92ea07f3 | 3,656,814 |
def implicit_quantile_network(num_actions, quantile_embedding_dim,
network_type, state, num_quantiles):
"""The Implicit Quantile ConvNet.
Args:
num_actions: int, number of actions.
quantile_embedding_dim: int, embedding dimension for the quantile input.
network_type: named... | 2782f94b2003dca0a8865298dab2dbb17ec4cb45 | 3,656,815 |
def get_waitlist(usercode):
"""
Запрос /api/waitlists/{usercode} - возвращает waitlist контент по usercode
"""
user_by_usercode = (
AppUsers.query.filter(AppUsers.usercode == usercode).one_or_none()
)
if user_by_usercode is None:
abort(
409,
"Usercode {us... | 0592d188020b967198c1cb052d1e4b3adbc1ed21 | 3,656,816 |
def not_empty(message=None) -> Filter_T:
"""
Validate any object to ensure it's not empty (is None or has no elements).
"""
def validate(value):
if value is None:
_raise_failure(message)
if hasattr(value, '__len__') and value.__len__() == 0:
_raise_failure(messag... | f1ee9b43936978dfbd81550b9931d0cc8800eef2 | 3,656,817 |
def temporal_affine_forward(x, W, b):
"""
Run a forward pass for temporal affine layer. The dimensions are consistent with RNN/LSTM forward passes.
Arguments:
x: input data with shape (N, T, D)
W: weight matrix for input data with shape (D, M)
b: bias with shape (M,)
Outputs:
... | 2eca1c3ef36eb8bdbcaaad88c3b2f1234227e2d4 | 3,656,818 |
def uniform_regular_knot_vector(n, p, t0=0.0, t1=1.0):
"""
Create a p+1-regular uniform knot vector for
a given number of control points
Throws if n is too small
"""
# The minimum length of a p+1-regular knot vector
# is 2*(p+1)
if n < p+1:
raise RuntimeError("Too small n for a u... | e0e1bc9f2e2ea2e74d70c76d35479efebc42d2f7 | 3,656,819 |
def generateCM(labelValue, predictValue):
"""Generates the confusion matrix and rteturn it.
Args:
labelValue (np.ndarray): true values.
predictValue (np.ndarray): predicted values.
"""
FPMtx = np.logical_and((labelValue <= 0), (predictValue > 0))
FPIndices = np.argwhere(FPMtx)
FPNum = np.sum(FP... | 3ea5751bb9c9153edf4fdce12512319b75f80484 | 3,656,820 |
def get_cosine_similarity(word2vec: Word2Vec) -> np.ndarray:
"""Get the cosine similarity matrix from the embedding.
Warning; might be very big!
"""
return cosine_similarity(word2vec.wv.vectors) | b9a976de8faef0cd85265c4afdb80dd8720128f5 | 3,656,821 |
def get_bot_id() -> str:
"""
Gets the app bot ID
Returns:
The app bot ID
"""
response = CLIENT.auth_test()
return response.get('user_id') | 6dcf2121fb11fb4af1615c9d739923e86299cc0a | 3,656,822 |
import os
def extract_rawfile_unique_values(
file: str
) -> list:
"""Extract the unique raw file names from "R.FileName" (Spectronaut output), "Raw file" (MaxQuant output),
"shortname" (AlphaPept output) or "Run" (DIA-NN output) column or from the "Spectral Count" column from the
combined_peptide.tsv ... | 594744409537f977530e111826237161e6121d47 | 3,656,823 |
def _fetch_from_s3(bucket_name, path):
"""Fetch the contents of an S3 object
Args:
bucket_name (str): The S3 bucket name
path (str): The path to the S3 object
Returns:
str: The content of the S3 object in string format
"""
s3 = boto3.resource('s3')
bucket = s3.Bucket(bu... | 3e284b653c046a826b92e82bf60e7e12547280b2 | 3,656,824 |
def vrv_getatttype(schema, module, gp, aname, includes_dir = ""):
""" returns the attribut type for element name, or string if not detectable."""
# Look up if there is an override for this type in the current module, and return it
# Note that we do not honor pseudo-hungarian notation
attype, hun... | 88d014aedcc17a307e32daebd205f93e9c1e2e89 | 3,656,825 |
def inc_date(date_obj, num, date_fmt):
"""Increment the date by a certain number and return date object.
as the specific string format.
"""
return (date_obj + timedelta(days=num)).strftime(date_fmt) | 560d82b8e72614b8f9011ab97c10a7612d1c50b0 | 3,656,826 |
def recombine_edges(output_edges):
"""
Recombine a list of edges based on their rules.
Recombines identical Xe isotopes. Remove isotopes.
:param output_edges:
:return:
"""
mol = Chem.MolFromSmiles(".".join(output_edges))
# Dictionary of atom's to bond together and delete if they come in ... | 1bbce0bb315990f758aa47a0dae2dc34bff9fb2a | 3,656,827 |
from typing import List
import os
def parse_comments(content: str) -> List[str]:
"""Parses comments in LDF files
:param content: LDF file content as string
:type content: str
:returns: a list of all comments in the LDF file
:rtype: List[str]
"""
comment = os.path.join(os.path.dirname(__fi... | aed403e1888c0db73f86b172888b95e8320adabc | 3,656,828 |
def excludevars(vdict, filters):
"""
Remove dictionary items by filter
"""
vdict_remove = dict()
for filtr in filters:
a = filtervars_sub(vdict, filtr)
vdict_remove.update(a)
vdict_filtered = vdict.copy()
for key in vdict_remove.keys():
del vdict_filtered[key]
re... | 5050e946454c096a11c664d1a0910d2b2f7d985a | 3,656,829 |
def __updateEntityAttributes(fc, fldList, dom, logFile):
"""For each attribute (field) in fldList,
adds attribute definition and definition source,
classifies as range domain, unrepresentable-value domain or enumerated-value domain, and
for range domains, adds rangemin, rangemax, and un... | f304f31ea64dab2b186736af6a7177fee93afefe | 3,656,830 |
def make_laplace_pyramid(x, levels):
"""
Make Laplacian Pyramid
"""
pyramid = []
current = x
for i in range(levels):
pyramid.append(laplacian(current))
current = tensor_resample(
current,
(max(current.shape[2] // 2, 1), max(current.shape[3] // 2, 1)))
... | 88b8c94a8f5ca3fda3329c0ac8fa871693c1482f | 3,656,831 |
def create_component(ctx: NVPContext):
"""Create an instance of the component"""
return ToolsManager(ctx) | 24cf48073bb16233046abdde966c28c570cf16c0 | 3,656,832 |
import os
def _load_csv_key(symbol_key):
"""
针对csv存储模式,通过symbol_key字符串找到对应的csv具体文件名称,
如从usTSLA->找到usTSLA_2014-7-26_2016_7_26这个具体csv文件路径
:param symbol_key: str对象,eg. usTSLA
"""
# noinspection PyProtectedMember
csv_dir = ABuEnv.g_project_kl_df_data_example if ABuEnv._g_enable_example_env_ipy... | ebfdb88713e5943863f75455aa9d276d8f780450 | 3,656,833 |
def get_routing_table() -> RouteCommandResult:
"""
Execute route command via subprocess. Blocks while waiting for output.
Returns the routing table in the form of a list of routes.
"""
return list(subprocess_workflow.exec_and_parse_subprocesses(
[RouteCommandParams()],
_get_route_com... | 817d8350e7a2af514e3b239ec5d7dbc278fb7649 | 3,656,834 |
import array
def xor_arrays(arr1, arr2):
""" Does a XOR on 2 arrays, very slow"""
retarr = array('B')
for i in range(len(arr1)):
retarr.append(arr1[i] ^ arr2[i])
return retarr | 5ff978aa1a48a537a40132a5213b907fb7b14b4b | 3,656,835 |
def delete_category():
"""Delete category specified by id from database"""
category = Category.query.get(request.form['id'])
db.session.delete(category)
db.session.commit()
return '' | 47347299dd39c6afa9fd8d1cd10e1dc0906f6806 | 3,656,836 |
def gen_dd(acc, amt):
"""Generate a DD (low-level)"""
read()
dd_num = dd_no()
while dd_num in dds.keys():
dd_num = dd_no()
dd = {
'ac_no': acc,
'amount': amt
}
return dd_num, dd | 251a36131dae66f4d24dc2ce45db27f81da39845 | 3,656,837 |
def coranking_matrix(high_data, low_data):
"""Generate a co-ranking matrix from two data frames of high and low
dimensional data.
:param high_data: DataFrame containing the higher dimensional data.
:param low_data: DataFrame containing the lower dimensional data.
:returns: the co-ranking matrix of ... | 7cc77cd5ef70d7adef9020cab6f33a5dbf290557 | 3,656,838 |
def gaussian_dist_xmu1xmu2_product_x(mu1,Sigma1,mu2,Sigma2):
"""Compute distribution of N(x|mu1,Sigma1)N(x|mu2,Sigma2)"""
InvSigmaHat = np.linalg.inv(Sigma1) + np.linalg.inv(Sigma2)
SigmaHat = np.linalg.inv(InvSigmaHat)
muHat = np.dot(SigmaHat,np.linalg.solve(Sigma1, mu1) + np.linalg.solve(Sigma2,mu2))
... | 5eb50e98165bc77bc0754a93eef4f62b0665ea30 | 3,656,839 |
def default_marker_size(fmt):
""" Find a default matplotlib marker size such that different marker types
look roughly the same size.
"""
temp = fmt.replace('.-', '')
if '.' in temp:
ms = 10
elif 'D' in temp:
ms = 7
elif set(temp).intersection('<>^vd'):
ms = 9
else... | feebe9bdda47a2e041636f15c9b9595e5cd6b2cc | 3,656,840 |
def vote_smart_candidate_rating_filter(rating):
"""
Filter down the complete dict from Vote Smart to just the fields we use locally
:param rating:
:return:
"""
rating_filtered = {
'ratingId': rating.ratingId,
'rating': rating.rating,
'timeSpan': rating.times... | f4fec92e46f58444abb8dab56f28acc7e670aab0 | 3,656,841 |
def get_syntax(view):
""" get_syntax(view : sublime.View) -> str
>>> get_syntax(view)
'newLISP'
>>> get_syntax(view)
'Lisp'
Retuns current file syntax/language
"""
syntax = view.settings().get('syntax')
syntax = syntax.split('/')[-1].replace('.tmLanguage', '')
return syntax | a5be75f51de105af63ce53df7c3b7094537d28f3 | 3,656,842 |
def random_otp():
"""
:return: OTP for Event
:return type: string
"""
try:
all_events = Events.query.all() # Here Error if no Event
all_holded_events = HoldedEvents.query.all()
used_otps = set()
for otp_ in all_events:
used_otps.add(str(otp_.otp))
... | e343addc9252de4ca9d69a344beea05254c9ebb0 | 3,656,843 |
def read_config(path):
"""Read the complete INI file and check its version number
if OK, pass values to config-database
"""
return _read_config(path) | bbb95e5e02d54dd831082d556e19307109e1113d | 3,656,844 |
def getPath(file):
"""Get the path of a source file.
Use this to extract the path of a file/directory when the file
could be specified either as a FileTarget, DirectoryTarget or string.
@param file: The object representing the file.
@type file: L{FileTarget}, L{DirectoryTarget} or C{basestring}
"""
asse... | b80e5f0ead8be98dd40bbd444bc8ae9201eb54ed | 3,656,845 |
import torch
def optical_flow_to_rgb(flows):
"""
Args:
A tensor with a batch of flow fields of shape [b*num_src, 2, h, w]
"""
flows = flows.cpu().numpy()
_, h, w = flows[0].shape
rgbs = []
for i in range(len(flows)):
mag, ang = cv2.cartToPolar(flows[i, 0, ...], flows[i, 1,... | d27074eab88f0f1181c5e1acae4839cbed984e17 | 3,656,846 |
from re import MULTILINE
def get_motes_from_simulation(simfile, as_dictionary=True):
"""
This function retrieves motes data from a simulation file (.csc).
:param simfile: path to the simulation file
:param as_dictionary: flag to indicate that the output has to be formatted as a dictionary
:return... | bbf09378a45cee9a96dca136bc7751ea9372eeac | 3,656,847 |
def menu_bar():
"""each mini-game has a menu bar that allows direct access to
the main menu. This allows story mode to be bypassed after
starting war, but the game state will not be saved"""
pygame.draw.rect(SCREEN, TEAL, (0, 460, 640, 40))
menu_font = pygame.font.Font('freesansbold.ttf', 15)
m... | 0b5b16db2f53c1cbb45236512597d954bb28e7da | 3,656,848 |
def merge_sort(a, p, r):
""" merge sort
:param a: a array to sort, a[p:r+1] need to be sorted
:param p: index of array, p < r, if p >= r , the length of a is 1, return
:param r: index of array, p < r, if p >= r , the length of a is 1, return
"""
if p < r:
q = int((p + r) / 2)
# ... | 07aab16ea75cb01f2f1fb3ae32f1b1ac31c76cfb | 3,656,849 |
def get_flow_graph(limit, period):
"""
:type limit int
:type period int
:rtype: list[dict]
"""
rows = ElasticsearchQuery(
es_host=ELASTICSEARCH_HOST,
period=period,
index_prefix='logstash-other'
).query_by_string(
query='kubernetes.labels.job-name:* AND '
... | f51bb6aa6132303e2cd5ed3090507435739c0452 | 3,656,850 |
import re
import time
def upload(server_ip, share, username, password, domain, remote_path, local_path, verbose=True):
""" Get file and folder on the remote file server.
server_ip (str): This value is the ip smb server's ip.
share (str): This value is the share file name.
user... | 552079181faa10b50c306b1ee9e02c190b9711a4 | 3,656,851 |
from typing import Union
import platform
def list_directory_command(api_client: CBCloudAPI, device_id: str, directory_path: str, limit: Union[int, str]):
"""
Get list of directory entries in the remote device
:param api_client: The API client
:param device_id: The device id
:param d... | 228d4884d2fd4f69e8c7a44d737bfeca7b40f753 | 3,656,852 |
def _hparams(network, random_seed):
"""
Global registry of hyperparams. Each entry is a (default, random) tuple.
New algorithms / networks / etc. should add entries here.
"""
hparams = {}
def _hparam(name, default_val, random_val_fn):
"""Define a hyperparameter. random_val_fn takes a Ra... | 34ea9ac295f3150b870e8d1c7ce0f1b867f75122 | 3,656,853 |
def bidding_search(request):
"""
"""
query = ''
form = BiddingSearchForm(shop=request.shop, data=request.GET)
if form.is_valid():
query = form.get_query()
results = form.search()
else:
results = form.all_results()
pager = Paginator(results, PAGE_SEARCH)
... | cda6c4ebccec88c40ae714cd81392946165b184f | 3,656,854 |
def clean_code(code, code_type):
""" Returns the provided code string as a List of lines """
if code_type.startswith(BOOTSTRAP):
if code_type.endswith(CLEAN):
return code.split("\n")
code = code.replace("\\", "\\\\")
if code_type.startswith(PERMUTATION):
if code_type.end... | fff65103003a202a039fd4683da83735b0342a7a | 3,656,855 |
def level(arr, l, ax=2, t=None, rounding=False):
"""
As level 1D but accepts general arrays and level is taken is some
specified axis.
"""
return np.apply_along_axis(level1D, ax, arr, l, t, rounding) | 80835140850dbf7883f9b4cb1f92543ee2253845 | 3,656,856 |
def updateStore(request, storeId):
""" view for updating store """
if canViewThisStore(storeId, request.user.id):
# get the corresponding store
store = Store.objects.get(id=storeId)
metadata = getFBEOnboardingDetails(store.id)
if request.method == "POST":
# Create a ... | 8cb92e31f2dc59a28281c45d698a7d810b573587 | 3,656,857 |
def i(t, T, r, a, b, c):
"""Chicago design storm equation - intensity. Uses ia and ib functions.
Args:
t: time in minutes from storm eginning
T: total storm duration in minutes
r: time to peak ratio (peak time divided by total duration)
a: IDF A parameter - can be calculated fro... | 3d31d64502fc4590b1d83e0d3a32a5de9cae2a56 | 3,656,858 |
def get_primary_id_from_equivalent_ids(equivalent_ids, _type):
"""find primary id from equivalent id dict
params
------
equivalent_ids: a dictionary containing all equivalent ids of a bio-entity
_type: the type of the bio-entity
"""
if not equivalent_ids:
return None
id_rank... | 489f9d431e553772f114f1e4a3a2577c831addda | 3,656,859 |
def get_L_max_C(L_CS_x_t_i, L_CL_x_t_i):
"""1日当たりの冷房全熱負荷の年間最大値(MJ/d)(20c)
Args:
L_CS_x_t_i(ndarray): 日付dの時刻tにおける暖冷房区画iの冷房顕熱負荷 (MJ/h)
L_CL_x_t_i(ndarray): 日付dの時刻tにおける暖冷房区画iの冷房潜熱負荷 (MJ/h)
Returns:
float: 1日当たりの冷房全熱負荷の年間最大値(MJ/d)
"""
# 暖冷房区画軸合算(暖冷房区画の次元をなくす)
L_CS_x_t = np.sum(L... | 2c5e769baacfec0d75e711b3493b07ab65796690 | 3,656,860 |
def complete_session(session: namedtuple, speeches: list) -> dict:
"""
This will result in loss of data bc content will be reduced to speeches.
HTML_classes, speaker_flow, speaker_role etc. will not be given any longer
since it's assumed that speakers are either members of parliament or
ministers.
... | 185e1518e48252fcdc222aeddf8f2ba30884c93e | 3,656,861 |
import fileinput
import re
def replace_text_in_file(file_path, replace_this, for_that, case_insensitive=False, is_regex=False, keep_copy=False,
number_of_subs=0):
""" replace a string or regex (if is_regex is set) from a file given in file_path, with another string.
This is a rep... | 12c978759fd5a31bacb396d3068ab762b442dd27 | 3,656,862 |
def load_annotations(ann_file):
"""Load the annotation according to ann_file into video_infos."""
video_infos = []
anno_database = mmcv.load(ann_file)
for video_name in anno_database:
video_info = anno_database[video_name]
video_info['video_name'] = video_name
video_infos.append(... | ac337917f313e5c695a5388c481e12787d7d78a0 | 3,656,863 |
import argparse
def commandline(args):
"""
Settings for the commandline arguments.
Returns the parsed arguments.
"""
parser = argparse.ArgumentParser(description='Checks the timestamps for files in a directory.')
parser.add_argument("-p", "--path", required=True,
help... | f3c1726e0dfde2bce6cd3e62a2300abbace7900e | 3,656,864 |
from typing import List
from typing import Dict
def seq_hist(seq_lens: List[int]) -> Dict[int, int]:
"""Returns a dict of sequence_length/count key/val pairs.
For each entry in the list of sequence lengths, tabulates
the frequency of appearance in the list and returns the
data as a dict. Useful for histogra... | 5778b7566d1b64e8db0e2dce6bbf53e06cdb196d | 3,656,865 |
import os
def make_ms_url( syndicate_host, syndicate_port, no_tls, urlpath="" ):
"""
Make a URL to the MS.
Return the URL.
"""
scheme = "https://"
default_port = 80
if no_tls:
default_port = 443
scheme = "http://"
if syndicate_port != default_port:
return scheme + ... | 4aec60c48285a8e8f8d58b18ea29928e338fa1bc | 3,656,866 |
from typing import List
def clifford_canonical_F(
pauli_layer: List[int], gamma: np.ndarray, delta: np.ndarray
) -> Circuit:
"""
Returns a Hadamard free Clifford circuit using the canonical form of elements of the Borel group
introduced in https://arxiv.org/abs/2003.09412. The canonical form has the s... | 9818866b3196ccf9608f7ea8a17145bfa9ddb2d2 | 3,656,867 |
def calculate_second_moment_nondegenerate(
mu1: float, mu2: float, sigma1: float, sigma2: float, a: float, alpha: float
) -> float:
"""The second (raw) moment of a random variable :math:`\\min(Y_1, Y_2)`.
Args:
mu1: mean of the first Gaussian random variable :math:`Y_1`
mu2: mean of the sec... | 74869b0b461777ae9cce658829c2c90ff9a4adff | 3,656,868 |
from re import X
def q_make( x, y, z, angle):
"""q_make: make a quaternion given an axis and an angle (in radians)
notes:
- rotation is counter-clockwise when rotation axis vector is
pointing at you
- if angle or vector are 0, the identity quaternion is returned.
double x, y, z : ... | bd95a3d6f89599297a089d75882aa319e474a1b7 | 3,656,869 |
def create_mssql_pymssql(username, password, host, port, database, **kwargs): # pragma: no cover
"""
create an engine connected to a mssql database using pymssql.
"""
return create_engine(
_create_mssql_pymssql(username, password, host, port, database),
**kwargs
) | a4d644839879ae374ba091f1b9e79fd210c03e3e | 3,656,870 |
def get_right_list_elements(result):
"""Some of the results are empty - therefore, the try-except.
Others are lists with more than one element and only specific
elements are relevant.
Args:
result (dict of lists): result of the xpath elements.
Returns:
dict of strs
"""
for... | b81e80363f82dfe43878b3d8cb319f7129ebfc50 | 3,656,871 |
def gen_pixloc(frame_shape, xgap=0, ygap=0, ysize=1., gen=True):
"""
Generate an array of physical pixel coordinates
Parameters
----------
frame : ndarray
uniformly illuminated and normalized flat field frame
xgap : int (optional)
ygap : int (optional)
ysize : float (optional)
... | e09bb42cc0b003f6cedf5eed79ee65293aab13e2 | 3,656,872 |
def select(df: pd.DataFrame, time_key,
from_time='00-00-00 00', to_time='99-01-01 00'):
"""
:param df:
:param time_key:
:param from_time:
:param to_time:
:return:
:rtype: pandas.DataFrame
"""
select_index = (df[time_key] >= from_time) & (df[time_key] < to_time)
return ... | e925c2543bfabf9091fae18d9dc47c01364e1df8 | 3,656,873 |
def load_apogee_distances(dr=None, unit='distance', cuts=True, extinction=True, keepdims=False):
"""
Load apogee distances (absolute magnitude from stellar model)
:param dr: Apogee DR
:type dr: int
:param unit: which unit you want to get back
- "absmag" for absolute magnitude
... | 763d646c284cb056295ae57d7a7c9ced87964406 | 3,656,874 |
import json
import logging
def userstudy(config, data_train):
"""
Update the model based on feedback from user study.
- [config]: hyperparameters for model fine-tuning
- [data_train]: data pool to sample from
"""
def preprocess_data(doc, queries):
"""
Create a new field in [doc... | d3240142b55b202833364a9583b9c7c7e237bea2 | 3,656,875 |
import re
def clique_create(request):
"""
Creates a new grouping in the database (this integration must be stored in the db to be useful)
Arguments: /group-create "groupname" "@user1 @user2"
"""
requesting_user_id = request.POST.get('user_id')
args = re.findall(DOUBLE_QUOTE_ARG_REGEX, request.... | b990079ad0685b8c524dec65166da40f0e664ef7 | 3,656,876 |
import warnings
def cg_atoms(atoms, units, sites, scale, scaleValue, siteMap, keepSingleAtoms,
package):
"""
Get positions for atoms in the coarse-grained structure and the final
bond description. Returns a dictionary of the lattice, fractional
coordinates, and bonds. Also provides the... | 5cd2a6b8b0ce886b92912eb3dd8b14f0ea14f602 | 3,656,877 |
def read_tickers(video, ocr = None, debug = False, **kwargs):
"""
Reads news stories from sliding tickers on video.
Returns lists of dictionaries which contain:
text: news story text
start time: time when news story shows up
end time: time when news story disappears
Each list co... | 9fc853d6af98c67434fcb0d18d09f42a15b7318c | 3,656,878 |
def compute_msa_weights(msa, threshold=.8):
"""
msa (Bio.Align.MultipleSeqAlignment): alignment for which sequence frequency based weights are to be computed
threshold (float): sequence identity threshold for reweighting
NOTE that columns where both sequences have a gap will not be taken into account w... | 13663501f57eef204533795c2271276a99b4a403 | 3,656,879 |
def search_storefront(client, phrase):
"""Execute storefront search on client matching phrase."""
resp = client.get(reverse("search:search"), {"q": phrase})
return [prod for prod, _ in resp.context["results"].object_list] | 0509c39cd9adb0b4c6d0849c8b068dcb3455b807 | 3,656,880 |
def is_repo_in_config(config, repo, rev, hook_id):
"""Get if a repository is defined in a pre-commit configuration.
Parameters
----------
config : dict
Pre-commit configuration dictionary.
repo : str
Repository to search.
rev : str
Repository tag revision.
hook_id : Ho... | 855315c50f4bfe53a4f9b7a5d392bb539e364617 | 3,656,881 |
def mat33_to_quat(mat):
"""
Convert matrix to quaternion.
:param mat: 3x3 matrix
:return: list, quaternion [x, y, z, w]
"""
wxyz = transforms3d.quaternions.mat2quat(mat)
return [wxyz[1], wxyz[2], wxyz[3], wxyz[0]] | 1dcedf919674895a1ed647314c328525e4068dfe | 3,656,882 |
def reshape(x, new_shape):
"""
Reshapes a tensor without changing its data.
Args:
x (Tensor): A tensor to be reshaped.
new_shape (Union[int, list(int), tuple(int)]): The new shape should be
compatible with the original shape. If the tuple has only one element,
the re... | 583ffc9e40c328586ec9d21b7a73cbc610eb5c29 | 3,656,883 |
def update_depth(depth_grid, elapsed_ts, depth_factor):
"""Just in time Update Depth for lake to pond
Parameters
----------
depth_grid: np.array like (float)
grid of current lake depths
elapsed_ts: float
number timesteps since start year
depth_factor: float
Returns
----... | e3fe2498421697ce584b385544a7501f54c02b85 | 3,656,884 |
def get_submissions(config, event_name, state='new'):
"""
Retrieve a list of submissions and their associated files
depending on their current status
Parameters
----------
config : dict
configuration
event_name : str
name of the RAMP event
state : str, optional
s... | e724c44b00db489f27c42acf7b21ba06a4ce0def | 3,656,885 |
def split_dataframe(df, size=10*1024*1024):
"""Splits huge dataframes(CSVs) into smaller segments of given size in bytes"""
# size of each row
row_size = df.memory_usage().sum() / len(df)
# maximum number of rows in each segment
row_limit = int(size // row_size)
# number of segments
seg... | 46f34d388e6f596bfcf803b4569eb3015344bafb | 3,656,886 |
from pathlib import Path
from typing import Optional
def convert_table_codes(input_filename: Path, output_filename: Path = None, column: str = 'countryCode',
namespace: Optional[str] = None, fuzzy:int = 0) -> Path:
"""
Adds a 'regionCode' column to the given table containing iso-3 country codes.
Parameters
----... | 1bba37fda512cf13e99a08a0ab7ebfdf10a4e330 | 3,656,887 |
def allow_view(user):
"""Is the current user allowed to view the user account?
Yes, if current user is admin, staff or self.
"""
if not flask.g.current_user: return False
if flask.g.am_admin: return True
if flask.g.am_staff: return True
if flask.g.current_user['username'] == user['username']... | 334e56796235e5bfab6f2220443c80fc5ff68a51 | 3,656,888 |
from datetime import datetime
import time
def httptimestamp(inhttpdate):
"""
Return timestamp from RFC1123 (HTTP/1.1).
"""
dat = datetime.datetime(*eut.parsedate(inhttpdate)[:5])
return int(time.mktime(dat.timetuple())) | acfcdbea1a9d331b7623478841c6cd1d45fd45bf | 3,656,889 |
from datetime import datetime
def calculate_duration(start_date, end_date=None):
""" Calculate how many years and months have passed between start and end dates """
# If end date not defined, use current date
if not end_date:
end_date = datetime.date.today()
years = end_date.year - start_date.... | d41c52d4d0274ce3b829b33f07c9730a34ab4cbd | 3,656,890 |
import os
def GetSourceRoot(filename):
"""Try to determine the root of the package which contains |filename|.
The current heuristic attempts to determine the root of the Chromium source
tree by searching up the directory hierarchy until we find a directory
containing src/.gn.
"""
# If filename is not ab... | cb1956998cef01138a74e3278df7c27651260f73 | 3,656,891 |
import typing
def actives(apikey: str) -> typing.List[typing.Dict]:
"""
Query FMP /actives/ API
:param apikey: Your API key.
:return: A list of dictionaries.
"""
path = f"actives"
query_vars = {"apikey": apikey}
return __return_json_v3(path=path, query_vars=query_vars) | de4eecc6f3006158407efd51d67b6a5ac40d2cfd | 3,656,892 |
def print_unicodeinfo(val: str, key: str) -> str:
"""
Prints the occurrence, unicode character or guideline rules and additional information
:param args: arguments instance
:param val: count of the occurrences of key
:param key: key (glyph or guideline rules)
:return:
"""
return f"{val:-... | 194bb1d03613e9708f8deea8c233d02dacd3e3b6 | 3,656,893 |
def qx_to_npx(df):
""" Return df with qx converted to npx.
"""
df = 1 - df
out = df.cumprod().shift()
for i in df.index:
out.loc[i, i] = 1
return out | 683a26f57dfb7ae1762df84f74186f0b88cb4688 | 3,656,894 |
def homepage(selenium, config):
"""Get homepage with selenium."""
selenium.get(config.BASE_URL)
selenium.set_window_size(config.WINDOW_WIDTH, config.WINDOW_HEIGHT)
custom_click_cookie_rollbar(selenium, config.MAX_WAIT_TIME)
return selenium | 39217a38ac09d41093070ed06803e36485f04e2b | 3,656,895 |
import torch
def _if_scalar_type_as(g, self, tensor):
"""
Convert self into the same type of tensor, as necessary.
We only support implicit casting for scalars, so we never
actually need to insert an ONNX cast operator here; just
fix up the scalar.
"""
if isinstance(self, torch._C.Value):... | 8e53bf67c8bbc78f142ffcb8027c0876eed951fe | 3,656,896 |
def read_images_text(path):
"""
see: src/base/reconstruction.cc
void Reconstruction::ReadImagesText(const std::string& path)
void Reconstruction::WriteImagesText(const std::string& path)
"""
images = {}
with open(path, "r") as fid:
while True:
line = fid.readline(... | 2aed7477e43bdcb73ad9eb866960b814278bbf0c | 3,656,897 |
def emailIsValid(email):
"""Return true if email is valid otherwise false"""
return EMAIL_RE.match(email) is not None | d9e28b68e31f1ab95c63aa80cd4a2a461cbac852 | 3,656,898 |
def calculate_line_number(text):
"""Calculate line numbers in the text"""
return len([line for line in text.split("\n") if line.strip() != ""]) | f35533945203ec2f47a89e7072ddd9b172f5554b | 3,656,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.