content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
from pathlib import Path
def csv_path(csv_dir: str) -> Path:
"""Build csv Path object & mkdir"""
pwd = Path.cwd()
base = pwd.joinpath(csv_dir)
base.mkdir(exist_ok=True)
return base | 52d894ca30b3dc9f81c65b09d3739d18eafee7ba | 3,596,977 |
from typing import Dict
def make_grid(content: Dict) -> Table:
""" """
grid = Table.grid(expand=False)
grid.add_column()
grid.add_column(justify="right")
for key, val in content.items():
left_col = f"[bold]{key}"
for (
val_type,
val_highlighter,
... | 6c86a121c828fac996006fae4094497f3ac0d58a | 3,596,978 |
def cal_to_j(energy_cal):
"""
simple conversion
:param energy_cal: energy in calories
:return: energy in Joules
"""
return energy_cal * J_IN_CAL | 9265a985bc481b4d878dc1b6a0c93ede417fc0f8 | 3,596,979 |
def proximal(path1, path2, window_min, window_max, upstream=False, downstream=False, bins=None):
"""
This is the main function of pairwise_asymmetries.py
Uses pybedtools closest function to find proximal coordinates
Then calculates asymmetry through orientation function for proximal pairs
... | 9661208c1b14a31e5da50070d7773b8bcc880f2a | 3,596,980 |
def generate_test_list(country_code: str, category_codes: tuple, limit: int):
"""Generate test list based on the amount of measurements in the last N days
"""
log = current_app.logger
out = []
li = fetch_reactive_url_list(country_code)
for entry in li:
if category_codes and entry["catego... | 8745b233d56596e08d1404f656c40c0c11a0eb96 | 3,596,981 |
def my_fmin_bfgs(f, x0, fprime=None, args=(), gtol=1e-5, norm=Inf,
epsilon=_epsilon, maxiter=None, full_output=0, disp=1,
retall=0, callback=None):
"""Minimize a function using the BFGS algorithm.
:Parameters:
f : callable f(x,*args)
Objective function to be m... | 73951b35d0800eca6568d48a1cdf301ae3063cdc | 3,596,982 |
def discover_process_tree(log):
"""
Given an event log, the function discovers the process tree using inductive miner algorithm.
Parameters:
log (EventLog): Given event log
Returns:
tree (ProcessTree): The generated Process tree from the log
"""
tree = inductive_mi... | 469031d43adc32cdf3326d269e956afdddf05d52 | 3,596,983 |
import collections
def mutual_information(cond_counts):
"""
Compute the mutual information I(X; Y):
I(x, y) = H(x) - H(x|y)
"""
if isinstance(cond_counts, dict):
cond_counts = list(cond_counts.values())
if isinstance(cond_counts[0], collections.Counter):
counts = collection... | d5d61794cc40688c2c2e0378e9e359965efee725 | 3,596,984 |
def token_predicting(model, tokenizer, text, labels):
""" Token-prediction for tasks like named entity recognition, ... """
text = cleanize(text)
tokens = tokenizer.tokenize(tokenizer.decode(tokenizer.encode(text)))
inputs = tokenizer.encode(text, return_tensors="tf", max_length=128)
outputs = mode... | a9ee59094be01b94127dea01e13d7f2bca80c17b | 3,596,985 |
def for_loop(pos: int, *statements: str) -> str:
"""
繰り返し. 破壊版
>>> for_loop(3, "+")
'>>>[-<<<+>>>]<<<'
"""
return block_of(
exec_pos(pos, "[-"),
block_of(*statements),
exec_pos(pos, "]")
) | 1dc5cd373283631a55bc4164431d31474863b33a | 3,596,986 |
from .sequence import Array
def atom_to_spec_map(rep):
""" Convert an unknown variable atom into a specficiation map suitable
for mappings which comprise a list of pairs. Each pairs is of the form:
(name, spec)
"""
key_map = []
if isinstance(rep, basestring):
rep = tokenize_lines(rep)... | 5e99eddc781cab838e18e10298a3fc167f353c69 | 3,596,987 |
def _sparkline_dataframe(self, col, *args, **kwargs):
"""Generate a basic sparkline graph, consisting of `width` bars, of an
iterable of numeric data. Each bar represents the mean of that fraction of
the data. Allowed `plottype`s are "bar" and "shade". If `hist` is true,
plot a histogram of the data in ... | 911c886d2d748abbd487706aecb2bb2e55778bb3 | 3,596,989 |
def gen_noise(fs,T_obs,psd):
"""
Generates noise from a psd
"""
N = T_obs * fs # the total number of time samples
Nf = N // 2 + 1
dt = 1 / fs # the sampling time (sec)
df = 1 / T_obs
amp = np.sqrt(0.25*T_obs*psd)
idx = np.argwhere(psd==0.0)
amp[idx] = 0.0
... | d1436d6457fa1eabc13ecfbae93c69bf3ea13ee2 | 3,596,990 |
def view(query, use_currency=None):
"""
Main rendering function, entry point for this module.
Returns rendered view for the ``query``.
If currency is specified in ``query``, it overrides ``currency``.
If ``currency`` is not specified, USD is used.
"""
try:
coin, coin2, time_begin, t... | 287e3de83102223107a3bd1f0019f1dd98312bd1 | 3,596,991 |
import re
def get_validated_seqids(sequences_list):
"""
A inputted list is checked for Seq-ID format, each of the Elements that are validated are returned to the user
sequences_list: list of Seq-IDs to be validated
"""
validated_sequence_list = list()
regex = r'^(2\d{3}-\w{2,10}-\d{3,4})$'
... | 9f1e2d145245d0bc40639999cda176a0e65b42ac | 3,596,992 |
import itertools
def LigandDetails(request, ligand_id):
"""
The details of a ligand record. Lists all the assay experiments for a given ligand.
"""
ligand_records = AssayExperiment.objects.filter(
ligand__properities__web_links__index=ligand_id
).order_by('protein__entry_name')
record... | 01bc621c2372d7a69c89bb07f72157d2abc54d94 | 3,596,993 |
from re import T
def all_leaves(iterable: T.Iterable) -> py.bool:
"""Tests whether all elements in the given iterable are all leaves.
>>> tree = {"a": [1, 2, 3]}
>>> assert all_leaves(jax.tree_leaves(tree))
>>> assert not all_leaves([tree])
This function is useful in advanced cases, for example ... | ab5e1ab0958329a766c186954076815cd7396aa9 | 3,596,994 |
def toHex(mobj):
"""Cache the given `mobj` and return its hex value
See :func:`toHash` for docstring.
"""
node = Node(mobj)
return node.hex | f108c6acccbde0fe1e6d0362571a34c521cc6e90 | 3,596,995 |
from typing import List
from typing import Tuple
def _split_signature(signature: str) -> List[Tuple[str, ...]]:
"""Convert text signature into tuples of axes size names
Parameters
----------
signature : str
Text signature of matrix operation, without optional axes or spaces,
Returns
... | f724b9251b781484f9ae6790283639c564ba61a5 | 3,596,996 |
from datetime import datetime
def _expiration(duration):
"""
Generate a datetime now + duration seconds
"""
return datetime.utcnow() + timedelta(seconds=duration) | be45ae5feecdf9ab36bb003bfe8ed0af8072703b | 3,596,997 |
from Starfish.grid_tools import CIFISTGridInterface as BTSETTL
from typing import Union
from typing import List
from typing import Tuple
def load_btsettl_spectrum(
params: Union[ndarray, List[float]],
photons: bool = True,
air: bool = False,
wl_range: Union[List[float], Tuple[float, float]] = (3000, 3... | b94a197b727a33472517f1d3a1b4b23adb534dce | 3,596,999 |
def sigmoid(x):
"""
シグモイド関数
Args:
x(np.array): 入力値
Returns: 活性化関数によって変換した出力値
"""
return 1 / (1 + np.exp(-x)) | a5d1bbe421922a0405f986f648026d734dd0c21f | 3,597,001 |
import json
def read_repos_as_list() -> tuple[list[str], list[str]]:
"""
Converts the repos from json to list of links
"""
with open("../data/repos.json", "r") as f:
json_data = json.load(f)
repos_list = []
branch_links = []
for repo in json_data["ruleSources"]:
for settin... | a59d7c3e42f64967e6626fbeb45267c8f2cadf8b | 3,597,002 |
def jacobian(f, dim):
"""Find the Jacobian."""
return [[diff(f, x[i], x[j]) for i in range(dim)] for j in range(dim)] | 5dadbb5e16be888f92e65838c0797204e406cadf | 3,597,003 |
def elbow_parity_str( parity ):
"""
Convert the numerical code for elbow parity into a descriptive string.
:Parameters:
parity: int
The elbow parity:
* 1 means elbow right armed
* -1 means elbow left armed
"""
if parity == PARITY_RIGHT:
... | dc86d04807c583013ea57516d1366334d158d433 | 3,597,004 |
def uniform(array):
"""Fill-in empty strings to empty cells to make it MxN
:param list in_array: a list of arrays
"""
width = longest_row_number(array)
if width == 0:
return 0, array
else:
for row in array:
row_length = len(row)
for index in range(0, row_... | 9428d55638fa8694f84f62fc1b7f32f5ad09b982 | 3,597,005 |
def addstrp(arg1, arg2):
"""
Comme addstr() au dessus mais ajoute un espace entre les deux si nécessaire
Args:
arg2: whatever, will be translated via str()
arg1: whatever, will be translated via str()
"""
a = str(arg1)
b = str(arg2)
return u'{}{}{}'.format(a, ' ' if a and b ... | fc161017d135daaa744bd9154a9669a8c7c634b1 | 3,597,006 |
from datetime import datetime
import pytz
def get_timestamp_from_turn_message(message: dict) -> datetime:
"""
Gets the timestamp from a turn message, returns it as a timezone aware datetime
object.
"""
try:
return datetime.fromtimestamp(int(message["timestamp"]), tz=pytz.utc)
except Ty... | fc01784a74f960f5b9fd836ebf884ac19e543b9f | 3,597,007 |
def return_filtered_comments(submission):
"""Takes in a submission object, returns a list of comments that are
filtered based on blacklist, maxwords, top x comments"""
submission.comment_sort = COMMENT_SORT_BY
submission.comment_limit = COMMENT_LIMIT
filtered_comments = []
for top_level_comment ... | 612cf9aea9aaeecfc017990670ce1a1ddb8b9d54 | 3,597,008 |
import math
import random
def queryMechanism(S,delta,Ycardinality,dic,dimension):
"""
:param S:
:param delta:
:param Ycardinality: =len(dic)
:param dic: list of keys
:param dimension: [0,1]
:return:
"""
n = len(S)
Answer_Table = []
attr={}
if len(dimension)==1:
... | a30a10558dc5dfe822efbfdc6ea8b85eb892e5bd | 3,597,010 |
def multiple(clases):
"""
Busca la relacion entre cada numero del 2-9
y el numero de clases que tienen un dimension multiple de M y != 0
:param clases: list - lista de todas las lases
:return: dict: dict - relacion entre cada numero del 2-9
y el numero de clases que tienen un dimension multipl... | a2e9f8a6ed0b86ad958eec7c1d3d6b935c715362 | 3,597,011 |
import torch
def std_normal(size):
"""
Generate a standard Gaussian of a given size
"""
return torch.normal(0, 1, size=size).cuda() | 67fba227f277105bac60ac500138c4208b2c74db | 3,597,013 |
from typing import Tuple
from typing import List
def create_row_strings(rows) -> 'Tuple[List[str], List[int]]':
"""テーブルデータを表示用に整形する.
Args:
rows (List[List[str]]): テーブルデータ
Returns
Tuple[List[str], List[int]]: row_strings: 表示用に整形したテーブルデータ, sizes: 各カラムの文字列長
"""
def _len(string: str... | 469dc1ad2c7ab3c26554807dc40d1813cd47be67 | 3,597,014 |
import torch
def generate_red_car_gan(
model: RecursiveScriptModule, latent_z: np.ndarray
) -> Image.Image:
"""
generate_red_car_gan
a generator function for the Red Car GAN, which takes in a latent z vector
and generates a red car based on those values
Args:
model: the red c... | 0db7d16dababd7d4dc524e53eed7a54f2c693912 | 3,597,015 |
def getBlocks(convLayers: list):
""" group layers in convLayers into layer of same channel number """
convBlocks = []
debut = 0
current = convLayers[0].output.shape[-1]
for i in range(1, len(convLayers)):
fm_nb = convLayers[i].output.shape[-1]
if current != fm_nb:
end = ... | b069e6e89506479245c0035372950092c1b8324e | 3,597,016 |
def convert_to_Hessenberg_symmetric_double(A):
"""Tridiagonalize a symmetric square matric to Hessenberg form using Householder reflections.
Costs 4/3 * n^3 + O(n^2) operations.
.. code-block:: matlab
function A = mytridiagturbo(A)
[m,n] = size(A);
if (m ~= n)
error('... | 7f80dc7090752a07d13aa983c415089782c07d63 | 3,597,018 |
def autofill(field, value):
"""
Return a bcm dictionary with a command to automatically fill the
corresponding "field" with "value"
"""
return {'mode': 'autofill', 'field': field, 'value': value} | 7b96ccd0e9756cdd6aab9919996b183be1478f8f | 3,597,019 |
async def estrai_persona(
ricereca_persona: PersonaSearch = Depends(),
authtoken: str = Header(None)
):
"""
Binding del servizio SOAP U-GOV [estraiPersona](https://wiki.u-gov.it/confluence/pages/releaseview.action?pageId=79822895#WSACPersonaFisica(SOAP)-estraiPersona)
"""
auth = check_t... | 809ac3ed63a1057e251016d546e0d28176dfbf86 | 3,597,020 |
def verify_threshold(dut, **kwargs):
"""
Verify Threshold
Author: Prudvi Mangadu (prudvi.mangadu@broadcom.com)
:param :dut:
:param :threshold_type: priority-group|queue
:param :buffer_type: if threshold_type:priority-group {shared|headroom} |
... | 86988620306c203995a609e533562ae67be39c5b | 3,597,021 |
def make_query_result(results: str, query: InlineQuery) -> InlineQueryResultArticle:
"""Making result for default inline query"""
return InlineQueryResultArticle(
id='1',
title='The search for "{}" is done ✅'.format(query.query),
description='Click me if you want to see results😊',
... | 27d7142f5f4cb7b0bbe78fe6f036caa92e4ac3dd | 3,597,022 |
def unwrap(image, wx, wy, sx, sy, px=0, py=0, is_column=True):
"""
Unrwap an image into an array.
Parameters
----------
image : af.Array
A multi dimensional array specifying an image or batch of images.
wx : Integer.
Block window size along the first dimension.
... | e8e29bb8c39375bafa112ebd7680f4785a5192dd | 3,597,023 |
from scipy.stats import kendalltau
def correlation_kendalltau(data1:np.array,
data2:np.array,
alpha:float = 0.05,
return_corr:bool = False,
verbose:bool = False)->float:
"""
Test if two numerical/or... | f33a545afb8d7ca8399d902d671e4e1793b370bd | 3,597,024 |
def _render_timed_frame(offset, buffer, cell_height, cell_width, definitions):
"""Return a group element containing an SVG version of the provided frame.
:param buffer: 2D array of CharacterCells
:param cell_height: Height of a character cell in pixels
:param cell_width: Width of a character cell in pi... | 913b8e2ef2095c735f28d93a343778272bb63dc3 | 3,597,025 |
import array
def cumhisto(a,da=1.,amin=[],amax=[]): # --DC
"""
Histogram of 'a' defined on the bin grid 'bins'
Usage: h=histogram(p,xp)
"""
if amin == []:
amin = min(a)
if amax == []:
amax = max(a)
nnn = (amax - amin) / da
if less(nnn - int(nnn), 1e-4):
amax ... | d34dd32de942a0810dc7c37edf5a2ceabf40b8bb | 3,597,027 |
def get_anisotropic_noise(shape,wcs,rms,lknee,alpha,template_file=None,tmin=0,tmax=100):
"""
This function reads in a 2D PS unredenned template and returns a full 2D noise PS.
It doesn't use the template in the most sensible way though.
"""
ops = get_anisotropic_noise_template(shape,wcs,template_fil... | 5c7db78c352447f8d70310454e7831253fd74b21 | 3,597,028 |
def get_google_authtoken(appname, email_address, password):
"""
Make secure connection to Google Accounts and retrieve an authorisation
token for the stated appname.
The token can be send to the login front-end at appengine using
get_gae_cookie(), which will return a cookie to use for the user sess... | ad479814e3a058ed352b0fd84addb2d64f0563ff | 3,597,029 |
def calculate_gc_correction(his_rd_gc, mean, sigma, bin_size=1):
""" Calculate GC correction from RD-GC histogram
"""
max_bin = min(int(max(2 * mean, mean + 5 * sigma) / bin_size), his_rd_gc.shape[0])
his = his_rd_gc[1:max_bin, :]
rd = np.repeat((np.arange(1, max_bin * bin_size, bin_size)[:max_bin -... | df85e63b2bb4cf50dbde63a01fa6598f2735a7dd | 3,597,030 |
def xdet_resnet_v4_generator(block_fn, layers, data_format=None):
"""Generator for X-Det ResNet v2 models.
Args:
block_fn: The block to use within the model, either `building_block` or
`bottleneck_block`.
layers: A length-4 array denoting the number of blocks to include in each
layer. Each laye... | 1d457dea858393f513caab16189b181c154e80f0 | 3,597,032 |
def kj_per_mol_to_joules(value):
"""Converts values in kJ/mol units to J"""
return value * 1000 / AVOGADRO | aa9a3fe24fb064f0db12558f5ef57a49820574b6 | 3,597,033 |
def translate_individual(network_info, individual):
"""
Translates individual to prepare cost evaluation
Extract building plant locations (building names) and a list of disconnected buildings from the individual
:param individual: the individual to extract the information (coded as genes) from
:pa... | c4216041744040bb8bebdb285e58e70171e451f2 | 3,597,034 |
async def accept_offer(request, offer_id):
"""Request for authorized Account to accept Offer"""
required_fields = ['count', 'target']
common.validate_fields(required_fields, request.json)
offer = await offers_query.fetch_offer_resource(
request.app.config.DB_CONN, offer_id)
offer_holdings ... | bebb872e811b85a6828f25e1198e712556a1d044 | 3,597,035 |
def valid_vlan_id(vlan_id, extended=True):
"""Validates a VLAN ID.
Args:
vlan_id (integer): VLAN ID to validate. If passed as ``str``, it will
be cast to ``int``.
extended (bool): If the VLAN ID range should be considered extended
for Virtual Fabrics.
Returns:
... | c046bf6c1e558eb679c9c53fa4e091213a1b7d46 | 3,597,036 |
from typing import Tuple
from typing import Union
def assign_color(color: Color,
quilt: Tuple[Tuple[Union[Color, None], ...], ...],
x: int,
y: int) -> Tuple[Tuple[Union[Color, None], ...], ...]:
"""
Create a new quilt with block (`x`, `y`) has the color `colo... | c31f7b00909363f065257dc2facb5ada5f4ae181 | 3,597,037 |
from typing import Optional
from typing import Dict
from typing import Union
def model_to_petab(
model: Model,
output_path: Optional[TYPE_PATH] = None,
) -> Dict[str, Union[petab.Problem, TYPE_PATH]]:
"""Generate the PEtab problem for a model.
Args:
model:
The model.
outpu... | 63a7a81d27e9fd4335e7070ca9ec4b4a8602ae80 | 3,597,040 |
import json
def fighters_gender_promotion(gender, promotion):
"""Return fighters by gender and promotion."""
fighters = session.query(Fighter).filter(Fighter.gender == gender,
Fighter.promotion == promotion).all()
data = [fighter.as_dictionary() for fighter in fighters]
data = sorted(data,... | a07919effa063a64924166dad4e2cfd03bf9d903 | 3,597,041 |
def trigram(text1: str, text2: str, split_num: int=3):
"""
Find the similarity between two strings using ngrams.
Returns float score value, 0.0 being completely different strings and 1.0 being equal strings.
Arguments:
text1: main string to compare against.
text2: second string to compa... | d38f2496d8df24d72d22ab2a5ee00be2f4d57866 | 3,597,043 |
def clean_metadata_table(tbl):
"""Return a tuple of (clean metadata, control-metadata, duplicate-metadata, duplicate-map).
All values are pandas dataframes/series.
"""
tbl = tbl.query('project != "CSD17_AIR"')
tbl['city'] = tbl['city'].map(lambda val: 'honolulu' if val == 'antarctica' else val)
... | 6f1d09c414027b02f371741526e9924ead6edb30 | 3,597,044 |
from typing import Optional
def test_map_iou() -> Optional[float]:
"""Helper to test map_iou function"""
boxes_true = [100, 100, 200, 200]
boxes_pred = [100, 100, 300, 200]
boxes_true = np.reshape(boxes_true, (1, 4))
boxes_pred = np.reshape(boxes_pred, (1, 4))
result = map_iou(boxes_true, boxe... | 0f146fccfa4d0805eea1d3c2111e58021a7403ec | 3,597,045 |
def sha2_512() -> HashAlgorithm:
"""
Convenience function to create hash algorithm object.
"""
return HashAlgorithm(HashAlgorithmId.SHA2_512) | 3fbf2af475cc5283b82f6f43462b5174d442e050 | 3,597,046 |
def wavelet_transform_fft(values, g_widths):
"""create a grid of gaussian line profiles and perform a wavelet transform
over the grid. (a.k.a. simply convolve the data with all line profiles
in the grid in an efficient way and then return an asarray that contains
all of these convolutions.
inpu... | 12b637c793532ef88365eee370f6a7aaf4bffde1 | 3,597,047 |
from pioreactor.logging import create_logger
from typing import Callable
from typing import Any
from typing import Optional
def subscribe_and_callback(
callback: Callable[[MQTTMessage], Any],
topics: str | list[str],
hostname: str = leader_address,
last_will: Optional[dict] = None,
name: Optional[... | a25f76ea70813aee29b1037431e4a702fe35d4d8 | 3,597,048 |
def fix_misspelled_words2(text):
"""
Fixes the misspelled words on the specified text (uses predefined misspelled dictionary)
:param text: The text to be fixed
:return: the fixed text
"""
mispelled_dict = {'colour': 'color', 'centre': 'center', 'favourite': 'favorite', 'travelling': 'traveling',... | 2f4a99f924d97e25179b0a539113a7a8ccc24f06 | 3,597,049 |
import csv
def read_file(filename):
""" Read file gets an input file(csv) from the same directory and generates a features and dataset.
:param filename:
filename - string: The filename of the csv file in the folder.
Example: ecoli.csv
Yields:
feature_attribute_set: Generates... | 7921a3091cfbf6eb8321a478b75d246a8c692c14 | 3,597,050 |
def get_traj(traj_data, frame_ids, person_id):
"""Select the traj matching the frame_ids and person_id."""
person_data = traj_data[traj_data[:, 1] == person_id, :]
filtered_data = person_data[np.isin(person_data[:, 0], frame_ids), :]
return (person_id, filtered_data[:, 2:].tolist()) | dd91995ecc4079fca05f53cfa532d86b30a64053 | 3,597,051 |
def coarse_grind_to_fine_grind(coarse_grind, fc_diff=FC_DIFF_TWO_ROW):
"""
Coarse Grind to Fine Grind Percentage
:param float coarse_grind: A percentage from the malt bill
:param float fc_diff: The F/C difference percentage from the malt bill
:return: Fine Grind Percentage
:rtype: float
"""... | 41df8e823cdfe2c989ea49bfcaee5513c701036a | 3,597,052 |
def login():
"""Log user in"""
# Forget any user_id
session.clear()
# User reached route via POST (as by submitting a form via POST)
if request.method == "POST":
# Ensure username was submitted
if not request.form.get("username"):
return apology("must provide username"... | de433c78758f99f859d55ad8102e93482945122c | 3,597,053 |
def initial_permissions() -> [[str, str]]:
"""The initial permissions that are added when the first user is created"""
return {'admin_all': ['user__Admin', 'resource__All'],
'guest_all': ['user__Guest', 'resource__All']} | 058a821cfef40afee2300e3a2511a8ff69a3f5c7 | 3,597,054 |
def gaussian_generator(mean, dev):
"""
Random Gaussian variables of mean "mean" and standard deviation "dev".
Parameters
----------
mean : array_like
Gaussian mean.
dev : array_like
Gaussian dispersion.
Returns
-------
x : array_like
Random Gaussian variable... | 24c5ff623747e1f20084bb66e23bcfdeb0f872a5 | 3,597,056 |
def remove_slides(nb: notebooknode.NotebookNode) -> notebooknode.NotebookNode:
"""Remove all slide blocks and return."""
new_cells = []
for cell in nb.cells:
if cell.cell_type=='markdown':
lines = cell.source.splitlines()
blk = []
in_blk = False
for l ... | 737c8215a099b90493800e709c8bd8fef19e0f7a | 3,597,057 |
def compare_2(num1: int, num2: int) -> int:
"""
:param num1: int
:param num2: int
:return: int
"""
return abs((num1) - (num2)) | 587445a5b496afc189d65f1207692ed9f0cbb658 | 3,597,058 |
def mat_vec(v: PyTree, centered_oks: PyTree, diag_shift: Scalar) -> PyTree:
"""
Compute (S + δ) v = 1/n ⟨ΔO† ΔO⟩v + δ v = ∑ₗ 1/n ⟨ΔOₖᴴΔOₗ⟩ vₗ + δ vₗ
Only compatible with R→R, R→C, and holomorphic C→C
for C→R, R&C→R, R&C→C and general C→C the parameters for generating ΔOⱼₖ should be converted to R,
... | 02db682f76115fe8c7575d99f0aae02d6701f260 | 3,597,059 |
def nonMaximumSupression(detections):
"""
:param detections: detections returned from darknet
:return: only detection of highest confidence. Return None, if no individual was detected
"""
if len(detections) != 0:
det_sorted = sorted(detections, key=itemgetter(2))
max_conf_detection =... | 524faf0abab6323f05a5a4eb1b2721a1d6e168a3 | 3,597,060 |
def _closure_probability_extensional(intent, subset, rel_matrix):
"""
Return True if the closure of the subset of the extent given in input is
equal to the intent given in input
Parameters
----------
intent : array
Set of the attributes of the concept
subset : list
List of objects t... | 85d02babaab0648141a4153757e4de8178b08c42 | 3,597,061 |
import math
def compute_ciou(box1, box2):
"""Calculates the complete intersection of union between box1 and box2.
Args:
box1: a `Tensor` whose shape is [..., 4] and represents the coordinates
of boxes in x_center, y_center, width, height.
box2: a `Tensor` whose shape is [..., 4] and represents the ... | d5af61976f465657254234ff6fefb67eaf8aa248 | 3,597,062 |
import json
def pipelines_views():
""" Analytics/Pipelines/Views Route
Endpoint for returning analytics related to pipeline page views on the portal
Args:
None
Returns:
Object
"""
elements = []
page_views = []
id = request.args.get('id', None)
... | 937e48115ad9d9e5570fe1caa3ee75a23c532b9c | 3,597,063 |
def environ(request):
"""Provide environment variable override, and restore on finalize.
"""
manager = EnvironManager()
request.addfinalizer(manager.unpatch)
return manager | 80c535b815b956e453ce6f54e629d1e45f62f68f | 3,597,064 |
def pad_omni_image(image, pad_size, image_dims=None, f=None):
"""
Pad an omni-directional image with the correct image wrapping at the edges.
:param image: Image to perform the padding on *[batch_shape,h,w,d]*
:type image: array
:param pad_size: Number of pixels to pad.
:type pad_size: int
... | 18265f025fa98773390775629fc848c3533413d7 | 3,597,067 |
def return_metric_df(model, metrics, **kwargs):
"""
Return the evaluation results in a dataframe
:param model: sklearn model
:param metrics: List, a list of evaluation metrics
**kwargs: additional parameters to pass to return_metric_df_helper()
:return: Pandas DataFrame
"""
lst_metric_t... | 6e5da3d60b2fe606990723097464d360ff9baa1b | 3,597,068 |
def read_settings(settings_file_path):
"""
Returns all user settings
:return: dict
"""
path = settings_file_path or settings_path()
data = dict()
try:
data = read_json(path)
except Exception:
LOGGER.exception('Cannot read settings from "{}"'.format(path))
return dat... | 71fff83dfdf0a6637a2c11ab03c35b15685bbed8 | 3,597,069 |
def get_window(width, height, display, **kwargs):
"""
Will create a pyglet window from the display specification provided.
"""
screen = display.get_screens() # available screens
config = screen[0].get_best_config() # selecting the first screen
context = config.create_context(None) # create GL... | 3ee0931708be56ab92590d402568470ef86f8f16 | 3,597,070 |
def chebyshev(s1, s2):
"""
Computes the chebychev distance between two vector.
Parameters:
s1: `numpy array`
The first vector.
s2: `numpy array`
The second vector.
Returns: `float`
Chebychev distance between s1 and s2.
"""
return np.amax(np.... | a97ffd14456d8515e0dc9930b079d3ce8eaa8444 | 3,597,071 |
def store_chunk(x, out, index):
"""
A function inserted in a Dask graph for storing a chunk.
Parameters
----------
x: array-like
An array (potentially a NumPy one)
out: array-like
Where to store results too.
index: slice-like
Where to store result from ``x`` in ``out... | 8b26af638abdbe829cb009e33c8478aa89f34c94 | 3,597,073 |
def pick_texture(train_rs_closest_picks: dict, train_s_closest_picks: dict, house_closest_picks: dict, room_type: frozenset, surface_type: str,
textures: dict) -> ImageDescription:
"""
Pick a suitable texture for an unobserved surface.
:param train_rs_closest_picks: RS statistics computed o... | 395da0406c1db85d6fecb90a62288db31467e3d5 | 3,597,074 |
def get_audits(args):
"""Get audits from local STIG database (SQLite).
"""
success, conn = lib.db_sqlite3.connect(path=args.PATH, filename='stig.db')
if not success:
return False
data = {}
sql = """SELECT *
FROM profile as p
LEFT JOIN control as c ON p.control_id = c.id
... | 214dcdcd41d5c59609bf446e197522d466d22bf2 | 3,597,075 |
def create_perspective_projection_matrix(fovy, aspect, near, far, dtype=None): # TDOO: mark as deprecated
"""Creates perspective projection matrix.
.. seealso:: http://www.opengl.org/sdk/docs/man2/xhtml/gluPerspective.xml
.. seealso:: http://www.geeks3d.com/20090729/howto-perspective-projection-matrix-i... | c8eb3d258c70fed7f955f449770bbc9f7b08b70c | 3,597,076 |
def init_menu(mocker):
"""Initialize a dummy MenuFile for testing."""
mocker.patch.multiple(
houdini_package_runner.items.xml.MenuFile,
__init__=lambda x, y, z, u: None,
)
def _create():
return houdini_package_runner.items.xml.MenuFile(None, None, None)
return _create | d7b63e036db9ba52053609f23ce7d553233d31fb | 3,597,077 |
async def find_content_by_id(db_session: Session, content_id: int):
"""Get notification content by id."""
db_notification = db_session.query(ContentModel)\
.filter(ContentModel.id == content_id).first()
return db_notification | b3368159173ca73b324c9b35246b4a832af64431 | 3,597,078 |
def TTF_SetFontHinting(font, hinting):
"""Sets the rendering hinting mode for a given font.
The hinting mode can be specified using one of the following constants:
============= =======================
Hinting type Constant
============= =======================
Normal ``TTF_HINTING... | 19cbb0a83f326a2c786d15568569ee1be1fa35e0 | 3,597,079 |
import asyncio
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry):
"""Set up Emporia Vue from a config entry."""
global device_gids
global device_information
device_gids = []
device_information = {}
entry_data = entry.data
email = entry_data[CONF_EMAIL]
password = en... | cb5e1f2789e1333a9e185480a7872ed543e324c4 | 3,597,080 |
def calc_W_dash_b2_d_t(W_b2_d_t):
"""1時間当たりの浴槽自動湯はり時における節湯補正給湯量 (L/h) (6e)
Args:
W_b2_d_t(ndarray): 浴槽自動湯はり時における基準給湯量 (L/h)
Returns:
ndarray: 1時間当たりの浴槽自動湯はり時における節湯補正給湯量 (L/h)
"""
# 浴槽における節湯の効果係数
f_sb = watersaving.get_f_sb()
return W_b2_d_t * f_sb | c967dd311ab33365980e063328a806698a884d6b | 3,597,081 |
def get_loss_ft(logits, labels):
"""Add l2_loss to all the trainable variables"""
labels = tf.cast(labels, tf.int64)
cross_entropy = tf.nn.softmax_cross_entropy_with_logits(
labels=labels, logits=logits, name='cross_entropy_per_example'
)
cross_entropy_mean = tf.reduce_mean(cross_entropy, na... | 7f7c80fce563999c2e4a92743cbc4ca616f44f1e | 3,597,082 |
def make_cache_key(*args, **kwargs):
"""Creates a memcache key for a url and its query/form parameters
Returns:
(obj): Flask request url
"""
mimetype = get_mimetype()
return f"{mimetype}:{request.full_path}" | 35df4cdce38537273282c2eea0d037dea65c6e1f | 3,597,083 |
def get_external_temp_hum():
"""
Get temperature and huidity from openweathermap
"""
data = loads(urlopen("http://api.openweathermap.org/data/2.5/weather?q=Southampton&units=metric&APPID=615df34fae24f3b1e0de372fe3f80bfa", timeout=2).read())[u'main']
temperature = data[u'temp']
humidity = dat... | 969092fed799e3b2636ab0ef5e702b70042aa3e1 | 3,597,084 |
def PLUGIN_ENTRY():
"""
Required plugin entry point for IDAPython plugins.
"""
return PatchingPlugin() | 2f2e9b42e55ed6b5490c5d86f1c91dfa0bc74961 | 3,597,085 |
def get_turning_pts(y, x=None, getindex=True, tol=1e-6, atol=None):
"""
Find turning points (where slope changes) in a vector.
Parameters
----------
y : array_like
y-axis data vector
x : array_like or None; optional
If vector, x-axis data vector; must be monotonically ascending
... | df4517f58fbc9e7b39a8d36a55eee98ef1cd2fdb | 3,597,086 |
def ml_nms(boxlist, nms_thresh, max_proposals=-1, fixed_size=False):
"""
Performs non-maximum suppression on a boxlist, with scores specified
in a boxlist field via score_field.
Args:
boxlist (data.structures.Boxes):
nms_thresh (float): the score threshold for nms
max_proposals ... | d97e762f145702584c8c4427a659a81c1313b65d | 3,597,087 |
def is_jamo(character):
"""
Check if a single character is a jamo character.
Valid jamo includes all modern and archaic jamo, as well as all HCJ.
Only check of assigned code points.
"""
return is_in_charsets(character, hangul_jamo_assigned_all) or is_hcj(character) | 090d80328b434eacadb96764cc29b38f87b21472 | 3,597,089 |
def view_profile(request):
""" view moderators and users profile """
user = request.user
if is_moderator(user):
template = 'manage.html'
else:
template = 'user.html'
context = {'template': template, 'user': user}
return my_render_to_response(request, 'yaksh/view_profile.html', co... | fd4e65270031c62ed0883287e31c754203a4c2b1 | 3,597,090 |
import asyncio
async def open_port(host, port):
"""Repeatedly try if a port on a host is open until duration seconds passed
Parameters
----------
host : str
Host IP address or hostname
port : int
Port number
Returns
-------
awaitable bool
"""
try:
_rea... | 9642cf112c2c3bb83d578c522d70880be064c827 | 3,597,091 |
from typing import List
def recall_at_position_k_in_n(labels: list, k: list = [1], n: int = 10, tar: float = 1.0) -> List:
""" Rn@k 召回率指标计算
:param labels: 数据列表
:param k: top k
:param n: 样本范围
:param tar: 目标值
:return: 所得指标值
"""
score = labels[0]
label = labels[1]
length = len(k... | a1721c9fcf0b460b94068af68763211d13397272 | 3,597,092 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.