content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def sort_characters(text, alphabet):
"""Counting Sort"""
dim = len(text)
order = [0] * dim
count = {k: 0 for v, k in enumerate(alphabet)}
for char in text:
count[char] += 1
for j in range(1, len(alphabet)):
count[alphabet[j]] += count[alphabet[j-1]]
for i, char in reversed... | 9beb0f28a7f1ffb892e1393522b94f12e873ba66 | 3,633,600 |
def get_rp_throughput_summary(isamAppliance, date, duration, aspect, summary=True, check_mode=False, force=False):
"""
Retrieving a summary of throughput for all Reverse Proxy instances
"""
return isamAppliance.invoke_get("Retrieving a summary of throughput for all Reverse Proxy instances",
... | a559ae507939d8fc29db8ac92fdacda7742ee522 | 3,633,601 |
from typing import Optional
from typing import Union
from typing import Dict
from typing import List
from typing import Tuple
def do_regress(
test_features: np.ndarray,
train_features: np.ndarray,
train_targets: np.ndarray,
nn_count: int = 30,
batch_count: int = 200,
loss_method: str = "mse",
... | 49257c187462cfea362b35b3cb399d2851f4a7e5 | 3,633,602 |
def set_computer_policy(
name, setting, cumulative_rights_assignments=True, adml_language="en-US"
):
"""
Set a single computer policy
Args:
name (str):
The name of the policy to configure
setting (str):
The setting to configure the named policy with
cum... | 708b39564e7e97be8a986981dab3b2eedec5e01f | 3,633,603 |
import requests
def get_api_result(url):
"""
Retrieve JSON data from API via a supplied URL
"""
s = requests.Session()
r = s.get(url)
return r.json() | 933bd000b2e352f950ec86f8b6f1470ff2b0ecbd | 3,633,604 |
from functools import reduce
def lens_compose(big_lens, *smaller_lenses):
"""
Compose many lenses
"""
return reduce(_lens_compose2, smaller_lenses, big_lens) | f1be58ba017235661b5cd08bf38dbdfb3fcdfdd6 | 3,633,605 |
import logging
import collections
def create_left_maskval_to_projmat_dict(seed, whimsy_server_weights,
whimsy_client_weights, left_mask,
right_mask, build_projection_matrix):
"""Creates a dictionary mapping the values of `left_mask` and... | 8d3c034b97266123b583f1b890d1e019173f22ae | 3,633,606 |
def renew_defs(func: PrimFunc):
"""Re-generate the definition nodes for a TIR, including VarDef, BufferDef.
This pass works as a simple DeepCopy to duplicate a function with different Vars and
Buffers but the same behavior
Parameters
----------
func: PrimFunc
The input function
Ret... | 838ebc2e30e72d6b3a9405980be2843800091cea | 3,633,607 |
def requires_common_raster(method):
"""
A decorator for spectrum methods that require that another spectrum as an input and require it to be sampled on the
same wavelength raster as us.
:param method:
A method belonging to a sub-class of Spectrum.
"""
def wrapper(spectrum, other, *args... | 5ba5fb3c4dca60f730e201fa0a25781f898f5c97 | 3,633,608 |
def k8s_conf_dict(boot_conf, hb_conf):
"""
Generates and returns a dict of the k8s deployment configuration
:param boot_conf: the snaps-boot config dict
:param hb_conf: the adrenaline config dict
:return: dict with one key 'kubernetes' containing the rest of the data
"""
k8s_dict = __generat... | 49d6ee49a7c665f521dde4f9a2cf2d9e10442064 | 3,633,609 |
def autodetect_mode(a, b):
"""
Return a code identifying the mode of operation (single, mixed, inverted mixed and
batch), given a and b. See `ops.modes` for meaning of codes.
:param a: Tensor or SparseTensor.
:param b: Tensor or SparseTensor.
:return: mode of operation as an integer code.
""... | 48d7af7f075113863090380f1823349fc676f9ec | 3,633,610 |
def f_unc(x, k, weight):
"""
similar to the raw function call, but uses unp instead of np for uncertainties calculations.
:return:
"""
term = 1
# calculate the term k^x / x!. Can't do this directly, x! is too large.
for n in range(0, int(x)):
term *= k / (x - n) * unp.exp(-k/int(x))
... | 6f24688bd9c08d7632846b145ef540235da6cd4f | 3,633,611 |
import csv2_help
from os import getenv
def check_keys(gvar, mp, rp, op, not_optional=[], key_map=None, requires_server=True):
"""
Modify user settings.
"""
# Summarize the mandatory, required, and optional parameters for the current command.
mandatory = []
required = []
options = []
... | 4ba5ccbb5fc10a06ab7ecbcee7dc68e823a5c457 | 3,633,612 |
def get_data(n_clients):
"""
Import the dataset via sklearn, shuffle and split train/test.
Return training, target lists for `n_clients` and a holdout test set
"""
print("Loading data")
diabetes = load_diabetes()
y = diabetes.target
X = diabetes.data
# Add constant to emulate interce... | 0459f2ffbeaf1e21780efba9785c96d75a641d93 | 3,633,613 |
def fn(r):
"""
Returns the number of fields based on their radial distance
:param r: radial distance
:return: number of fields at radial distance
"""
return 4 * r + 4 | 5fa4a5e8f2304f907b9dd806281dc77a2152f431 | 3,633,614 |
def do_icon(name, *args, **kwargs):
"""
Render an icon
This template is an interface to the `icon` function from `django_icons`
**Tag name**::
icon
**Parameters**:
name
The name of the icon to be rendered
title
The title attribute for the icon
... | 7b8addf38d056c070af20f447435a67e29a09a8a | 3,633,615 |
def ED_BldGag(ED):
""" Returns the radial position of ElastoDyn blade gages
INPUTS:
- ED: either:
- a filename of a ElastoDyn input file
- an instance of FileCl, as returned by reading the file, ED = weio.read(ED_filename)
OUTPUTS:
- r_gag: The radial positions of the ga... | fa95475218bf35a90790296ce7149a286440a39e | 3,633,616 |
from typing import List
from typing import Dict
def multiclass_confusion_matrix_metrics(
cm: np.ndarray, labels: List[str]
) -> Dict[str, int]:
"""
Create a dictionary of multiple class labels and their TP, TN, FP, FN values
:param cm: Confusion matrix
:param labels: string labels corresponding to... | 4098dfd1e8618b1d9d87f93b924400925e047680 | 3,633,617 |
import argparse
def parse_arguments():
"""
Parse the command line arguments
"""
ap = argparse.ArgumentParser()
ap.add_argument("-ann", "--annotations_path", required=True,
help="Path to the directory containing the annotation files or path to the single annotation file.")
a... | e564699cbc74fba69b2bba90372a0513a81ae84c | 3,633,618 |
import textwrap
def is_perf_benchmarks_scheduling_valid(
perf_waterfall_file, outstream):
"""Validates that all existing benchmarks are properly scheduled.
Return: True if all benchmarks are properly scheduled, False otherwise.
"""
scheduled_non_telemetry_tests = get_scheduled_non_telemetry_benchmarks(
... | 732664db5c17b8c7e4474048da6822c0e5ea207a | 3,633,619 |
import base64
def download_link(object_to_download, download_filename, download_link_text):
"""Generates a link from which the user can download object_to_download
Method from https://discuss.streamlit.io/t/heres-a-download-function-that-works-for-dataframes-and-txt/4052
Args: object_to_download ... | 81299651997d0bf41cf0c2e000741e6e5f7ba3d2 | 3,633,620 |
def run_epoch(sess, cost_op, ops, reset, num_unrolls):
"""Runs one optimization epoch."""
sess.run(reset)
for _ in range(num_unrolls):
results = sess.run([cost_op] + ops)
return results[0], results[1:] | 975634b3498d6385b53222a88b8f79b7d3ee4d3d | 3,633,621 |
def transformToUTM(gdf, utm_crs, estimate=True, calculate_sindex=True):
"""Transform GeoDataFrame to UTM coordinate reference system.
Arguments
---------
gdf : :py:class:`geopandas.GeoDataFrame`
:py:class:`geopandas.GeoDataFrame` to transform.
utm_crs : str
:py:class:`rasterio.crs.C... | 02405ca581054b5d804c6e4eb49be96d0915e3de | 3,633,622 |
import re
def remove_prohibited_characters(prompt_str: str) -> str:
"""
Remove prohibited characters.
"""
prohibited_chars = ["[", "]", "<", ">", "#", "%", "$", ":", ";", "~", "\r", " ", "\n"]
result_str = prompt_str
for ch in prohibited_chars:
result_str = result_str.replace(ch, "")
... | 8eabb923b5ee59656fb41164d14be0ba6e4535f4 | 3,633,623 |
import scipy
def correction_factors(kappa, eta, gamma, b0, use_eta=True):
"""Computes correction factors for MLE of high dimensional logistic reg."""
system_ = get_system(kappa, eta, gamma, b0, use_eta)
if use_eta:
init = np.array([2, 2, np.sqrt(eta / 2), b0 / 2])
else:
init = np.array([2, 2, np.sqrt(... | 633183d63fc4c974b4f95d587f5bd625ab14e8b9 | 3,633,624 |
import subprocess
def bzr_find_files(dirname):
"""Find versioned files using bzr, for use in 'setuptools.file_finders'
entry point in setup.py."""
cmd = 'bzr ls --versioned ' + dirname
proc = subprocess.Popen(
cmd.split(), stdin=subprocess.PIPE,
stdout=subprocess.PIPE, stderr=subproces... | 8bfc6975b3aaaabc3a955dbef92d96dcea15f518 | 3,633,625 |
def make_style_prompt(choices: list, default: str = None, prompt_msg: str = "Would you like to:",
main_style: str = "none",
frame_style: str = "none",
frame_border_style: str = "none") -> str:
"""
Prompts user in a cool way and retrieves what the... | 06f20893f6e8616998142fee43ae5cb8ccb16bad | 3,633,626 |
from typing import OrderedDict
def jsonfile_1():
""" A JSON File object """
return thresh.TabularFile(
content=OrderedDict({"bar": 4, "foo": 3}), alias="JSON_", length_check=False, namespace_only=True
) | 7c9d856f7619fad54a7614107d018ec4be645498 | 3,633,627 |
def convert(digits, base1, base2):
"""Convert given digits in base1 to digits in base2.
digits: str -- string representation of number (in base1)
base1: int -- base of given number
base2: int -- base to convert to
return: str -- string representation of number (in base2)"""
# Handle up to base 3... | 7a51d56d0c8d04e4c2c1a178da214d900a52d908 | 3,633,628 |
def _get_cmfs_xy():
"""
xy色度図のプロットのための馬蹄形の外枠のxy値を求める。
Returns
-------
array_like
xy coordinate for chromaticity diagram
"""
# 基本パラメータ設定
# ------------------
cmf = CMFS.get(CMFS_NAME)
d65_white = D65_WHITE
# 馬蹄形のxy値を算出
# --------------------------
cmf_xy = X... | 67517dedbb53a30270b6bf2022dec64f796e1e31 | 3,633,629 |
def square_matrix_multiply(A, B):
""" 定義通りの計算 Θ(n^3)
"""
n = len(A)
C = [[0] * n for _ in range(n)]
for i in range(n):
for j in range(n):
for k in range(n):
C[i][j] += A[i][k] * B[k][j]
return C | e0c2766bb9f5f77df1f95f9158fd027db6b7eadb | 3,633,630 |
def _filter_irregular_boxes(boxes, min_ratio=0.2, max_ratio=5):
"""Remove all boxes with any side smaller than min_size."""
ws = boxes[:, 2] - boxes[:, 0] + 1
hs = boxes[:, 3] - boxes[:, 1] + 1
rs = ws / hs
keep = np.where((rs <= max_ratio) & (rs >= min_ratio))[0]
return keep | 31c6113c45195a31c0a9325a113363cc018a0a24 | 3,633,631 |
import http
def login(user, password):
"""
Authenticate against SomethingAwful, both storing that authentication in
the global cookiejar and returning the relevant cookies
:param user: your awful username for somethingawful dot com
:param password: your awful password for somethingawful dot com
... | ad76dc9e1af0e33cfb9d64b6a64dc7d1b3d4e57e | 3,633,632 |
def streams(url: str, **params):
"""
Initializes an empty Streamlink session, attempts to find a plugin and extracts streams from the URL if a plugin was found.
:param url: a URL to match against loaded plugins
:param params: Additional keyword arguments passed to :meth:`streamlink.Streamlink.streams`
... | 58a3cefa0c2957a168282f41457d1844fafdb728 | 3,633,633 |
def get_questionnaire_example() -> pd.DataFrame:
"""Return questionnaire example data.
Returns
-------
data : :class:`~pandas.DataFrame`
dataframe with questionnaire example data
"""
return load_questionnaire_data(_get_data("questionnaire_sample.csv")) | ed067c3a051e91d95326002fa52245304d1d7085 | 3,633,634 |
import os
def auto_dsk(dsk_row,synth,bounds,conv_limit=0,conv_bounds=[None,None],phase_args=(0.,360.,1.),highcut=0.,order=3):
"""
Returns the maximum likelihood phase shift to deskew the data to match a provided synthetic given a bounds
on a window to match.
Parameters
----------
dsk_row : P... | 9c26daac03e7e54ca80db0b04268cbaf12784c9e | 3,633,635 |
def tabulate_e2e_vectors(*, tau_n=dna_params['tau_n'], unwrap=None):
"""Return a lookup table of entry->exit vectors with the right magnitude in
nm. Multiply on the left with the entry orientation matrix to obtain the
entry to exit displacement vector.
One vector for each possible level of unwrapping.
... | 469e5e4389ea7215cad44862f8377a517714137f | 3,633,636 |
def load_fooof_task_pe(data_path, side='Contra', param_ind=1, folder='FOOOF'):
"""Loads task data for all subjects, selects and return periodic FOOOF outputs.
data_path : path to where data
side: 'Ipsi' or 'Contra'
"""
# Collect measures together from FOOOF results into matrices
all_alphas = n... | 7b7b6c26343b58c7c579c890d384f3d8a31611fa | 3,633,637 |
def warning(message):
"""Generic warning message formatter.
Args:
message (string): A message that describes the warning.
Returns:
(str): Formatted warning message.
"""
return bcolors.WARNING + "WARNING: " + bcolors.ENDC + message | d7a06aaf90f24cbb18028a8b921086d3c83efe76 | 3,633,638 |
def GetResult(cl, opts, result):
"""Waits for jobs and returns whether they have succeeded
Some OpCodes return of list of jobs. This function can be used
after issueing a given OpCode to look at the OpCode's result and, if
it is of type L{ht.TJobIdListOnly}, then it will wait for the jobs
to complete, other... | 8bdee53bc6a693436084362f8c6c643e3e565a0d | 3,633,639 |
from .SpectralDecomposer import Decomposer
from .model_housing import indivmodel
def decomposition_method(input):
"""
Decomposition of an individual spectrum using input guesses from the parent
SAA
Parameters
----------
input : list
A list which contains the following:
spectr... | 071ce1bde7d5302d09d41fc30216d578263cfbbf | 3,633,640 |
from typing import Tuple
import os
def create_feature_columns() -> Tuple[list, list, list]:
"""
生成MMOE模型输入特征和label
Returns:
dense_feature_columns (list): 连续特征的feature_columns
category_feature_columns (list): 类别特征的feature_columns(包括序列特征)
label_feature_columns (list): 因变量的feature... | aa09ff0e690d389b08754a7db7d7ba068827ec05 | 3,633,641 |
def cal_features(pm):
"""
only one track in pm, all bars are calculated
Returns:
used_pitch
used_note
pitch_histogram
pitch_interval_hist # not for track 2
pitch_range
onset_interval_hist
duration_hist
"""
result_features = {}
chromagram = np.zeros(12)
duration_h... | aad1d644b97c4b294c6bf25b6a5447475bcaaf4a | 3,633,642 |
def grayscale(img):
"""Applies the Grayscale transform
"""
return cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
# Or use BGR2GRAY if you read an image with cv2.imread()
# return cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) | 7e6408b4decb2b3a6a66b92afc1359fba2036735 | 3,633,643 |
def sample_user(email='test@joeshak.com', password='testpass'):
""" Create a sample user """
return get_user_model().objects.create_user(email, password) | a999bba7581edfd65491eee68ea6b9f0b786dcf0 | 3,633,644 |
from typing import Concatenate
def GroupConv1D(x, in_channels, out_channels, groups=1, kernel=1, strides=1, name=''):
"""
group Convolution 1D
group=1 means pointwise convolution
----
input:
- x:
input tensor
- in_channels:
input channels
- out_chann... | 7921e245a4988c0b5cbe4e45061d8aa1a97ece7a | 3,633,645 |
import logging
def get_logger_obj(logger=None):
"""Get a logger object that can be specified by its name, or passed as is.
Defaults to the root logger.
"""
if logger is None or isinstance(logger, py.builtin._basestring):
logger = logging.getLogger(logger)
return logger | 263b2f70211fa82891a41dce0cdee23cc7ca3e93 | 3,633,646 |
import logging
import sys
import os
def opt_validate_predictd ( options ):
"""Validate options from a OptParser object.
Ret: Validated options object.
"""
# gsize
try:
options.gsize = efgsize[options.gsize]
except:
try:
options.gsize = float(options.gsize)
... | 6418e5792ee043d3b854bb0371d511fe55d24cf3 | 3,633,647 |
import copy
def associate_trajectories(traj_1, traj_2,
max_diff=0.01, offset_2=0.0,
first_name="first trajectory", snd_name="second trajectory"):
"""
Synchronizes two trajectories by matching their timestamps.
:param traj_1: trajectory.PoseTrajectory3D object of first trajectory
:param... | f6c38f11da445ef17ea095abe01bed4a1826b531 | 3,633,648 |
def calculate_wake_wing_influence_matrix(cpoints, wake, normals):
"""
Calculate influence matrix (steady wake contribution).
Parameters
----------
cpoints : np.ndarray, shape (m, n, 3)
Array containing the (x,y,z) coordinates of all collocation points.
wake : np.ndarray, shape (n, 4, 3)... | d99ca1c1291688462a8044fcfd558fbbba5f09b4 | 3,633,649 |
def get_recent_games(summoner_id):
"""
https://developer.riotgames.com/api/methods#!/1016/3445
Args:
summoner_id (int): the ID of the summoner to find recent games for
Returns:
RecentGames: the summoner's recent games
"""
request = "{version}/game/by-summoner/{summoner_id}/rece... | 12e5ec6816b987af74b79b0839c76b582793c145 | 3,633,650 |
import itertools
def create_daily_rate_line_plot(sources, services, y_axis_type='log', y_range=(1, 10**7)):
"""
Returns
-------
plotting.figure
A Bokeh plot that can be shown.
"""
# create plot with a datetime axis type
p = plotting.figure(plot_width=700, plot_height=1200, x_axi... | ef71f51aef3ebb039661c64a6ec9e7191ce04d21 | 3,633,651 |
def masked_loss(y_gt, y_pred, loss_fn, **kwargs):
"""Calculate 2d loss by removing mask, normally it's durrations/f0s/energys loss."""
real_len = tf.reduce_sum(tf.cast(tf.math.not_equal(
y_gt, 0), tf.float32), axis=1) # shape [B,]
max_len = tf.shape(y_gt)[1]
max_len = tf.cast(max_len, real_len... | eb9491d0dde283942a2983bce582d61c34aaa95c | 3,633,652 |
def call_ft(function, *args):
"""Call an FTDI function and check the status. Raise exception on error"""
status = function(*args)
if len(bRaiseExceptionOnError) > 0:
if status != FT_OK:
raise DeviceError(status)
return status | b78b7f39b06d990199f73c6d705408e291b85a91 | 3,633,653 |
import random
def reshuffle_words_to_fit(word_tuples_to_fit):
"""Within each length-class, reshuffle the words."""
new_word_tuples_to_fit = deepcopy(word_tuples_to_fit)
distinct_lens = set(len(wt.board) for wt in new_word_tuples_to_fit)
for word_len in distinct_lens:
word_inds_with_len = [i fo... | 17ef2434dbf540757daf194ae96ae5b8f6c098e6 | 3,633,654 |
def make_tree_all_params(species, dbh, height, stem_x, stem_y, stem_z,
lean_direction, lean_severity, crown_ratio, crown_radius_E,
crown_radius_N, crown_radius_W, crown_radius_S,
crown_edge_height_E, crown_edge_height_N, crown_edge_height_W,
crown_edge_height_S, s... | c7be83ebd67d6de21a2c7f82248903c23d63a83d | 3,633,655 |
def get_cfg_defaults():
"""Get a yacs CfgNode object with default values"""
# Return a clone so that the defaults will not be altered
# This is for the "local variable" use pattern
return _C.clone() | 7cbf9b8f325ba417cf6c959d900b61c727cec816 | 3,633,656 |
import os
import logging
def outage_check(data, filename='outage.txt'):
"""
Quality assurance check on the weather service :-)
"""
outage_checker = Outage(data)
outage_checker.check_outage()
outage_result = outage_checker.parse_outage()
outfilepath = os.path.join(data['output_dir'], filename)
if outa... | 071a8215763a15a00049d0d74942a535b5ce18e3 | 3,633,657 |
from typing import List
import fnmatch
def should_ignore(file: str, exclusions: List[str]) -> bool:
"""Check if a file matches a line in the exclusion list."""
for excl in exclusions:
if fnmatch(file, excl):
return True
return False
# for file in Path(".").glob("**/*.py*"):
# ... | ea8c4e4a6546d4f73009296208718696a443ac9f | 3,633,658 |
def fpn_classifier_graph(rois, feature_maps,image_shape, pool_size, num_classes,config):
"""Builds the computation graph of the feature pyramid network classifier
and regressor heads.
selector: 0 for training and 1 for inference
rois: [batch, num_rois, (y1, x1, y2, x2)] Proposal boxes in normalized
... | 3d6b649b2d4eab53aa856b169d87d83ba4c2eaff | 3,633,659 |
def fit_unitarity(depths, shifted_purities, weights=None):
"""Construct and fit an RB curve with appropriate guesses
:param depths: The clifford circuit depths (independent variable)
:param shifted_purities: The shifted purities (dependent variable)
:param weights: Optional weightings of each point to ... | a8fb739b4c64cf63ceff51ef9eabd276c2b6c48d | 3,633,660 |
import re
def filter_paragraph(p):
"""Simple filter to remove obviously bad paragraphs (bad text extraction).
Note this needs to run very quickly as it is applied to every paragraph
in the corpus, so nothing fancy! This whole method should be linear
expected time in len(p).
Args:
p: string, paragraph
Returns:
... | 4458a480c176149d1375dfafb13211b4fd7ee9d0 | 3,633,661 |
def get_matching_tables(tables, path):
"""Get list of matching tables for provided path
Return list is sorted by longest matching path part
:param tables: List of `Table' objects
:param path: Path like string
:return: List of matched by path tables
"""
candidates = []
for table in tabl... | e91e93cef56d3eb6e5b6ae85f522fbb042e472a9 | 3,633,662 |
import requests
def email_video_link(talk):
"""Send the presenter a link to their video, asking to confirm."""
meeting_recordings = common.zoom_request(
requests.get,
common.ZOOM_API + f"/meetings/{talk['zoom_meeting_id']}/recordings"
)
if not len(meeting_recordings["recording_files"])... | f47139dd42606a57406295f2079fdcc18e8fcfc0 | 3,633,663 |
import traceback
def make_import_user_csv_files(uw_accounts,
filepath):
"""
:param uw_accounts: a list of UwAccount objects
Writes all csv files. Returns number of records wrote out.
"""
if not uw_accounts or len(uw_accounts) == 0:
return 0
file_size = ge... | f41077fa18103edc63b727574b2e2c8ea8d039c8 | 3,633,664 |
def distanceInOval(x, y, a=3, b=2, k=0.2):
"""
:param x: high-dimension embedding of cell A
:param y: high-dimension embedding of cell B
:param a: major axis length
:param b: minor axie length
:param k: Deformation parameter
:return: distance between cell A and B in oval whose function is
... | acea2495d146a858ddfe5770025d95899f00c797 | 3,633,665 |
def file_generator(
wrapped=None,
ids=["file"],
names=[uuid4().hex],
suffixes=[""],
dirs=[SANDBOX],
properties=None,
):
"""Decorator which automates setup and return for file generation functions.
The decorator fulfills 3 tasks:
1. Generating required temporary file names.
... | ea36dbb67f722513bb149250f7536f331f95918d | 3,633,666 |
def optimal_t_from_selection(x, y, ts, J, min_n):
"""
Time complexity:
O(T*N)
Space complexity:
O(N+T) - to store the input
"""
N = len(x)
best_loss = np.inf
best_t = -np.inf
idx = None
for t in ts: # O(T)
# evaluate loss for splitting [:s], [s:]
y_l = y[x <= ... | 90e882f97cbf83c66dd395c8bf45993ae445cd9a | 3,633,667 |
def _deserialize_qnode(qnode_id, qnode):
"""Returns a QNode from a single deserialized QueryGraph node in a
TRAPI request
"""
constraints = []
try:
ids = qnode.get('ids')
categories = qnode.get('categories')
is_set = qnode.get('is_set')
req_constraints = qnode.get('co... | 81278d775ecc68b9202fc3941549414f98e8b7f9 | 3,633,668 |
def combined_f1_rmse(y_true, y_pred):
"""Difference between F1 score and root mean square error (rmse).
The optimal values for F1 score and rmse are 1 and 0 respectively.
Therefore, the combined optimal value is 1.
"""
return f1_score(y_true, y_pred) - rmse(y_true, y_pred) | e43511cbea8a6a7fe5eaa5e142ece568d59ec0f8 | 3,633,669 |
from pathlib import Path
def get_images_with_annotations(host, public_key, private_key, project_id=None, download=True, annotation_ids=None):
"""
Find and download (if not present) annotation information and images
:param annotation_ids: List of annotations to fetch
:param download: Whether or not to ... | 75ac5e025ead946e9d2c626799eb54d02e0cde71 | 3,633,670 |
import requests
import json
import os
def read_inap(room_name='K1N0624', start='2018-02-01', end='2018-03-01'):
"""
Function to download Indoor Environmental Quality (IEQ) data monitored by INAP sensors in SL demo-case
using IRI-UL web api. You may need to update the token if the current one is expired (c... | 2fe5af49654a425b5be8bcf4cb5dfc2403a9ae32 | 3,633,671 |
async def infer_type_make_record(engine, _cls: dtype.TypeType, *elems):
"""Infer the return type of make_record."""
cls = _cls.values[VALUE]
if cls is ANYTHING:
raise MyiaTypeError('Expected a class to inst')
expected = list(cls.attributes.items())
if len(expected) != len(elems):
rai... | 8389217a1fee854b73d6189cf811a26a7613680a | 3,633,672 |
from functools import reduce
import operator
def concatenate(trajectories):
"""Return the concatenation of a sequence of trajectories.
Parameters
----------
trajectories : sequence of sequences
A sequence of trajectories.
Returns
-------
sequence
The concatenation of `tra... | dee2e64b579d07adea0842eb375c543453e9eede | 3,633,673 |
def dlonlat_at_grid_center(ctr_lat, ctr_lon, dx=4.0e3, dy=4.0e3,
x_bnd = (-100e3, 100e3), y_bnd = (-100e3, 100e3),
proj_datum = 'WGS84', proj_ellipse = 'WGS84'):
"""
Utility function useful for producing a regular grid of lat/lon data,
where an approximate spacing (dx, dy) and total span of t... | a64fefbad5593e33af4dde3fb362aec54c0d6225 | 3,633,674 |
def attribute_test_service(request):
"""
Displays a list of all :model:`rr.Attribute` and values
found from environment variables.
**Context**
``object_list``
List of dictionaries containing attribute values and metadata.
``logout_url``
Logout URL.
**Template:**
:temp... | 79e7e4b861e74ab6739ccd3c2ea226d01d4bbe02 | 3,633,675 |
import re
import threading
import uuid
from datetime import datetime
import json
def create_foundation_entity_instance(entity):
"""Create an instance of a Foundation SDK Entity"""
# Get an SDK class and use the configuration generation behaviour to pass in parameters
sdk_instance = SDK(**(request.get_json... | 78d3bfcf4baa922213feedde1420112a9db7bf04 | 3,633,676 |
def guided_alignment_cost(
attention_probs, gold_alignment, sequence_length=None, cost_type="ce", weight=1
):
"""Computes the guided alignment cost.
Args:
attention_probs: The attention probabilities, a float ``tf.Tensor`` of shape
:math:`[B, T_t, T_s]`.
gold_alignment: The true alignme... | b1acea456d0f17ff3e0917a071cc84d69b7893ad | 3,633,677 |
def _log_object_event(
ctx,
dbOperationsEvent=None,
event_status_id=None,
dbAcmeAccount=None,
dbAcmeAccountKey=None,
dbAcmeDnsServer=None,
dbAcmeOrder=None,
dbCertificateCA=None,
dbCertificateCAChain=None,
dbCertificateRequest=None,
dbCoverageAssuranceEvent=None,
dbDomain... | 91e395e6dd9c512b93531c292056c2e324084622 | 3,633,678 |
from matplotlib.ticker import FuncFormatter
import matplotlib
import os
def catlogmatch_plot(catalog_mt, dd=0.2, dir_fig='.', figformat='png', fnametag=None):
"""
To plot the pie figure after comparing two catalogs.
Parameters
----------
catalog_mt : dic
a comparison catalog, for detail s... | a7c6b168d3f42657c8a2bb8fbc53c940472dbfd6 | 3,633,679 |
def dismiss_message_url(course):
"""
Returns the URL for the dismiss message endpoint.
"""
return reverse(
'openedx.course_experience.dismiss_welcome_message',
kwargs={
'course_id': str(course.id),
}
) | aeabf651b2576f280634d7562d31e52fb7e0748f | 3,633,680 |
def cllr(lrs, y, weights=(1, 1)):
"""
Calculates a log likelihood ratio cost (C_llr) for a series of likelihood
ratios.
Nico Brümmer and Johan du Preez, Application-independent evaluation of speaker detection, In: Computer Speech and
Language 20(2-3), 2006.
Parameters
----------
lrs : ... | 31b7e022de94aec36efd570318e930d665349169 | 3,633,681 |
import torch
def heatmaps_to_keypoints(maps: torch.Tensor, rois: torch.Tensor) -> torch.Tensor:
"""
Extract predicted keypoint locations from heatmaps.
Args:
maps (Tensor): (#ROIs, #keypoints, POOL_H, POOL_W). The predicted heatmap of logits for
each ROI and each keypoint.
roi... | 1755ebd45ab741ef267b17f1d24a658143e5f6c5 | 3,633,682 |
import os
from sys import flags
def get_credentials():
"""Gets valid user credentials from storage.
If nothing has been stored, or if the stored credentials are invalid,
the OAuth2 flow is completed to obtain the new credentials.
Returns:
Credentials, the obtained credential.
"""
hom... | c83dcef79c93f651e00c6e3d649dbfc20d1f02a0 | 3,633,683 |
import sys
import re
import json
import time
def logs(args):
"""View service logs"""
stacks = StackCache.load()
try:
config = stacks[args.name]
except KeyError:
sys.stderr.write("Unknown stack '{}'. Available stacks are: {}\n".format(args.name, ', '.join(stacks.keys())))
return... | d9397f836831cad45ab8d618aada731270ea7d03 | 3,633,684 |
def add_user_input_to_scene(scene, user_input, keep_space_around_bodies=True):
"""Converts user input to objects in the scene.
Args:
scene: scene_if.Scene.
user_input: scene_if.UserInput or a triple (points, rectangulars, balls).
keep_space_around_bodies: bool, if True extra empty space... | 4020253049b3615d81d2cbca829433c211c3f9c1 | 3,633,685 |
def language_add():
"""Return the page to add a language."""
is_user_logged_in = True if 'username' in login_session else False
context = {'is_user_logged_in': is_user_logged_in}
if request.method == 'POST':
if not is_user_logged_in:
flash('You have to log in to add a language.')
... | 8098ce3c3e6e8f8930790a636405ae69ce95cdd8 | 3,633,686 |
def pyramid_sum(lower, upper, margin = 0):
"""Returns the sum of the numbers from lower to upper,
and outputs a trace of the arguments and return values
on each call."""
blanks = " " * margin
print(blanks, lower, upper) # Print the arguments
if lower > upper:
print(blanks, 0) # Print th... | 751facb309f362c35257aab2b239a37b39a98a04 | 3,633,687 |
def grad_qform_1_ZV(a,f_vals,X_grad,ind,n,alpha):
"""
Gradient for quadratic form in ZV-1 method
"""
Y = f_vals[:,ind] + X_grad @ a
return 2./(n-1) * (X_grad*(Y - np.mean(Y)).reshape((n,1))).sum(axis=0) + 2*alpha*a | aab2ac9cc79a4cf43e4391872ebf905e849ba7d9 | 3,633,688 |
def get_plot_extent(df, grid_stepsize=None, grid=False) -> tuple:
"""
Gets the plot_extent from the values. Uses range of values and
adds a padding fraction as specified in globals.map_pad
Parameters
----------
grid : bool
whether the values in df is on a equally spaced grid (for use in... | 9acc348ed56f09d78589e7b9fa1a72c558ea51b0 | 3,633,689 |
def is_learner(user, program):
"""
Returns true if user is a learner
Args:
user (django.contrib.auth.models.User): A user
program (courses.models.Program): Program object
"""
return (
not Role.objects.filter(user=user, role__in=Role.NON_LEARNERS, program=program).exists()
... | 4773a6ebcc2b892a5306614a1bde699d0e17f191 | 3,633,690 |
import warnings
import math
def calculate_rupture_rates(
nhm_df: pd.DataFrame,
rup_name: str = "rupture_name",
annual_rec_prob_name: str = "annual_rec_prob",
mag_name: str = "mag_name",
) -> pd.DataFrame:
"""Takes in a list of background ruptures and
calculates the rupture rates for the given ... | a58e656980454de2f53fb1db2f5b0ec37fec9334 | 3,633,691 |
def checkScriptParses(scriptVersion, script):
"""
checkScriptParses returns None when the script parses without error.
Args:
scriptVersion (int): The script version.
script (ByteArray): The script.
Returns:
None or Exception: None on success. Exception is returned, not raised.
... | da49e2ca94fe38ef93e92eac27acc4eafd02f3e9 | 3,633,692 |
import unicodedata
def normalize_caseless(text):
"""Normalize a string as lowercase unicode KD form.
The normal form KD (NFKD) will apply the compatibility decomposition,
i.e. replace all compatibility characters with their equivalents.
"""
return unicodedata.normalize("NFKD", text.casefold()) | c26f8470ea6312cce7a97930999d489ee30eb692 | 3,633,693 |
def select_device_mirrored(device, structured):
"""Specialize a nest of regular & mirrored values for one device."""
def _get_mirrored(x):
if isinstance(x, DistributedValues):
if not isinstance(x, Mirrored):
raise TypeError(
"Expected value to be mirrored across replicas: %s in %s." %
... | 5b69c9464e1d8a4597f5661d85c056e90deb70bf | 3,633,694 |
from typing import Dict
from typing import Any
from typing import Counter
def default_base_builder(individual: "Individual", frame: Frame, **kwargs) -> Dict[str, Any]:
"""Get base stats of the frame"""
v = dict()
# nodes
nodes = individual.nodes(frame_selector=frame, data=True)
v['nodes'] = list(... | de0c3ea0120bef893d29e6917ec6cc0e19e451b9 | 3,633,695 |
def calculate_maximum_potential_edge_counts(channel_composition, N, max_ble_span):
"""Computes the maximum number of possible occurrences per potential edge type.
Parameters
----------
channel_composition : Dict[str, int]
Channel composition description.
N : int
Number of BLEs in th... | 55f891631bd109066735e9997cbb3dc35de8d21a | 3,633,696 |
def generic_document_type_formatter(view, context, model, name):
"""Return AdminLog.document field wrapped in URL to its list view."""
_document_model = model.get('document').document_type
url = _document_model.get_admin_list_url()
return Markup('<a href="%s">%s</a>' % (url, _document_model.__name__)) | c00934e8778c5232092427e2b507785ef429570d | 3,633,697 |
def string_to_bool(value):
"""
boolean string to boolean converter
"""
if value == "true":
return True
else:
return False | 0796b21c98d09592d8d3a6ae1dfc5b98564aec7f | 3,633,698 |
def g_logv(s):
"""read a logical variable
:param str s:
:return bool:
"""
return s == '1' or s.lower() == 'yes' or s.lower() == 'true' | e9984eced79cccc09a465b07bfac5185db72a604 | 3,633,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.