content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def compute_iou(box, boxes):
"""Calculates IoU of the given box with the array of the given boxes.
box: a polygon
boxes: a vector of polygons
Note: the areas are passed in rather than calculated here for
efficiency. Calculate once in the caller to avoid duplicate work.
"""
# Calculate inters... | 169cb66f025c7a3f6161a406bd6b0636a35816d3 | 34,200 |
def far(scores, labels, frr_op):
"""
Calculates FAR from FRR operating point.
Parameters
----------
scores: np array
It holds the score information for all samples (genuine and impostor).
It is expected that impostor (negative) scores are, at least by design, greater than genuine (... | 9873f854887982e6aa393eb4fa0b915f31dbd15f | 34,201 |
def iso_to_plotly_time_string(iso_string):
"""Remove timezone info and replace 'T' delimeter with ' ' (ws)."""
# make sure we don't send timezone info to plotly
if (iso_string.split("-")[:3] == "00:00") or (iso_string.split("+")[0] == "00:00"):
raise Exception(
"Plotly won't accept times... | 2a8f8dede7a50d07e283897bf6028fbfdcaa90d6 | 34,202 |
def mk_vis_txt_pair_datalist(anno_path, data_ratio=1.0,
vis_id_key="coco_id", txt_key="caption"):
"""
Args:
anno_path: str, path to .jsonl file, each line is a dict
data_ratio: float, (0, 1], when < 1, use part of the data.
vis_id_key: str, image/video file i... | 3c36ff18f447e0ce5977d39c0bdc14bda94e3a64 | 34,203 |
def index_greater(array, prec=1e-8):
"""
Purpose:
Function for finding first item in an array that has a value greater than the first element in that array
If no element is found, returns None
Precision:
1e-8
Return:
int or None
"""
item=array[0]
for idx, val ... | 43f9401dc37426b1514ff1eb9dda79c39e347a7a | 34,204 |
import torch
def get_ssl_sampler(labels, valid_num_per_class, annotated_num_per_class, num_classes):
"""
:param labels: torch.array(int tensor)
:param valid_num_per_class: the number of validation for each class
:param annotated_num_per_class: the number of annotation we use for each classes
:para... | 05d7aa1700c096bc7a8250251cc73969c46ddabf | 34,205 |
import copy
def load_parse_dict():
"""Dicts for parsing Arc line lists from NIST
Rejected lines are in the rejected_lines.yaml file
"""
dict_parse = dict(min_intensity=0., min_Aki=0., min_wave=0.)
arcline_parse = {}
# ArI
arcline_parse['ArI'] = copy.deepcopy(dict_parse)
arcline_parse[... | b02ae8446b9cc198ac1908dbbbe2bec78088178b | 34,206 |
def is_test(method) -> bool:
"""
Checks if the given method is a test method.
:param method: The method to check.
:return: True if the method is a test method,
False if not.
"""
return getattr(method, _constants.IS_TEST_ATTRIBUTE, False) | 23b5dc04b29b029ca5c44dc57df59f63087d61a6 | 34,207 |
def data_transform(array, array2=np.asarray((None)),type='z_score_norm', means=None, stds=None):
"""
Transforms data in the given array according to the type
array :an nd numpy array.
array2 :an nd numpy array(optional-for multidimensional datasets)
type :'z_score_norm' = implements z score n... | f851bce2f0a88717873544506361bd6ef7c73813 | 34,208 |
import re
def load_items(reader):
"""Load items from HDF5 file:
* reader: :py:class:`guidata.hdf5io.HDF5Reader` object"""
with reader.group("plot_items"):
names = reader.read_sequence()
items = []
for name in names:
klass_name = re.match(
r"([A-Z]+[A-Za-z0-9\_]*)\_(... | ba473b9aa8c5af2beba8e22c68646a3204179c3d | 34,209 |
def zmatrix(file_prefix):
""" generate zmatrix JSONObject
:param file_prefix: path to file
:type file_prefix: str
:param json_prefix: top level keys
ex: ('energy', ['gaussian', 'b3lyp', 'cc-pvdz', 'RR'])
:type json_prefix: tuple
:return: instance of JSONObject class
:rtype: JSONObje... | 9f22e8f4480fe21b853101a4cfb58c641207a0c1 | 34,210 |
def sequence_nd(
seq,
maxlen=None,
padding: str = 'post',
pad_val=0.0,
dim: int = 1,
return_len=False,
):
"""
padding sequence of nd to become (n+1)d array.
Parameters
----------
seq: list of nd array
maxlen: int, optional (default=None)
If None, will calculate m... | 83ec761d679b2c91592e000e1ee832341645a8e9 | 34,211 |
def random_dists(filename):
"""
Given a Excel filename with a row for each variable and columns for the
minimum and maximum, create a dictionary of Uniform distributions for
each variable.
Parameters
----------
filename : string
Number of parameter settings to generate
... | d49229064979deb671fcade3518d260450718130 | 34,212 |
import re
def is_changed(event, old_event):
"""
Compares two events and discerns if it has changes that should trigger a push
:param event:
:param old_event:
:return: bool
"""
# Simple changes
if any(
event.get(field) != old_event.get(field) for field in ["severity", "certaint... | a0c403caf71fb5547a4b4c7a52d3fcdcef4c4b34 | 34,213 |
def view(self, view_id):
"""Get a particular view belonging to a case group by providing view id
Arguments:
id(int): view id
Returns:
List of :class:`rips.generated.generated_classes.EclipseView`
"""
views = self.views()
for view_object in views:
if view_object.id == v... | 0dadbe53c326d2d324e11222b2a751a09750bc82 | 34,214 |
from typing import Tuple
def enu2geodetic(
e: ndarray,
n: ndarray,
u: ndarray,
lat0: ndarray,
lon0: ndarray,
h0: ndarray,
ell: Ellipsoid = None,
deg: bool = True,
) -> Tuple[ndarray, ndarray, ndarray]:
"""
East, North, Up to target to geodetic coordinates
Parameters
---... | d552b072a428042435703f453a0f90bb9a1fded5 | 34,215 |
def Standard_GUID_HashCode(*args):
"""
* H method used by collections.
:param aguid:
:type aguid: Standard_GUID &
:param Upper:
:type Upper: int
:rtype: int
"""
return _Standard.Standard_GUID_HashCode(*args) | 951ed1db9f0bc7c33345969e0b234bf31aaf463b | 34,216 |
import ast
def get_import_stmt_str(alias_list, import_src=None, max_linechars=88):
"""
Construct an import statement by building an AST, convert it to source using
astor.to_source, and then return the string.
alias_list: List of strings to use as ast.alias `name`, and optionally also
... | f4c7dad79b7c949bd7e9045b9c9ae474a09303d2 | 34,217 |
def convert_into_decimal(non_binary_number: str, base: int) -> int:
"""
Converts a non binary string number into a decimal number
:param non_binary_number:
:param base:
:return: a decimal number
"""
decimal_number = 0
for digit in range(len(non_binary_number)):
decimal_number += int(n... | fecdd152000399fbc33a259a647118b0607daac9 | 34,218 |
from typing import Sequence
def sgld_sweep() -> Sequence[SGMCMCConfig]:
"""sweep for vanilla sgld."""
sweep = []
for learning_rate in [
1e-5, 5e-5, 1e-4, 5e-4, 1e-3, 5e-3, 1e-2
]:
for prior_variance in [0.01, 0.1, 0.5]:
sweep.append(SGMCMCConfig(learning_rate, prior_variance))
return tuple(s... | 9f64505c8aa7efb33f2fbc4a7e0756ef896ee9c3 | 34,219 |
def stringify(num):
"""
Takes a number and returns a string putting a zero in front if it's
single digit.
"""
num_string = str(num)
if len(num_string) == 1:
num_string = '0' + num_string
return num_string | 7cf37776bc774d02bce0b2016d41b26b8ab94cf7 | 34,220 |
import json
from datetime import datetime
def get_symbols(market):
"""
Gets top 100 symbols by market cap for which
historical and incremental data refresh dags will be run.
"""
@task()
def find_symbols(market):
"""
Gets the most popular X number of symbols and stores them
... | 9e8c42a4605b0a49e17474fed0734969c9b35280 | 34,221 |
def euc_distance(vertex, circle_obstacle):
"""
Finds the distance between the point and center of the circle.
vertex: Vertex in question.
circle_obstacle: Circle obstacle in question.
return: Distance between the vertex and the center of the circle.
"""
x = vertex[0] - circle_obstacle.posi... | 60ed338eb7a81fc282196c38d41cecda8f28efb7 | 34,222 |
def less(x, y):
"""
Returns the truth value of (x < y) element-wise.
Parameters
----------
x : tensor
Must be one of the following types: float32, float64, int32, uint8,
int16, int8, int64, bfloat16, uint16, half, uint32, uint64.
y : tensor
A Tensor. Must have the same t... | 6db5cf54e7f23e174050676f7f1e319e8dd6982d | 34,223 |
import typing
import subprocess
def get_commit_shas_since(sha: str, dir: str) -> typing.List[str]:
"""Gets the list of shas for commits committed after the given sha.
Arguments:
sha {str} -- The sha in the git history.
dir {str} -- An absolute path to a directory in the git repository.
R... | 356cd92667f82f98a46f64be3ebbdf5de1957093 | 34,224 |
def decision_tree_learning(examples: list, attributes: list, parent_examples,
importance_function: callable):
"""
Decision tree learning algorithm as given in figure 18.5 in Artificial
Intelligence A Modern Approach.
:param examples: list of dictionaries containing examples t... | df9dd631b5df38451e03cfab65d8a8c0f6a218eb | 34,225 |
def modified_bessel(times, bes_A, bes_Omega, bes_s, res_begin, bes_Delta):
""" Not Tested. """
b = np.where(times > res_begin + bes_Delta / 2.,
special.j0(bes_s * bes_Omega *
(- res_begin + times - bes_Delta / 2.) ),
(np.where(times < res_begin - bes_Delta / 2.,
spe... | 1afcb27b53b364199289dff2bd7850fe6e5027fa | 34,226 |
def predict_csr_val(csr_op, rs1_val, csr_val, csr_mask):
"""
Predicts the CSR reference value, based on the current CSR operation.
Args:
csr_op: A string of the CSR operation being performed.
rs1_val: A bitarray containing the value to be written to the CSR.
csr_val: A bitarray containing the current... | 1e8be22540b89db9719ea078dbb4e1d11e53bdcc | 34,227 |
def request(url: str, args: dict = None, method: str = 'GET'):
"""
Custom Method that requests data from requests_session
and confirms it has a valid JSON return
"""
response = request_session(url, method, args)
try:
# you only come here if we can understand the API response
retu... | 603712a7aa2978fc00e664eaebf18929108064e3 | 34,228 |
def link():
"""Link the user's account with ORCID (i.e. affiliates user with their org on ORCID)."""
# TODO: handle organisation that are not on-boarded
redirect_uri = url_for("orcid_callback", _external=True)
external_sp = app.config.get("EXTERNAL_SP")
if external_sp:
sp_url = urlparse(exte... | ea1be1a81b6b1f24833c83171b07f258f5eda430 | 34,229 |
def create_se3(ori, trans=None):
"""
Args:
ori (np.ndarray): orientation in any following form:
rotation matrix (shape: :math:`[3, 3]`)
quaternion (shape: :math:`[4]`)
euler angles (shape: :math:`[3]`).
trans (np.ndarray): translational vector (shape: :math:`[... | c564b8e3761b737bfc95c94e5134c57cec05805e | 34,230 |
def build_negative_log_likelihood(
image,
telescope_description,
oversampling,
min_lambda,
max_lambda,
spe_width,
pedestal,
hole_radius=0 * u.m,
):
"""Create an efficient negative log_likelihood function that does
not rely on astropy units internally by defining needed values as ... | 10c481448b1b2eb2e09eb4d76dda228bc6ed894d | 34,231 |
import cmd
def kube_deploy_reloadbalance(name, namespace, d_app):
"""Re-loadbalance deployment resource."""
if not name:
s_msg = 'name is not defined.'
return (False, s_msg)
if not namespace:
s_msg = 'namespace is not defined.'
return (False, s_msg)
if not d_app:
... | 63369972d93661cace0eb9eedd3c24912c6e7cd0 | 34,232 |
import collections
def _ParseParameterType(type_string):
"""Parse a parameter type string into a JSON dict for the DF SQL launcher."""
type_dict = {'type': type_string.upper()}
if type_string.upper().startswith('ARRAY<') and type_string.endswith('>'):
type_dict = collections.OrderedDict([
('arrayTyp... | 213a6d6e119c76da7fc6193493e11b57e260f200 | 34,233 |
import time
def get_now_utc_epoch():
"""
Returns the epoch
:return:
"""
return int(time.time()) | 7e9836908aed9598bab1f01365fe255aa43a94e0 | 34,234 |
from typing import List
def get_top_words(text: str, blacktrie: dict, top_n: int) -> List[str]:
"""Get top words in a string, excluding a predefined list of words.
Args:
text (str): Text to parse
blacktrie (dict): Trie built from a blacklist of words to ignore
top_n (int): Number of top words to return
Ret... | 20839162d06447f7651c1051ed88feef9d62db72 | 34,235 |
def get_fluid_colors(fXs, fVs, normalize=False):
## I realized that with limited data, this coloring does not make much sense
"""
Given the velocity field (Ux, Uy) at positions (X,Y), compute for every x in (X,Y) if the position is contributing to the inflow or the outflow. This can be obtained by u*x (scal... | cda836658f30c7f8cfd96d774f2654e2a056de51 | 34,236 |
def getitem(x, item):
"""returns specific item of a tensor (Functional).
# Arguments
item: Item list.
# Returns
A new functional object.
"""
validate_functional(x)
res = x.copy()
ys = []
lmbd = [Lambda(lambda xx: xx.__getitem__(item)) for xx in x.outputs]
for l, y ... | 7854bad7ff67aa3d04be7e26b25785832ce04522 | 34,237 |
import torch
from typing import Optional
def norm_range(
data: torch.Tensor, min: float, max: float, per_channel: bool = True, out: Optional[torch.Tensor] = None
) -> torch.Tensor:
"""
Scale range of tensor
Args:
data: input data. Per channel option supports [C,H,W] and [C,H,W,D].
min... | 52f36f0b9a74d8813ee72bc7a773620e92c4923b | 34,238 |
def get_mvarg(size_pos, position="full"):
"""Take xrandrs size&pos and prepare it for wmctrl (MVARG) format
MVARG: <G>,<X>,<Y>,<W>,<H>
* <G> - gravity, 0 is default
"""
allowed = ["left", "right", "top", "bottom", "full"]
if position not in allowed:
raise ValueError(f"Position has... | 0b8a9c3f5ca7e24212502a3f2c76b18167deef6e | 34,239 |
def fr2date(edate, **kwargs):
"""
Wrapper function for :func:`date2date` with French input and
standard output date formats
That means `date2date(edate, fr=True, **kwargs)`;
but *fr* given in call will overwrite *fr=True*.
Examples
--------
>>> edate = ['12/11/2014 12:00', '01/03/2015 ... | 4bdf32e344585caa159d64bcdaa3e870b41f8633 | 34,240 |
def convert_species_tuple2chianti_str(species):
"""
Convert a species tuple to the ion name format used in `chiantipy`.
Parameters
-----------
species: tuple (atomic_number, ion_number)
Returns
--------
str
ion name in the chiantipy format
Examples
---------
>>> co... | d37aa9c9a9e186febc4ef6df2f3b53f9110ace7a | 34,241 |
from sys import platform
from packaging.version import LegacyVersion, parse
from os import getenv
from datetime import datetime
import subprocess
def calculate_version(validate=False, error_on_invalid=False):
"""Construct a version string from date, time, and short git hash
If input argument `validate` is se... | 51e3f6e83701c587d59fc46fc3f9b55b5df322e9 | 34,242 |
import hashlib
def vote(request, village_no, day_no):
"""投票処理"""
vote_id = request.POST['vote']
login_id = request.session.get('login_id', False)
participant = VillageParticipant.objects.get(village_no=village_no, pl=login_id, cancel_flg=False)
ability = VillageParticipantExeAbility.objects.get(vi... | 4935ee87645d037e9455e61c588168f3f276f8ce | 34,243 |
def read_header_offsets(file, block_size):
"""Reads the PBDF header (not checking the included file size) and returns the list of offsets adjusted to match
decrypted data positions.
Args:
file: The decrypted input file.
block_size (int): The block size in bytes at which end a checksum is pla... | cf2d5c89083bebf3dff1b92bd2365e1a62b2f97e | 34,244 |
def level_2_win_play(x):
"""
Probability that a deck with x SSGs will win on the play using level two reasoning
:param int x: SSGs in deck
:return float:
"""
return sum([
level_2_hand_odds_play(i, x) * mull_to_play(i, x) for i in range(0, 8)
]) | 94834ad0cc603b2923c0f5c441def95196197c25 | 34,245 |
def getfullargspec(func):
"""Get the names and default values of a function's arguments.
A tuple of seven things is returned:
(args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults annotations).
'args' is a list of the argument names.
'varargs' and 'varkw' are the names of the * and ** argumen... | d239d6d9b7399689157d6a5f025148e287f06b68 | 34,246 |
import json
def get_json(file_path):
"""
Faz a leitura de um arquivo Json com codificacao utf-8,
apenas para arquivos dentro do diretorio folhacerta_settings
:param file_path: (string) nome do arquivo json com extensao
:return: Dicionario com os dados do json
"""
with open... | bd475d7427705026ad17d32d25a1a016d6c6f93d | 34,247 |
def color_array(arr, alpha=1):
""" take an array of colors and convert to
an RGBA image that can be displayed
with imshow
"""
img = np.zeros(arr.shape + (4,))
for row in range(arr.shape[0]):
for col in range(arr.shape[1]):
c = mpl.colors.to_rgb(arr[row, col])
img[... | dbfdf7e78788365f6bc0bb61b7c7607aec79e250 | 34,248 |
def showturtle():
"""Makes the turtle visible.
Aliases: showturtle | st
No argument.
Example (for a Turtle instance named turtle):
>>> turtle.hideturtle()
>>> turtle.showturtle()
"""
return __SingletonTurtle().showturtle() | 011edcca34c25d42831826c73f8a823d992448b7 | 34,249 |
def get_setting(db, name):
"""
Get a specific setting
@param db The database connection
@param name The setting's name
@return The setting's value
"""
result = _query(db, "SELECT value FROM settings WHERE name=%(name)s;", { "name" : name })
if len(result) > 0:
return getattr(res... | 1a82faf9e2f222328d9deb9c0beb19a8a7b22862 | 34,250 |
import os
def set_up_directory_simple(rootdir, classname):
"""rootdir is the root directory,
classname is the wnid or human-readable name,
directory will be rootdir/classname
Creates directories if they don't exist;
throws an error if classname directories exist and aren't empty."""
dir_path ... | bc9db796ec9799bba8f6d1bd55c0aab36cc0c0cc | 34,251 |
def check_table_exists(client: AitoClient, table_name: str) -> bool:
"""check if a table exists in the instance
:param client: the AitoClient instance
:type client: AitoClient
:param table_name: the name of the table
:type table_name: str
:return: True if the table exists
:rtype: bool
"... | b45a7cbe8a896040903af6f5ece177d53773d098 | 34,252 |
def bytes_to_str(s, encoding='latin-1'):
"""Extract null-terminated string from bytes."""
if b'\0' in s:
s, _ = s.split(b'\0', 1)
return s.decode(encoding, errors='replace') | 7d98d91443ab16478f1b8ecba39311110e92009c | 34,253 |
from typing import Pattern
import re
from typing import Optional
from typing import Match
from typing import AnyStr
from typing import Dict
def get_time_delta(time_string: str) -> timedelta:
"""
Takes a time string (1 hours, 10 days, etc.) and returns
a python timedelta object
:param time_string: the... | 8a1df45286f0994e1f9aab4f4209ea14f639e8b9 | 34,254 |
def lens_of(data):
"""Apply len(x) to elemnts in data."""
return len(data) | e10cba2bd801afd8f41dd0b15bfc23b7849c06ba | 34,255 |
from typing import Any
def _format_phone(
phone: Any, output_format: str, fix_missing: str, split: bool, errors: str
) -> Any:
"""
Function to transform a phone number instance into the desired format.
The last component of the returned tuple contains a code indicating how the
input value was cha... | 97341088f03f5d276339c83d0061bbfec28933b9 | 34,256 |
def mvg_all_joints(jLs, face_keypoints=True, upper_sternum=True, upper_body=True, lower_body=True, wsize=6):
"""
:param jLs: list of lists with length 54 derived from text file
including x,y,z coordinates for each joint as separately list.
:type jLs: list
:param face_keypoints... | cf6b2d5092cbbf902fe33902efbb4ca9dbe32d74 | 34,257 |
def check_in_all_models(models_per_expt):
"""
Check intersection of which models are in all experiments
:param models_per_expt: an ordered dictionary of expts as keys with a list of valid models
:return: list of models that appear in all experiments
"""
in_all = None
for key, items in mod... | 75e17b8558a592471dda8a855959f60c40b06759 | 34,258 |
import torch
def _translate_x(video: torch.Tensor, factor: float, **kwargs):
"""
Translate the video along the vertical axis.
Args:
video (torch.Tensor): Video tensor with shape (T, C, H, W).
factor (float): How much (relative to the image size) to translate along the
vertical... | 925a9dc0b67b70330937b38cc1694c8cebd93e1c | 34,259 |
import numpy
def get_volume_pixeldata(sorted_slices):
"""
the slice and intercept calculation can cause the slices to have different dtypes
we should get the correct dtype that can cover all of them
:type sorted_slices: list of slices
:param sorted_slices: sliced sored in the correct order to cre... | f935a3b820211fe1535a95d24f021cc2e8d48fbe | 34,260 |
import logging
def read_val_dataframe_from_hdf5(input_pattern, val_fold=0):
"""Reads the hdf5 tables for the validation fold only.
Args:
input_pattern: String with the path for the hdf5 with a '%d' for the fold.
val_fold: Integer. The zero-based validation fold num.
Returns:
A pandas dataframe cont... | 894e59c893b6e2eb7beaa7bd2dd67ac2eeca7a99 | 34,261 |
from pathlib import Path
def hash_file(hash_obj, fout: Path):
"""Create a hash of the file.
Parameters
hash_obj () The hash object
fout (Path) : Path to file to be written.
Return
str : If fout was found.
None : If fout was not found.
"""
try:
with fout.open('r... | b57b87b192dbd63a3cd3136ffd7a6b98fd8ed7dd | 34,262 |
import scipy
def Get_Wav_EMA_PerFile(EMA_file, Wav_file, F, EmaDir, MFCCpath, BeginEnd, XvectorPath, cfg):
"""Return mean and variance normalised ema, mfcc, and x-vectors if required (of the cross-corpus).
Parameters
----------
EMA_file: str
path to ema file
Wav_file: str
path ... | 91d77fb4dd2a3202f7c94db2fa7a029c9562b63a | 34,263 |
def is_class_name(class_name):
"""
Check if the given string is a python class.
The criteria to use is the convention that Python classes start with uppercase
:param class_name: The name of class candidate
:type class_name: str
:return: True whether the class_name is a python class otherwise Fa... | 2b4b6a09f2a112f7e8163f3caf97fdfca0c93e12 | 34,264 |
def is_pesummary_json_file_deprecated(path):
"""Determine if the results file is a deprecated pesummary json file
Parameters
----------
path: str
path to results file
"""
return _is_pesummary_json_file(path, _check_pesummary_file_deprecated) | 49ddd8f84e259cf26955220013bcfe7003bcca5d | 34,265 |
def popart(image_array):
"""
Applique la fonction popart 4 fois avec des paramètres un peu différents
:return: une image avec moins de couleurs.
"""
h = get_image_height(image_array)
w = get_image_width(image_array)
small_height = h // 2
small_width = w // 2
small_image = image_array... | 77b8af2bc5db976289a94118d8e01789c535b2b0 | 34,266 |
from AugSeg.get_instance_group import extract
from AugSeg.affine_transform import transform_image, transform_annotation
from datasetsAug.roidb import combined_roidb_for_training
def _get_image_blob(roidb, coco):
"""Builds an input blob from the images in the roidb at the specified
scales.
"""
num_imag... | 637983405303c304bdf480feca7ea29f1a06d6a6 | 34,267 |
def solve_lu(A, P, B, options=MATPROP.NONE):
"""
Solve a system of linear equations, using LU decomposition.
Parameters
----------
A: af.Array
- A 2 dimensional arrayfire array representing the coefficients of the system.
- This matrix should be decomposed previously using `lu_inplac... | 96eb1f222618c5b17db48a69535204b6246b873f | 34,268 |
import mimetypes
def guess_type(filename, strict=False, default="application/octet-stream"):
""" Wrap std mimetypes.guess_type to assign a default type """
content_type, encoding = mimetypes.guess_type(filename, strict=strict)
if content_type is None:
content_type = default
return content_type, encoding | ae3dae1d005797b2dc96cd893f4a79d20922e6a2 | 34,269 |
def _lookup_alias(aliases, value):
"""
Translate to a common name if our value is an alias.
:type aliases: dict of (str, [str])
:type value: str
:rtype: str
>>> _lookup_alias({'name1': ['alias1']}, 'name1')
'name1'
>>> _lookup_alias({'name1': ['alias1', 'alias2']}, 'alias1')
'name1... | df0641b1f8aca964f76afd2a83fb91a587d52e1d | 34,270 |
def triplet_loss(anchor, positive, negative, alpha):
"""Calculate the triplet loss according to the FaceNet paper
Args:
anchor: the embeddings for the anchor images.
positive: the embeddings for the positive images.
negative: the embeddings for the negative images.
Returns:
t... | 7c3d218833e86f62a0de493ff8dc1045fd3a7788 | 34,271 |
import json
def loadConfig() -> list:
"""Loads configuration from CONFIG_PATH
Returns:
[list] -- the CONFIG_VARS as loaded from CONFIG_PATH
"""
configData = json.load(open(CONFIG_PATH, 'r', encoding='utf-8'))
returnValue = []
# make sure we're not missing anything
for configItem i... | f115cd8896ca5d52086f4054cc7fb5a05c230d0e | 34,272 |
import httpx
async def get_corrected_name_api(keyphrase: str) -> str:
"""
Get corrected artist name via Last.fm API method
artist.getCorrection. See: https://last.fm/api/show/artist.getCorrection
:param keyphrase: Name of an artist or a band.
:return: Corrected artist name.
"""
async with ... | befe2f89b233bf0453873d710531483e61832786 | 34,273 |
def missing_columns(df, missing_threshold=0.6):
"""Find missing features
Parameters
----------
df : pd.DataFrame, shape (n_samples, n_features)
Training data, where n_samples is the number of samples and n_features is the number of features.
missing_threshold : float, default=0.6... | 4d31673670d894556b6571a0233ec36c8452570a | 34,274 |
from typing import Tuple
from typing import List
import re
from pathlib import Path
import sys
def extract() -> Tuple[int, int, int, int, int, int]:
""" """
global args
global data_to_stdout
data: InfoData = read_info_file(args.extract)
# Need perlreg expressions instead of shell pattern
pat... | 8b45f1b76223dee1a17f7b270592c75c87963ae5 | 34,275 |
import re
import yaml
def read_message(raw_data: bytes):
"""Reads a UDP raw message, split the metadata, and decode data.
:param raw_data: Raw UDP packet
:type raw_data: bytes
:return: Metadata and decoded data required for packet reassembly.
:rtype: tuple
"""
header, data = read_raw_mess... | bd039b55f579971be6750519bcc79f5ac6670ea4 | 34,276 |
import os
def _get_nagios_macros():
"""Read all ENV vars then save and rename the Nagios Macros in a dictionary."""
MACROS=dict()
for k, v in sorted(os.environ.items()):
if k.startswith('NAGIOS_'):
k = k.replace('NAGIOS_', '')
MACROS[k] = v
# Inject Nagios location for ... | 32db96b6cf5af324aedc4deac563e88520faa5bd | 34,277 |
def is_ordered(treap):
""" Utility to check that every node in the given Treap satisfies the following:
Rules:
- if v is a child of u, then v.priority <= u.priority
- if v is a left child of u, then v.key < u.key
- if v is a right child of u, then v.key > u.key
"""
# iterate through all n... | 38b7fd7690931e017e9ece52b6cba09dbb708400 | 34,278 |
def log_prob(x, df, loc, scale):
"""Compute log probability of Student T distribution.
Note that scale can be negative.
Args:
x: Floating-point `Tensor`. Where to compute the log probabilities.
df: Floating-point `Tensor`. The degrees of freedom of the
distribution(s). `df` must contain only posit... | 6714c53e1be59aaa8c9194ea30b6e51d665caba9 | 34,279 |
import os
def find_files(t):
"""
Find the files to move, return a list of tuples - location & name
"""
walked_path = quick_join(os.environ['HOME'], t.source)
files = []
for dirpath, _, filenames in os.walk(walked_path):
location = dirpath.replace(walked_path, '').strip('/')
for... | 47171479255fcaed792d5b5a94771b06367055ba | 34,280 |
def get_cleaned_query_data_http_error(handler, *args):
"""
同上
:param handler:
:param args:
:return:
"""
data = {}
for k in args:
try:
data[k] = clean_data(handler.get_query_argument(k))
except MissingArgumentError:
raise HTTPError(400)
return d... | f5513034be8cd9082a3ad632c77ed4d364644819 | 34,281 |
import http
from datetime import datetime
def CreateOrUpdateActivity(request, program, activity=None):
"""Creates or updates an activity.
Caller must provide the program. Activity is optional when creating a new one.
Args:
request: A request.
program: A models.Program under which we are either creatin... | 15ddb2a423a82f4a3ebfda43b20a697be54d0d1d | 34,282 |
import json
def dowork(lon, lat):
""" Actually do stuff"""
pgconn = get_dbconn('postgis')
cursor = pgconn.cursor()
res = dict(mcds=[])
cursor.execute("""
SELECT issue at time zone 'UTC' as i,
expire at time zone 'UTC' as e,
product_num,
product_id
from text_products WHERE pil... | 4acc671cd3701562866c237b06267f7b5038413b | 34,283 |
from scdali.models.gp import SparseGP
def run_interpolation(
A, D,
cell_state,
kernel='Linear',
num_inducing=800,
maxiter=2000,
return_prior_mean=False,
n_cores=1):
"""Run scDALI interpolation of allelic rates for each region.
A, D are assumed to be n-b... | ccc07014ebae18a37e878f34c968b84b23995a5f | 34,284 |
def extended_knapsack_dp(value_set, weight_set, total_allowed_weight, max_number_of_elements):
"""Knapsack with limited number of elements allowed.
Notes
-----
The rows are the number of elements in value_set
Columns are the number of weights, ranging from 0 to weight_set.
The third dimension ... | 85527b28706a92eeb822594a0a98e90e4e6f6257 | 34,285 |
from typing import Tuple
import argparse
import shutil
import os
def parse_arguments(version: str = "?") -> Tuple[argparse.ArgumentParser, argparse.Namespace]:
"""Build the argument parser and parse the command line arguments."""
# Ensure that the help info is printed using all columns available
os.enviro... | 8f121b1795bd50a16932d5611d04c6615dd2f826 | 34,286 |
def get_matrix_rbf(X, var, have_var=True):
"""e^-||(x_i - x_j)||/ 2*var^2 RBF"""
(rows, _) = X.shape
K = np.empty((rows, rows))
for i in range(rows):
c = np.sum(np.abs(X - X[i]) ** 2, axis=-1) ** (1. / 2) # norm
if (have_var):
c = c / (2 * (var ** 2))
K[i] = c
w ... | b5260a44a1abca1ddbf9703a68e9a562feb22dc6 | 34,287 |
import clr
from ..csnative.dotnet_helper import get_clr_path
def AddReference(name, use_clr, verbose=True):
"""
Imports a :epkg:`C#` dll.
@param name assembly name
@param use_clr use :epkg:`pythonnet` or not
(native bridge)
@param verbose ... | 7c877356f80e08ee060137b1c6c251f4bdd7c9fb | 34,288 |
import time
import logging
def buildDict(filterKeys=None, mapColumns=False, targetDatasets=None):
""" Maps the dataset names, contained tables, and contained
columns in the projects BigQuery.
Args:
filterKeys (LIST of STRING): A list of substrings,
one of which must be included in
the table n... | 882ab375eacd946f8d3751055076566d30a1af46 | 34,289 |
from functools import reduce
def build_gaussian_pyramid(im, max_levels, filter_size):
"""
Construct a Gaussian pyramid for a given image
:param im: a grayscale image with double values in [0,1]
:param max_levels: the maximal number of levels in the resulting pyramid.
:param filter_size: the size o... | 9e7975695a3ba435644595ea6c2ce1e876d022b1 | 34,290 |
import sys
from pathlib import Path
import itertools
def main():
"""Runs bigqueries and writes results."""
sql, stublib, tables = sys.argv[1], sys.argv[2], sys.argv[3:]
sqlpath = Path(sql)
sqltext = sqlpath.read_text(encoding='utf8')
def make_fields(dbc, petopia):
trie = pygtrie.StringTr... | f61561817b9163c36a601fdecb2b4beb02eab5e9 | 34,291 |
def broadcast_weeks(start, end):
"""return broadcast weeks with start, end for date range"""
starts = broadcast_week_starts(start, end)
return [(start, start+timedelta(days=6)) for start in starts] | 1a19fb8128104c480d2c2bd2ccd2b3c4e7a2d428 | 34,292 |
def _aix_iqn():
"""
Return iSCSI IQN from an AIX host.
"""
ret = []
aix_cmd = "lsattr -E -l iscsi0 | grep initiator_name"
aix_ret = salt.modules.cmdmod.run(aix_cmd)
if aix_ret[0].isalpha():
try:
ret.append(aix_ret.split()[1].rstrip())
except IndexError:
... | f51a1f95bb42db9f8bc42ae26f8409074d3c81f7 | 34,293 |
def generate_token(user):
""" Currently this is workaround
since the latest version that already has this function
is not published on PyPI yet and we don't want
to install the package directly from GitHub.
See: https://github.com/mattupstate/flask-jwt/blob/9f4f3bc8dce9da5dd8a567dfada0854e0cf656ae/f... | e357d33f0ba8ee5a80f1d45d3576e0676ca6660d | 34,294 |
def _make_replica_groups(parameters):
"""Construct local nearest-neighbor rings given the JAX device assignment."""
if 'bn_group_size' not in parameters or parameters['bn_group_size'] <= 1:
return None
inner_group_size = parameters['bn_group_size']
world_size = parameters['num_replicas']
if parameters['n... | 7909727f1fe4ef768fdff1dbee4d4c9376cfaabb | 34,295 |
from typing import Counter
def calculate_lines_per_gloss(lines):
"""
Calculates lines per gloss of lines
Parameters
----------
lines : list
lines in the corpus
Returns
-------
number : int
the count of lines per gloss
"""
line_counts = [len(x[1]) for x in lin... | 5e7a3ab4b819f4a7dd0cc7053eb09a5572e5f448 | 34,296 |
def random_selection(population: np.ndarray, mut_p: float) -> np.ndarray:
"""Randomly select genes to mutate
Args:
population (np.ndarray): Population of chromosomes
chromosome_size (int): Number of genes per chromosome
mut_p (float): Mutation probability
Returns:
np.ndarra... | b498bf816d085aa1cd4a2f68d144e4b4df051d77 | 34,297 |
def _combo_runner(fn, combos, constants, split=False, parallel=False,
num_workers=None, executor=None, verbosity=1, pool=None):
"""Core combo runner, i.e. no parsing of arguments.
"""
executor = _choose_executor_depr_pool(executor, pool)
n = prod(len(x) for _, x in combos)
ndim = ... | 86a57d1800457166395ae2baa4e04ca8ea4c0cdf | 34,298 |
from typing import Optional
from typing import Union
import os
from pathlib import Path
def push_to_hub_keras(
model,
repo_path_or_name: Optional[str] = None,
repo_url: Optional[str] = None,
log_dir: Optional[str] = None,
commit_message: Optional[str] = "Add model",
organization: Optional[str]... | 51c1551728a37692aa84ee54a96b0e7e62c0415f | 34,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.