content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def global_scaling(gt_boxes, points, scale_range):
"""
Args:
gt_boxes: (N, 7), [x, y, z, dx, dy, dz, heading]
points: (M, 3 + C),
scale_range: [min, max]
Returns:
"""
if scale_range[1] - scale_range[0] < 1e-3:
return gt_boxes, points
noise_scale = np.random.unifor... | e8bc52c8001a24a4aae9a33bd30d6b217eff18e4 | 3,619,100 |
import inspect
async def parse_annotation(param: inspect.Parameter, default, arg: str, index: int, message: discord.Message):
""" Parse annotations and return the command to use.
index is basically the arg's index in shelx.split(message.content) """
if default is param.empty:
default = None
... | 2ce54a9a70f1eac3ad94b0783e81fd0508ccd731 | 3,619,101 |
from pathlib import Path
def api(path:str):
"""Associate a path with a given method."""
def inner(fn):
fn.path = Path(path)
return fn
return inner | a03d5ea05c5b91e3e18b121fba7771691f508b0c | 3,619,102 |
def wlan_exp_init_time(nodes, time_base=0, output=False, verbose=False, repeat=1):
"""Initialize the time on all of the WLAN Exp nodes.
Attributes:
nodes -- A list of nodes on which to initialize the time.
time_base -- optional time base
output -- optional output to see jitter acro... | dc7681c5649b6d180fca3d9da6b66bb329e2a43c | 3,619,103 |
def GilmoreEick_equation(t, x):
"""Compute one integration step
using the Gilmore--Eick equations.
"""
global T
R = x[0]
R_dot = x[1]
pg = x[2]
pinf = sc_pstat - sc_pac * np.sin(sc_omega * t)
pinf_dot = -sc_pac * sc_omega * np.cos(sc_omega * t)
T_gas = T_gas_0 * pg * R ** 3 /... | 0187050c12dd83d538b4e196eb0e20fa77f645f4 | 3,619,104 |
def hello_world():
# TODO add costring
""" Note add docstring """
return "hello cma" | 356199e7b39cbe815ba206d9659af0ab82ec275f | 3,619,105 |
import sys
import json
import os
def generate_boutiques_descriptor(
module,
interface_name,
container_image,
container_type,
container_index=None,
verbose=False,
save=False,
save_path=None,
author=None,
ignore_inputs=None,
tags=None,
):
"""
Generate a JSON Boutiques... | 8ce35ed96df8b6423d5e806c6a5fbae0b016d032 | 3,619,106 |
def findAbsFuncUFromRelaU(CompMean, ru):
"""
:param CompMean:
:param ru:
:return:
"""
result = CompMean * ru
resultString = result.to_eng_string()
intPart = resultString.split('.')[0]
try: # may not have '.'
decimalPart = resultString.split('.')[1]
digiteff = 0
... | 2edb3c08837138f12249705be38ff3b57bf30d5d | 3,619,107 |
import json
def get_all_services(as_json=False, as_json_schema=False):
"""Get all registered services, as objects (default) as JSON, or as JSON schema.
:param bool as_json: If True, return JSON instead of objects. Supersedes as_json_schema.
:param bool as_json_schema: If True, return JSON schema instead ... | d7c47b47ba110748ae3bfec9c455ea82c5d2cf3b | 3,619,108 |
def gen_jets_groomed_precrit(num_events, z_cut, beta, f,
jet_type='quark',
radius=1., acc='LL'):
"""Generates a list of num_events jet_type jets
through angularity based parton showering.
"""
# Setting up for angularities
jet_list = []
f... | b0f3bc11501445c7e1092bf36947d4963ab2bd2f | 3,619,109 |
import os
def fixture_encode_flac_u8():
"""fixture_encode_flac_u8"""
wav_path = os.path.join(
os.path.dirname(os.path.abspath(__file__)),
"test_audio",
"ZASFX_ADSR_no_sustain.wav",
)
audio = tf.audio.decode_wav(tf.io.read_file(wav_path))
value = audio.audio
value = (val... | 0138f36881fa8f8064c8920de3a4bf51f3e84819 | 3,619,110 |
import torch
def randn(*args, **kwargs):
"""
In ``treetensor``, you can use ``randn`` to create a tree of tensors with numbers
obey standard normal distribution.
Example::
>>> import torch
>>> import treetensor.torch as ttorch
>>> ttorch.randn(2, 3) # the same as torch.randn... | e92e45bc0210f6b00c468629c741eab2d0a7a50a | 3,619,111 |
def parse_host_port(address, default_port=None):
"""
Parse an endpoint address given in the form "host:port".
"""
if isinstance(address, tuple):
return address
if address.startswith('tcp:'):
address = address[4:]
def _fail():
raise ValueError("invalid address %r" % (addr... | 966e53c3c945d7fc728bd4b9a680ae62f4e2b7bf | 3,619,112 |
def synapses2nodepoints(x, layer_scale):
"""Generate nodepoints (point A, point B) from synapses for given neuron(s).
Parameters
----------
x : CatmaidNeuron | CatmaidNeuronList or TreeNeuron | NeuronList
neuron or neuronlist of different formats
layer_scale : int | float
... | 9756830e2b580155ca50d5f67586a6d5552c9a4f | 3,619,113 |
def p52():
""" Smallest integer n s.t n,2*n,...,6*n all have same digits. """
# Returns the digits in the decimal representation of a positive integer n
def digits(n):
ret = []
while n > 0:
ret.append(n % 10)
n = n / 10
ret.sort()
return ret
# C... | e252998ab15a99aa58139005aa9334c9d99005f8 | 3,619,114 |
from typing import Type
def get_microphone_class(system: str) -> Type[RhasspyActor]:
"""Get class type for profile microphone."""
assert system in [
"arecord",
"pyaudio",
"dummy",
"hermes",
"stdin",
"http",
"gstreamer",
], ("Unknown microphone system... | a1b915601ffdfbe0a2f038a380be1a68b66bf85a | 3,619,115 |
import torch
def fit_gibbs_global_batch_aligned(hdx_set, initial_guess, r1=2, r2=5, epochs=100000, patience=50, stop_loss=0.05,
optimizer='SGD', **optimizer_kwargs):
"""
Batch fit gibbs free energies to two HDX measurements. The supplied HDXMeasurementSet must have alignment information
(su... | ac741d26701d987d848af18e1e75d2e9cd15a6a5 | 3,619,116 |
def addition(a,b):
""" return sum of a and b """
c = a + b
if abs(c) > Largest:
if c < 0:
return -(Largest)
return Largest
return c | 98a08514dea1dc2c58151917563360946c5fac87 | 3,619,117 |
import os
def panoimg():
"""Panoramic US image of a musculoskeletal muscle
"""
return _load(os.path.join(data_dir, "panoramic_echo.jpg")) | d442c7acceac90c9ba7e2dd063d9b2fc73e27edf | 3,619,118 |
import requests
def subscribe_in_pubsubhubbub(channel_id: str) -> int:
"""The subscription request to find out when a new video arrives on a
specific channel is made from this function. Basically here the
necessary data for this activity is informed for Pubsubhubbub
Parameters
----------
chan... | 1d65c5c9621d41ea54bf0a68fb3f824a342bb804 | 3,619,119 |
def hsv_complement_color(h, s, v):
""" get the complement of a rgb color
:param h: Hue value (0-360)
:param s: Saturation value (0-255)
:param v: Value value (0-255)
:return: HSV tuple """
# perform 180° hue change
tmp = 180
if h > 180:
tmp = -tmp
return h + tmp, s, v | dd9769b93742349eaca124ee60d65f047c18f2b5 | 3,619,120 |
def get_complex_polar(mag, angle):
"""Angle must be in radians"""
# TODO: this doesn't belong here.
return mag * np.exp(1j * angle) | 15c9e9c8d279cc879ef4f069027aac6f31c2f421 | 3,619,121 |
import requests
def telegram_bot_sendtext(bot_message: str, *, bot_token: str, bot_chatid: str):
"""Send a notification to a telegram channel.
Args:
bot_message (str): Message you want to send.
Returns:
[request]: Returns a request object which is the response to send to the channel.
... | 372d350ad5513a233b148b3f75b8fa5bdd2f2904 | 3,619,122 |
import torch
from typing import Optional
def focal_loss(output: torch.Tensor,
target: torch.Tensor,
reduction: str = "mean",
normalized: bool = False,
gamma=2,
reduced_threshold: Optional[float] = None,
eps: float = 1e-6,
... | d1fcadc9273a6a25a617c40e71e91515352a4bb2 | 3,619,123 |
def preprocess_words_scores(type2freq_1, type2score_1, type2freq_2, type2score_2,
stop_lens, stop_words, handle_missing_scores):
"""
Filters stop words according to a list of words or stop lens on the scores
Parameters
----------
type2freq_1, type2freq_2: dict
Ke... | fe91586acbd9722e24daebcb942971e969f990d2 | 3,619,124 |
from pathlib import Path
def load_mappings_file(fpath: Path) -> list:
"""
Read the mappings file shared by Abu farha (CVPR'18) to read the class
names.
"""
res = []
with open(fpath, 'r') as fin:
for line in fin:
res.append(line.rpartition(' ')[-1].strip())
# convert to ... | 3e450e7ff07516c4149041008cc2cf3b3a1bb364 | 3,619,125 |
def _satisfies_wolfe(val_0,
val_c,
f_lim,
sufficient_decrease_param,
curvature_param):
"""Checks whether the Wolfe or approx Wolfe conditions are satisfied.
The Wolfe conditions are a set of stopping criteria for an inexact line se... | d4afc60f4a6e3d7749935fbbf6d291f4224cc04c | 3,619,126 |
def load_edf(eeg_file):
"""This function uses mne library.
WARNING: The function has strange behaviour, please don't use"""
data = mne.io.read_raw_edf(eeg_file)
sfreq = data.info['sfreq']
signals = data.get_data()
return signals, int(sfreq) | e05a1ed0b013a813c32c43a55bc16bb73dc0f03b | 3,619,127 |
def get_clean_codes(stressed_endings, assonance=False, relaxation=False):
"""Clean syllables from stressed_endings depending on the rhyme kind,
assonance or consonant, and some relaxation of diphthongs for rhyming
purposes. Stress is also marked by upper casing the corresponding
syllable. The codes for ... | 88d0e7a1929e16e4b1eb0bdb43bdf94a641b7394 | 3,619,128 |
def fit_parabola(x1,x2,x3,y1,y2,y3):
"""Returns the parabola coefficients a,b,c given 3 data points [y(x)=a*x**2+b*x+c]"""
denom = (x1-x2)*(x1-x3)*(x2-x3)
a = (x3*(y2-y1)+x2*(y1-y3)+x1*(y3-y2))/denom
b = (x1**2*(y2-y3)+x3**2*(y1-y2)+x2**2*(y3-y1))/denom
c = (x2**2*(x3*y1-x1*y3)+x2*(x1**2*y3-x3**2*y1... | e077f5a895e353d5b980b15bee603be5c34d3ec4 | 3,619,129 |
import threading
import os
def download(sensor, id):
""" Create a .csv file of requested sensor and id and delete it later
"""
# Get (list of dict) records from data_api
records = api_get_data(sensor, id)['data']
# Use Pandas for easy csv creation
df = pd.DataFrame.from_records(recor... | 3cd15adcb50022a5894fd49c926efc1165d33cb2 | 3,619,130 |
def _augment(image, op):
"""Image augmentation"""
if op[0]:
image = np.rot90(image, 1)
if op[1]:
image = np.fliplr(image)
if op[2]:
image = np.flipud(image)
return image | 43a693069629f05f12fd4139a9f2fb1c5de9fe3e | 3,619,131 |
def generate_list(usb_dict: dict) -> list:
"""
wrapper for list conversion
:param usb_dict: usb dictionary
:return: list of usb devices for tui print
"""
devices = []
for usb in usb_dict.values():
devices.append(usb)
return devices | 8d1d106c7b9fd4078b0d78f0370bd9d22ecda368 | 3,619,132 |
def file_test_list(tmpdir_factory, string_test_list):
"""An example of output from
tempest run --list-tests
"""
filename = tmpdir_factory.mktemp('data').join('file_test_list_one').strpath
with open(filename, 'w') as f:
f.write(string_test_list)
return filename | 6ce88df4834d90b1507e9b9171946a5fda1d557a | 3,619,133 |
def read_companies(excel_file: ExcelFile) -> pd.DataFrame:
"""
:param excel_file: (ExcelFile)
:return melted_companies: (DataFrame)
code | (String)
date | (Datetime)
name | (String)
...
"""
# Read excel file.
raw_companies = excel_file.parse(COMPANY, sk... | 8d451f7aeb472a1b9b447a97c9710d6f120b6ff8 | 3,619,134 |
def check_level(level):
"""
Check if given level is valid and return a normalized copy.
"""
if level is None:
return DEFAULT_LEVEL
if level not in LOG_LEVELS:
raise ValueError(f"invalid debug level: {level!r}")
return level | f987e03cc160ee55a839bf63f4165a2805af6b4e | 3,619,135 |
def GXY_B2(
code, error, mag=0.002617993877991494, propagation='random',
NEV=True, **kwargs
):
"""
SPE 90408 Table 4
"""
dpde = np.full((len(error.survey_rad), 3), [0., 0., 1.])
dpde[:, 2] = np.where(
error.survey.inc_rad <= kwargs['header']['XY Static Gyro']['End Inc'],
cos(... | 99cf7c392503e7c9b6276c6caf1fa049c1bd0a64 | 3,619,136 |
def is_lead_worker(rank):
"""
-1 = means serial code so main proc = lead worker = master
0 = first rank is the lead worker (in charge of printing, logging, checkpoiniting etc.)
:return:
"""
am_I_lead_worker = rank == 0 or is_running_serially(rank)
return am_I_lead_worker | 924d847a964d13cbf19e02acc187a89f088de810 | 3,619,137 |
def handler408(request):
""" Custom response handler """
return HttpResponse(content="Custom 408 handler", status=408) | aad27b4d5d81995e1d959e88ea61ade510b03ac6 | 3,619,138 |
def resolve_type_id_to_type_name(type_id, raise_exception=True):
"""
Resolves an EVE Online type_id to type_name. Falls back to ESI if not found in static database.
Returns None if not found.
"""
query = "select typeName from invTypes where typeID = %s" % type_id
type_name = query_static_databa... | 7866ecee769eb677a721b2fa4792ea8af3c41ba0 | 3,619,139 |
import re
def FindTasksByName(searchstr, ignore_case=True):
""" Search the list of tasks by name.
params:
searchstr: str - a regex like string to search for task
ignore_case: bool - If False then exact matching will be enforced
returns:
[] - array of task objec... | cdca2b4ea9122293261c075637880e53f7349379 | 3,619,140 |
def _get_model_checkpoint_directory(_params):
"""
:param _params: [argparse.Namespace] attr: experiment_name, run_name, pretrained_model_name, dataset_name, ..
:return: model_checkpoint_directory [str]
"""
return join(env_variable("DIR_CHECKPOINTS"), _params.experiment_run_name_nr) | d1f9a0097360e5e344fd29bb6cb9de9057e305cf | 3,619,141 |
def run_clients():
"""Force create driver for client """
clients = request.form.get('clients')
if not clients:
return jsonify({'Error': 'no clients provided'})
result = {}
for client_id in clients.split(','):
if client_id not in drivers:
init_client(client_id)
init_timer(client_id)
result[client_id] ... | 88735ee5485c1e2f9af3cb0da4eb94f909c42b1e | 3,619,142 |
import requests
import logging
def makeDataGetRequest(endpoint, apiKey, data={}):
"""
Helper function to make post request
:param str endpoint: Endpoint to hit
:param str apiKey: Api key to use to build header
:param dict json: Optional json data
"""
headers = {'X-API-KEY': apiKey, 'Conten... | 9ef03d5df5aaba20437d497f62a29eb0edf74d5a | 3,619,143 |
def gauss_pdf(x, a = 1, mu = 0, sigma = 1, bg = 0):
"""using scipy module function
"""
return a*norm.pdf(x, mu, sigma) + bg | d44d43e8cb35b22c500b1e5039b4aa5773a8edf9 | 3,619,144 |
def compute_emissions(tdf, df_with_emission_functions, dict_of_fuel_types_in_tdf):
"""Compute instantaneous emissions with equations used in [Nyhan et al. (2016)].
For each point in a TrajDataFrame, computes instantaneous emissions of 4 pollutants (CO_2, NO_x, PM, VOC).
Parameters
----------
tdf : TrajDataFrame
... | abe44e82a9ea637445c5996185f683f22725fc34 | 3,619,145 |
def _otbn_assemble_sources(ctx):
"""Helper function that, for each source file in the provided context, adds
an action to the context that invokes the otbn assember (otbn-as),
producing a corresponding object file. Returns a list of all object files
that will be generated by these actions.
"""
c... | f7083f17db1383135c28b324e2bc659c64c0f05c | 3,619,146 |
def reset_line_breaks(curr_boundary={}):
"""
Builds a fresh line breaks dictionary while keeping any
information provided concerning line boundaries.
Parameters
----------
curr_boundary: dict
Line boundaries to be preserved
Returns
-------
dict
The newly initialize... | da7f1fc0f206e8a39f0a0d42f1652a3c4bb23200 | 3,619,147 |
def stop(M, i):
"""
Check if the algorithm converged.
:param M: input matrix
:param i: iteration steo
:return: boolean: True if converged
"""
# this saves time, so we dont have to do multiplication in the first 7 iterations
if i > 6:
M_temp = M ** 2 - M
m = M_temp.max() -... | 3fc6cec40db8e52aed6e435a5552a8cf8edb68a1 | 3,619,148 |
def getTurnHold(mouse_x, mouse_y, army):
"""Get hold on list of turn"""
x, y = getTileAtPixel(mouse_x, mouse_y)
if x is not None and y is not None:
direction = getDirectionByPosition(x, y, army)
if direction == UP:
return [[x, y], [x + 1, y], [x - 1, y]]
elif direction ==... | 8e42918447bdc9a7c9346f2f9ccdff439729fcb2 | 3,619,149 |
def sorted_binop_expected_locs(binop_expected_locs):
"""Sorted expected locs when used in tests for sample generation."""
sort_by = attrgetter("lineno", "col_offset", "end_lineno", "end_col_offset")
return sorted(binop_expected_locs, key=sort_by) | 69ea0263716469f50ec4819deb1c1c9f87b11165 | 3,619,150 |
def InrecaMoreIsBetter(caseAttrib, queryValue, jump, weight):
"""
Returns the similarity of two numbers following the INRECA - More is better formula.
"""
try:
queryValue = float(queryValue)
# build query string
queryFnc = {
"function_score": {
"query": {
"match_all": {}
},
"script_score... | 3488ae92e463cdd2baae917e25d91415a44d5ec5 | 3,619,151 |
def sigmoid_prime(x: Tensor) -> Tensor:
"""
Derivation of the sigmoid activation function.
derivation:
f'(x) = f(x) * (1 - f(x))
Args:
x (:obj:`Tensor`): input to the function
Returns:
:obj:`Tensor`: f'(x), applies derivation of activation function
"""
return sigm... | 2d7e4328f29b50225047ccc5dd8f9c527153cef4 | 3,619,152 |
def process_xml(xml_sitemap, regex):
""" extract links from xml """
site_map_paths = set([])
url_paths = set([])
try:
# need to strip namespaces
ns_stripped = ET.iterparse(StringIO(xml_sitemap))
for _, element in ns_stripped:
if '}' in element.tag:
ele... | 848d92e48ec31584f68b43386601d953a84acf2e | 3,619,153 |
def lvar (inlist):
"""
Returns the variance of the values in the passed list using N-1
for the denominator (i.e., for estimating population variance).
Usage: lvar(inlist)
"""
n = len(inlist)
mn = mean(inlist)
deviations = [0]*len(inlist)
for i in range(len(inlist)):
deviations[i] = inlist... | 9ba4b6405569271eab39e4f49bc285a2efc51376 | 3,619,154 |
def glove_embeddings(text_data, vids, paddings=50):
"""Get glove embeddings of text, video pairs.
Args:
text_data (list): list of text data.
vids (list): list of video data
paddings (int, optional): Amount to left-pad data if it's less than some size. Defaults to 50.
Returns:
... | cca30d5509a685368dc24c02811832a898dceb77 | 3,619,155 |
import argparse
def get_args():
""" Get command-line arguments. """
parser = argparse.ArgumentParser(
description='get extent of the given image')
parser.add_argument(
'path_img', metavar='path_img', type=str, nargs='+',
help='path of the remote sensing image (.tif)')
ret... | 1209d3b48bd05a5a5e0b7fa116c962183d8eae12 | 3,619,156 |
def sbert_encoder(text_list, pretrained_reference='distilbert-base-nli-stsb-mean-tokens'):
"""
Helper function using sentence_transformers which simplifies the embedding call
Args:
text_list (list): list of strings to embed
pretrained_reference (string, optional): the pretrained model to us... | 6ee99a2fc5a46e9cb5776ad80d004465d3d681e1 | 3,619,157 |
import sys
def find_reasonable_font():
"""Try to return system font path, or some other font"""
if sys.platform.startswith("win"):
path = "C:/Windows/Fonts/arial.ttf"
if exists(path):
return path
else:
return None
else:
with open(get_res_path("qlibs/... | c2c82b29362a5f0a3da7bb7879e3d18db3844888 | 3,619,158 |
def check_pipeline_config(cfg, pure_pipelines):
"""
Check pipeline configuration, displaying a message in the Notebook
for every problem found. Returns whether the configuration is
usable at all.
"""
(okay, messages) = cfg.is_valid(pure_pipelines=pure_pipelines)
for msg in messages:
... | add7a8dcaa8e857f2b663188ddc2f067b145b728 | 3,619,159 |
def swapAMP(oldAMP, newAMP):
"""
Swap delivery of messages from an old L{AMP} instance to a new one.
This is useful for implementors of L{StoreSpawnerService} since they will
typically want to create one protocol for initializing the store, and
another for processing application commands.
@par... | cf47e038be3b2c89ab9e6f23777cd6b39d073c20 | 3,619,160 |
def get_effective_reminder_time():
""" Isolate this particular use of now() so that the effective reminder time is
practical to patch within tests.
"""
return now() | 510915a3da1914c87da1894439b791a815eccf8e | 3,619,161 |
from datetime import datetime
def do_pack():
"""generates a tgz archive"""
try:
date = datetime.now().strftime("%Y%m%d%H%M%S")
if isdir("versions") is False:
local("mkdir versions")
file_name = "versions/web_static_{}.tgz".format(date)
local("tar -cvzf {} web_static... | 3be153bdf8057e4ef7d780a39127bbd21319aaa4 | 3,619,162 |
def jaccard(box_a, box_b):
"""Compute the jaccard overlap of two sets of boxes.
Args:
box_a: (tensor) Ground truth bounding boxes, Shape: [num_objects,4]
box_b: (tensor) Prior boxes from priorbox layers, Shape: [num_priors,4]
Return:
jaccard overlap: (tensor) Shape: [box_a.size(0), b... | e38e2a52f9fe09ca684f22dbbaf5b65fd39c62ee | 3,619,163 |
def show_states_func(sp):
"""Function returning states for each frame
"""
E0 = sp.params["E0"]
dE = sp.params["dE"]
omega = sp.params["omega"]
return [[E0,"--k"], [E0+dE, "--b"], [E0+dE-omega, "--r"]] | b7d426682c324b08d622efd202b8d5cdf78336cd | 3,619,164 |
def pack_images( images ):
"""Returns the packed images (all of same size)"""
width = images[0].size[0]
height = images[0].size[1]
out_width = min([len(images), 10]) * width
out_height = ((len(images)-1) / 10 + 1) * height
out_image = Image.new("RGBA", (out_width,out_height))
x = 0
y... | 8c55e5646cbb31acd714a809b4f2c8f9f9d2aa97 | 3,619,165 |
import itertools
def makeDelayedFunctionCall(func, args, kwargs):
"""Utility function for creating a lazily-evaluated function call."""
props = set().union(*(requiredProperties(arg)
for arg in itertools.chain(args, kwargs.values())))
def value(context):
subvalues = (valueInContext(arg, con... | 001a63b7b3ec61f8b8bff875e6a22445ac31dbd3 | 3,619,166 |
def elina_scalar_cmp_int(scalar, b):
"""
Compare an ElinaScalar to a double.
Parameters
-----------
scalar : ElinaScalarPtr
Pointer to the ElinaScalar that needs to be compared.
b : c_int
Integer to be compared.
Returns
-------
result : c_int
The res... | 6429bb3d9b7c4dc8c455b175139b2e12116777e8 | 3,619,167 |
import json
def get_budget_entries(request):
"""returns budgets with the given id
"""
logger.debug("get_budget_entries starts")
budget_id = request.matchdict.get('id', -1)
budget = Budget.query.filter(Budget.id == budget_id).first()
if not budget:
transaction.abort()
return Re... | c7b603ed8daaec1166934ab01004d986c054d3b1 | 3,619,168 |
import os
def desktop():
"""
This function returns the full path to the desktop directory
:return:
"""
return os.path.expanduser("~/Desktop") | c9b26b4a329a3ea7811717bd6754de6a8936cebf | 3,619,169 |
def get_extra_idx(metric):
"""Collects the extra indexes added by Operations for the metric tree.
Args:
metric: A Metric instance.
Returns:
A tuple of column names which are just the index of metric.compute_on(df).
"""
extra_idx = metric.extra_index[:]
children_idx = [
get_extra_idx(c) for c... | d3d90bccc9fd13d4fbfdc13893b29d14a82b09cf | 3,619,170 |
def yuv444to420p(img: np.ndarray, inter=cv2.INTER_LINEAR) -> np.ndarray:
"""
yuv444转420p,可自定义方法
:param img: 图像
:param inter: 插值方法
:return: 一维数组
"""
[y, u, v] = img.astype(np.uint8).transpose((2, 0, 1))
w, h = y.shape[1] >> 1, y.shape[0] >> 1
u, v = resize(u, w, h, inter), resize(v, w... | c9a3749c63a0adc4ded13208c853c6c3734a4d30 | 3,619,171 |
import math
def compute_rotation_matrix(w, phi, k, degrees=False):
"""
Computes Rotation matrix from the rotation angle w, phi, k
related to x, y and z.
Returns
-------
r_matrix: Rotational Matrix M
[cos(phi)cos(k) sin(w)sin(phi)cos(k)+cos(w)sin(k) -cos(w)sin(phi)cos(k)+sin(w)sin(... | d8a8c257f7b8c7ab3baead84e1e546274875b829 | 3,619,172 |
def iuwt_decomposition(in1, scale_count, scale_adjust, store_smoothed):
"""
This function calls the a trous algorithm code to decompose the input into its wavelet coefficients. This is
the isotropic undecimated wavelet transform implemented for a single CPU core.
INPUTS:
in1 (no def... | 5a3fdc9be644902e403fce12fd15193a3cc65ef3 | 3,619,173 |
def _album_candidates(items, artist, album, va_likely):
"""Search for album matches. ``items`` is a list of Item objects
that make up the album. ``artist`` and ``album`` are the respective
names (strings), which may be derived from the item list or may be
entered by the user. ``va_likely`` is a boolean ... | 60408c0949be952a3e4e6cab512a5416b2201c60 | 3,619,174 |
def create_disk_v3_onion_service(onion_service_dir, tor_control_port, client_pub_key,
port, ip_address="127.0.0.1", client_name=None):
"""Creates a permanent Tor v3 Onion Service.
Args:
onion_service_dir: A pathlib object containing the path to the Tor Onion Service dir... | cffee272c64ee7a8f48d142309327122ac7a5c53 | 3,619,175 |
def machine_available():
""" Display an input, validate the client choice and returns the corresponding choice. """
client_choice = input(f"What would you like? ({menu_object.get_items()}):").lower()
if client_choice in menu_object.get_items():
menu_item = menu_object.find_drink(client_choice)
... | 3a11cafa4d62c35abc735e9ae1eececbc12c8fec | 3,619,176 |
def strict_type_hints(func):
"""
Enforce type hints on the parameters and return types of the decorated
function.
Also require type hints to be provided for all parmeters and the return
value.
"""
return EnforceTypeHints(func, require_args=True, require_return=True) | 99b341dd8d2015787274185dd51bace79d0aa420 | 3,619,177 |
import zipfile
import sys
import os
import stat
def extract_zip(filename):
"""
Uses zipfile package to extract a single zipfile
:param filename:
:return: new filename
"""
try:
file = zipfile.ZipFile(filename, 'r')
except FileNotFoundError:
puts(colored.red(f"{filename} Does... | 03b07ca1ab109da085dd3ac6a777d57cb556aa7f | 3,619,178 |
def initializeCentroids(points, k):
"""returns k centroids from the initial points"""
centroids = points.copy()
np.random.shuffle(centroids)
return centroids[:k] | 54176cef35fbf305edb245c15262705d75f9556c | 3,619,179 |
def split_text(text, sep='\n'):
"""Split text."""
if isinstance(text, bytes):
text = text.decode("utf8")
return [elm.strip() for elm in text.split(sep) if elm.strip()] | 5247919ab151b2e4d1b4e631046d7030e673a68a | 3,619,180 |
import yaml
import logging
def parse_config(configfile='config.yml'):
"""
Loads the config file
Arguments:
- configfile: File to parse, default config.yml
Returns:
Configuration dict
Raises:
YAMLError if config file is not a valid YML
... | 4369bcd1998980cb4b2557b017462a74d3b7bdae | 3,619,181 |
def fit_linear_models(train_embs, train_labels, val_embs, val_labels,
model_type='svm'):
"""Fit Log Regression and SVM Models."""
if model_type == 'linear':
_, train_acc, val_acc = fit_linear_model(train_embs, train_labels,
val_embs, val_labels)... | dded20d9d6ce748868e16f6f6bf7d364460cc421 | 3,619,182 |
import sys
import os
def make_pip_cmd(pip_args, constraint_file_path):
"""Inject a lockfile constraint into the pip command if present.
:param pip_args: pip arguments.
:param constraint_file_path: Path to a ``constraints.txt``-compatible file.
:returns: pip command.
"""
pip_cmd = [sys.execut... | 354b9da696a69d3b0736b55efb95a3a675120390 | 3,619,183 |
from subprocess import call
import time
def GetWindowsProcesses_method2():
"""
Gets list of windows processes using BAT file
"""
batFile = 'GETWINPROCESS.BAT'
print('creating BAT file - ' + batFile)
with open(batFile,'w') as f:
cols = 'description,WorkingSetSize,PrivatePageCount... | f3b5554823eb5433caf307a799225a28a4831c16 | 3,619,184 |
def jwt_get_secret_key(payload=None):
"""
For enchanced security you may use secret key on user itself.
This way you have an option to logout only this user if:
- token is compromised
- password is changed
- etc.
"""
User = get_user_model() # noqa
if api_settings.JWT_GET... | f330a766386a69c729d14225defa9a78b3617b9c | 3,619,185 |
async def api_will_snow():
"""Find out if it will snow in Berlin soon."""
wx = await get_weather()
return {"willSnow": will_snow(wx), "dataUpdated": wx["currently"]["time"]} | 4b8f5d15c4124dd2dd31a0ad411487e29b97554a | 3,619,186 |
import os
def write_csv(df, **kwargs):
"""
write csv
:param df:
:param kwargs: file_name: file name
file_path: file path
sep: sep
path_or_buf: path or buffer
header: ['A', 'B']
ind... | ac98530b24c48dae9abc79e021a32f274a57f3e6 | 3,619,187 |
def run(args):
"""Partition command. Prepares models from the specified module for partitioning"""
names = []
mod = args['module']
try:
mod_clss = filter(lambda obj: isinstance(obj, type), __import__(mod, fromlist=mod).__dict__.values())
except ImportError as e:
raise ImportProblemE... | bb84d6423e3a08d222e57fe7052fc94d759ca159 | 3,619,188 |
import yaml
def get_available_configs(config_file_path):
"""Retrieves all of the exiting configurations.
Args:
config_file_path: str, the name or the full path of the config file.
Returns:
A list of available config keys.
"""
with open(_get_config_file_path(config_file_path)) as config_file:
c... | 01660a829d3d4cbfbbf19d9e4fcd060f206535a5 | 3,619,189 |
import logging
import os
import sys
def run_as_admin(function):
"""check if we're admin, and if not relaunch the script as admin.""",
rc = 0
if not isUserAdmin():
logging.warning("Access Denied - Admin Priveleges Required.", os.getpid(), "params: ", sys.argv)
rc = runAsAdmin()
exit... | 11407ca889cefdf1aa60752e82f06614ce365901 | 3,619,190 |
from . import search
def create_app(test_config=None) -> Flask:
"""Main entry point of the service. The application factory is responsible for
creating and confguring the flask app. It also defines a http ping endpoint and registers blueprints.
Returns:
Flask: the flask app
"""
app = Flas... | e812d285fa09fb74b39083b571014989ccb0b5dd | 3,619,191 |
def dir_is_git_repo(path: str) -> bool:
"""Check if directory is a Git repository.
Args:
path: (str) path to directory.
Returns:
bool: True if successful, False otherwise.
"""
try:
Repo(path)
except InvalidGitRepositoryError:
return False
return True | 05eb624680ce9d7be5cf10644f8f8602b7b600ee | 3,619,192 |
from typing import Sequence
def to_vertices_sequence(points: Sequence[Point[Scalar]],
size: int,
context: Context) -> Sequence[Point[Scalar]]:
"""
Based on chi-algorithm by M. Duckham et al.
Time complexity:
``O(len(points) * log len(points))``
... | e69297f3aba5b7daa22951cba0662e46d5a0a608 | 3,619,193 |
import re
def replace_image_link(target_str):
"""
Replace the shorthand of an image link { image.jpg } with the full link {{ img_tag("image.jpg") | safe }}
:param target_str: String with images in it to be edited
:return: string with images formatted as {{ img_tag("image.jpg") | safe }}
"""
# ... | d72cbaacecec7d2654a20f50098f21059130dbc3 | 3,619,194 |
def ST_Affinediffeo_transformer_batch(U, thetas, out_size):
""" Batch version of the diffeomorphic affine transformer. Applies a batch
of affine transformations to each image in U.
Arguments:
U: 4D-`Tensor` [n_batch, height, width, n_channels]. Input images to
transform.
... | 4097d285223b9a9393a698f22f3c004aafb5edc4 | 3,619,195 |
import scipy.optimize
import esutil
def histoGauss(ax,array):
"""
Plot a histogram and fit a Gaussian to it. Modeled after IDL histogauss.pro.
parameters
----------
ax: Plot axis object
If None, return coefficients but do not plot
array: float array to plot
returns
-------
... | ac05c1dd642cf7102e454ded008c32db008103d3 | 3,619,196 |
from typing import Optional
def _maybe_get_mask(
values: np.ndarray, skipna: bool, mask: Optional[np.ndarray]
) -> Optional[np.ndarray]:
"""
Compute a mask if and only if necessary.
This function will compute a mask iff it is necessary. Otherwise,
return the provided mask (potentially None) when ... | d905dbecef3358e3e6f80edff8a8e72b2d1af2de | 3,619,197 |
def create_option(option, display, window, active=True):
"""
Returns an option `dict` to be used by lottus
:param option `str`: the value of the option
:param option `str`: the value that will be displayed
:param window `str`: the name of the window that this option points to
... | 31eb71dee85a7876997d4b41914f974cbcfcf938 | 3,619,198 |
import os
import shutil
import re
def fetch_ts(data_dir, clean=False):
"""
convenience function to read in new data
uses csv to load quickly
use clean=True when you want to re-create the files
"""
ts_data_dir = os.path.join(data_dir,"ts-data")
if clean:
shutil.rmtree(ts_data_... | 53051afe230476c93df7b102a190e6350de807f9 | 3,619,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.