content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import json
def read_json_vectors(filename):
"""Return np array of vectors from json sources"""
vectors = []
with open(filename) as json_file:
json_data = json.load(json_file)
for v in json_data:
vectors.append(v)
print("Read {} vectors from {}".format(len(vectors), filename))
... | 04010096dda8b210fad260ef955ce3c5c393e51a | 35,100 |
from lmfit import Parameters, minimize
from typing import Pattern
def optimize_density_and_bkg_scaling(data_pattern, bkg_pattern, composition,
initial_density, initial_bkg_scaling, r_cutoff, iterations=2,
use_modification_fcn=False):
"""
... | 281c1ec6c57854fcc703ca9d4f1b364cea9ccf98 | 35,101 |
import sys
def get_error_hint(ctx, opts, exc):
"""Get a hint to show to the user (if any)."""
module = sys.modules[__name__]
get_specific_error_hint = (
getattr(module, 'get_%s_error_hint' % exc.status, None))
if get_specific_error_hint:
return get_specific_error_hint(ctx, opts, exc)
... | 5dad7b9a0c35170ae83efcbc076b2b9f4b3dd1d8 | 35,102 |
def detail(root, name, my, request, actie="", msg=""):
"""bouw het scherm met actiegegevens op.
de soort user wordt meegegeven aan het scherm om indien nodig wijzigen onmogelijk te
maken en diverse knoppen te verbergen.
"""
## msg = request.GET.get("msg", "")
if not msg:
if request.u... | fd53b4ed2bb860ce20d8c7a6474c6effe5b33a71 | 35,103 |
def define_areas(
pixel_filtered_map: np.ndarray, district_heating_zone_threshold: float
):
"""
This function defines areas where the sum of the pixel values for a given
area exceeds a certain threshold.
Inputs :
* pixel_filtered_map : pixel filtered map (MWh).
* district_heating_zo... | 67d4f4418e5fd456f12454a6de81840da5e8cb39 | 35,104 |
def get_relation(filename):
"""read relation file, return rel2idx"""
rel2idx = {}
f = open(filename, 'r')
lines = f.readlines()
for (n, rel) in enumerate(lines):
rel = rel.strip().lower()
rel2idx[rel] = n
f.close()
return rel2idx | 1c239ec3343cf63e502bf9de485171c9a346e240 | 35,105 |
def id_for_base(val):
"""Return an id for a param set."""
if val is None:
return "No base params"
if "editor-command" in val:
return "Long base params"
if "ecmd" in val:
return "Short base params"
return "Unknown base params" | ecf54fa40195ba4de7db13874e44388a04527bed | 35,106 |
import math
def __bilinear(lat, lon, table):
"""Return bilinear interpolated data from table"""
try:
lat = float(lat)
lon = float(lon)
except ValueError:
return ''
if _non_finite(lat) or _non_finite(lon):
return ''
if math.fabs(lat) > 90 or math.fabs(lon) > 180:
... | 83a665437e4391fd44c87aa8b4631c63c0da4756 | 35,107 |
def serialize_serializable(obj, spec, ctx):
""" Serialize any class that defines a ``serialize`` method. """
return obj.serafin_serialize(spec, ctx) | 936c3b51257c60c156cd9686e38b09ec55a929f2 | 35,108 |
import time
import torch
def train_baseline(train_loader, model, criterion, optimizer, epoch):
"""
:param train_loader: data loader with training images
:param model: model used for training
:param criterion: loss function
:param optimizer: optimizer
:param epoch: current training epoch
:r... | ccac87a4e7a9d43fd5f5f85f00ab4cf797c23def | 35,109 |
def best_match(supported, header):
"""Return mime-type with the highest quality ('q') from list of candidates.
Takes a list of supported mime-types and finds the best match for all the
media-ranges listed in header. The value of header must be a string that
conforms to the format of the HTTP Accept: he... | b7774bcce984dce5d55b5351218ec71163fc5032 | 35,110 |
def hourly_median(hours, series, all_hours=True):
"""
Calculate hourly binned medians of a time series.
Parameters
----------
hours : array_like
Time series of the hour number. Must be of the same length as `series`.
series : array_like
Time series of the data.
all_hours : b... | 7712b425e9445a520eda6bcc8cc18a6ac8274de4 | 35,111 |
def is_orthonormal_direct(basis):
"""
Returns True if the basis is orthonormal and direct:
Parameters
----------
basis
Returns
-------
"""
return is_orthonormal(basis) and np.allclose(
np.cross(basis[0, :], basis[1, :]), basis[2, :]
) | d58f5f9c30ea82d52fd6444febf0515fb99a9147 | 35,112 |
def matlab_style_gauss2D(shape=(3, 3), sigma=0.5):
"""
2D gaussian mask - should give the same result as MATLAB's fspecial('gaussian',[shape],[sigma])
Acknowledgement : https://stackoverflow.com/questions/17190649/how-to-obtain-a-gaussian-filter-in-python (Author@ali_m)
"""
m, n = [(ss - 1.) / 2. fo... | 4be8f129fd7063bc959802e206782bee46310dae | 35,113 |
def triangle2str(idx, triangle):
"""
converts a triangle to a string
"""
return f"shapes[{idx}] = makeShape(" + \
f"materials[{triangle['matid']}]," + \
f"makeTriangle({vec32str(triangle['a'])}," + \
f"{vec32str(triangle['b'])}," + \
f"{vec32str(triangle['c'])}));" | 13761396602855bf38901f5eef365f0bbc2592bf | 35,114 |
import socket
def get_hosts_from_yaml(test_yaml, args, key_match=None):
"""Extract the list of hosts from the test yaml file.
This host will be included in the list if no clients are explicitly called
out in the test's yaml file.
Args:
test_yaml (str): test yaml file
args (argparse.N... | 4dce69fe52769972c396208859d9cc5cfe4cf64a | 35,115 |
def parse_labels_mapping(s):
"""
Parse the mapping between a label type and it's feature map.
For instance:
'0;1;2;3' -> [0, 1, 2, 3]
'0+2;3' -> [0, None, 0, 1]
'3;0+2;1' -> [1, 2, 1, 0]
"""
if len(s) > 0:
split = [[int(y) for y in x.split('+')] for x in s.split(';')]
e... | d2f77876f1759e6d4093afc720e7631f1b4d9ff4 | 35,116 |
from typing import Optional
from typing import Any
from typing import Dict
def sraa_eedi3(clip: vs.VideoNode, rep: Optional[int] = None, **eedi3_args: Any)-> vs.VideoNode:
"""Drop half the field with eedi3+nnedi3 and interpolate them.
Args:
clip (vs.VideoNode): Source clip.
rep (Optional[int]... | 24f5bcaedbd16fe0feabfb589fdf4244554888ae | 35,117 |
from typing import Any
import dataclasses
def _is_nested(x: Any) -> bool:
"""Returns whether a value is nested."""
return isinstance(x, dict) or dataclasses.is_dataclass(x) | 798000adfd8eb900b61be988ab6a31e1b062540d | 35,118 |
import math
def pedel(lsize, seq_len, mps, dist_fx=poisson):
"""
Pedel calculates library diversity given library size and mutational load.
For poisson distribution use poisson (default).
For pcr distribution, use first pcr_distribution_factory(efficiency, cycles) to obtain a function specific to thos... | d5f75a1032272961a407dc7f02292e3095966281 | 35,119 |
def contains_pept(name):
"""Checks if the saccharide name contains the peptide fragment,
such as EES, GS, SA etc"""
contains_pept = False
for pept_stub_name in ('_E', '_G', '_S', '_A'):
if (pept_stub_name in name) and ('_NRE' not in name):
contains_pept = True
return contains... | 937679a96b21766e96eb455baca51c1695412287 | 35,120 |
import torch
def check_stacked_complex(data: torch.Tensor) -> torch.Tensor:
"""
Check if tensor is stacked complex (real & imag parts stacked along last dim) and convert it to a combined complex
tensor.
Args:
data: A complex valued tensor, where the size of the final dimension might be 2.
... | afce7ac1840ff64199c9ebc9f4222e1d3f09dafd | 35,121 |
def circle(x, y, a, b, width):
"""
widthで指定された直径の中に含まれているかを判定
:param x:
:param y:
:param a:
:param b:
:param width:
:return:
"""
_x = round(((x - a) ** 2), 3)
_y = round(((y - b) ** 2), 3)
_r = round(((width/2) ** 2), 3)
if (_x + _y) <= _r:
return _r - (_x + _... | fabddad9e3c404dc36e1cf1830ebcc107cf66516 | 35,122 |
def fetch_representative_points(
service_area_ids,
include_census_data,
engine=connect.create_db_engine()
):
"""
Fetch representative points for a list of service areas.
Prepares responses for use by the frontend.
"""
if not service_area_ids:
return []
query_params = {
... | daec38168159c537454d55696f6bcac72799b586 | 35,123 |
def get_most_similar(candidates, target_val, endpointService):
"""
select the entity from candidates that are most similar to the original one
ties are broken by overall popularity
"""
closest_dist = float('inf')
closest_matches = []
target_val = target_val.lower()
for cand in candidat... | 0f4c99e0ed9428160880a778385c35597732b322 | 35,124 |
def dict_remove_none(starting_seq=None, extend_chained=True, chained=None, chained_status=None):
"""
Given a target sequence, look for dictionary keys that have values of None and remove them.
By default, ``chained`` will have ``.extend()`` or ``.update()`` called on it with
``starting_seq`` as the onl... | ce43ce9cdfff92fcce329b50cf25aeb8f74b6ff5 | 35,125 |
import requests
def get_scoped_token(os_auth_url, access_token, project_id):
"""
Get a scoped token, will try all protocols if needed
"""
unscoped_token, protocol = get_unscoped_token(os_auth_url, access_token)
url = get_keystone_url(os_auth_url, "/v3/auth/tokens")
body = {
"auth": {
... | 1ebeeb09e90ae6ad6091ef2623c9be59b27a22d5 | 35,126 |
def catch_error(method):
"""Decorator to catch and handle errors on handlers"""
@wraps(method)
def wrapper(self, *args, **kwargs):
try:
return method(self, *args, **kwargs)
except Exception as e:
self.statsd.incr(self.__class__.__name__+'.error')
logger.wa... | 060764d16cd65388b93082e59df7722037bc1fe5 | 35,127 |
import os
import random
import string
import json
def create_tenant_users(no_of_users_to_create, tenant_name, cluster_name="ceph"):
"""
This function is to create n users with tenant on the cluster
Parameters:
no_of_users_to_create(int): users to create with tenant
cluster_name(char): Nam... | 36afaca5ec5e3066e8063c1a75eb9a6bb51355e4 | 35,128 |
import logging
from pathlib import Path
import os
import torchvision
import torch
def get_data(args, opts, train=True, async_dataloader=False, return_remaining=False, fine_tuning=False):
"""
A factory method to create a dataload responsible for sending data
to the IPU device. This build the appropriate da... | 6532b352645ec3235da9176fed4adcba4da3e0f4 | 35,129 |
def split_feature_class(label: str, frame: pd.DataFrame):
""" Split features and class from encode dataset. `label` is the class, and
`frame` is the dataset which has been encoded.
"""
sub_cols = [attr for attr in frame.columns if attr.startswith(label)]
if len(sub_cols) <= 1:
return frame, ... | 03cd3b4f3c2909aaf03ec8832bb7a543a6c1f789 | 35,130 |
def user_form_test(): # <dev>
"""recommender user form.
Returns:
request: dictionary (json object)
list of user's strain description
schema:
{"type_list": [""],
"effect_list": [""],
"flavor_list": [""]}
"""
return render_template("index.h... | 3f853f197ffa7d879af77a6c1777ec6f9ea394dc | 35,131 |
def bestfit_sphere_numpy(points):
"""Returns the sphere's center and radius that fits best through a set of points.
Parameters
----------
points: list of points
XYZ coordinates of the points.
Returns
-------
tuple: center, radius
sphere center (XYZ coordinates) and sphere r... | 52cee41806ef1ea7dc5c3b3c00109ab686b606cd | 35,132 |
import numpy
def absupearson(a,b,weights):
"""Distance between two points based on the pearson correlation coefficient.
By treating each data point as half of a list of ordered pairs it is
possible to caluclate the pearson correlation coefficent for the list. The
correlation coefficent is then ... | 7bc70816f96a8bd90a424eb7ca13fd291d086b06 | 35,133 |
def plot_met(data_df: pd.DataFrame, data_interp_df: pd.DataFrame, met_selection: list, scaled_conc: bool = False,
x_scale: str = 'linear', y_scale: str = 'linear', x_lim: tuple = (10 ** -10, 1), y_lim: tuple = None):
"""
Plots a given metabolite across all models in altair. Uses line plots.
Ar... | cad99c352a4c04a1a9492811bb79fa61853fb25a | 35,134 |
import sys
import os
def get_data_files():
"""Return data_files in a platform dependent manner"""
if sys.platform.startswith('linux'):
data_files = [('/usr/share/icons/hicolor/scalable/apps',
['icons/pysigview.svg']),
('/usr/share/applications',
... | 7e50de2ebd0bfe11ef34fbf86743d41b17ae1292 | 35,135 |
def get_page(db: Session, name: str) -> models.Page:
"""
Get the page with the given name.
:param db: The db session to check.
:param name: The name of the page to find.
:return: The desired page in the db, or None if DNE.
"""
return db.query(models.Page).filter(models.Page.name == name).fir... | f4fb59efe5dc68260e9a261858e77a9e946502f8 | 35,136 |
import os
def get_spider_queues(config):
"""Return a dict of Spider Queues keyed by project name"""
dbsdir = config.get('dbs_dir', 'dbs')
if not os.path.exists(dbsdir):
os.makedirs(dbsdir)
d = {}
for project in get_project_list(config):
dbpath = os.path.join(dbsdir, '%s.db' % proje... | 19d85493cb2c0dc7b63732cd21a3b032bc82a50f | 35,137 |
from typing import Tuple
def _dbms_utility_name_resolve(
connection: oracle.Connection, name: str, context: int
) -> Tuple[str, str, str, str, int, int]:
"""Wrapper for Oracle DBMS_UTILITY.NAME_RESOLVE procedure"""
with connection.cursor() as cursor:
schema = cursor.var(str)
part1 = cursor... | 43bdf191c8f7b296cbac93f9d63a405a7f0f1115 | 35,138 |
def func_call(instance: ARIA, func_name: str, command_name: str, demisto_arguments: list, args: dict):
""" Helper function used to call different demisto command
Args:
instance: An ARIA instance.
func_name: Name of the functions in the ARIA class.
command_name: Related demisto command n... | 2d55693c7df9179f4771717ed00da45ea74f2d1d | 35,139 |
def admin_role_required(f):
"""
Grant access if user is in Administrator role
"""
@wraps(f)
def decorated_function(*args, **kwargs):
if g.user.role.name != 'Administrator':
return redirect(url_for('error', code=401))
return f(*args, **kwargs)
return decorated_function | e0f67f97339af3867227f9507047e240fea43eaa | 35,140 |
def format_location_detail_tract(data):
"""Reformat the list of data to Location Detail format for tract
Args:
data (list): A list of FSF object
Returns:
A pandas formatted DataFrame
"""
df = pd.DataFrame([vars(o) for o in data])
df.rename(columns={'fsid': 'fsid_placeholder'}, i... | 3d99e5790aab8e3031494fac824dd5425acf2463 | 35,141 |
from typing import List
def pgcdDesDistancesEntreRepetitions(crypted: List[int], i: int) -> int:
"""
Returns pgcd{ }
"""
assert 0 <= i < len(crypted) - 2, "i must be in [0, len(crypted)-2)"
search_for = crypted[i:i+2+1]
current_pattern: List[int] = []
distances: List[int] = []
for i, ... | 7843c9d86f5dc0a28793cb6158261cdb9425df84 | 35,142 |
import numpy
def preprocess(simulation, field):
"""
Store DOF and geometry info that will not change unless the mesh is
updated (which is not handled in any way)
"""
mesh = simulation.data['mesh']
dofmap = field.function_space().dofmap()
conFC = simulation.data['connectivity_FC']
# Da... | 552cba3b5c092ea530f2089ec8252991349a0853 | 35,143 |
def drop_probable_entities(X):
"""
:param X: a data matrix: a list wrapping a list of strings, with each sublist being a sentence.
:return:
>>> drop_empty_lists(drop_arabic_numeric(drop_probable_entities([['Catullus'], ['C.', 'VALERIVS', 'CATVLLVS'],['1','2', '2b', '3' ],['I.', 'ad', 'Cornelium'],['Cui... | 18e21d21212d56e256fd015f9513e06b31ed1027 | 35,144 |
def wrong_obj_msg(*objs, allow="sources"):
"""return error message for wrong object type provided"""
assert len(objs) <= 1, "only max one obj allowed"
allowed = allow.split("+")
prefix = "No" if len(allowed) == 1 else "Bad"
msg = f"{prefix} {'/'.join(allowed)} provided"
if "sources" in allowed:
... | 09294ccc6da5f02718edbdc2e04c8a92f213eb4a | 35,145 |
def text2haiku(text, keep_chance=0.75, iterations=2000):
"""
Given a string of text, try to make a haiku
returns a haiku as a string or None if it fails
"""
word_list = text_to_word_list(text)
haiku = bagging_haiku_maker(word_list, keep_chance=keep_chance, iterations=iterations)
return haiku | 759e6a94698e252f2df29911700a9fa6b945e61d | 35,146 |
from cache_requests import Memoize
def test_bust_cache_reevaluates_function(redis_mock):
""":type redis_mock: mock.MagicMock"""
# LOCAL TEST HELPER
# ------------------------------------------------------------------------
def call_count():
try:
return redis_mock.get.call_count, ... | 7d61180ea48be9985f9f861777d33e95640795e6 | 35,147 |
import os
def load_housing_data(housing_path=HOUSING_PATH):
"""
Load housing data from csv into pandas dataframe
housing_path: path to the dataset
return: pandas.DataFrame
"""
# file path
csv_path = os.path.join(housing_path, "housing.csv")
#retu... | 9cb5bd92855b33b314c1154dc943bb1a4b5dfa57 | 35,148 |
from scipy.sparse import csc_matrix
def read_ccs(fname):
"""
Read a CCS matrix from file into a scipy csc matrix.
This routine uses the CCS matrix files that CheSS generates.
Args:
fname (str): name of the file.
Result:
scipy.sparse.csc_matrix: the matrix in the file.
"""
da... | 74d893eeb7176b5dfa967fe1ad009cc64e7e9a4e | 35,149 |
def demo__google_result_open_in_new_tab(raw_text, content_mime):
"""Force google search's result to open in new tab. to avoid iframe problem
在新标签页中打开google搜索结果
"""
def hexlify_to_json(ascii_str):
_buff = ''
for char in ascii_str:
if char in '\'\"<>&=':
_buff ... | 9e11f59ab66d037887c60fa0e5b636af2c5fc0c8 | 35,150 |
def to_location_via_telescope_name(self):
"""Calculate the observatory location via the telescope name.
Returns
-------
loc : `astropy.coordinates.EarthLocation`
Location of the observatory.
"""
return EarthLocation.of_site(self.to_telescope()) | 928fa0afa141dc4a974eb29ad4302b751ab4793b | 35,151 |
def mailmangle_linked(email):
"""
Weakly obfuscates an email address using JavaScript and displays it
with a mailto link. If JS not present (i.e. what's in ``<noscript>``),
displays a link to a reCAPTCHA.
"""
encoded = _encoder(
'<a href="mailto:{0}" class="email">'
'{0}'
... | b6b7a3edfd8e3f714ec3de70e428b1551f3635ac | 35,152 |
def hamiltonian(ncomp, freq, controls):
"""Assemble hf for one spin, given a detuning freq, the control amplitudes
controls, and ncomp components of the control pulse."""
nc = 2 * ncomp + 1 # number of components in hf
hf = np.zeros((nc, 2, 2), dtype=np.complex128)
for k in range(ncomp):
# ... | 50d2c938319d7f817f7272761e3c29799f7b686b | 35,153 |
def delete_database_cluster(rds_client, db_identifier):
"""Function to delete RDS instance.
Args:
rds_client (Client): AWS RDS Client object.
db_instance_identifier (str): RDS instance to delete
Returns:
bool: True if instance was deleted successfully or does not exist,
... | 6469dbb722cb5f546dedbae0a228719e068b668a | 35,154 |
def get_nbow_vecotr(word_string, label_dict):
"""
Calc nBOW vector
:param word_string:
:param label_dict:
:return:
"""
n_bow = label_dict.transform([word_string]) # nBOW vector
n_bow = n_bow.toarray().ravel()
n_bow = n_bow.astype(np.double)
n_bow /= n_bow.sum()
return n_bow | 453a0b9754aef2742aba29f1680bc9d4b99200b6 | 35,155 |
import base64
def google_audio_settings_to_mod9(google_audio_settings):
"""
Map from Google-style audio input to Mod9 TCP server-style audio
input.
Args:
google_audio_settings (dict):
Google-style audio.
Returns:
Union[str, Iterable[bytes]]:
Mod9-style aud... | 65e81e26316201e0032db68ad4cad161e93fc69b | 35,156 |
def get_sequence_lengths(sequence_batch: Array, eos_id: int) -> Array:
"""Returns the length of each one-hot sequence, including the EOS token."""
# sequence_batch.shape = (batch_size, seq_length, vocab_size)
eos_row = sequence_batch[:, :, eos_id]
eos_idx = jnp.argmax(eos_row, axis=-1) # returns first occurren... | 7db2c66c19ad08033126773d8575bac2ee62654d | 35,157 |
def create_status():
"""Post a new status.
The status should be posted as JSON using 'application/json' as
the content type. The posted JSON needs to have 3 required fields:
* user (the username)
* content
* api_key
An example of the JSON::
{
"user": "r1cky",
... | 0f5177204733b5d6d21abd452d7944abf4e9a86f | 35,158 |
def Shift(parent, shift, da_mode="nearest", constant=0.0, name=""):
"""\
Shift the input image.
:param parent: parent layer
:param shift: list of maximum absolute fraction for the horizontal and
vertical translations
:param da_mode: one of "nearest", "constant"
:param constant: fill value... | 8b7d4aa4909bab9dd937d2df03e937c87dcfcf21 | 35,159 |
def iterations_for_terms(terms):
"""
Parameters
----------
terms : int
Number of terms in the singular value expansion.
Returns
-------
Int
The number of iterations of the power method needed to produce
reasonably good image qualit for the given number of terms in th... | 4142d8325f132e16e0525c36d114dd989873870f | 35,160 |
def explained_variance(y_pred, y):
"""
Returns 1 - Var[y - y_pred] / Var[y]
"""
assert y.ndim == 1 and y_pred.ndim == 1
variance = np.var(y)
return np.nan if variance == 0 else 1 - np.var(y - y_pred) / variance | 80ea05c9d83f3d48cfe49a038b81f9712a04df16 | 35,161 |
import itertools
def get_3d_points_from_multiple_observation(candidate_sets, camera_matrixs, fundamental_matrixs, threshold_sv = 15.0):
"""
param candidate_sets : [[np.array{2}, ...], ...] list of candidate sets(list) in cameras
param camera_matrixs : np.array{ v x 3 x 4 }
return : [np.array{3}, ...] ... | 3e1171c798c0ab7f0a587d94ff262d9fafda4b8a | 35,162 |
def get_macro(macro_name):
"""
Get the configured macro
:param macro_name: The name of the macro to add
:return: The macro itself in string form
"""
return MACROS[macro_name] | 624bc6912ce1d32d68ffd11c029b6c84e2bf563f | 35,163 |
def part_1(input_data: str) -> int:
"""What do you get if you multiply your final horizontal position by your final depth?
Returns:
int: [final horizontal position * final depth]
"""
h_pos, depth = 0, 0 # Your horizontal position and depth both start at 0.
commands = parse_input(input_data)... | 4ae988405c568d8f409935dee1eb6413fc68e8a5 | 35,164 |
def preprocess_image(img, cam_values):
"""
Function to prepare image for lane extraction:
1. undistort image
2. crop a region of interest
3. convert image to hsv
4. Get binary gradient image using sobel
5. transfer binary image using the roi
Args:
img ([type]): [description]
... | b4d132144629de64c4556c9f16fa16ce9a54a23d | 35,165 |
import struct
import tqdm
def init_compress_eigerdata(
images,
mask,
md,
filename,
bad_pixel_threshold=1e15,
hot_pixel_threshold=2 ** 30,
bad_pixel_low_threshold=0,
nobytes=4,
bins=1,
with_pickle=True,
reverse=True,
rot90=False,
direct_load_data=False,
data_path... | 71d60adabb48e1b6566e7888dbeca06d54647d88 | 35,166 |
import re
def parseTomEval(inFile, strand):
"""parse the tomtotm.txt file and return a dict of e-values between motifs """
#dict between query and target Ids
matchDict = {}
#read the tomtom.txt file and see if any known are found
with open(inFile, 'rb') as handler:
for line in handler:
line = line.strip()
... | d9394111d35444199f93bf97e7de606d919b9bb3 | 35,167 |
from typing import Dict
from typing import Union
from pathlib import Path
import tqdm
import warnings
def prepare_peoples_speech(
corpus_dir: Pathlike,
output_dir: Pathlike,
) -> Dict[str, Union[RecordingSet, SupervisionSet]]:
"""
Prepare :class:`~lhotse.RecordingSet` and :class:`~lhotse.SupervisionSe... | 48605c9511824a5fbe0e130fa4df0368228a8d0a | 35,168 |
def process_edit_distances(mx, reference_counter, reference_values, search_values):
"""Extract search values that has minimum edit distance from reference values. Multiple hits are enabled."""
min_distances = mx.min(axis=1)
matches = []
for i in range(mx.shape[0]):
min_dist = min_distances[i]
... | 87ea6d8adfd6810c8aa56eb248bb3126acf25022 | 35,169 |
def get_jobs():
"""Get a list of jobs"""
query = "SELECT * FROM urls"
result = db.execute(query)
return jsonify(result) | 03b2987a8a11c88b493c6e6e435434b96e0741db | 35,170 |
def get_leaf_nodes(struct):
""" Get the list of leaf nodes.
"""
leaf_list = []
for idx, node in enumerate(struct):
if node['is_leaf']:
leaf_list.append(idx)
return leaf_list | 90c66e49bac0c49ef5d2c75b4c1cbe6f4fdd4b83 | 35,171 |
def cg_build_w_env(A, B, i):
""" Build the environment for constructing the ith HOTRG isometry
for A and B.
"""
A_indices1 = [1,2,3,4,5,-11]
A_indices2 = [1,2,3,4,5,-12]
A_indices1[i] = -1
A_indices2[i] = -2
A2 = ncon((A, A.conjugate()), (A_indices1, A_indices2))
B_indices1 = [1,2,3... | 4ea4e660dc1dc95cebcb2612c1d9a46d0d7d85ac | 35,172 |
def get_node_edge(docs, w2d_score, d2d_score):
"""
:param docs:
:param w2d_score:
:param d2d_score:
:return:
"""
wid2wnid = {}
w_id, d_idx = [], []
w_d_wnid, w_d_dnid = [], []
w_d_feat = {"score": [], 'dtype': []}
d_d_dnid1, d_d_dnid2 = [], []
d_d_feat = {"score": [], '... | 40e4d0a11fdd671971319ae8d463ad94a7e3ca9a | 35,173 |
def get_elixier_org_by_id_local(id_local):
""" ..liefert den zu id_local passenden Datensatz """
items = DmsElixierOrg.objects.filter(id_local=id_local)
if len(items) > 0:
return items[0]
else:
return None | fdecff1dbc8cda34da994b87fb197b1c88515a75 | 35,174 |
def nearest_approach_to_any_vehicle(traj, vehicles):
"""
Calculates the closest distance to any vehicle during a trajectory.
"""
closest = 999999
for v in vehicles.values():
d = nearest_approach(traj, v)
if d < closest:
closest = d
return closest | de09f23d0886f48ce34c455a41f12c0bb435d216 | 35,175 |
def getAllQuery():
""" This will get all the records in the userQuery table
"""
rows = []
with engine.begin() as conn:
sel = userQuery.select()
rows = conn.execute(sel).fetchall()
return rows | d7800ea523877e930f7e0e0d4c4d70e70ad608ca | 35,176 |
def testingParameters(cal_file = None):
"""
Create a Spliner parameters object.
"""
params = parameters.ParametersSpliner()
params.setAttr("max_frame", "int", -1)
params.setAttr("start_frame", "int", -1)
params.setAttr("background_sigma", "float", 8.0)
if cal_file is not None:... | fbd5c4a20ce036274bf221d4fb9e16933b94d332 | 35,177 |
def fetch_labels(k, kmeans_history, offset=-1):
"""This fetches the original edges of a hierarchical mean.
"""
labels = kmeans_history[1]
passes = labels.shape[0]
indices = np.array([k])
for i in range(offset, -(passes + 1), -1):
try:
indices = np.array([np.nonzero(labels[i]... | b6752505be9cd6b2c849a79ef9e7f9ef6528651f | 35,178 |
def _reshape(t: 'Tensor', shape) -> 'Tensor':
"""
Also see
---------
:param t:
:param shape:
:return:
"""
data = t.data.reshape(shape)
requires_grad = t.requires_grad
if requires_grad:
def grad_f(grad: 'np.ndarray') -> 'np.ndarray':
return grad.reshape(t.s... | 46677d4bbe6fb384fa1759b8c7e08ae481bba5e7 | 35,179 |
from datetime import datetime
def get_target_month(month_count, utc_now=None):
"""
Return datetime object for number of *full* months older than
`month_count` from now, or `utc_now`, if provided.
:arg month_count: Number of *full* months
:arg utc_now: Used for testing. Overrides current time wit... | c2a8f79add91cb176d537cf7a523f70d8c3ec2c2 | 35,180 |
from datetime import datetime
def mark_notifications_read(db: orm.Session = Depends(get_db)):
"""Mark all the notifications as read
Returns:
List of schema.Notification: A list of all the notifications updated to read
"""
notifications = db.query(model.Notification).all()
for notifi... | bb659f1d5676c9442aba4a0bc00c810f51493bad | 35,181 |
import copy
def created_task(result, status=202, mimetype='application/vnd.task-v1+json',
headers={}):
"""
Created response for celery result by creating a task representation and
adding a link header.
:param result:
:type result: AsyncResult
:param status: Http status code. ... | ef56fdb129585e5b078bc20a0a449204c75705d7 | 35,182 |
def _get_dir_list(names):
"""This function obtains a list of all "named"-directory [name1-yes_name2-no, name1-no_name2-yes, etc]
The list's building occurs dynamically, depending on your list of names (and its order) in config.yaml.
The entire algorithm is described in "img" in the root directory and in th... | 284c328878c2c8d0e0ae273c140798e2884ef13f | 35,183 |
def mapCardToImagePath(card):
"""
Given a card, return the relative path to its image
"""
if card == "01c":
return 'src/imgs/2C.png'
if card == "02c":
return 'src/imgs/3C.png'
if card == "03c":
return 'src/imgs/4C.png'
if card == "04c":
return 'src/imgs/5C.png... | f2a8d4918b26617335a274a536a0569c845cb526 | 35,184 |
from typing import Optional
def update_partition(chain_parent_in: list, job_id: str, partition_name: str) -> Optional[dict]:
"""
NOTE: This task is part of a chain(). At very first, it is evaluated if the previous tasks contain any errors.
:param chain_parent_in: Output of parent task.
:param job_id:
... | 72aa1ba409cb83d179cc178daad7677db6f17504 | 35,185 |
import os
import yaml
def get_config():
"""Read config file and return Python dictionary"""
config_file = os.environ.get(config_environ) or default_path
with open(config_file) as f:
config = yaml.load(f)
return config | 1ce7b5d2f30a4cf48839674885c82f19f1142f33 | 35,186 |
def consolidate_gauge(df):
""" takes in gauge columns and normalizes them all to stiches per inch """
try:
df['gauge_per_inch'] = df.loc[:,'gauge']/df.loc[:,'gauge_divisor']
except:
print("Error occured when consolidating gauge")
return df | a3a1eecec97b521c19bc50f2d1496f1aba9fbce6 | 35,187 |
import time
def parse_data(driver):
"""Return a float of the current price given the driver open to the TMX page of the specific symbol."""
# The driver needs time to load the page before it can be parsed.
time.sleep(5)
content_obj = driver.find_element(by="id", value="root")
content_text = conten... | 289a71909753278336c414a0b3c3854aeb60b05f | 35,188 |
def grab_images_and_videos(adir):
"""Grabs image and video files
Args:
adir: directory with images
Returns:
files: image and video files
"""
return grab_images(adir) + grab_videos(adir) | 6acf0559c8e26dde8b179e170693210bc72b43de | 35,189 |
def get_docstring(
node: AST,
strict: bool = False,
) -> tuple[str | None, int | None, int | None]:
"""Extract a docstring.
Parameters:
node: The node to extract the docstring from.
strict: Whether to skip searching the body (functions).
Returns:
A tuple with the value and ... | 5e1d7f8f10053f09df528399f49d78581cd58adf | 35,190 |
def _get_default_siaf(instrument, aper_name):
"""
Create instance of pysiaf for the input instrument and aperture
to be used later to pull SIAF values like distortion polynomial
coefficients and rotation.
Parameters
----------
instrument : str
The name of the instrument
aper_nam... | d0b4d72d8bd1323521552452a8531a5339c26f56 | 35,191 |
def add_shift_steps_unbalanced(
im_label_list_all, shift_step=0):
"""
Appends a fixed shift step to each large image (ROI)
Args:
im_label_list_all - list of tuples of [(impath, lblpath),]
Returns:
im_label_list_all but with an added element to each tuple (shift step)
"""
... | 63fc45bc14e54ec5af473ec955bd45602f3c7041 | 35,192 |
def load_img_embeddings(source_file):
""" Load image embeddings saved as pickle file
:param source_file: The pickle file where the embeddings are stored
:return: a list of image embeddings
"""
img_embeddings = load_pickle_file(source_file)
img_embed = list(img_embeddings.values())
img_embed... | 775b965d9b90a4aed4e5d68658d9877ca3a24c81 | 35,193 |
def are_aabb_colliding(a, b):
"""
Return True if given AABB are colliding.
:param AABBCollider a: AABB a
:param AABBCollider b: AABB b
:return: True if AABB are colliding
:rtype bool:
"""
a_min = [a.center[i] - a.size3[i] / 2 for i in range(3)]
a_max = [a.center[i] + a.size3[i] / 2 for i in range(3)]
b_min ... | e4d3174cbde1bcffb8e43a710ad2434fb9e4e783 | 35,194 |
def edit_distance(str1, str2):
"""
Given two sequences, return the edit distance normalized by the max length.
"""
matrix = [[i + j for j in range(len(str2) + 1)] for i in range(len(str1) + 1)]
for i in range(1, len(str1) + 1):
for j in range(1, len(str2) + 1):
if (str1[i - 1] ==... | df8f2b5cd6ef2b20c9f8440fe2f65cc0a6185fcf | 35,195 |
import logging
def scoped_logger(module_name: str, config_name: str = "maestral") -> logging.Logger:
"""
Returns a logger for the module ``module_name``, scoped to the given config.
:param module_name: Module name.
:param config_name: Config name.
:returns: Logger instances scoped to the config.
... | 30bf30f1502ad4b89ed2ef0dc006aa12f1db0bff | 35,196 |
def parse (line):
"""Parse line into an array of numbers (`EMPTY`, `OCCUPIED`, or `FLOOR`)
for each spot in the seatring area.
"""
return [ CharToInt[c] for c in line.strip() ] | 708a446fb24e595fb4d8fd7b096543f3a56af1e0 | 35,197 |
def aic(X, k, likelihood_func):
"""Akaike information criterion.
Args:
X (np.ndarray): Data to fit on.
k (int): Free parameters.
likelihood_func (function): Log likelihood function that takes X as input.
"""
return 2 * k - 2 * likelihood_func(X) | 18ec376d15bdb8190818730b4676febdc01bd476 | 35,198 |
from typing import Callable
from typing import Any
def lazy_formatter_gettext(
string: str, lazy_formatter: Callable[[str], str], **variables: Any
) -> LazyString:
"""Formats a lazy_gettext string with a custom function
Example::
def custom_formatter(string: str) -> str:
if current_a... | d9a1a88a146443ba7b4d8b2dc114a4f613128573 | 35,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.