content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def repaint_surface(
surface: pygame.Surface,
old_color: pygame.Color,
new_color: pygame.Color,
) -> pygame.Surface:
"""Replaces paints `surface` with `color`."""
# Parses the boolean surface to a tensor.
surf = pygame_surface_to_ndarray(surface)
R = surf[..., 0]
G = surf[..., 1]
B = surf[..., 2... | d7b0946e2b3f292ed94159313ff6a90523a08003 | 67,000 |
def _get_poll_counter():
"""Increment and return the poll counter"""
global NUM_POLLS
NUM_POLLS += 1
return NUM_POLLS | d15fb3c6111c256f9ed4976bea544cbf76c895aa | 67,001 |
def remind_public_clt(clt):
"""
:param clt:collection对象
:return msg对象
"""
msg = {
"title": "征集者提醒",
"btn_label": [
{"title": "去看看", "url": f"https://up.anrunlu.net/collections/{clt['_id']}"},
{"title": "忽略", "url": f"https://up.anrunlu.net/collections/{clt['_i... | 5ad4543b2285e983168e0b6314b2d8ca5dbbb73a | 67,002 |
def read_ovaldefgroup_file(testfile):
"""Read oval files"""
with open(testfile, 'r') as test_file:
body = test_file.read()
return body | a472777f700e5e768c0995af6a1db4c476fc029f | 67,003 |
import torch
from typing import Optional
from typing import Union
from typing import List
def top_hat(input_tensor: torch.Tensor,
structuring_element: torch.Tensor,
origin: Optional[Union[tuple, List[int]]] = None,
border_value: Union[int, float, str] = 'geodesic'):
""" Top-hat... | 9f31ec963d488d09bea71d9600e5d06f324a8950 | 67,004 |
import time
import logging
import inspect
def wait_on(
condition, *args, wait_message="Waiting {}", timeout=None,
fail_callback=None, wait=None, timeout_callback=None):
"""Wait on a condition to be non-False.
Args:
condition: Function that returns either False or a non-False value.
... | 8fdaf676cb6f5a1894bf098c3d0d4a3a80e57faa | 67,005 |
def login_navbar() -> Response:
"""Login from navbar."""
user = User.query.filter_by(username=request.form["navbarusername"]).first()
if user is None or not user.check_password(request.form["navbarpassword"]):
flash("Invalid username or password.")
return redirect(url_for("auth.login"))
... | 89f78b74991b76c9fa54449ef484a0ab5d62b5cd | 67,006 |
import torch
def cal_metrics(num_classes, preds, targets, iou_thres):
"""计算目标检测的关键指标
Args:
num_classes (int): 类别数量
preds (list): 所有预测box,每个元素为二维数组,columns的格式为 (class_id, x1, y1, x2, y2, conf)
targets (list): 所有真实标签,每个元素为二维数组,columns的格式为 (class_id, x1, y1, x2, y2)
iou_thres (fl... | 4555f77bbd31d37b36d645a0cdc731e2f05136d0 | 67,007 |
def validate(request):
"""Method to validate a request and return blocked if they fail"""
if not request.session.get('ipviking'):
#we need to validate them
ip = request.remote_addr
if ip == '127.0.0.1':
ip = '208.74.76.5' #the API doesn't like localhost, so we'll use the sand... | 43f816199be6cb80555c52999fdfaae5ac19eeb1 | 67,008 |
import string
def get_navigation_menu(lines, *args):
""" liefert das linke Menu """
n_args = 0
menu = []
for n in xrange(4):
try:
menu.append(args[n])
n_args += 1
except:
menu.append('')
ret = u''
select = 0
for line in lines:
my_depth, my_alias, res = get_data_left(line)
... | 07319421e8aad1150d43e6c9fb5ec72471ddd221 | 67,009 |
def cross2D(v1,v2):
"""calculates the scalar cross product magnitude of two 2D vectors, v1 and v2"""
return v1[0]*v2[1] - v1[1]*v2[0] | 6bbe95ac483b349cda500a0c5045181035b46314 | 67,010 |
import re
import sys
import requests
import os
import json
def get_book2(book_id, s=None, local_path='.\\Books', url=None):
"""
given a url of book on shanbay.com, automatically save the book in format of json
if the book exists locally, load it
separate wordlists
:param book_id:
:param s:
... | 9da2a3e8052052af024855e150a47c728ae91ea7 | 67,011 |
import http
def prepare_private_key():
"""`before_request` handler that checks the Referer header to see if the user
is requesting from a view-only link. If so, reappend the view-only key.
NOTE: In order to ensure the execution order of the before_request callbacks,
this is attached in website.app.in... | 5bb5565d2a82d4524541086ab63b3c6be933de87 | 67,012 |
def getAllTitles():
"""Returns a list of strings of window titles for all visible windows."""
return [window.title for window in getAllWindows()] | bd8c451e4c760ebee6efc3218ff104091273e141 | 67,013 |
from pyhocon import ConfigFactory, HOCONConverter, ConfigTree
def _load_custom_config(run_config):
"""Load custom configuration input HOCON file for cromwell.
"""
conf = ConfigFactory.parse_file(run_config)
out = {}
if "database" in conf:
out["database"] = HOCONConverter.to_hocon(ConfigTre... | cc3e561d5110b98dc152757292f7457437119a82 | 67,014 |
def get_xml_obj_from_response(response):
"""
Returns an XML object (``lxml.Element``) from the text inside the
``Response`` object.
"""
src = get_text_from_response(response)
start = src.find('?>')
if start > 0:
start += 2
else:
start = 0
return etree.fromstring(src[s... | c6e2f2c655b4207a0c0ce93e9e199309dd02ef21 | 67,015 |
import os
import pathlib
async def did_definition(ls, params):
"""Return location of definition of a need."""
if not ls.needs_store.is_setup():
return
need_type, need_id = get_need_type_and_id(ls, params)
# get need defining doc
try:
need = ls.needs_store.needs[need_id]
exce... | 09f660ee3194a307bb4b6bb1e1e4888c8132391d | 67,016 |
import sys
import six
def prompt_for_choice(prompt, *choices):
"""
Prompt the user for multiple choice input.
Keep prompting until a valid choice is received. Choice shortcuts require
unique first letters. The user can either respond with a single letter or
an entire word.
"""
letters = s... | 59d7388897f4b8cad6e0d9b750b867d5125df16b | 67,017 |
def gammaln(x):
"""
Logarithm of the Gamma function
"""
return flib.gamfun(x) | 034152775bcc3f7935301ead23321b409660b34d | 67,018 |
def template_test(request):
"""Render a simple template"""
return render_to_response('test.html', locals()) | a1cd89a67664255cf31ef3897e25d05fd321a2bf | 67,019 |
from re import T
import logging
def setup_log(config: T.Dict[T.Text, T.Any]) -> logging.Logger:
"""Setup the logger."""
fmt = setup_formatter()
level = getattr(logging, config["level"])
handlers = [setup_console_handler(fmt, level)]
if config["syslog"]:
handlers.append(setup_syslog_handler... | c302a3f061b8ce4d6d5c4d628197dd36d5ae02f6 | 67,020 |
from operator import add
def run(data_s: str) -> tuple[int, int]:
"""Solve the puzzles."""
trees = [parse(eval(line)) for line in data_s.splitlines()]
# Part 1
total = trees[0]
for other in trees[1:]:
total = add(total, other)
# Part 2
magnitudes = []
for tree1, tree2 in comb... | 034d31e8dfe6ef47e78ebf713ef0bbc11b4c098b | 67,021 |
def add_resource(request):
""" A view allowing admin to add a resource to the resources page """
if not request.user.is_superuser:
messages.error(request, 'Sorry, only admin can add resources.')
return redirect(reverse('home'))
if request.method == 'POST':
form = ResourceForm(reques... | 9f3798e34d3599b8c43501febdb80b088cab3b9a | 67,022 |
import array
def kernel_evaluate(pos, tree, tree_mcom, rmin, rmax, kvals):
"""
kvals - logarithmically spaced values between rmin and rmax
"""
lib = _initlib(null_log)
n_kernel = len(kvals)
res = lib.init_kernel(n_kernel, array(kvals, dtype=float32), rmin, rmax)
if res!=0:
ra... | c1f0b47a750f7510632c73aea9eb559672e44eb7 | 67,023 |
def graph_db(request) -> graph_tuple_database.Database:
"""A test fixture which returns a graph database with random graphs."""
graph_y_dimensionality, node_y_dimensionality = request.param
db = graph_tuple_database.Database(testing_databases.GetDatabaseUrls()[0])
random_graph_tuple_database_generator.PopulateD... | 71e873041f3ec7fa1c4550a3e7ea3e3ff66aacaf | 67,024 |
def qualified_name_to_object(qualified_name: str, default_module_name='builtins'):
"""
Convert a fully qualified name into a Python object.
It is true that ``qualified_name_to_object(object_to_qualified_name(obj)) is obj``.
>>> qualified_name_to_object('unittest.TestCase')
<class 'unittest.case.Tes... | f8758a80aaa4196aa559b18a5850840ba4bbd69b | 67,025 |
def aggregated_data_from_experiments(experiments, contains_err=False):
"""
experiments: Is a dict of score dicts with each key being the scores of an experiments
contains_err: If True, for each metric score a error is expected under the key metric_label + '_std'
Returns: a structured list that can be ... | 561f967e3777230484c2b355a3af109d7172350a | 67,026 |
def auc(actual, posterior): # pylint: disable=doc-string-with-all-args, doc-string-with-returns
"""
Computes the area under the receiver-operater characteristic (AUC)
This function computes the AUC error metric for binary classification.
Parameters
----------
actual : list of binary numbers, nu... | 1cf2098dd1d872092e7514ae7be9a09de72aa274 | 67,027 |
def integer_or_string(items: list[str]) -> tuple[list[str], list[str]]:
"""
given a list of strings return two lists, the first list will be the
strings that can be converted to integers. The second list will be
the list of strings that cannot be converted to a string.
"""
number_items = []
... | b543f820a474f9495cd1401423516191613d6715 | 67,028 |
from sys import path
def fixtures(filename):
"""
Read and cache a challenge fixture
Returns: HTML (bytes): The HTML challenge fixture
"""
if not cache.get(filename):
print('reading...')
with open(path.join(path.dirname(__file__), 'fixtures', filename), 'r') as fp:
cach... | d9cf39577c3476e9cfe98fb3c52e7a0a4eccebd6 | 67,029 |
def CheckForDoubles(String):
"""Prüft ob mehrere Personen gleichzeitig sprechen und teilt diese dann auf einzelne Einträge auf.
Rückgabe Liste der sprechenden Pers. : "#Anna #Berta" -> ["#Anna", "#Berta"]"""
stringList = []
y = len(String)
x = 0
for i in range(len(String) - 1, -1, -1):
i... | 5555d50e2bb1d6fedcf6e7d74c3c1c5c866cea3b | 67,030 |
def create_class_Cartesian_3D_Vector(name, component_names, *, brackets='<>', sep=', ', cnull=0, cunit=1, functions=None):
"""Function that creates a cartesian vector class with 3 dimensions"""
hf.verify_class_name(name)
dimensions = 3
component_names = [ *component_names ]
if len(component_names) ... | 57e10f2cf61b35262beb2dc94e4b81a7323fad8a | 67,031 |
import argparse
def parse_args():
"""Parse command-line arguments"""
parser = argparse.ArgumentParser("Rhasspy")
parser.add_argument(
"--profile", "-p", required=True, type=str, help="Name of profile to load"
)
parser.add_argument(
"--host", type=str, help="Host for web server", de... | 8cfe9d1f97a1f6bee81b29a370908d636122a219 | 67,032 |
from ..preprocessing import szFactor
def adata_processing_TF_link(adata, nt_layers, TF_list, gene_filter_rate=0.1, cell_filter_UMI=10000):
"""preprocess adata and get ready for TF-target gene analysis"""
n_obs, n_var = adata.n_obs, adata.n_vars
# filter genes
print(f"Original gene number: {n_var}")
... | 217855b77dbce9290f24162dbb81ea890e8dd9e2 | 67,033 |
def monitoredsystems():
"""this method returns the current list of monitored systems"""
# Replace this with sql logic to get monitored systems later
monitored = ['Arque', 'Zaonce', 'Teorge', 'Tianve', 'Tionisla', 'Neganhot', 'Orrere', 'Oguninksmii']
return monitored | 0590360d7a97e93ab6f00e5139dc94a7bb7c8c7c | 67,034 |
def preprocess_initial(train, image_size):
"""Initial preprocessing function for training on smaller resolution.
For training, do random_horizontal_flip -> random_crop.
For validation, just resize.
No color-jittering has been used.
"""
def _pp(image, label, train):
if train:
... | 8620fa7d56de80f093848f87d6af11f9e8fc8a68 | 67,035 |
import requests
from bs4 import BeautifulSoup
def forbes_rank(indicator: str = "2020福布斯美国富豪榜") -> pd.DataFrame:
"""
福布斯中国-榜单
https://www.forbeschina.com/lists
https://www.forbeschina.com/lists/1750
:param indicator: choice of {"2020福布斯美国富豪榜", "2020福布斯新加坡富豪榜", "2020福布斯中国名人榜", *}
:type indicator... | c543fb83220b091eaab6d3b114e22b54b56dde38 | 67,036 |
def sample(predictions, temperature):
""""Simulates creativity by sampling predicted probabilities of next character."""
predictions = np.asarray(predictions).astype('float64')
if temperature is None or temperature == 0.0:
return np.argmax(predictions)
predictions = np.log(predictions + K.ep... | 9e4cfc19305aea0417a7ab81b61ed7c9e8010fd0 | 67,037 |
import torch
def area_under_roc(pred, target):
"""
Area under receiver operating characteristic curve (ROC).
Parameters:
pred (Tensor): predictions of shape :math:`(n,)`
target (Tensor): binary targets of shape :math:`(n,)`
"""
if target.dtype != torch.long:
raise TypeErro... | 73fe771d46994cc0d72c726fc18e51a9d48f3c7d | 67,038 |
def vec_2d(v) -> np.ndarray:
"""Converts a higher order vector to a 2D vector."""
assert len(v) >= 2
return np.array(v[:2]) | 5e829483365cf000cfebf4f486a54c1a6136b9e8 | 67,039 |
def acceptable_drift(drMeasure, Tm, Thm, lowerBound, upperBound):
"""
Function that return true if drift is acceptable (based on lowerBound and upperBound), false otherwise
"""
mrMeasure = Tm/Thm
mrMeasure = preprocess_mr(mrMeasure)
drMean = np.mean(drMeasure)
drSTD = np.std(drMeasure)
m... | 63b8e59385548630083bf4661647140c9d40689b | 67,040 |
def get_crypto_layer(exr_file: OpenEXR.InputFile, layer_mapping: exr_info.CryptoLayerMapping) -> np.ndarray:
"""Extract one of the cryptomatte layers as a 4-channel numpy array.
Each cryptomatte layer has 4 channels for RGBA.
Note:
- By default, there are 3 crypto layers in an EXR, corresponding to... | 7c6e2fc0b48211d9008ec636cd852c7b1eaae708 | 67,041 |
def concatenate(matrices, out=None, dtype=None):
"""Concatenate matrix transformations.
Chain multiply matrices describing transform operations into a single matrix
product, that when applied, transforms points and vectors with each
operation in the order they're specified.
Parameters
--------... | 1d429d72f1094d599340a3afb4872e6b7b183ed8 | 67,042 |
def covidstats_df(data):
""" Dado un json de datos de un deparamento de covidstats devuelve un DataFrame con:
- indice la fecha
- casos_fa, casos_reporte
- CAMPO_acum el acumulado respectivo
- CAMPO_14acum acumulado en 14 dias
"""
day = pd.Series(pd.date_range(data['fecha_ini... | 3589ea71da4fc3df9f902d8b75a0068fabd744bf | 67,043 |
import yaml
def _write_and_build_prj(fp, d):
"""
Write project config file and build Project.
:param str fp: path to config file
:param dict d: project config data
:return looper.Project: newly built Project instance
"""
with open(fp, 'w') as f:
yaml.dump(d, f)
return Project(... | 860a563e9999cdf484d9280179d4406ed77573d5 | 67,044 |
from re import DEBUG
def getToken(a = 0):
"""
Returns a string value corresponding of the telegram bot token found in
the table "telegram" field token of the mysql DB
"""
token = exFetch("SELECT token FROM telegram")
token = str(token[a][0]) #Cast from list to string
if(DEBUG):
print("getToken() returned te... | 2f58541fb7b531ceecad826cb5c6353d78b4062c | 67,045 |
import torch
def unnormalize_img(img, mean, std, in_gpu=True):
"""
img: [3, h, w]
"""
img = img.detach().cpu().clone()
# img = img / 255.
img *= torch.tensor(std).view(3, 1, 1)
img += torch.tensor(mean).view(3, 1, 1)
min_v = torch.min(img)
img = (img - min_v) / (torch.max(img) - mi... | 52698e7644e2d20e18e3ed44108af5b901d4f01b | 67,046 |
import base64
import io
def parse_data(filename, contents="", isFileOnly=None, transpose=False):
"""
-> parse uploaded .csv | .xlsx data
-> [isFileOnly] if True will read from file only (default onStart file to load data)
:param contents:
:param filename:
:param isFileOnly
:return: pandas ... | 84bce76a00f5bee18afa44031456c6857c96cd43 | 67,047 |
import math
def get_scalar_min_max_by_column(df, target_columns, column_to_properties):
"""Get a dictionary indexed by column name with minimum and maximum values.
(useful e.g., for normalized processing of subgroups).
If column to properties is set, for a column, the minimum and maximum are taken from t... | f35bdea2ac780610e95b3286e5ac2a21d870877e | 67,048 |
def get_options(optionset_label, current_only=True, as_stored=False):
"""
Return all options for this app_label as dictionary with the option name
being the key.
"""
#Hit the cache
cached = {}
if ls.ADMIN_CACHE_DB_OPTIONS:
cached = cache.get(get_option_cache_key(optionset_label), {}... | 65d635251cfae6054926bc12b2ce6082dbf7c522 | 67,049 |
def build_url(hub_base_url: str, org: str, workspace: str) -> str:
"""
Build the base URL of the Chaos Hub workspace where the experiment and
the journal will be stored and be made visible.
"""
return '/'.join([hub_base_url, 'api', org, workspace]) | 116b9b7f6211ca50b48550689b7e161cee0b4d9d | 67,050 |
def batched_nms_pattern(boxes, scores, idxs, iou_threshold, num_boxes, indices):
"""A pattern to detect batched_nms function in torchvision
The inputs to this function, boxes, scores, idxs, iou_threshold are wildcard
patterns which can be used later in the rewriting to extract matched Relay fragments.
... | e1e0f0bdf21b1cb466fff583c8f39871be3400f0 | 67,051 |
import types
import functools
def cmp_using(
eq=None,
lt=None,
le=None,
gt=None,
ge=None,
require_same_type=True,
class_name="Comparable",
):
"""
Create a class that can be passed into `attr.ib`'s ``eq``, ``order``, and
``cmp`` arguments to customize field comparison.
The ... | 0e463b4ca64b2f26e254e38c754cfe2ab4e9b918 | 67,052 |
def plot_single_sd(sd,
cmfs='CIE 1931 2 Degree Standard Observer',
out_of_gamut_clipping=True,
modulate_colours_with_sd_amplitude=False,
equalize_sd_amplitude=False,
**kwargs):
"""
Plots given spectral distribution.
... | 435a6ecf007ee0120806cf3feb02bea826a5be96 | 67,053 |
from datetime import datetime
def datetimes_equal(dt1, dt2):
"""Compare if datetimes are equal to the nearest second."""
diff = dt1 - dt2
return abs(diff) < datetime.timedelta(seconds=1) | de7c08c6360887b69e188f5cf638851195de03c7 | 67,054 |
import os
import subprocess
def first_part():
"""
It is the first part. It is used to call pyani program to calculate ANI of each strain pair.
:return: success message
"""
logger.info('Part 1: Calculating average nucleotide identity (ANI) of each strain pair...')
genbank_folder = os.path.join(... | cfdd54f40fc1f10da3a7272bdc64b7a82d747dc1 | 67,055 |
def _repopulate_partitions(partition_string: str, partition_metadata: dict) -> tuple:
""" For each val in the partition string creates a list that can be added back into the dataframe
Args:
partition_string (str): S3 bucket to fetch from
partition_metadata (dict): A dictionary of all partitions... | b26c5e1c44b1158cfbfd6fd2c236f6de7593d35b | 67,056 |
def clean(key, value):
""""Clean the values"""
if key.startswith('WS'):
return QUANTITY(value, UREG.mph).to(UREG.knots).m
if key.startswith('RH') and value > 100:
return 100.
if pd.isnull(value):
return None
return value | e6f8f109a3222837690a2f84e4fd3aa481ceaf00 | 67,057 |
def _GetAddress(compute_client, address_ref):
"""Returns the address resource corresponding to the given reference.
Args:
compute_client: GCE API client,
address_ref: resource reference to reserved IP address
Returns:
GCE reserved IP address resource
"""
errors = []
messages = compute_client.m... | 544c7b30a8da5762ff50cb2cc563d3fc251121be | 67,058 |
def generate_active_htmls(conn: Connection) -> t.Iterable[str]:
"""Get HTML stored in the database for active sections."""
sql = "SELECT html FROM Notes WHERE html IS NOT NULL ORDER BY id ASC"
return (html.strip() for html, in conn.execute(sql)) | 6c61fb9d892518245d92e154e88b18eb1ff9c4f3 | 67,059 |
def parse_vcf_line(line):
"""
Parse a line in the VCF file.
:param line: a line from the VCF file
:type line: str
:return: :class:`.vcf.VCFRecord`
"""
if isinstance(line, str):
if line.startswith('#'):
return None
elem = line.strip().split('\t')
elif isinst... | a41e4efda445311c09ed97b079823d23867658f9 | 67,060 |
def fieldify(embed: discord.Embed, names: list, values: list, inline: bool = True, limit: int = None):
"""Easy embed fieldification
:returns embed:
"""
embed = embed
if not limit:
for name, val in zip(names, values):
embed.add_field(name=name, value=val, inline=inline)
... | c8a02d11abfd75921e988701a2e79112f0a0bf74 | 67,061 |
def init_floodfill(cpoint, opoints, xypoints, mincoord, xyreso):
"""
cpoint: center point
opoints: detected obstacles points (x,y)
xypoints: (x,y) point pairs
"""
centix, centiy = cpoint
prev_ix, prev_iy = centix - 1, centiy
ox, oy = opoints
xw, yw = xypoints
minx, miny = mincoo... | b5dc61459fac947161e611942b575d5ea9f65ff7 | 67,062 |
def naive_closest_pair(plane):
"""
Find the closest pair of points in the plane using the brute
force approach
Args:
plane: List of points [(p1_x, p1_y), (p2_x, p2_y), ...]
Returns:
Distance between closest pair of points and closest pair
of points: [dist_bw_p1_p2, (p1_x, p1... | 653fe7f35999a0c8827ee3108e720d323856c63a | 67,063 |
def _compute_factored_isogeny_prime_power(P, l, e):
"""
This method takes a point `P` of order `l^e` and returns
a sequence of degree-`l` isogenies whose composition has
the subgroup generated by `P` as its kernel.
EXAMPLES::
sage: from sage.schemes.elliptic_curves import hom_composite
... | cc5ec271b2bf0d39ee615d9eb21c96674c7b8748 | 67,064 |
import os
import pickle
def get_gcal_service():
"""Create a Google Calendar service object.
copied from https://developers.google.com/calendar/quickstart/python
"""
# If modifying these scopes, delete the file token.pickle.
SCOPES = ['https://www.googleapis.com/auth/calendar']
"""Shows basic... | f8a00f117807d8ae07f84a6edbef6cc54d1baaa2 | 67,065 |
def lanczosSubPixKernel( subPixShift, kernelShape=3, lobes=None ):
"""
Generate a kernel suitable for ni.convolve to subpixally shift an image.
"""
kernelShape = np.array( [kernelShape], dtype='int' )
if kernelShape.ndim == 1: # make it 2-D
kernelShape = np.array( [kernelShape[0], kernelSha... | 3208dd080ba737a1ab5d224b52352a86dd9769d3 | 67,066 |
def load_python_exec(text_data, builtins=None):
"""
Function to provide compatibility with python 3.7 for loading text formwatted in
python using exec buil-in method. Exec syntaxis in pyton 2.6 different
comared to python3.x and python3 spits "Invlaid Syntaxis error" while trying to
run code below... | 9f16866ec38138b8a7bfd359244bc10f7a2ac93c | 67,067 |
import os
import errno
import csv
from io import StringIO
def clean_position_data(filename, max_speed=DEFAULT_MAX_SPEED,
distance_accuracy=DEFAULT_DISTANCE_ACCURACY):
"""
Identify and remove invalid postions in a positions file.
Outputs a positions file with "raw_" stripped from t... | 1089090361e54fb15d619841fd274ee22981c300 | 67,068 |
def one_hot_encoding(y):
"""creates one-hot vector for the target variables
for example,if a training set consists of multiple classes y=(0,1,2...n)
one-hot vector for y(0)=[1,0,0,..n],y(2)=[0,0,1,0,..n]"""
no_=y.shape[0]
class_set=set([_[0] for _ in y if isinstance(_,(list,np.ndarray))])
temp=np.full([no_,len(cl... | 16780d443fe83eb4473a1dfd66d5e860e122d43f | 67,069 |
def get_disassembler(disassembler=None):
"""
lazy import (so we can still change global path)
"""
if disassembler is None:
if ida_available:
disassembler = 'ida'
else:
disassembler = 'ghidra'
if disassembler == 'ida':
return IDA()
if disassembler ... | 2eb389278a5f1a70b6cf61ff325e195f62d2ba73 | 67,070 |
def icon_sys_title(icon_sys, encoding = None):
"""Extract the two lines of the title stored in an icon.sys tuple."""
offset = icon_sys[1]
title = icon_sys[14]
title2 = shift_jis_conv(title[offset:], encoding)
title1 = shift_jis_conv(title[:offset], encoding)
return (title1, title2) | ef66e05fcad94cdd558b1b1abe22300d9e8beb48 | 67,071 |
import os
def files_to_be_sourced():
"""Returns a list of files to be sourced"""
datadir = os.path.join(
spack_root, 'lib', 'spack', 'spack', 'test', 'data'
)
files = [
os.path.join(datadir, 'sourceme_first.sh'),
os.path.join(datadir, 'sourceme_second.sh'),
os.path.joi... | 10a2c3a987bf056bfa6e8df5306ab32b90167dc2 | 67,072 |
def get_old_color(request):
"""
Returns the old color of the label when edited
:param request: incomming request
:return: old color of the label (String)
"""
if('color' in request.json['changes']):
return request.json['changes']['color']['from'] | 8711c91e00ff5d5e550d4153f5eddbee56e710ea | 67,073 |
def unfold_tensor(tensor, dim, window_sz):
"""Unfold a tensor by applying a sliding window on a certain dimension with step 1 and padding of 0's. The window
dimension is added as the last dimension
:param tensor: the tensor to be unfolded, with shape [d_1, d_2, ..., T, ..., d_n]
:param dim: the dimensi... | 352b72ccb7a8e23d5c6e26d54f89bf6a6f8c1f72 | 67,074 |
def vectorized_lower_tri_to_mat(v, dim):
"""
:param v: a list of length (dim * (dim + 1) / 2)
:param dim: the number of rows (equivalently, columns) in the output array.
:return: Return the symmetric 2D array defined by taking "v" to
specify its lower triangular entries.
"""
rows, cols, va... | 38fb2a778806dc3cdad12217ceb387188d95e5a8 | 67,075 |
import random
def calc(metric: str, Y_mean: np.ndarray, Y_var: np.ndarray,
current_max: float, t: float,
beta: int, xi: float, stochastic: bool) -> np.ndarray:
"""Call corresponding metric function with the proper args"""
if metric == 'random':
return random(Y_mean)
if metric == ... | 588c7df0f25a24f22538d66934837abac4a6c685 | 67,076 |
def list_lookup(list_, select, default=0):
"""
Use `select` as an index into `list` (similar to a case statement)
`default` is used when `select` does not match any of the indices (e.g.
when the select width is longer than the list) and has a default value of
0.
"""
output = default
for... | b52c8e830999f01f6fe7f3ca43ddd1fabb04897a | 67,077 |
from typing import Optional
def mean_dist_probs(
df: pd.DataFrame,
model: Model,
opening: Optional[str] = "<{>",
closing: Optional[str] = "<}>",
n: Optional[int] = None,
) -> pd.DataFrame:
"""
Get the distance between opening and closing tokens and the mean probability of each closing toke... | 8c6095195fd13776a7af2162f3c32c3915781b5c | 67,078 |
def unquote_unreserved(uri):
"""Un-escape any percent-escape sequences in a URI that are unreserved
characters. This leaves all reserved, illegal and non-ASCII bytes encoded."""
return ''.join(_gen_unquote(uri)) | 04f53539406a7561adf2d6553d7d5e483592c5c0 | 67,079 |
from operator import inv
def GLS(x, A, L):
"""
x: sample matrix, each column is a link flow vector sample; 24 * K
A: path-link incidence matrix
P: logit route choice probability matrix
L: dimension of xi
----------------
return: xi
----------------
"""
K = np.size(x, 1)
S =... | be0918ed4db96c07819f22d246c19df57bca654d | 67,080 |
def SelectDBSeveralFittest(n, db_list):
"""
Function: SelectDBSeveralFittest
=================================
Select n fittest individual
@param n: the number of fittest individuals
@param db_list: the ordered list of fitnesses with associated unique ids obtained from the database
... | b43709032f21e4854dd0cc7b00a1e7cae983d762 | 67,081 |
def get_image_resize_method(resize_method, batch_position=0):
"""Get tensorflow resize method.
If resize_method is 'round_robin', return different methods based on batch
position in a round-robin fashion. NOTE: If the batch size is not a multiple
of the number of methods, then the distribution of methods will ... | f54dd3a340a90f75fa9080fda561d231328a0797 | 67,082 |
import os
import json
def load_index(path, forward_file="forward_index",
inverted_file="inverted_index",
id_file="documents_id"):
"""Load index from files.
If files don't exist, return empty entities.
:return dict forward_index:
:return dict inverted_index:
... | c7ba0e618aa4468537262874f8c34208bc9e1c39 | 67,083 |
import scipy
def abund_log_prob(genotype, abundance, refrabund=None, mean=30.0, sd=8.0,
error=0.001):
"""Calculate probability of k-mer abundance conditioned on genotype.
The `genotype` variable represents the number of assumed allele copies and
is one of {0, 1, 2} (corresponding to ge... | 59b6261cfe0759aaa084a5b6ddd8f56f9c6e38af | 67,084 |
import time
def train_model(model: Model, dataset: Dataset, epochs: int, batch_size: int, use_wandb: bool = False) -> Model:
"""Train model."""
callbacks = []
if EARLY_STOPPING:
early_stopping = EarlyStopping(monitor="val_loss", min_delta=0.01, patience=3, verbose=1, mode="auto")
callback... | 11034fc52a47485eeacdd6a2a1aadc58758eddc1 | 67,085 |
import xml
def ParseSVGFile(filename):
"""Parse an SVG file name and return an Art object for it.
Args:
filename: string - name of file to read and parse
Returns:
geom.Art
"""
dom = xml.dom.minidom.parse(filename)
return _SVGDomToArt(dom) | c657427fd599a1e89393a0b8a43c4810a4f281ee | 67,086 |
def writer_cache():
""" Singleton for WriterDriverCache
"""
# pylint: disable=protected-access
if not hasattr(writer_cache, '_instance'):
writer_cache._instance = WriterDriverCache('datacube.plugins.io.write')
return writer_cache._instance | e2a4f40a6544daa2293cece525ebabf4bef25784 | 67,087 |
def new_fcompiler(plat=None,
compiler=None,
verbose=0,
dry_run=0,
force=0):
""" Generate an instance of some FCompiler subclass for the supplied
platform/compiler combination.
"""
if plat is None:
plat = os.name
try:
... | af269c902382db2573218b980b3a7d0b2b91d903 | 67,088 |
def compute_rbf_encoding(input, rbf_center, rbf_sig=0.15):
"""
Compute the rbf encoding from trained rbf center to new input
m := n_frames * n_test_seq
n := n_neurons * n_train_seq
:param input: (n_feature, m)
:param rbf_center:(n_feature, n)
:param rbf_sig:
:return:
"""
# f_i... | b38865212e37e55e588289f78d3be9664eeacfa2 | 67,089 |
def longest_peak(relative_angles):
"""
Find the longest area < 0
:param relative_angles: list of angles
:return: coordinates of the area
"""
length = relative_angles.shape[0]
longest = (0, 0)
j = 0
for i in range(length):
if relative_angles[i] >= 0:
... | 742359ed60f4b6cebc9da8510cb801a08a40df99 | 67,090 |
def create_mesmer_input(membrane_files, nucleus_file):
"""Create membrane and nuclear images for input to Mesmer.
Parameter:
membrane_files : str list
paths to membrane marker (grayscale) images
nucleus_file : str
path to nuclear marker (grayscale) image
Returns:
... | b4fe0075a4f68a71daba1ce9b4ad6d96b93d5cc7 | 67,091 |
def add_event(event=None):
"""Add a data event.
Report a new data event to be retained in the archives.
:param event: Required inputs for creating a data archive.
:type event: dict | bytes
:rtype: None
"""
if connexion.request.is_json:
event = APIEvent.from_dict(connexion.request.... | 6d6eb77a7587d8ca09f7db3593e1fbc6010e64a5 | 67,092 |
def HtmlColorCode_to_floats(value):
"""
Convert a HTML color code
like '#FFCC00' or 'FFCC00'
to a list of floats [1.0, 0.8, 0.0]
"""
# return (float.fromhex('0x'+x)/255 for x in HtmlColorCode_to_strings(value)) # fromhex is python 2.6!
return [float(int(x, 16))/255 for x in HtmlColorCode_to... | 6ad60b806188524b15854c81482c9681721f931b | 67,093 |
from docker import client
def get_client():
"""Returns the client or initialize it"""
if 'client' not in __st__:
__st__['client'] = client.from_env()
return __st__['client'] | cf12d4e286e2a2813dfaab270da06f9442017e3f | 67,094 |
def uu_query_STK_EXCHANGE_LINK_CALENDAR():
"""
记录沪港通、深港通和港股通每天是否开市
:param :query(finance.STK_EXCHANGE_LINK_CALENDAR):表示从finance.STK_EXCHANGE_LINK_CALENDAR这张表中查询市场沪港通、深港通和港股通交易日历的信息,还可以指定所要查询的字段名,格式如下:query(库名.表名.字段名1,库名.表名.字段名2),多个字段用英文逗号进行分隔;query函数的更多用法详见:sqlalchemy.orm.query.Query对象
finance.S... | 454f6481fde72a1ba9d4449cda0f78d975b4bda2 | 67,095 |
from typing import Callable
from typing import Any
import functools
def agent_must_be_ready(f: Callable[..., Any]) -> Callable[..., Any]:
"""Any Agent method decorated with this will raise if the agent is not ready."""
@functools.wraps(f)
def decorated(self, *args: Any, **kwargs: Any) -> Any:
if ... | bec74702355d6aaa7796527a05d9510048513910 | 67,096 |
def min_sample_size(bcr, mde, power=0.8, sig_level=0.05):
"""Returns the minimum sample size to set up a split test
Arguments:
bcr (float): probability of success for control, sometimes
referred to as baseline conversion rate
mde (float): minimum change in measurement between control
... | a604255f40d8e150b575f346ffd9f826307c258a | 67,097 |
import math
def gcj02_to_bd09(lng, lat):
"""
火星坐标系(GCJ-02)转百度坐标系(BD-09)
谷歌、高德——>百度
:param lng:火星坐标经度
:param lat:火星坐标纬度
:return:
"""
z = math.sqrt(lng * lng + lat * lat) + 0.00002 * math.sin(lat * x_pi)
theta = math.atan2(lat, lng) + 0.000003 * math.cos(lng * x_pi)
bd_lng = z * ... | f2babb243037b2accc6d64d9fe7e06c78ceb785f | 67,098 |
def show_machine(machine_id):
"""Get machine."""
data = _get_request_args()
return utils.make_json_response(
200,
machine_api.get_machine(
machine_id, user=current_user, **data
)
) | ab85b3d6e626b4e349906d81617c575bc9913f88 | 67,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.