content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def About(parent):
"""Display the about SPPAS dialog.
:author: Brigitte Bigi
:organization: Laboratoire Parole et Langage, Aix-en-Provence, France
:contact: develop@sppas.org
:license: GPL, v3
:copyright: Copyright (C) 2011-2018 Brigitte Bigi
:param parent: (wx.Window)
... | 9ffb3c7adcd237a9efec4a748a59352d25105386 | 3,613,500 |
import os
import json
def load_fold_indices(path):
"""Load the stard and end indices of the test set for every fold."""
filename = os.path.join(path, 'dataset_fold_indices.json')
with open(filename, 'r') as handle:
parsed = json.load(handle)
return json.dumps(parsed['short'], indent=4) | 9408eef31d38c11a63faa544a59d6ef7fef8e7ce | 3,613,501 |
from typing import List
from typing import Tuple
from typing import Optional
from typing import Dict
from typing import Any
import platform
def _map_remote_share(share_system_name: str = None, share_user: str = None,
share_pass: str = None, share_location_format_str: str = None,
... | 194d88089bc5a846abdd6ad70ed1d2a13d07842d | 3,613,502 |
def default_formatter(route_docs):
"""
解析所有路由中方法的doc成为字典
in: {url_pattern:{ method:method_doc, method:method_doc }}
Return:{url_pattern:{ method:method_dict, method:method_dict }}
"""
paths_dict = dict( (up, dict()) for up in route_docs.iterkeys())
for up, method_dict in route_docs.iter... | 28a724e5e347638066fbe5227b9a6892d18d5932 | 3,613,503 |
from typing import Callable
from typing import Iterable
def values_reducer(values_fn: Callable) -> Reducer:
"""Return a reducer that just applies values_fn to its values"""
def reduce(key, values: Iterable) -> KV:
return (key, values_fn(values))
return reduce | ae61633fa7221fd71be93d117cc41ab699b3492c | 3,613,504 |
def background_subtraction_quant_function(im, spool, t, frames, quant_radius=3, quant_z_radius=1, quant_voxels=20, background_radius=30, other_pos_radius=None, threads_to_quantify=None, quantified_voxels=None):
"""
Takes the mean of the 20 brightest pixels in a 3x7x7 square around the specified position minus t... | 7420951a0791be9bf59ab8493696e06048edeaaa | 3,613,505 |
import requests
import json
def _get_topics_by_token(push_token):
"""
:param push_token: required
:return: topics, to which this token is subscribed (tags)
"""
firebase_server_key = "SERVER_KEY"
firebase_info_url = "FIREBASE_INFO_URL" # "https://iid.googleapis.com/iid/info/"
auth_key = "k... | a1265c6ab177caec92c3c550eebae3ecd35887c6 | 3,613,506 |
def set_product_options(name, version):
"""Set the options needed by the product template"""
data = request.get_data().decode('utf-8')
product = registry.get_product(name, version)
product.options = data
return '', 204 | 7dddd862a6077ad1ae40105d7d9a5e34374ccc47 | 3,613,507 |
def compute_and_update_frame_translations_dt(imp, channel, dt, process, shifts = None):
""" imp contains a hyper virtual stack, and we want to compute
the X,Y,Z translation between every t and t+dt time points in it
using the given preferred channel.
if shifts were already determined at other (lower) dt
the... | b56d719c80ca8109ed51b3de21c915981c335696 | 3,613,508 |
import pytz
from datetime import datetime
def query_data_for_timespan(pdb, start, end):
"""
Retrieve all desired data for one day, from PuppetDB
:param pdb: object representing a connected pypuppetdb instance
:type pdb: one of the pypuppetdb.API classes
:param start: beginning of time period to g... | a0e240b0b94daee9ab85981b76c4ca6c9e82dcf8 | 3,613,509 |
import numpy
def sigmoid_activation(aggregate: numpy.ndarray) -> float:
"""
:param aggregate: an array whose elements are the aggregate of all the inputs from the previous layer.
For instance, the first element of the array is the aggregate of all input coming into the first node,
the second element ... | d86c98e2edcd9b92efbbd244f68539f87ada9b62 | 3,613,510 |
def remove_dev(id):
"""Apagar parametro filtrando pela id"""
index = id
del devs[index]
return jsonify({'message': 'Dev is no longer alive'}), 200 | 02f20695e043582f9616a6f1422ce22d623691af | 3,613,511 |
def _get_configuration(resource_root, cluster_name, type, tag="version1"):
"""
Get configuration of a cluster
@param resource_root: The root Resource .
@param cluster_name: cluster_name
@param type: type of config
@return: A ConfigModel object
"""
dic = resource_root.get(
paths.C... | d3dcfc309fce62a7d0b1591a94fbba54b40e5352 | 3,613,512 |
def create_job():
"""Create a job."""
blob = request.get_json(force=True)
payload = blob["payload"]
state = blob.get("state", None)
job = request.q.create(payload, state)
return jsonify(job_as_json(job)), 200 | 73ed457478556123443ad08d3600435ae47f48fe | 3,613,513 |
def import_model(sklearn_model):
"""
Load a tree ensemble model from a scikit-learn model object
Parameters
----------
sklearn_model : object of type \
:py:class:`~sklearn.ensemble.RandomForestRegressor` / \
:py:class:`~sklearn.ensemble.RandomForestClassifier... | b807bac59de36589b672a7fadd2be9d6e63d0e63 | 3,613,514 |
def cir_Randles_simplified_Fit(params, w):
"""
Fit Function: Randles simplified -Rs-(Q-(RW)-)-
Return the impedance of a Randles circuit. See more under cir_Randles_simplified()
NOTE: This Randles circuit is only meant for semi-infinate linear diffusion
Kristian B. Knudsen (kknu@berkeley.edu || kr... | b87924de478402a9597b4686f6bef0afda4745c1 | 3,613,515 |
import collections
def read_pubmed_to_genes():
"""NCBI provides a list of articles (PMIDs) that discuss a particular gene (Entrez IDs).
These provide a nice positive distant supervision set, as mentions of a gene name in
an article about that gene are likely to be true mentions.
This returns a dictionary t... | 5e5d151e33aab538841a1db504cc18bc884ce33f | 3,613,516 |
def MTFL(args):
"""
The protected feature is faces with or without glasses.
Clusters are tested in binary gender classification.
Pictures are 224x224 with 2 labels.
"""
transform = transforms.Compose([ # suggested transform for resnet50 encoder
transforms.Resize(256),
transforms... | 479eb18f3da0d2dd43897f51b65f3e22e0866283 | 3,613,517 |
def return_slice(axis, index):
"""Prepares a slice tuple to use for extracting a slice for rendering
Args:
axis (str): One of "x", "y" or "z"
index (int): The index of the slice to fetch
Returns:
tuple: can be used to extract a slice
"""
if axis == "x":
return (sli... | ac6db30fc12509062efa4481d1f7b2fdaff8149b | 3,613,518 |
import os
import re
import fnmatch
def load_files_from_dir(dir, pattern = None):
"""Given a directory, load files. If pattern is mentioned, load files with given pattern
Keyword arguments:
text -- given text
delimiter - type of delimiter to be used, default value is '\n\n'
"""
... | 2b7ad778421598247975a2f37722efae3fd3f718 | 3,613,519 |
def load_data(pickle_file):
"""Loads a data from a pickle file."""
print("Loading data...")
dict_dataset = load_pickle(pickle_file)
train_dataset = dict_dataset['train_dataset']
val_dataset = dict_dataset['val_dataset']
test_dataset = dict_dataset['test_dataset']
train_labels = dict_dataset[... | d88570826d0b3b7a42ed9ea41274e4cc8944dfc0 | 3,613,520 |
def unfold(data, prefix='', delimeter='__'):
"""
>>> _dd(unfold({'a': 4, 'b': 5}))
"{'a': 4, 'b': 5}"
>>> _dd(unfold({'a': [1, 2, 3]}))
"{'a__0': 1, 'a__1': 2, 'a__2': 3}"
>>> _dd(unfold({'a': {'a': 4, 'b': 5}}))
"{'a__a': 4, 'a__b': 5}"
>>> _dd(unfold({'a': {'a': 4, 'b': 5}}, 'form'))
... | 26414f86499ff2302be6f56bb686bfbc23641e65 | 3,613,521 |
def get(*args, **kwargs):
"""Decorates a test to issue a GET request to the application. This is
sugar for ``@open(method='GET')``. Arguments are the same as to
:class:`~werkzeug.test.EnvironBuilder`.
Typical usage::
@frontend.test
@get('/')
def index(response):
ass... | c6322bd1340f5fe919ba25d70823be52ec368363 | 3,613,522 |
def photographer_required(func):
"""
if used to make sure the the current user is sa photographer
:param func:
:return:
"""
@wraps(func)
def decorated_view(*args, **kwargs):
if current_user.photographer is None:
flash("You are not yet registered as a photographer")
... | eb7ccc85b4ad6d30e0b4a8b44fa3df2b98cb5417 | 3,613,523 |
import json
def parse_arch_json_from_file(arch_json_path: str, photoroom_csv_path: str) -> House:
"""
Parses a house given the arch.json and the photoroom.csv
:param arch_json_path: str: Path to arch.json
:param photoroom_csv_path: str: Path to photoroom.csv
:return: Parsed house
"""
with... | 4dd40a80c4d7e7486cbaec71fd6401a9d3b7dc51 | 3,613,524 |
def Singleton_args(theClass):
""" decorator for a class to make a singleton out of it """
classInstances = {}
def getInstance(*args, **kwargs):
""" creating or just return the one and only class instance.
The singleton depends on the parameters used in __init__ """
key = (theCla... | 0aea083099c9731134f093dc9f73ff411a4f35f2 | 3,613,525 |
def read_py_file(filename, skip_encoding_cookie=True):
"""Read a Python file, using the encoding declared inside the file.
Parameters
----------
filename : str
The path to the file to read.
skip_encoding_cookie : bool
If True (the default), and the encoding declaration is found in t... | c7c7c0ecb82f185452e126ee92e453c9119f60b1 | 3,613,526 |
def atSendCmdGetTradingTime(targetList, kFreq, beginDay, endDay):
""" 获取标的频率周期的交易时间
:param targetList: targetList: list[dict] [{'Market':marketName, 'Code': CodeName },]
:param kFreq: K线频率
:param beginDay: 开始时间
:param endDay: 结束时间
:return: str, mat 文件路径 或者 at 返回的错误信息
::
保存交易时间的mat文件... | 72f60be0ec8abc456d2aafff3d81b2fda97b8ef4 | 3,613,527 |
def ts_min(x):
"""
[Definition] 对x中的每个时间序列在period范围内滚动求最小值
[Category] 统计
"""
# 取前n天数据的最小值
return 'ts_min(%s,%s)' %(x, pe.gen_param('ts_min','period')) | 27570afa1c9ab67618f254588dd57c2aa3acbccf | 3,613,528 |
def rotation_matrix(angle, direction, point=None, dtype=np.float32):
"""Return matrix to rotate about axis defined by point and direction.
http://www.lfd.uci.edu/~gohlke/code/transformations.py.html
"""
assert direction.dtype == dtype, "Wrong: %s" % direction.dtype
sina = dtype(np.math.sin(angle))
... | d4aaf7d18ea7e32be1707619d2caac51d773db5d | 3,613,529 |
def good_partner_matrix(results, nplayers, repetitions):
"""
An n by n matrix of good partner ratings for n players
Parameters
----------
results : list
A cooperation results matrix of the form:
[
[[a, j], [b, k], [c, l]],
[[d, m], [e, n], [f, o]],
... | 3b4f73f7b3a83e310618a3da5e50eb5d32ecc09c | 3,613,530 |
def _date_keyboard(possible_dates):
"""Creates a keyboard of possible crab dates."""
date_keyboard = [
[InlineKeyboardButton(possible_dates["1"]["formatted"], callback_data=possible_dates["1"]["string"]),
InlineKeyboardButton(possible_dates["2"]["formatted"], callback_data=possible_dates["2"]["... | 072fe9fac119dd7d19748d3c5725bf08e8c7db78 | 3,613,531 |
import os
def parse_filename(filename):
""" Extract parameters from filename with the pattern
prediction_w=100_k=200_m=4096.txt
"""
w, k, C = None, None, None
for token in os.path.splitext(os.path.basename(filename))[0].split("_"):
if "=" in token:
param, value = token.split("... | 6f2f5a77a9a7ddb53d26df4fd7477b359cf161ec | 3,613,532 |
def lite_plus_tot_functions():
""" Return the total number of lite_plus function extentions."""
return len(GLOBAL_REGISTER_LIST) | ac4e0a8b0a10ecb3493571c8c3a45aa2ccf89fff | 3,613,533 |
def add(high, low):
"""Vector Arithmetic Add
:param high:
:param low:
:return:
:real:
"""
return ADD(high, low) | 07376d4b7d91bfc6a1351ac0afde7afd147bec96 | 3,613,534 |
import argparse
import sys
def FunctionExitAction(func):
"""Get an argparse.Action that runs the provided function, and exits.
Args:
func: func, the function to execute.
Returns:
argparse.Action, the action to use.
"""
class Action(argparse.Action):
def __init__(self, **kwargs):
kwargs... | a6b292ed2491189e14e36df1ef7fb4d38d0102e2 | 3,613,535 |
import numpy
def features(im, max_features=6, min_pixels=50):
"""
Returns a list of features found in `im`.
Args:
im (Image): Source image.
max_features (int): The maximum number of features to return.
min_pixels (int): The minimum number of pixels a feature must
conta... | 2b7895391512ceb1554ba5b43f7918673cbeaf13 | 3,613,536 |
import os
def execute_barrbap(organism, dna_file):
"""determines the 16sRNA sequences using barrnap tool"""
# barrnap output file name e.g. barrnap.NC_000913
barrnap_out = cwd + "/barrnap." + organism
# > /dev/null 2>&1 is to disable stdout from displaying on terminal
barrnap_cmd = "barrnap " + st... | 9ec13d41343e5b31582f3af8d4de2917e2a84bdc | 3,613,537 |
def _buffer_proxy(filename_or_buf, function, reset_fp=True,
file_mode="rb", *args, **kwargs):
"""
Calls a function with an open file or file-like object as the first
argument. If the file originally was a filename, the file will be
opened, otherwise it will just be passed to the underl... | c5680ebb183559a00f1c635ec81d3cac135b7de5 | 3,613,538 |
def word_tokenize(text):
"""
convert a string to list of normal word tokens
"""
return filter_stopwords(tokenizer(text)) | 9b3778504945f43df699e9bc2e8d512d904c77b0 | 3,613,539 |
import re
import ast
def _parseSpec(values):
"""
Split the argument string. Example:
--arg name:value0,value1,key2=value2,key3=value3
gets split into
name, args, kwargs = (
"name",
(value0, value1),
{"key2":value2, "key3":value3},
)
"""
split = values.split(":", 1)
name = split[0].str... | 2708b106bc83a82b44df71742fc7b689016921a1 | 3,613,540 |
def get_mask(mask_path):
"""Loads the data from a given mask.
Parameters
----------
mask_path : str
Path to the mask.
Returns
-------
numpy.ndarray
Data of the given mask.
"""
return nibabel.load(mask_path).get_data() | d44e0cb9324ab31a192867dcef762ee392fe0560 | 3,613,541 |
def haversine(lon1, lat1, lon2, lat2):
"""
Calculate the great circle distance between two points
on the earth (specified in decimal degrees)
"""
# convert decimal degrees to radians
lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2])
# haversine formula
... | 94f918aa5b10057d34edc7c3606348cb75f60f1f | 3,613,542 |
def PLUS_DI(df, time_period=14):
"""
+DI 最高价上涨的次数
+ di是真实范围的百分比。di是真实范围下降的百分比。当+ di越过di时,生成一个买入信号。当di越过+ di时,产生一个卖出信号。你应该等到交易进入极限点为止。也就是说,你应该等待进入一个长期的交易,直到价格达到高的酒吧上di di越过di,并等待进入短期贸易,直到价格达到低的酒吧上的di越过+ di。
python API
real=PLUS_DI(high, low, close, timeperiod=14)
:return:
"""
high = df['h... | 8e183cca7cff54ca3b9cf1048a7bb1222564a114 | 3,613,543 |
def map_records_nb(records, map_func_nb, *args):
"""Map each record to a scalar value.
`map_func_nb` must accept a single record and `*args`, and return a scalar value."""
result = np.empty(records.shape[0], dtype=np.float_)
for r in range(records.shape[0]):
result[r] = map_func_nb(records[r], ... | ed4f693361abeaf1ee56ba1345caf2434fefe7e1 | 3,613,544 |
def schema():
"""
Returns the basic schema of :class:`.Agent`
.. http:get:: /api/v1/agents/schema HTTP/1.1
**Request**
.. sourcecode:: http
GET /api/v1/agents/schema HTTP/1.1
Accept: application/json
**Response**
.. sourcecode:: http
... | c42655d0afb00c1d1b7b763e64a5566d9300d220 | 3,613,545 |
def storage_root(state: State, address: Address) -> Root:
"""
Calculate the storage root of an account.
Parameters
----------
state:
The state
address :
Address of the account.
Returns
-------
root : `Root`
Storage root of the account.
"""
assert sta... | ebebb135693ff1814b8a6e08bc5e0e6106971edd | 3,613,546 |
def sort_out_edges(g, tag, tag_offset_name='_TAG_OFFSET'):
"""Return a new graph which sorts the out edges of each node.
Sort the out edges according to the given destination node tags in integer.
A typical use case is to sort the edges by the destination node types, where
the tags represent destinatio... | 78fda8d04aa49c95efec266da07dd523770426e0 | 3,613,547 |
def _count_dot_semicolumn(value):
"""Count the number of `.` and `:` in the given string."""
return sum([1 for c in value if c in [".", ":"]]) | 57ee0c88d31ed62168e562191bb1dd4ebb3de859 | 3,613,548 |
import re
def FixIP(pattern):
"""If a stand alone IP, fix it so RE does not go off the rails"""
if re.search(pattern,"^([0-9]{1,3}\.){3}[0-9]{1,3}$"):
# If IP, make sure "." is not interpreted as a regexp "." instead of a period seperator
pattern = pattern.replace(".",r"\.")
return pattern | 6cddfc3afda7f4c00ec7167a2a468791d8cc6632 | 3,613,549 |
def grant_staff_access(actor, user, is_staff):
"""
Grant staff access to a user via an actor.
"""
user.is_staff = is_staff
user.save()
return user | 18624d0c9968e0e495235c4684d243650183dae0 | 3,613,550 |
from typing import Dict
def _random_cropping_decoder(
sequences: Dict[str, media_sequences.EncodedSequence],
*,
image_size: int,
min_crop_window_area: float,
max_crop_window_area: float,
min_crop_window_aspect_ratio: float,
max_crop_window_aspect_ratio: float,
) -> Dict[str, brave_datasets... | d57c58d25512c22532ea83dc0f7506d4df357c76 | 3,613,551 |
def generate_curve(A, B, C, D):
"""
if Seg(A1, B1) and Seg(A2, B2) intersects at P,
then C is the closest point to A in the trajectory1 opposite to the direction of B,
and D is the closest point to B opposite to the direction of A
output: Bezier curve
"""
line_CA = Line(C, A)
line_BD = ... | 53c9d6b8146753858ef0f0dea527bdac6a1a2115 | 3,613,552 |
from typing import Dict
from typing import List
import copy
def nutanix_hypervisor_task_results_get_command(client: Client, args: Dict):
"""
Poll tasks given by task_ids to check if they are ready.
Returns all the tasks from 'task_ids' list that are ready at the moment
Nutanix service was polled.
... | 5a50a208f4eb2665783311e3faa5ebfbe038809f | 3,613,553 |
def concatenate(adatas, merge_var_cols=None, **kwargs):
"""
Extension of scanpy's native `concatenate` funcion.
Allows to merge columns in `var` of the same name with same
contents into a single one instead of
generating col-1, col-2, ...
The columns to merge need to be specified explicitly.
... | e643a14fc3e6a0756dd0650b3209c5c788d75a2d | 3,613,554 |
import os
def parse_options(option_name: str) -> dict:
"""Parse a Kakoune map option and return a str-to-str dict."""
items = [
elt.split('=', maxsplit=1)
for elt in os.environ[f"kak_opt_{option_name}"].split()
]
return {v[0]: v[1] for v in items} | 94e38b2cb0d1887036c0d0c778974067a45f4ae0 | 3,613,555 |
def downgrade_images(I_MS,I_PAN,ratio,sensor):
"""
downgrade MS and PAN by a ratio factor with given sensor's gains
"""
I_MS=np.double(I_MS)
I_PAN=np.double(I_PAN)
ratio=np.double(ratio)
flag_PAN_MTF=0
if sensor=='QB':
flag_resize_new = 2
GNyq = np.asarray([0.34, 0.3... | b356418b9b7e14af043345f58c68f8b7889fd896 | 3,613,556 |
def less_equal(evaluator, ast, state):
"""Evaluates "left <= right"."""
res = UppaalBool(evaluator.eval_ast(ast["left"], state) <= evaluator.eval_ast(ast["right"], state))
return res | c7adef576ff63441c48a11e3e054dd891c126729 | 3,613,557 |
def get_vo_oasis_managers(global_data, vo):
"""return OASIS Managers list for given vo, if any, else an empty list"""
vos_data = global_data.get_vos_data()
return safe_dict_get(vos_data, vo, "OASIS", "Managers", default=[]) | f649cab2ba24c43a222d45a1cc93904159620958 | 3,613,558 |
import re
def normalize_string(string, able=None):
"""
Parameters
----------
string: str
able: list[str] or None, default None
Returns
-------
str
"""
if able is None:
return string
if "space" in able:
string = re.sub(r"[\t\u2028\u2029\u00a0\u1680\u180e\u20... | eb50298d476fba2b1a313afb3051233c1b16e4b5 | 3,613,559 |
def load_data(filename, smooth=False, filter_window=3, order=1):
"""
Reads the input datafile which is a multiindex pandas array generated by DeepLabCut as a result of analyzing a video.
Parameters
----------
filename: string
Full path of the multiindex pandas array(.h5) file as a string.
... | 42e4f6940cfdb778a1bec7fec1da480720150060 | 3,613,560 |
from typing import get_args
def create_function_dictionary(node):
"""Creates a dictionary from a node describing a FunctionDef
Args:
**node (:obj: `ast.FunctionDef`)**: The node to create the dictionary for
Returns:
A dictionary
"""
func_dict = {
'new_name': hex_name(node... | 8a4e55cce2dea9a5da75831b5daeecee4c3527fb | 3,613,561 |
import sqlite3
def create_connection(db_file):
""" create a database connection to the SQLite database
specified by db_file
:param db_file: database file
:return: Connection object or None
"""
try:
conn = sqlite3.connect(db_file)
return conn
except Error as e:
... | 9a2cde9bbd38571dea154f9a197bf82ee8a197aa | 3,613,562 |
def get_p_Y_val_approx_mahalanobis(post_samples, y_mean, y_truth, cov):
"""Calculate the percentage of draws from the predicted distribution that
encompasses the truth, for all of the examples in the validation set.
Parameters
----------
post_samples : np.array of shape [n_samples, n_sightlines, Y_... | d38f217510befd24ad44b0b0b80707713da5578d | 3,613,563 |
from typing import Dict
from typing import Any
import struct
def parse_data_frame(data_bytes: bytearray, data_format_name: str) -> Dict[int, Any]:
"""Convert bytearray block from XEM buffer into formatted data.
Args:
data_bytes: a data block from the FIFO buffer
data_format_name: a designatio... | 5ed942e0cfed332a4df5ae569addd41e81b079da | 3,613,564 |
import torch
def cmcf(vertices, faces, max_iters: int, step_size=0.05, threshold_rd=1e-3):
"""
cMCF implementation in Python using Pytorch
See : https://arxiv.org/pdf/1203.6819.pdf
:param vertices: torch.float [V, 3], vertices coordinates of the mesh in euclidean space
:param faces: torch.long [F,... | e3219760cd514f76585bbba86269193d185346e7 | 3,613,565 |
def wavs_in_ranges(wavs, ranges):
"""Determine if wavelength is in one of the ranges given.
wavs: wavelengths to check
ranges: list of (lower limit, upper limit) pairs
Returns
-------
in_range: np.array containing True if the wavelength at the same
index was in one of the ranges
"""
... | 3a6f974fc2012b6d1c8f6234d085bdf9e7327b3b | 3,613,566 |
def node_compute_accuracy(l_inferred, l_targets) -> dict:
"""
- l_inferred : list of tensors of shape (N_nodes_i)
- l_targets : list of tensors of shape (N_nodes_i)
"""
return edgefeat_compute_accuracy(l_inferred, l_targets) | bc189fa32172f17ee736d65366c92acc9e25c33c | 3,613,567 |
import tqdm
def _eval_knn(k,train_x,train_y,query_x,query_y,dist_metric,compute_loss=True):
"""
knn algorithm
Inputs:
k: (list) k[0]:lower bound of number of nearest neighbours; k[1]:upper bound of number of nearest neighbours
train_x: (np.array) input training vector
train_y: (np... | 35dc3b362f3e6fec298e87af2b3252f5f438fa51 | 3,613,568 |
def spherical_uniform(size, dim=3, r=1.):
"""
Samples points from a uniform distribution on a spherical manifold.
Uniform sampling on the sphere can be achieved by sampling from a Gaussian
in the ambient space of the CCM, and then projecting the samples onto the
sphere.
:param size: number of po... | 9d4cb35c43c232da4789e4e2221f1f60dddd311b | 3,613,569 |
def la_roots(n, alpha, mu=False):
"""Gauss-generalized Laguerre quadrature
Computes the sample points and weights for Gauss-generalized Laguerre
quadrature. The sample points are the roots of the `n`th degree generalized
Laguerre polynomial, :math:`L^{\\alpha}_n(x)`. These sample points and
weight... | 483876befb137b3f06aee7f2f2b140e925e4cda0 | 3,613,570 |
def modify_coco(coco):
"""
:param coco: json file containing coco ground truth, loaded with coco
:return: json file containing coco ground truth where each object (all sailing ships) is segmented separately
"""
anns = coco['annotations']
L_im = [[] for i in range(16)]
idx = 0
for i in r... | d800f261c44dd35f0a6b4c304f914b714c358c28 | 3,613,571 |
def average_above_zero(tab):
"""
Brief:
computes of the avrage of the positive value sended
Arg:
a list of numeric values, except on positive value, else it will raise an Error
Return:
a list with the computed average as a float value and the max value
Raise:
Valu... | 307846cdd75d8e415c6a7d819ffc0d5f7bc70da6 | 3,613,572 |
def _sample_discrete_actions(batch_probs):
"""Sample a batch of actions from a batch of action probabilities.
Args:
batch_probs (ndarray): batch of action probabilities BxA
Returns:
List consisting of sampled actions
"""
action_indices = []
# Subtract a tiny value from probabilitie... | 3b897d8df682d8abe5f5d3887ac7a55421c3e58d | 3,613,573 |
from pathlib import Path
def get_data_dir() -> Path:
"""
* relative path: relative to package
* Path with ~ is expanded
* Absolute paths supported
"""
path = Path(config["global"]["datadir"].get()).expanduser()
path = path if path.is_absolute() else DIR.parent / path
if not path.exists... | 8a449610cb9a3ae0ea7356eae8eb06b682db20a3 | 3,613,574 |
from re import T
def first(seq: Seq[T], default=NOT_GIVEN) -> T:
"""
Return the first element of sequence.
Raise ValueError or return the given default if sequence is empty.
Examples:
>>> sk.first("abcd")
'a'
See Also:
:func:`second`
:func:`last`
:func:`n... | ac1ca1cf1fb701310c19646d3dc0a6fae3728a6d | 3,613,575 |
def se3ToVec(se3mat):
""" Converts an se3 matrix into a spatial velocity vector
:param se3mat: A 4x4 matrix in se3
:return: The spatial velocity 6-vector corresponding to se3mat
Example Input:
se3mat = np.array([[ 0, -3, 2, 4],
[ 3, 0, -1, 5],
... | 8a662704a0d2481352f63b2ede93c39523ab8cc8 | 3,613,576 |
def CommentPattern(lang_id=0):
"""Returns a list of characters used to comment a block of code
@keyword lang_id: used to select a specific subset of comment pattern(s)
"""
if lang_id == synglob.ID_LANG_SQUIRREL:
return ['//']
else:
return list() | e79d46c3530343f1bc5732227c280d48f754c081 | 3,613,577 |
import click
import traceback
def handle_exception(e: Exception, verbose: bool) -> int:
"""
Handle exception from a scan command.
"""
if isinstance(e, click.exceptions.Abort):
return 0
elif isinstance(e, click.ClickException):
raise e
else:
if verbose:
trace... | 6f295f1c260d8ca92ac1e04ec504177a711c200e | 3,613,578 |
from datetime import datetime
def windrose(
station,
database="asos",
months=np.arange(1, 13),
hours=np.arange(0, 24),
sts=datetime(1970, 1, 1),
ets=datetime(2050, 1, 1),
units="mph",
nsector=36,
justdata=False,
rmax=None,
sname=None,
sknt=None,
drct=None,
valid... | 39878da6f59660ec22af0448c09bdce51849b08e | 3,613,579 |
def get_std(array, axis=None):
"""
Computes the standard deviation of an array, along a
given axis.
Parameters
----------
array: numpy array
The array over which the operation will be done.
axis : None, int
Axis along which the operation will be done.
Returns
---... | f71ac61e6419b7b6d2a28a853e2310b0789656b1 | 3,613,580 |
def calc_montage_horizontal(border_size, *frames):
"""Return total[], pos1[], pos2[], ... for a horizontal montage.
Usage example:
>>> calc_montage_horizontal(1, [2,1], [3,2])
([8, 4], [1, 1], [4, 1])
"""
num_frames = len(frames)
total_width = sum(f[0] for f in frames) + (border_siz... | 8fe5de84d9b1bff9950690ec99f63e174f2f0d22 | 3,613,581 |
def getArkoudaClientLogger(name : str) -> ArkoudaLogger:
"""
A convenience method for instantiating an ArkoudaLogger that retrieves the
logging level from the ARKOUDA_LOG_LEVEL env variable and outputs log
messages without any formatting to stdout.
Parameters
----------
name : str
... | f5fe0abe2aefda7eac58c352ac79769bae20c2ba | 3,613,582 |
def is_valid_file(ext, argument):
""" Checks if file format is compatible """
formats = {
'input_dataset_path': ['csv'],
'output_results_path': ['csv'],
'output_plot_path': ['png']
}
return ext in formats[argument] | 85bd0ee9cb0eafc1244271d6b2b91b88fcbd3acc | 3,613,583 |
def load_data(filename, kfold=3, seed=333, split='random'):
"""
Function to load the pressure data with stratified k fold
Parameters
----------
filename : string
Path to the data file.
augment : bool, optional
Whether or not to add random noise to the pressure data.
The ... | 597f70d2eb9fc2cde99f084873ea8fa023d964ff | 3,613,584 |
def get_media_importer():
"""Get an importer function for `pyglet.media.Source` resources.
Given the resource subfolder and accepted extensions, return a
function in the form of :py:attr:`GameModel.LAMBDA_SIG` that will
only accept files in the given resource subfolder(`location`) and
returns the p... | 74fbe30bec6e84854cc88ecbe07cd54cfcde4e71 | 3,613,585 |
async def add_user_to_group(
group_id: int,
group_user_add: GroupUserAddOrRemove,
db: Session = Depends(get_db)):
"""
Add user to group.
todo: add only if not already added
"""
group = UserGroupsRepository(db).get(group_id)
user = UserRepository(db).get(group_user_add.use... | f8e7c957b1b519f71f4f26153c810ba6fa216bb5 | 3,613,586 |
def distance(pointA, pointB):
"""Donne la distance entre deux points
Args:
pointA (Point): Point A
pointB (Point): Point B
Returns:
float: Distance entre A et B
Raises:
TypeError: Si A ou B n'est pas un point
"""
if isinstance(pointA, Point) and isinstance(pointB, Point):
return sqrt((... | 478efa71b7786c51c61a3c38fa04bdd886906d5a | 3,613,587 |
def confused(total, max_part, threshold):
"""Determine whether it is too complex to become a cluster.
If a data set have several(<threshold) sub parts, this method use the total
count of the data set, the count of the max sub set and min cluster threshold
to determine whether it is too complex to becom... | eb674774a8792b4e06d810738fb46f50589b7815 | 3,613,588 |
import torch
def rbf_kernel_conv(X, Y, gamma, sigma, device=DEFAULT_DEVICE):
"""
Vectorized implementation
Performs rbf kernel convolution on input distributions and hinge point grid
"""
N, d = X.shape
if gamma is None:
gamma = 1. / d
if sigma is None:
sigma = torch.zeros(N... | 6ecc556a28667c99b811f5a3a26906fc1ffec905 | 3,613,589 |
def rs(axes, natom):
""" rs density parameter (!!!! axes MUST be in units of bohr)
Args:
axes (np.array): lattice vectors in row-major, MUST be in units of bohr
Returns:
float: volume of cell
"""
vol = volume(axes)
vol_pp = vol/natom # volume per particle
rs = ((3*vol_pp)/(4*np.pi))**(1./3) # ... | 376a5a3262211496aff7bcb73edd4e3bb4bbf99e | 3,613,590 |
def predicted_retention(alpha, beta, t):
"""
Generate the retention probability r at period t, the probability of customer to be active at the
end of period t−1 who are still active at the end of period t.
Implementing the formula in equation (8).
"""
assert t > 0, "period t should be positive"
... | 0bc94878e93b65711fc0f520e2de898cd113b91f | 3,613,591 |
import torch
def nopeak_mask(size):
"""The function which generates an upper triangular matrix"""
opt = Opt.get_instance()
np_mask = np.triu(np.ones((1, size, size)),
k=1).astype('uint8')
np_mask = Variable(torch.from_numpy(np_mask) == 0).to(opt.device)
return np_mask | dcbd1a89cd0bd8358f77526954d280ee1d609a74 | 3,613,592 |
def is_palindrome(s):
"""
Determine whether or not given string is valid palindrome
:param s: given string
:type s: str
:return: whether or not given string is valid palindrome
:rtype: bool
"""
# basic case
if s == '':
return True
# two pointers
# one from left, one... | a9d700a2e7907e551cb5060f61de5c829ab77291 | 3,613,593 |
def range_to_level_window(min_value, max_value):
"""Convert min/max value range to level/window parameters."""
window = max_value - min_value
level = min_value + .5 * window
return (level, window) | 0a388ff48a29f0daff20a7cdfd200f8330a32a15 | 3,613,594 |
def miles_distant(entity_1, entity_2):
"""
_miles_distant
:entity_type: (airport_code, city_name)
:entity_type: (city_name, city_name)
"""
entity_type_1, entity_value_1 = get_entity_value(entity_1)
entity_type_2, entity_value_2 = get_entity_value(entity_2)
if entity_type_1 == 'airport_c... | b685d8854d47cf908ef44a4defbbd893b01e0215 | 3,613,595 |
def type_(printer, ast):
"""Prints "[const|meta|...] type"."""
prefixes_str = ''.join(map(lambda prefix: f'{prefix} ', ast["prefixes"]))
type_id_str = printer.ast_to_string(ast["typeId"])
return f'{prefixes_str}{type_id_str}' | cdf03cfb3ff0a00fa973aa4eaf7a32cb9b822191 | 3,613,596 |
def random_feature_table_filename(invalid_data):
"""
Generate Random Feature Table Filename
return: string containing imitation filename in ".tbl" format.
"""
# call random_filename, ignoring invalid_data information.
return (random_filename(invalid_data)[0] + '.tbl'), global_valid_data | 67e1eb94c3456102f6aeb638cbd8573d7ea9df62 | 3,613,597 |
def _tensor_run_opt_ext(opt, momentum, learning_rate, gradient, weight, accum, stat):
"""Apply sgd optimizer to the weight parameter using Tensor."""
success = True
success = F.depend(success, opt(weight, gradient, learning_rate, accum, momentum, stat))
return success | fc1185e2cbbc01c9a90dcb196471489fe2aa0a27 | 3,613,598 |
def split_by_quantile(data, q, env_name='Hopper-v2'):
"""splits the data according to the quantile q of the Dataset"""
if env_name == 'MountainCar-v0':
proxy_list = data['obs'][:,:,0].sum(axis=-1) / np.count_nonzero(data['obs'][:,:,0])
elif env_name == 'Hopper-v2':
proxy_list = [np.sum(... | 996a285cb4b7b2a76d3acfa1ca449b99a363c89f | 3,613,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.