content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def ns_diff(newstr, oldstr):
"""
Calculate the diff.
"""
if newstr == STATUS_NA:
return STATUS_NA
# if new is valid but old is not we should return new
if oldstr == STATUS_NA:
oldstr = '0'
new, old = int(newstr), int(oldstr)
return '{:,}'.format(max(0, new - old)) | bbf58a649ef71524e7413fb47501d0054b828919 | 3,643,084 |
def get_crab(registry):
"""
Get the Crab Gateway
:rtype: :class:`crabpy.gateway.crab.CrabGateway`
# argument might be a config or a request
"""
# argument might be a config or a request
regis = getattr(registry, 'registry', None)
if regis is None:
regis = registry
return re... | 6f8f02ac4bf7e82c8f4828fb4fdab4b78451ae49 | 3,643,085 |
def create_meal():
"""Create a new meal.
---
tags:
- meals
parameters:
- in: body
name: body
schema:
id: Meal
properties:
name:
type: string
description: the name of the meal
description:
type... | ee1c235410d7d6ca9f3661ea9f7a1f9fb434a730 | 3,643,086 |
def buscaBinariaIterativa(alvo, array):
""" Retorna o índice do array em que o elemento alvo está contido.
Considerando a coleção recebida como parâmetro, identifica e retor-
na o índice em que o elemento especificado está contido. Caso esse
elemento não esteja presente na coleção, retorna -1. Utiliza ... | e74fed0781b3c1bed7f5f57713a06c58bcbde107 | 3,643,087 |
def empiricalcdf(data, method='Hazen'):
"""Return the empirical cdf.
Methods available:
Hazen: (i-0.5)/N
Weibull: i/(N+1)
Chegodayev: (i-.3)/(N+.4)
Cunnane: (i-.4)/(N+.2)
Gringorten: (i-.44)/(N+.12)
California: (i-1)/N
Where i goes from ... | 6150361002d3f008185e5deafabfdc74b3189bd8 | 3,643,088 |
def CCT_to_xy_Kang2002(CCT):
"""
Returns the *CIE XYZ* tristimulus values *CIE xy* chromaticity coordinates
from given correlated colour temperature :math:`T_{cp}` using
*Kang et al. (2002)* method.
Parameters
----------
CCT : numeric or array_like
Correlated colour temperature :mat... | cb9462e2b38bf5c55e7d7984632923ba9029e1fb | 3,643,089 |
def tel_information(tel_number):
"""
check and return a dictionary that has element of validation and operator of number
if number is not valid it return validation = 'False' and operator = 'None'
"""
validation = is_valid(tel_number)
operator = tel_operator(tel_number)
info_dict = {'valida... | b68fe615a3adf5e8a7ac8528f4b89ba2d85b4067 | 3,643,090 |
import pathlib
from typing import Dict
from typing import Any
import yaml
import json
def load_file(file_name: pathlib.Path) -> Dict[str, Any]:
"""
Load JSON or YAML file content into a dict.
This is not intended to be the default load mechanism. It should only be used
if a OSCAL object type is unkno... | c042d9e94953c2130971fe6ebf4774cd31556256 | 3,643,091 |
from tests.test_plugins.documentations_plugin import DocumentPlugin
def DocumentPlugin():
"""
:return: document plugin class
"""
return DocumentPlugin | 8cbcc4eb3ee58236f9fbf861a6e33a696db2ddff | 3,643,092 |
import re
def remove_extended(text):
""" remove Chinese punctuation and Latin Supplement.
https://en.wikipedia.org/wiki/Latin-1_Supplement_(Unicode_block)
"""
# latin supplement: \u00A0-\u00FF
# notice: nbsp is removed here
lsp_pattern = re.compile(r'[\x80-\xFF]')
text = lsp_pattern.s... | 52d0f5082b519d06f7dd20ba3d755790b1f3166d | 3,643,094 |
def appointment_letter(request, tid):
"""Display the appointment letter."""
paf = get_object_or_404(Operation, pk=tid)
return render(
request, 'transaction/appointment_letter.html', {'paf': paf},
) | 765115cb98e4b99cdff1ad2ad010d635eabf4103 | 3,643,095 |
import random
from typing import Iterable
import itertools
def balance_targets(sentences: Iterable[Sentence], method: str = "downsample_o_cat", shuffle=True) \
-> Iterable[Sentence]:
"""
Oversamples and/or undersamples training sentences by a number of targets.
This is useful for linear shallow cl... | 2d0b5736bcfeb6e7b2566791dba4d74ac3c84456 | 3,643,096 |
def discriminator_loss(real_output, fake_output, batch_size):
"""
Computes the discriminator loss after training with HR & fake images.
:param real_output: Discriminator output of the real dataset (HR images).
:param fake_output: Discriminator output of the fake dataset (SR images).
:param batch_siz... | ade81d34b80226a8905d64249187f35c73d496ee | 3,643,097 |
def NNx(time, IBI, ibimultiplier=1000, x=50):
"""
computes Heart Rate Variability metrics NNx and pNNx
Args:
time (pandas.DataFrame column or pandas series): time column
IBI (pandas.DataFrame column or pandas series): column with inter beat intervals
ibimultiplier... | 94f7f7ec732532cddfe5c29a273af479733e4ced | 3,643,098 |
from datetime import datetime
def datetimeobj_YmdHMS(value):
"""Convert timestamp string to a datetime object.
Timestamps strings like '20130618120000' are able to be converted by this
function.
Args:
value: A timestamp string in the format '%Y%m%d%H%M%S'.
Returns:
A datetime ob... | d1f63b1e50f278bd4dcea78feea8942bc1112c6f | 3,643,099 |
def home():
"""List devices."""
devices = Device.query.all()
return render_template('devices/home.html', devices=devices) | d0f9b14cedf83fbeb35166e1ad9b2de295e2584f | 3,643,100 |
def translate_value(document_field, form_value):
"""
Given a document_field and a form_value this will translate the value
to the correct result for mongo to use.
"""
value = form_value
if isinstance(document_field, ReferenceField):
value = document_field.document_type.objects.get(id=for... | 5c72764efde00fb4f5093a800706082c1171b5b6 | 3,643,101 |
def error_404(error):
"""Custom 404 Error Page"""
return render_template("error.html", error=error), 404 | 1f1429b8c86ed7a486c498cae6955961f3084ef5 | 3,643,102 |
def sum_num(n1, n2):
"""
Get sum of two numbers
:param n1:
:param n2:
:return:
"""
return(n1 + n2) | 08477e596317f6b8750debd39b5cf0aa56da857c | 3,643,103 |
def intensity_slice_volume(kernel_code,
image_variables,
g_variables,
blockdim,
bound_box,
vol_dim,
voxel_size,
poses,
... | c5f64f7ee5a95210a2c5598a7e31e36541fcb320 | 3,643,104 |
def mean_filter(img, kernel_size):
"""take mean value in the neighbourhood of center pixel.
"""
return cv2.blur(img, ksize=kernel_size) | 58d5684e0691407f6f77d40d5717523eb617dde9 | 3,643,105 |
def main():
"""Return the module instance."""
return AnsibleModule(
argument_spec=dict(
data=dict(default=None),
path=dict(default=None, type=str),
file=dict(default=None, type=str),
)
) | 846aa9bf9ce23ba7a05aeb91158ad04770b7721e | 3,643,106 |
from typing import Optional
from pathlib import Path
def load_RegNetwork_interactions(
root_dir: Optional[Path] = None,
) -> pd.DataFrame:
"""
Loads RegNetwork interaction datafile. Downloads the file first if not already present.
"""
file = _download_RegNetwork(root_dir)
return pd.read_csv(
... | 15571c71ac3bd386518a0f2ec4d293b20394c4b2 | 3,643,107 |
def get_model_config(model, dataset):
"""Map model name to model network configuration."""
if 'cifar10' == dataset.name:
return get_cifar10_model_config(model)
if model == 'vgg11':
mc = vgg_model.Vgg11Model()
elif model == 'vgg16':
mc = vgg_model.Vgg16Model()
elif model == 'vgg19':
mc = vgg_mo... | eb3da4fa2e7308fe0b7394b6c654e171abaf2363 | 3,643,110 |
from datetime import datetime
def utc_now():
"""Return current utc timestamp
"""
now = datetime.datetime.utcnow()
return int(now.strftime("%s")) | 35edc0e19f236263a8f2efd0fa9be81663042484 | 3,643,111 |
def rrc_filter(alpha, length, osFactor, plot=False):
"""
Generates the impulse response of a root raised cosine filter.
Args:
alpha (float): Filter roll-off factor.
length (int): Number of symbols to use in the filter.
osFactor (int): Oversampling factor (number of samples per symbol... | 9fc5c916e646179ac465fb2d3d897d4dadadd9de | 3,643,112 |
def get_available_services(project_dir: str):
"""Get standard services bundled with stakkr."""
services_dir = file_utils.get_dir('static') + '/services/'
conf_files = _get_services_from_dir(services_dir)
services = dict()
for conf_file in conf_files:
services[conf_file[:-4]] = services_dir ... | b361eaefd0772ca9bcc75274f19e7550b02d1484 | 3,643,113 |
def build_insert(table, to_insert):
"""
Build an insert request.
Parameters
----------
table : str
Table where query will be directed.
to_insert: iterable
The list of columns where the values will be inserted.
Returns
-------
str
Built query.
"""
sq... | cf2e72c57e5502660ed3dcade6885076ff8c2014 | 3,643,114 |
from pathlib import Path
import json
def get_reference_data(fname):
"""
Load JSON reference data.
:param fname: Filename without extension.
:type fname: str
"""
base_dir = Path(__file__).resolve().parent
fpath = base_dir.joinpath('reference', 'data', fname + '.json')
with fpath.open()... | 73880586393ce9463a356d69880f2f285058637f | 3,643,115 |
def _is_l10n_ch_isr_issuer(account_ref, currency_code):
""" Returns True if the string account_ref is a valid a valid ISR issuer
An ISR issuer is postal account number that starts by 01 (CHF) or 03 (EUR),
"""
if (account_ref or '').startswith(ISR_SUBSCRIPTION_CODE[currency_code]):
return _is_l10... | 5709d8f67aefe9b9faac6f4541f8a050eb95c82f | 3,643,116 |
import struct
def little_endian_uint32(i):
"""Return the 32 bit unsigned integer little-endian representation of i"""
s = struct.pack('<I', i)
return struct.unpack('=I', s)[0] | 07f72baaf8f7143c732fd5b9e56b0b7d02d531bd | 3,643,117 |
def evaluate_scores(scores_ID, scores_OOD):
"""calculates classification performance (ROCAUC, FPR@TPR95) based on lists of scores
Returns:
ROCAUC, fpr95
"""
labels_in = np.ones(scores_ID.shape)
labels_out = np.zeros(scores_OOD.shape)
y = np.concatenate([labels_in, labels_out])
s... | f88a67f09496700ab783a3e91347b085767a2228 | 3,643,118 |
from typing import Union
def check_cardinality(attribute_name: str,
analysis: run_metadata_pb2.Analysis
) -> Union[None, str]:
"""Check whether the cardinality exceeds the predefined threshold
Args:
attribute_name: (string),
analysis: (run_metadata_pb2.Anal... | 8a9b9e0c709b64273a2120100730992276b52b46 | 3,643,119 |
def create_df_from(dataset):
"""
Selects a method, based on the given dataset name, and creates the corresponding dataframe.
When adding a new method, take care to have as index the ASN and the column names to be of the format "dataset_name_"+"column_name" (e.g., the column "X" from the dataset "setA", shou... | 3a5e6f1a9aa510ec19c6eeb1af8a89574b938ea1 | 3,643,120 |
def plasma_fractal(mapsize=256, wibbledecay=3):
"""
Generate a heightmap using diamond-square algorithm.
Return square 2d array, side length 'mapsize', of floats in range 0-255.
'mapsize' must be a power of two.
"""
assert (mapsize & (mapsize - 1) == 0)
maparray = np.empty((mapsize, mapsize), dtype=np.flo... | f3b0c65f7bff6526a91c8d398a430a72cf744421 | 3,643,121 |
import pickle
def read_ids():
"""
Reads the content from a file as a tuple and returns the tuple
:return: node_id, pool_id (or False if no file)
"""
if not const.MEMORY_FILE.exists():
return False
with open(const.MEMORY_FILE, 'rb') as f:
data = pickle.load(f)
assert typ... | 89606543b149cac636765a6f3e2aef34f2adc38b | 3,643,123 |
from pymbolic.primitives import Call
def _match_caller_callee_argument_dimension_(program, callee_function_name):
"""
Returns a copy of *program* with the instance of
:class:`loopy.kernel.function_interface.CallableKernel` addressed by
*callee_function_name* in the *program* aligned with the argument
... | 7c37a20776e1ff551dca3f2acd1b36e47cf6b06e | 3,643,124 |
def new_automation_jobs(issues):
"""
:param issues: issues object pulled from Redmine API
:return: returns a new subset of issues that are Status: NEW and match a term in AUTOMATOR_KEYWORDS)
"""
new_jobs = {}
for issue in issues:
# Only new issues
if issue.status.name == 'New':
... | 74c9c96aeeea1d15384d617c266daa4d49f3a203 | 3,643,125 |
def make_data(revs, word_idx_map, max_l=50, filter_h=3, val_test_splits=[2, 3], validation_num=500000):
"""
Transforms sentences into a 2-d matrix.
"""
version = begin_time()
train, val, test = [], [], []
for rev in revs:
sent = get_idx_from_sent_msg(rev["m"], word_idx_map, max_l, True)
... | b141297c0ef8d2eeb2c6c62e00924f5e64ffe266 | 3,643,127 |
def init(param_test):
"""
Initialize class: param_test
"""
# initialization
param_test.default_args_values = {'di': 6.85, 'da': 7.65, 'db': 7.02}
default_args = ['-di 6.85 -da 7.65 -db 7.02'] # default parameters
param_test.default_result = 6.612133606
# assign default params
if no... | d86cd246d4beb5aa267d222bb12f9637f001032d | 3,643,128 |
def add_width_to_df(df):
"""Adds an extra column "width" to df which is the angular width of the CME
in degrees.
"""
df = add_helcats_to_df(df, 'PA-N [deg]')
df = add_helcats_to_df(df, 'PA-S [deg]')
df = add_col_to_df(df, 'PA-N [deg]', 'PA-S [deg]', 'subtract', 'width', abs_col=True)
return ... | ea866d161ca77d9d78f04fb613aa1ed8631566b2 | 3,643,129 |
def checkSeconds(seconds, timestamp):
""" Return a string depending on the value of seconds
If the block is mined since one hour ago, return timestamp
"""
if 3600 > seconds > 60:
minute = int(seconds / 60)
if minute == 1:
return '{} minute ago'.format(minute)
retu... | 2d07657a14300793a116d28e7c9495ae4a1b61ed | 3,643,130 |
def get_netrange_end(asn_cidr):
"""
:param str asn_cidr: ASN CIDR
:return: ipv4 address of last IP in netrange
:rtype: str
"""
try:
last_in_netrange = \
ip2long(str(ipcalc.Network(asn_cidr).host_first())) + \
ipcalc.Network(asn_cidr).size() - 2
except ValueEr... | 51305dc1540bbc0a361452a80d6732b1eb039fd4 | 3,643,131 |
def load_from_file(filepath, column_offset=0, prefix='', safe_urls=False, delimiter='\s+'):
"""
Load target entities and their labels if exist from a file.
:param filepath: Path to the target entities
:param column_offset: offset to the entities column (optional).
:param prefix: URI prefix (Ex: htt... | 2aa9b286e25c6e93a06afb927f7e0ad345208afb | 3,643,132 |
def _get_repos_info(db: Session, user_id: int):
"""Returns data for all starred repositories for a user.
The return is in a good format for the frontend.
Args:
db (Session): sqlAlchemy connection object
user_id (int): User id
Returns:
list[Repository(dict)]:repo_info = {
... | 78a126369355c1c76fc6a1b673b365e3423cd011 | 3,643,135 |
def ultimate_oscillator(close_data, low_data):
"""
Ultimate Oscillator.
Formula:
UO = 100 * ((4 * AVG7) + (2 * AVG14) + AVG28) / (4 + 2 + 1)
"""
a7 = 4 * average_7(close_data, low_data)
a14 = 2 * average_14(close_data, low_data)
a28 = average_28(close_data, low_data)
uo = 100 * ((a7... | 9803eda656cdb9dd49621a93785b55cf5bc15e7c | 3,643,136 |
def get_completions():
"""
Returns the global completion list.
"""
return completionList | 901718ea73b5328c277c357ecac859b40518890d | 3,643,138 |
def breadth_first_search():
"""
BFS Algorithm
"""
initial_state = State(3, 3, "left", 0, 0)
if initial_state.is_goal():
return initial_state
frontier = list()
explored = set()
frontier.append(initial_state)
while frontier:
state = frontier.pop(0)
if state.is_g... | 2c0dca233b2bdb4474dd17ee7386ed15f5af44c1 | 3,643,139 |
import pandas
def rankSimilarity(df, top = True, rank = 3):
""" Returns the most similar documents or least similar documents
args:
df (pandas.Dataframe): row, col = documents, value = boolean similarity
top (boolean): True: most, False: least (default = True)
rank (int): num... | 7ae5a90ced7dbbd79d5f296a6f31f1236384ba7a | 3,643,140 |
def change_controller(move_group, second_try=False):
"""
Changes between motor controllers
move_group -> Name of required move group.
"""
global list_controllers_service
global switch_controllers_service
controller_map = {
'gripper': 'cartesian_motor_controller',
'whole_... | 8521e1c2967368a5c8ac956fc26d4da879919a2d | 3,643,141 |
import base64
def base64_encode(text):
"""<string> -- Encode <string> with base64."""
return base64.b64encode(text.encode()).decode() | ce837abde42e9a00268e14cfbd2bd4fd3cf16208 | 3,643,142 |
def _signed_bin(n):
"""Transform n into an optimized signed binary representation"""
r = []
while n > 1:
if n & 1:
cp = _gbd(n + 1)
cn = _gbd(n - 1)
if cp > cn: # -1 leaves more zeroes -> subtract -1 (= +1)
r.append(-1)
n +=... | 5f9f57e02942264901f6523962b21d1c36accdb2 | 3,643,143 |
def get_neighbor_v6_by_ids(obj_ids):
"""Return NeighborV6 list by ids.
Args:
obj_ids: List of Ids of NeighborV6's.
"""
ids = list()
for obj_id in obj_ids:
try:
obj = get_neighbor_v6_by_id(obj_id).id
ids.append(obj)
except exceptions.NeighborV6DoesNot... | a51d618961fa3e60c0c464473838791d55ba1f6a | 3,643,146 |
import base64
def decode_b64_to_image(b64_str: str) -> [bool, np.ndarray]:
"""解码base64字符串为OpenCV图像, 适用于解码三通道彩色图像编码.
:param b64_str: base64字符串
:return: ok, cv2_image
"""
if "," in b64_str:
b64_str = b64_str.partition(",")[-1]
else:
b64_str = b64_str
try:
img = base6... | 66f0e7bb5028ad7247ef7cb468e904c2bc7afdb7 | 3,643,147 |
def _get_index_videos(course, pagination_conf=None):
"""
Returns the information about each video upload required for the video list
"""
course_id = str(course.id)
attrs = [
'edx_video_id', 'client_video_id', 'created', 'duration',
'status', 'courses', 'transcripts', 'transcription_s... | 5a3288ff8c2f371505fe2c6a3051992bfcc602eb | 3,643,148 |
def get_user_by_api_key(api_key, active_only=False):
"""
Get a User object by api_key, whose attributes match those in the database.
:param api_key: API key to query by
:param active_only: Set this flag to True to only query for active users
:return: User object for that user ID
:raises UserDoe... | b36373dbfcda80f6aac963153a66b54bce1d828d | 3,643,149 |
def get_pixel_values_of_line(img, x0, y0, xf, yf):
"""
get the value of a line of pixels.
the line defined by the user using the corresponding first and last
pixel indices.
Parameters
----------
img : np.array.
image on a 2d np.array format.
x0 : int
raw number of the st... | ea78efe02130302b34ba8402f21349035b05b2e0 | 3,643,150 |
def _filter_out_variables_not_in_dataframe(X, variables):
"""Filter out variables that are not present in the dataframe.
Function removes variables that the user defines in the argument `variables`
but that are not present in the input dataframe.
Useful when ussing several feature selection procedures... | 63b4cce75741a5d246f40c5b88cfebaf818b3482 | 3,643,151 |
import gzip
def file_format(input_files):
"""
Takes all input files and checks their first character to assess
the file format. 3 lists are return 1 list containing all fasta files
1 containing all fastq files and 1 containing all invalid files
"""
fasta_files = []
fastq_files = []
inv... | acd9a0f7b49884d611d0ac65b43407a323a6588b | 3,643,152 |
def sub_vector(v1: Vector3D, v2: Vector3D) -> Vector3D:
"""Substract vector V1 from vector V2 and return resulting Vector.
Keyword arguments:
v1 -- Vector 1
v2 -- Vector 2
"""
return [v1[0] - v2[0], v1[1] - v2[1], v1[2] - v2[2]] | 2c9878d6775fdcee554f959e392b2c8d2bad8c8e | 3,643,153 |
def create_validity_dict(validity_period):
"""Convert a validity period string into a dict for issue_certificate().
Args:
validity_period (str): How long the signed certificate should be valid for
Returns:
dict: A dict {"Value": number, "Type": "string" } representation of the
... | ba0ccdd5c009a930b4030b15fbafaa978fe753d4 | 3,643,154 |
def analyse_latency(cid):
"""
Parse the resolve_time and download_time info from cid_latency.txt
:param cid: cid of the object
:return: time to resolve the source of the content and time to download the content
"""
resolve_time = 0
download_time = 0
with open(f'{cid}_latency.txt', 'r') a... | 806a9969cc934faeea842901442ecececfdde232 | 3,643,155 |
import re
def process_ref(paper_id):
"""Attempt to extract arxiv id from a string"""
# if user entered a whole url, extract only the arxiv id part
paper_id = re.sub("https?://arxiv\.org/(abs|pdf|ps)/", "", paper_id)
paper_id = re.sub("\.pdf$", "", paper_id)
# strip version
paper_id = re.sub(... | a1c817f1ae7b211973efd6c201b5c13e1a91b57b | 3,643,156 |
import re
def augment_test_func(test_func):
"""Augment test function to parse log files.
`tools.create_tests` creates functions that run an LBANN
experiment. This function creates augmented functions that parse
the log files after LBANN finishes running, e.g. to check metrics
or runtimes.
No... | 081593b57dfc82df328617b22cf778fceffe4beb | 3,643,157 |
def nstep_td(env, pi, alpha=1, gamma=1, n=1, N_episodes=1000,
ep_max_length=1000):
"""Evaluates state-value function with n-step TD
Based on Sutton/Barto, Reinforcement Learning, 2nd ed. p. 144
Args:
env: Environment
pi: Policy
alpha: Step size
gamma: Discount facto... | 86d5ab58d4d185dcbf08a84bbc8eb67051d2af21 | 3,643,159 |
def open_file(path):
"""more robust open function"""
return open(path, encoding='utf-8') | 785ab196756365d1f27ce3fcd69d0ba2867887a9 | 3,643,160 |
def test_subscribe(env):
"""Check async. interrupt if a process terminates."""
def child(env):
yield env.timeout(3)
return 'ohai'
def parent(env):
child_proc = env.process(child(env))
subscribe_at(child_proc)
try:
yield env.event()
except Interru... | fa3170cc6167e92195587f06ae65b27da48fa8ff | 3,643,161 |
import gzip
def _parse_data(f, dtype, shape):
"""Parses the data."""
dtype_big = np.dtype(dtype).newbyteorder(">")
count = np.prod(np.array(shape))
# See: https://github.com/numpy/numpy/issues/13470
use_buffer = type(f) == gzip.GzipFile
if use_buffer:
data = np.frombuffer(f.read(), dty... | 42185d2425aa9aa14abc0a61a5bdabc95224d15c | 3,643,163 |
def test_target(target # type: Any
):
"""
A simple decorator to declare that a case function is associated with a particular target.
>>> @test_target(int)
>>> def case_to_test_int():
>>> ...
This is actually an alias for `@case_tags(target)`, that some users may find a bit... | ebbf94941e7b11224ee4c8ee9665cea231076f5d | 3,643,164 |
def plot_spatial(adata, color, img_key="hires", show_img=True, **kwargs):
"""Plot spatial abundance of cell types (regulatory programmes) with colour gradient
and interpolation (from Visium anndata).
This method supports only 7 cell types with these colours (in order, which can be changed using reorder_cma... | ffbf3cc0f6efdef9bf66b94bac22ef8bf8b39bab | 3,643,165 |
def stats_by_group(df):
"""Calculate statistics from a groupby'ed dataframe with TPs,FPs and FNs."""
EPSILON = 1e-10
result = df[['tp', 'fp', 'fn']].sum().reset_index().assign(
precision=lambda x: (x['tp'] + EPSILON) /
(x['tp'] + x['fp'] + EPSILON),
recall=lambda x: (x['tp'] + EPSIL... | c137e4076f837f51b0cab1acbe842ff827b62ee8 | 3,643,166 |
def in_this_prow(prow):
"""
Returns a bool describing whether this processor inhabits `prow`.
Args:
prow: The prow.
Returns:
The bool.
"""
return prow == my_prow() | 0f159cc9b57f407cbfefe9892689664f6d902f94 | 3,643,168 |
def _keypair_from_file(key_pair_file: str) -> Keypair:
"""Returns a Solana KeyPair from a file"""
with open(key_pair_file) as kpf:
keypair = kpf.read()
keypair = keypair.replace("[", "").replace("]", "")
keypair = list(keypair.split(","))
keypair = [int(i) for i in keypair]
r... | 1fdb4d72945d89db7c8d26c96bcbbd18071258dc | 3,643,169 |
import binascii
def val_to_bitarray(val, doing):
"""Convert a value into a bitarray"""
if val is sb.NotSpecified:
val = b""
if type(val) is bitarray:
return val
if type(val) is str:
val = binascii.unhexlify(val.encode())
if type(val) is not bytes:
raise BadConver... | 17081bb8b382763fa5ace4d7d2969b6eed4581ed | 3,643,170 |
def unpack_uint64_from(buf, offset=0):
"""Unpack a 64-bit unsigned integer from *buf* at *offset*."""
return _uint64struct.unpack_from(buf, offset)[0] | ce01d76d18e45a42687d997459da9113d9e3e45f | 3,643,171 |
def del_none(dictionary):
"""
Recursively delete from the dictionary all entries which values are None.
Args:
dictionary (dict): input dictionary
Returns:
dict: output dictionary
Note:
This function changes the input parameter in place.
"""
for key, value in list(dic... | 48b76272ed20bbee38b5293ede9f5d824950aec5 | 3,643,172 |
def get_table_header(driver):
"""Return Table columns in list form """
header = driver.find_elements(By.TAG_NAME, value= 'th')
header_list = [item.text for index, item in enumerate(header) if index < 10]
return header_list | 631e71e357beb37f50defe16fe894f5be3356516 | 3,643,174 |
from rx.core.operators.connectable.refcount import _ref_count
from typing import Callable
def ref_count() -> Callable[[ConnectableObservable], Observable]:
"""Returns an observable sequence that stays connected to the
source as long as there is at least one subscription to the
observable sequence.
"""... | e6f8b21e582d46fab75d9013121d764072630390 | 3,643,175 |
def radius_provider_modify(handle, name, **kwargs):
"""
modifies a radius provider
Args:
handle (UcsHandle)
name (string): radius provider name
**kwargs: key-value pair of managed object(MO) property and value, Use
'print(ucscoreutils.get_meta_info(<classid>).confi... | 9a5c5d62ff60a3a3a8499e4aaa944f758dc49f83 | 3,643,177 |
def _read_table(table_node):
"""Return a TableData object for the 'table' element."""
header = []
rows = []
for node in table_node:
if node.tag == "th":
if header:
raise ValueError("cannot handle multiple headers")
elif rows:
raise ValueErr... | e6ef6e5d5ec99ea2b15ddfcae61b4dd817f8232b | 3,643,178 |
def postorder(root: Node):
"""
Post-order traversal visits left subtree, right subtree, root node.
>>> postorder(make_tree())
[4, 5, 2, 3, 1]
"""
return postorder(root.left) + postorder(root.right) + [root.data] if root else [] | ddeaa6e0f2f466284d69908dfc7eb67bdc6748c8 | 3,643,179 |
def merge_triangulations(groups):
"""
Each entry of the groups list is a list of two (or one) triangulations.
This function takes each pair of triangulations and combines them.
Parameters
----------
groups : list
List of pairs of triangulations
Returns
-------
list
... | 0d39006892e0b248e1f50a62c86911c830b100ce | 3,643,180 |
def compute_relative_pose(cam_pose, ref_pose):
"""Compute relative pose between two cameras
Args:
cam_pose (np.ndarray): Extrinsic matrix of camera of interest C_i (3,4).
Transforms points in world frame to camera frame, i.e.
x_i = C_i @ x_w (taking into account homogeneous dime... | b185554b2961bd7cd70df5df714c176f2d5b6dcc | 3,643,182 |
def determine_clim_by_standard_deviation(color_data, n_std_dev=2.5):
"""Automatically determine color limits based on number of standard
deviations from the mean of the color data (color_data). Useful if there
are outliers in the data causing difficulties in distinguishing most of
the data. Outputs vmin... | 1a8b1240c50a01f645862b7fce76bc93c62bcb26 | 3,643,185 |
def ec_double(point: ECPoint, alpha: int, p: int) -> ECPoint:
"""
Doubles a point on an elliptic curve with the equation y^2 = x^3 + alpha*x + beta mod p.
Assumes the point is given in affine form (x, y) and has y != 0.
"""
assert point[1] % p != 0
m = div_mod(3 * point[0] * point[0] + alpha, 2 ... | 4489ef72ceb1297983c5f4ac4132fc1e04105365 | 3,643,186 |
def scaled_dot_product_attention(q, k, v, mask):
"""
Calculate the attention weights.
q, k, v must have matching leading dimensions.
k, v must have matching penultimate dimension, i.e.: seq_len_k = seq_len_v.
The mask has different shapes depending on its type(padding or look ahead)
but it must ... | 22110522c4f33ec30c076240ade20f5b66cb3fcd | 3,643,187 |
import re
def _parse_message(message):
"""Parses the message.
Splits the message into separators and tags. Tags are named tuples
representing the string ^^type:name:format^^ and they are separated by
separators. For example, in
"123^^node:Foo:${file}^^456^^node:Bar:${line}^^789", there are two tags and
t... | c961f2a49a21682eb247d4138646abd86135c560 | 3,643,188 |
def model_fn(features, labels, mode, params):
"""Model function."""
del labels, params
encoder_module = hub.Module(FLAGS.retriever_module_path)
block_emb = encoder_module(
inputs=dict(
input_ids=features["block_ids"],
input_mask=features["block_mask"],
segment_ids=features["b... | ff40f74501f26e880a9cf1421a608240fd059fb8 | 3,643,189 |
def get_rotated_coords(vec, coords):
"""
Given the unit vector (in cartesian), 'vec', generates
the rotation matrix and rotates the given 'coords' to
align the z-axis along the unit vector, 'vec'
Args:
vec, coords - unit vector to rotate to, coordinates
Returns:
rot_coords: ro... | f8504df4b7afef524e4147ce6303055a4b7a3cea | 3,643,190 |
def merge_on_pids(all_pids, pdict, ddict):
"""
Helper function to merge dictionaries
all_pids: list of all patient ids
pdict, ddict: data dictionaries indexed by feature name
1) pdict[fname]: patient ids
2) ddict[fname]: data tensor corresponding to each patient
"""
set_ids = s... | d0968de287a1c62ebb7638e5f1af7bd63041665c | 3,643,191 |
import requests
import numpy
def do_inference(hostport, work_dir, concurrency, num_tests):
"""Tests PredictionService over Tensor-Bridge.
Args:
hostport: Host:port address of the PredictionService.
work_dir: The full path of working directory for test data set.
concurrency: Maximum number of concurre... | ed2cc97ccaf6e3a8be2ae690b190640c67365f9d | 3,643,193 |
def test_true() -> None:
"""This is a test that should always pass. This is just a default test
to make sure tests runs.
Parameters
----------
None
Returns
-------
None
"""
# Always true test.
assert_message = "This test should always pass."
assert True, assert_message
... | f08cb5feb4e450b10b58fe32d751bf45985df84c | 3,643,195 |
def parseStylesheetFile(filename):
"""Load and parse an XSLT stylesheet"""
ret = libxsltmod.xsltParseStylesheetFile(filename)
if ret == None: return None
return stylesheet(_obj=ret) | 9e12e7ec5ace9eafe50e595d544bc09ff7ccef7d | 3,643,196 |
import torch
def tensor_to_index(tensor: torch.tensor, dim=1) -> np.ndarray:
"""Converts a tensor to an array of category index"""
return tensor_to_longs(torch.argmax(tensor, dim=dim)) | 7d72b18086a46c4f1c3f8cebaee28ddac12cf31c | 3,643,197 |
def _le_(x: symbol, y: symbol) -> symbol:
"""
>>> isinstance(le_(symbol(3), symbol(2)), symbol)
True
>>> le_.instance(3, 2)
False
"""
return x <= y | 336b164cbc249a1a9e9a3d965950a52ac01292ab | 3,643,199 |
from typing import List
def convert_country_codes(source_codes: List[str], source_format: str, target_format: str,
throw_error: bool = False) -> List[str]:
"""
Convert country codes, e.g., from ISO_2 to full name.
Parameters
----------
source_codes: List[str]
Lis... | 7589dec9ccec5edc7bf5ea356b40fac3898c7c77 | 3,643,200 |
def get_simple_lca_length(std_tree, test_gold_dict, node1, node2):
"""
get the corresponding node of node1 and node2 on std tree.
calculate the lca distance between them
Exception:
Exception("[Error: ] std has not been lca initialized yet")
std tree need to be initialized before running ... | 8433259814fe656bdbdd6997ca613b30c458f8b8 | 3,643,201 |
def edit_catagory(catagory_id):
"""edit catagory"""
name = request.form.get('name')
guest_id = session['guest_id']
exists = db.session.query(Catalogs).filter_by(name=name,
guest_id=guest_id).scalar()
if exists:
return abort(404)
if name... | a0d342490881968f39cf4636fb424176c6608e4a | 3,643,202 |
def match_patterns(name, name_w_pattern, patterns):
"""March patterns to filename.
Given a SPICE kernel name, a SPICE Kernel name with patterns, and the
possible patterns, provide a dictionary with the patterns as keys and
the patterns values as value after matching it between the SPICE Kernel
name... | a54b7f1fcda67b5649f92a21f4711874dd226ee9 | 3,643,203 |
def _generate_good_delivery_token_email(request, good_delivery, msg=''):
"""
Send an email to user with good_delivery activation URL
and return the token
:type request: HttpRequest
:type good_delivery: GoodDelivery
:type msg: String
:param structure_slug: current HttpRequest
:param str... | 4567c3d0ad3f2d65c850ed5291e602cb552b11cb | 3,643,204 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.