content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def get_config_type(service_name):
"""
get the config tmp_type based on service_name
"""
if service_name == "HDFS":
tmp_type = "hdfs-site"
elif service_name == "HDFS":
tmp_type = "core-site"
elif service_name == "MAPREDUCE":
tmp_type = "mapred-site"
elif service_name ... | 2fec790e67bdba757f8dffe058fae1d508b7d237 | 18,700 |
import requests
from io import StringIO
def batch_request(config, dataset_id, geographies, date_format,
record_offset=0, max_api_calls=10):
"""Fetch a NOMIS dataset from the API, in batches,
based on a configuration object.
Args:
config (dict): Configuration object, from which a... | 1f615ccd60464641a554bc3bf2bc39fe917d4df4 | 18,701 |
from typing import Dict
from typing import List
from typing import Tuple
import os
import tqdm
def get_val(in_root: str, wnid2idx: Dict[str, int]) -> List[Tuple[str, int]]:
"""Get validation split sample pairs.
Args:
in_root (str): Input dataset root directory.
wnid2idx (dict): Mapping of Wor... | 4f4cf7d1ec62dea5d128ef4a89fe9ca2ac02f317 | 18,702 |
def is_music(file: File) -> bool:
"""See if the ext is a Music type."""
return file.ext in {
"aac",
"m4a",
"mp3",
"ogg",
"wma",
"mka",
"opus",
"alac",
"ape",
"flac",
"wav",
} | 7e35a4f63c656d61d534a1a0116c84c6fc30fefd | 18,703 |
import torch
def sqeuclidean_pdist(x, y=None):
"""Fast and efficient implementation of ||X - Y||^2 = ||X||^2 + ||Y||^2 - 2 X^T Y
Input: x is a Nxd matrix
y is an optional Mxd matirx
Output: dist is a NxM matrix where dist[i,j] is the square norm between x[i,:] and y[j,:]
if y is not... | 7b9077ed847847bd1030b6f850259717ccc586fe | 18,704 |
import argparse
def parse_options() -> argparse.Namespace:
"""Parse command line arguments"""
parser: argparse.ArgumentParser = argparse.ArgumentParser(
"Arguments for pretraining")
parser.add_argument('--sample_size', type=int, default=3200,
help='sample size for training'... | e746865259d024b733ede7f1c353f37a93a3f9f2 | 18,705 |
import os
import shutil
def commit(dir_info):
"""
Moves files from the temp directory to the final directory based
on the input given. Returns list of all files
Keyword arguments:
dir_info -- dictionary of service to dir_info hash
"""
def walk_file_list(base_dir, srcdir, resultdir, do... | 7d9068e5203cdf961fa8abbcb76ac22ee41e5e34 | 18,706 |
def len(file, path):
"""获取dataset第一维长度。
Args:
file: 文件路径。
path: dataset路径。
Returns:
返回长度。
"""
with h5py.File(file, mode='r') as h5_file:
length = h5_file[path].len()
return length | d64d4ca0076a2bf76c5cb11dbba68adec15e34fa | 18,707 |
from re import T
def loop(step_fn, n_steps,
sequences=None, outputs_info=None, non_sequences=None,
go_backwards=False):
"""
Helper function to unroll for loops. Can be used to unroll theano.scan.
The parameter names are identical to theano.scan, please refer to here
for more information.
... | 8abd7c0ccfcabd3e44eca10c6d30a7d9a7add627 | 18,708 |
import torch
def get_model(hidden_size=20, n_hidden=5, in_dim=2, out_dim=1, penultimate=False, use_cuda=True, bn=False):
"""
Initialize the model and send to gpu
"""
in_dim = in_dim
out_dim = out_dim #1
model = Net(in_dim, out_dim, n_hidden=n_hidden, hidden_size=hidden_size,
a... | fd7169276a2a420ce59733ac9687a289e7c3b0af | 18,709 |
def convert_sweep(sweep,sweep_loc,new_sweep_loc,AR,taper):
"""This converts arbitrary sweep into a desired sweep given
wing geometry.
Assumptions:
None
Source:
N/A
Inputs:
sweep [degrees]
sweep_loc [unitless]
new_sweep_loc [unitless]
AR ... | 17b52460f8a9d32cc2e6f407ccad2851c3edb1f8 | 18,710 |
def is_circular(linked_list):
"""
Determine whether the Linked List is circular or not
Args:
linked_list(obj): Linked List to be checked
Returns:
bool: Return True if the linked list is circular, return False otherwise
The way we'll do this is by having two pointers, called "runne... | 5a641df602f983de78c9c74b825847412aa54c21 | 18,711 |
from typing import List
from typing import Any
def bm_cv(
X_train: pd.DataFrame,
y_train: pd.Series,
cv: int,
metrics: List[Any],
metrics_proba: List[Any],
metric_kwargs: dict,
model_dict: dict,
):
"""
Perform cross validation benchmark with all models specified under model_diction... | d1d1944fd4802f196ca7a1a78cf0f55222f6886c | 18,712 |
def index_get(array, *argv):
"""
checks if a index is available in the array and returns it
:param array: the data array
:param argv: index integers
:return: None if not available or the return value
"""
try:
for index in argv:
array = array[index]
return array... | d7fbf0011fd14da905d167735e6900b1bbaf1a8f | 18,713 |
def _env_vars_available() -> bool:
"""
Returns: `True` if all required environment variables for the Postgres connection are set, `False` otherwise
"""
return all(env_var in environ for env_var in DBConfigProviderEnvVarBasedImpl.required_env_vars) | 8fcc9c06115056bbe8b3b691d192186c0313aeef | 18,714 |
def precisionatk_implementation(y_true, y_pred, k):
"""Fujnction to calculate precision at k for a given sample
Arguments:
y_true {list} -- list of actual classes for the given sample
y_pred {list} -- list of predicted classes for the given sample
k {[int]} -- top k predictions we are i... | 945caa95b32681939569ca675475e2527dbdee78 | 18,715 |
import pandas
def add_plane_data(
data_frame: pandas.DataFrame,
file_path: str,
target_col: str = const.DF_PLANE_COL_NAME
) -> pandas.DataFrame:
"""Merges DataFrame with information about the flight planes
Args:
data_frame (pandas.DataFrame): Source DataFrame
f... | 0dbe3987cb4ee26f0ae6670173c65a3622ca9b5d | 18,716 |
def record(location):
"""Creates an empty record."""
draft = RDMDraft.create({})
record = RDMRecord.publish(draft)
return record | 77c8069e4fd894f2ed1d760fc983a9a2094c0f6d | 18,717 |
def firfls(x, f_range, fs=1000, w=3, tw=.15):
"""
Filter signal with an FIR filter
*Like firls in MATLAB
x : array-like, 1d
Time series to filter
f_range : (low, high), Hz
Cutoff frequencies of bandpass filter
fs : float, Hz
Sampling rate
w : float
Length of ... | 71c7c3fc229ce8745f5940593a6e5a2f9bf12490 | 18,718 |
def extract_and_coadd(ra, dec, pm_ra, pm_dec, match_radius=4./3600.,
search_radius=25./60, sigma_clip=None, query_timeout=60.,
upper_limits=True, return_exps=False):
"""
The top-level function of this module, extract_and_coadd finds sources in
GALEX archive matchi... | d28d62877ba0c8a99aba1596128dc764bc3e19b7 | 18,719 |
import aiohttp
async def create_payout(
session: ClientSession, data: CreatePayoutRequest
) -> CreatePayoutResponse:
"""
Create a payout.
"""
url = RAZORPAY_BASE_URL + "/payouts"
async with session.post(
url,
json=data.__dict__,
auth=aiohttp.BasicAuth(RAZORPAY_KEY_ID, ... | c4b9dae09111c83efb1d5a9c5fd88050f11b5510 | 18,720 |
def eval_ocr_metric(pred_texts, gt_texts):
"""Evaluate the text recognition performance with metric: word accuracy and
1-N.E.D. See https://rrc.cvc.uab.es/?ch=14&com=tasks for details.
Args:
pred_texts (list[str]): Text strings of prediction.
gt_texts (list[str]): Text strings of ground tru... | 0ec92be231d93abf9db8247369ba5ea546bd1b17 | 18,721 |
def get_all_zones():
"""Return a list of all available zones."""
cf = CloudFlare.CloudFlare(raw=True)
page_number = 0
total_pages = 1
all_zones = []
while page_number < total_pages:
page_number += 1
raw_results = cf.zones.get(params={'per_page':100, 'page':page_number})
z... | 0b9f6bf9b7b8fe274f7c6f856abf1d9397384c3c | 18,722 |
def entry_id(e):
"""entry identifier which is not the bibtex key
"""
authortitle = ''.join([author_id(e),title_id(e)])
return (e.get('doi','').lower(), authortitle) | 7c663d6c2bbdfcef8168c11a78e176e634cf644b | 18,723 |
def AskNumber(text="unknown task"):
"""
Asks the user to interactively input a number (float or int) at any point in the script, and returns the input number.
| __option__ | __description__
| --- | ---
| *text | an optional string to identify for what purpose the chosen number will be used.
"""
def ValidateN... | 41949d0a2e2d87b5cdb26d2db9bff9a64fbeeb1d | 18,724 |
def TokenEmphasis(character="_"):
"""
Italic (`<i>`, `<em>`) text is rendered with one asterisk or underscore
"""
assert character in ("_", "*")
return {
"type": "Characters",
"data": character,
"_md_type": mdTokenTypes["TokenEmphasis"],
} | 2012fdeb9ca4d9483b4cc403010f9900dcc1230f | 18,725 |
import os
def get_data(filename, **kwargs):
"""
get selected data file
"""
filepath = os.path.join(data.__path__[0], filename)
return np.genfromtxt(filepath, **kwargs) | dcf95489b95c3900819f10cad2a503b27fc5d88c | 18,726 |
import random
def generate_plan(suite, node):
"""Randomly generates a plan, completely ignoring norms. This is mainly for testing the norm driven algorithm"""
plan = [node]
next_actions = next_actions(suite,node)
# print "Next actions ", next_actions
while (next_actions != []):
a = random.... | 30d967986d1c4237b4b312470d47d1ecce06ecbc | 18,727 |
def update_y(pred_coords, ypart_tracker, history=1500):
"""
Update y-tracker and store last 1500 detection
:param pred_coords: y coordinates
:param ypart_tracker: choose keypoints based on input conditions
:return: y-tracker
"""
anks_val = (pred_coords[15] + pred_coords[16]) * 0.5
shdr_v... | ee1880e27b121dae4661a93286bf07117bc7bb34 | 18,728 |
def augmentData(features, labels):
"""
For augmentation of the data
:param features:
:param labels:
:return:
"""
features = np.append(features, features[:, :, ::-1], axis=0)
labels = np.append(labels, -labels, axis=0)
return features, labels | ef684ae2bf9eb4fca9a0636d3b0089020805f4be | 18,729 |
import tqdm
import torch
import os
def train_adversary():
""" Trains an adversary on data from the data censoring process. """
def accuracy(pred, true):
u = true.cpu().numpy().flatten()
p = np.argmax(pred.cpu().detach().numpy(), axis=1)
acc = np.sum(u == p)/len(u)
return ... | 33236a2260aa6df11a0b99bd58b5601fcd9ef052 | 18,730 |
def sigmoid(x):
""" Implement 1 / ( 1 + exp( -x ) ) in terms of tanh."""
return 0.5 * (np.tanh(x / 2.) + 1) | 95d6dd0cd62db2c43df419358ef368609ede42c8 | 18,731 |
def get_unique_output_values(signals):
"""
Based on segment length, determine how many of the possible four
uniquely identifiable digits are in the set of signals.
"""
unique_digit_count = 0
for signal in signals:
for digit in signal["output"]:
if len(digit) in (2, 3, 4, 7):... | 84098d4d294bfdd1b983ea70d51da1453b17245a | 18,732 |
import itertools
def split_and_pad(s, sep, nsplit, pad=None):
""" Splits string s on sep, up to nsplit times.
Returns the results of the split, pottentially padded with
additional items, up to a total of nsplit items.
"""
l = s.split(sep, nsplit)
return itertools.chain(l, itertools.rep... | 6c439301df7109d9b01a06a87bd7d6adafb8ee1e | 18,733 |
def transpose_report(report):
"""Transposes the report. Columns into rows"""
return list(map(list, zip(*report))) | bc59f9106496b0b830fdc9ac0266f3b774a8f759 | 18,734 |
def _shape_from_resolution(resolution):
"""
Calculate the shape of the global Earth relief grid given a resolution.
Parameters
----------
resolution : str
Same as the input for load_earth_relief
Returns
-------
shape : (nlat, nlon)
The calculated shape.
Examples
... | c726d599696cee2259bc450606e63480b0991451 | 18,735 |
def __virtual__():
"""
Load module only if cx_Oracle installed
"""
if HAS_CX_ORACLE:
return __virtualname__
return (
False,
"The oracle execution module not loaded: python oracle library not found.",
) | a64eddc8b78e5d7b3c8e0588a72a0c238b4c12d0 | 18,736 |
import pkgutil
import os
def find_plugins():
""" Finds all Python packages inside the port.plugins directory """
return [os.path.join(importer.path, name) for importer, name, ispkg in pkgutil.iter_modules(plugins.__path__) if ispkg] | 06b1217840686a4f4ad90b1f9b7dd32e8377df05 | 18,737 |
import os
def saturation(rgb_img, threshold=255, channel="any"):
"""Return a mask filtering out saturated pixels.
Inputs:
rgb_img = RGB image
threshold = value for threshold, above which is considered saturated
channel = how many channels must be saturated for the pixel to be masked out ("... | 588bdc18f87af48b322b653170126516942594f5 | 18,738 |
def get_fuel_from(mass: int) -> int:
"""Gets fuel from mass.
Args:
mass (int): mass for the fuel
Returns:
int: fuel necessary for the mass
"""
return mass // 3 - 2 | 37390c8cb9ba7e84c7b5c14841528d6c38f1589e | 18,739 |
def test_energy_density_function():
"""
Compute the Zeeman energy density over the entire mesh, integrate it, and
compare it to the expected result.
"""
mesh = df.RectangleMesh(df.Point(-50, -50), df.Point(50, 50), 10, 10)
unit_length = 1e-9
H = 1e6
# Create simulation object.
sim ... | 10a4da043554a93c3d6c90f32c554741b2fe2c7b | 18,740 |
def my_Bayes_model_mse(params):
""" Function fits the Bayesian model from Tutorial 4
Args :
params (list of positive floats): parameters used by the model (params[0] = posterior scaling)
Returns :
(scalar) negative log-likelihood :sum of log probabilities
"""
trial_ll = np.zeros_li... | b4a03e3edd0c9894b518ecd2589949aed8337479 | 18,741 |
def validate_request_tween_factory(handler, registry):
"""
Updates request.environ's REQUEST_METHOD to be X_REQUEST_METHOD if present.
Asserts that if a POST (or similar) request is in application/json format,
with exception for /metadata/* endpoints.
Apache config:
SetEnvIf Request_Method ... | 909e7d67044e31c1b3c0a97774d398f7d64d40bb | 18,742 |
async def get_rank(display_number: int, minimal_msg_number: int,
display_total_number: int, group_id: int) -> str:
""" 获取排行榜 """
repeat_list = recorder_obj.repeat_list(group_id)
msg_number_list = recorder_obj.msg_number_list(group_id)
ranking = Ranking(group_id, display_number, minim... | f1ca183890e33b15b77d7693771b37c33af9535e | 18,743 |
def feedback(request):
"""FeedbackForm"""
if (request.method == 'POST'):
form = forms.FeedbackForm(request.POST)
# pdb.set_trace()
if form.is_valid():
form.save()
type = form.cleaned_data['type']
type = dict(form.fields['type'].choices)[type]
... | 188dfa77d7e72555062e25acc15518f90c252b33 | 18,744 |
def get_convolutional_args(call, include_buffers=False, remove_constants=False):
"""A method to extract the arguments from conv2d or depthwise_conv2d extern call."""
args = call.args
conv_args = []
remove_indices = [0]
if remove_constants:
remove_indices += [41, 42, 44, 45]
for i, arg ... | 01db4d4e025bb9212bcb20a8852a7d4f1250e4b2 | 18,745 |
def view_party(party_id):
"""View dashboard for that party."""
party = party_service.find_party(party_id)
if party is None:
abort(404)
days = party_service.get_party_days(party)
days_until_party = (party.starts_at.date() - date.today()).days
orga_count = orga_team_service.count_member... | de02cf21c9afe35a1dc5ef7a896d99d40a9bd43f | 18,746 |
import _collections
def _sequence_like(instance, args):
"""Converts the sequence `args` to the same type as `instance`.
Args:
instance: an instance of `tuple`, `list`, `namedtuple`, `dict`,
`collections.OrderedDict`, or `composite_tensor.Composite_Tensor`
or `type_spec.TypeSpec`.
args: el... | 576e2c0ff6baeda2f0ff0a89773181ea021e725d | 18,747 |
def subcat_add():
"""
添加小分类
"""
if request.method == 'POST':
cat_name = request.form['cat_name']
super_cat_id = request.form['super_cat_id']
# 检测名称是否存在
subcat = SubCat.query.filter_by(cat_name=cat_name).count()
if subcat :
return "<script>alert('该小分类已经... | 046011d15be00557b28f9300d813ffc6e23d43e0 | 18,748 |
async def async_setup_entry(hass, config_entry, async_add_devices):
"""Set up the Alexa sensor platform by config_entry."""
return await async_setup_platform(
hass,
config_entry.data,
async_add_devices,
discovery_info=None) | b7a4a8a4573ecc008f43a4a9c3e9dcfa21fb0d78 | 18,749 |
def parse_duration(dur: str) -> int:
"""Generates seconds from a human readable duration."""
if not DURATION_REGEX.match(dur):
raise ValueError('Time passed does not match required format: `XX:XX` or `XX:XX:XX`')
parts = dur.split(':')
seconds = 0
if len(parts) == 3:
seconds += int... | ec60b2362d8dc2e898e278b4e1dbf0aca764bc87 | 18,750 |
import random
def shorter_uuid(length=7, starter=None, with_original=False):
"""
Generate an even shorter short UUID generated by the shortuuid library.
:param length: Length of trimmed ID.
:param starter: Whether to begin with an already-created ShortUUID.
Useful when using recur... | 80eca9d14ff3ebeccd77a4b989dde52e4786a042 | 18,751 |
from typing import Iterable
from typing import Callable
from typing import Optional
from typing import List
from typing import Dict
def group_by(s: Iterable[_ElementType],
key: Callable[[_ElementType], _GroupType],
gfunc: Optional[Callable[[List[_ElementType]], _ResultType]] = None) -> Dict[... | b515e0b3a3467b47ad29552bed39b14eca2d2978 | 18,752 |
def init_templateflow_wf(
bids_dir,
output_dir,
participant_label,
mov_template,
ref_template='MNI152NLin2009cAsym',
use_float=True,
omp_nthreads=None,
mem_gb=3.0,
modality='T1w',
normalization_quality='precise',
name='templateflow_wf',
fs_subjects_dir=None,
):
"""
... | 677218b13cbfc48881440523d87667eaed7ea2e8 | 18,753 |
def Qest(ICobj, r=None):
"""
Estimate Toomre Q at r (optional) for ICs, assuming omega=epicyclic
frequency. Ignores disk self-gravity
"""
if not hasattr(ICobj, 'sigma'):
raise ValueError, 'Could not find surface density profile (sigma)'
G = SimArray(1.0, 'G')
kB = ... | f262c0f68683dc069dd983981b2cbd1d9a9e608a | 18,754 |
def get_projector_csr_file(config_name: str) -> str:
"""Returns full path to projector server crt file"""
return join(get_run_configs_dir(), config_name, f'{PROJECTOR_JKS_NAME}.csr') | 159bc798d28bf23ce06d356591d8c41bcea40356 | 18,755 |
import os
def test_xiaomi():
"""
KITTI视差图——>深度图——>点云
"""
def disp2depth(b, f, disp):
"""
"""
disp = disp.astype(np.float32)
non_zero_inds = np.where(disp)
depth = np.zeros_like(disp, dtype=np.float32)
depth[non_zero_inds] = b * f / disp[non_zero_inds]
... | b95d4094e38ce17957b2cba9441f960c1022f653 | 18,756 |
import os
import PIL
def get_img(shape, path, dtype, should_scale=True):
"""Get image as input."""
resize_to = shape[1:3]
path = os.path.join(os.path.dirname(os.path.abspath(__file__)), path)
img = PIL.Image.open(path)
img = img.resize(resize_to, PIL.Image.ANTIALIAS)
img_np = np.array(img).ast... | 829ebfcdab258d5a5b57694c5209fe848300420c | 18,757 |
def make_epsilon_greedy_policy(Q: defaultdict, epsilon: float, nA: int) -> callable:
"""
Creates an epsilon-greedy policy based on a given Q-function and epsilon.
I.e. create weight vector from which actions get sampled.
:param Q: tabular state-action lookup function
:param epsilon: exploration fac... | f0fe733b18b416939db44acd830ee605bc41e18f | 18,758 |
def write_init(proxy_parameters=None, exception=None):
"""Encodes and returns an MPI ('Metadata Init') response."""
return _write_init(Method.MPI, MetadataProviderError, proxy_parameters,
exception) | 0a73c4949796a93549e208da523e805894170193 | 18,759 |
def pfam_to_pubmed(family):
"""get a list of associated pubmed ids for given pfam access key.
:param family: pfam accession key of family
:type family: str
:return: List of associated Pubmed ids
:rettype:list"""
url='https://pfam.xfam.org/family/'+family
pattern='http://www.ncbi.nlm.nih... | e3d63050d7e2e782ccd9d376fb4cd2d33c177be6 | 18,760 |
def cvConvexHull2(input, hull_storage=None, orientation=CV_CLOCKWISE, return_points=0):
"""CvSeq_or_CvMat cvConvexHull2(list_or_tuple_of_CvPointXYZ input, void* hull_storage=NULL, int orientation=CV_CLOCKWISE, int return_points=0)
Finds convex hull of point set
[ctypes-opencv] OpenCV's note: a vertex of th... | 3def10577e29e6b9bcf2611ad194dca2f6e2feb7 | 18,761 |
from typing import Union
from typing import Optional
from typing import Dict
def init_classifier(config: Union[str, mmcv.Config],
checkpoint: Optional[str] = None,
device: str = 'cuda:0',
options: Optional[Dict] = None) -> nn.Module:
"""Prepare a few sho... | 20f819892295f6bfeb9c01f4e6d558731a2f8e68 | 18,762 |
import sys
def get_twitter_auth():
"""Setup Twitter authentication.
Return: tweepy.OAuthHandler object
"""
try:
credentials = read_credentials()
consumer_key = credentials.get('consumer_key')
consumer_secret = credentials.get('consumer_secret')
access_token = credentia... | e84d24159bf4a8aeb4667547ef1f6324de3b8351 | 18,763 |
def Newton_method(f, df, start:float=0.0, max_step:int=32, sign_dig:int=6)->float:
"""
Newton method.
---------------------------
Args:
None.
Returns:
None.
Raises:
None.
"""
fun = lambda x: x - f(x)/df(x)
return fixed_point(fun, start, max_step, sign_dig) | d3a803a1a10b6c6d34831efeccd6fb7bae43689a | 18,764 |
def get_all(isamAppliance, count=None, start=None, filter=None, check_mode=False, force=False):
"""
Retrieve a list of federations
"""
return isamAppliance.invoke_get("Retrieve a list of federations",
"{0}/{1}".format(uri, tools.create_query_string(count=count, start=... | d65529bfc953976247fd44cb50051d5efddf10ea | 18,765 |
def roty(theta):
"""
Rotation about Y-axis
@type theta: number
@param theta: the rotation angle
@rtype: 3x3 orthonormal matrix
@return: rotation about Y-axis
@see: L{rotx}, L{rotz}, L{rotvec}
"""
ct = cos(theta)
st = sin(theta)
return mat([[ct, 0, st],
... | 702051efbd9f0999e04d5d7faca207c53520d712 | 18,766 |
def flush(name, family="ipv4", ignore_absence=False, **kwargs):
"""
.. versionadded:: 2014.7.0
.. versionchanged:: Magnesium
Flush current nftables state
family
Networking family, either ipv4 or ipv6
ignore_absence
If set to True, attempts to flush a non-existent table will n... | 67ab6d2f7e337ff5a68704be14d605298a1447aa | 18,767 |
def solution(s):
"""
Check if a string has properly matching brackets
:param s: String to verify if it is well-formed
:return: 1 if the brackets are properly matching, 0 otherwise
"""
return check_matching_brackets(s, opening="(", closing=")") | 4ba1bb92e0a1db05557980420f2fac3a88b93086 | 18,768 |
def process_to_annotation_data(df, class_names, video_fps, min_len):
"""
This function cleans the output data, so that there are
no jumping frames.
"""
j = 1 # Helper
# Minimum qty of frames of the same task in order to
# consider it a whole task
min_frames = int(float(min_len) * float... | eaa0537b217030664562489a2ceeec63cf7b32c0 | 18,769 |
def reduce_memmap(a):
"""Pickle the descriptors of a memmap instance to reopen on same file."""
m = _get_backing_memmap(a)
if m is not None:
# m is a real mmap backed memmap instance, reduce a preserving striding
# information
return _reduce_memmap_backed(a, m)
else:
# Th... | 4e4caf6bb5f1be1f62537c45671010232665ec0c | 18,770 |
def load_sparse_csr(filename):
"""Load a saved sparse matrix in csr format. Stolen from above source."""
loader = np.load(filename)
return sparse.csr_matrix((loader['data'], loader['indices'],
loader['indptr']), shape=loader['shape']) | 9654e8baedf5ada8b626d86860aef2335a04b565 | 18,771 |
from typing import Optional
def blank(name: Optional[str]) -> Output:
"""Generate a blank `Output` instance."""
return Output(file_suffix=name or _DEFAULT_SUFFIX, variables=dict()) | 0811dd8875983b89a8ae82a204243419effddcb4 | 18,772 |
def estatistica_regras(regras_pt, regras_lgp):
"""
Contagem das regras morfossintáticas no corpus.
:param regras_pt: Lado português das regras (lista)
:param regras_lgp: Lado LGP das regras (lista)
:return: Dicionário com a frequência de cada regra. Ex: {"(0, 'INT')": 1, "(1, 'CAN')": 1, "(2, 'INT')": 1}
"""
est... | 67e1edae2d0418e1a36eefbb16ea4795b04728d6 | 18,773 |
import json
import sys
def read_config():
"""
Reads the configuration info into the cfg dictionary.
:return: A dictionary with the SSH-IPS configuration variables.
"""
CONFIG_FILE = '/etc/ssh-ips/config.json'
try:
with open(CONFIG_FILE, "r") as f:
cfg = json.load(f)
except ValueError as e:
print(str(e))... | 325e2e63fdf47c892ab432930de3e835faf1831d | 18,774 |
def bq_create_dataset(bq_client):
"""Creates the BigQuery dataset.
If the dataset already exists, the existing dataset will be returned.
Dataset will be create in the location specified by DATASET_LOCATION.
Args:
bq_client: BigQuery client
Returns:
BigQuery dataset that will be used to store data... | ff2c0072210541261aff58ef8c590e94260e046d | 18,775 |
def root_node():
"""
Returns DCC scene root node
:return: str
"""
return scene.get_root_node() | 3a632bc0887a5c3a5696ec10f4387c917d12bfe5 | 18,776 |
def firsts(things):
"""
FIRSTS list
outputs a list containing the FIRST of each member of the input
list. It is an error if any member of the input list is empty.
(The input itself may be empty, in which case the output is also
empty.) This could be written as::
to firsts :list
... | 72141a7409cb17ac6785eabde91b45d5e9e0869f | 18,777 |
def inf_set_mark_code(*args):
"""
inf_set_mark_code(_v=True) -> bool
"""
return _ida_ida.inf_set_mark_code(*args) | 0395ab40bac5f036210802fdf548534c83c78951 | 18,778 |
def get_letter(xml):
"""
:param xml:
:return: everything between <bank> tag
"""
try:
left, right = xml.index('<bank '), xml.index('</bank>') + _BANK_OFFSET
return xml[left:right]
except ValueError:
return None | 3c7a601b2a25969902d530e3e17a48ddcf0819c1 | 18,779 |
def stim_align_all_cells(traces, time, new_start):
"""
Make stim-aligned PSTHs from trialwise data (eg. trial x cell x time array). The
advantage of doing it this way (trialwise) is the trace for each cell gets rolled around
to the other side of the array, thus eliminating the need for nan padding.
... | 18861b67b68f37c0c76caad40bd5d583868b1e70 | 18,780 |
def PowercycleNode(opts, args):
"""Remove a node from the cluster.
@param opts: the command line options selected by the user
@type args: list
@param args: should contain only one element, the name of
the node to be removed
@rtype: int
@return: the desired exit code
"""
node = args[0]
if (not ... | 557b48309bb897da29cc1c1f6f724cd6d3959e23 | 18,781 |
def collect_data(bids_dir, participant_label, queries, filters=None, bids_validate=True):
"""
Uses pybids to retrieve the input data for a given participant
"""
if isinstance(bids_dir, BIDSLayout):
layout = bids_dir
else:
layout = BIDSLayout(str(bids_dir), validate=bids_validate)
... | eaa15a3b3dacbae7c16b03f0c6347d71d939b57d | 18,782 |
def minimaldescriptives(inlist):
"""this function takes a clean list of data and returns the N, sum, mean
and sum of squares. """
N = 0
sum = 0.0
SS = 0.0
for i in range(len(inlist)):
N = N + 1
sum = sum + inlist[i]
SS = SS + (inlist[i] ** 2)
mean = sum / float(N)
... | ca1d821ef64b93218bdb22268bfdde737f2d731c | 18,783 |
def gen_filelist(infiles, tmpd) :
"""Write all audio files to a temporary text document for ffmpeg
Returns the path of that text document."""
filename = tmpd/"files.txt"
with open(filename, "w") as f:
for file in infiles:
# This part ensures that any apostro... | c7d21c62de34fea98725a39fec735836e0cfd3d9 | 18,784 |
import os
def check_envs():
"""Checks environment variables.
The MONGODB_PWD is a needed variable to enable mongodb connection.
Returns:
bool: If all needed environment variables are set.
"""
if not os.environ.get('MONGODB_PWD', False):
return False
return True | 22ac892b0eee827f63f7d8258ca49f0e462452fd | 18,785 |
def VMMemoryLower() -> tvm.ir.transform.Pass:
"""Perform memory lowering. Lowers the relax.builtin.alloc_tensor intrinsic to VM intrinsics.
Returns
-------
ret: tvm.ir.transform.Pass
"""
return _ffi_api.VMMemoryLower() | f636ea5f854e42413395669d1a0da3c2e439fb1e | 18,786 |
def _is_disk_larger_than_max_size(device, node_uuid):
"""Check if total disk size exceeds 2TB msdos limit
:param device: device path.
:param node_uuid: node's uuid. Used for logging.
:raises: InstanceDeployFailure, if any disk partitioning related
commands fail.
:returns: True if total disk... | ed39e885825cec7c2fba895121741b43e3661a58 | 18,787 |
def getLines(filename):
"""Return list of lines from file"""
with open(filename, 'r', errors='ignore') as ff:
return ff.readlines() | 36e515decaa3876eed3b5db8363fb81a5db89c84 | 18,788 |
import torch
def bbox_next_frame_v3(F_first, F_pre, seg_pre, seg_first, F_tar, bbox_first, bbox_pre, temp, name):
"""
METHOD: combining tracking & direct recognition, calculate bbox in target frame
using both first frame and previous frame.
"""
F_first, F_pre, seg_pre, seg_first, F_tar = s... | 62d782a04b5d7c114fe0096fec50d6cd2d9db7bf | 18,789 |
def hough_lines(img, rho=2, theta=np.pi / 180, threshold=20, min_line_len=5, max_line_gap=25, thickness=3):
"""Perform a Hough transform on img
Args:
img (numpy.ndarray): input image
rho (float, optional): distance resolution in pixels of the Hough grid
theta (float, optional): angular ... | f797e8b24255225d4c2beb41677da3fa6c6e42d6 | 18,790 |
import packaging
def verify_package_version(ctx, config, remote):
"""
Ensures that the version of package installed is what
was asked for in the config.
For most cases this is for ceph, but we also install samba
for example.
"""
# Do not verify the version if the ceph-deploy task is being... | 5ab0177738ccec3879c0383a13038515b2d6b6e9 | 18,791 |
import os
import glob
def convert_file():
"""Setup code to create a groceries cart object with 6 items in it"""
local_path = os.path.join('data', '2017-07-31_072433.txt')
fixture_path = os.path.join(
os.path.dirname(os.path.realpath(__file__)),
local_path,
)
files = glob.glob(fixture_path... | 1767d5ee584ef1a45f3ebfab92d2c461df6ff965 | 18,792 |
def decrypt(v1: int, v2: int):
"""funcao desencriptadora"""
palavra_encriptada = int(v1) ^ int(v2)
desencriptada = palavra_encriptada.to_bytes((palavra_encriptada.bit_length() + 7) // 8, 'big')
return desencriptada.decode() | 19887e070f0c6ae7e68f677d69c2c5eb24761bdb | 18,793 |
def enforce_mixture_consistency_time_domain(mixture_waveforms,
separated_waveforms,
mix_weights=None,
mix_weights_type=''):
"""Projection implementing mixture consistency in time domain.... | 294b1d927394ef388967de529ac5f24382ceec2c | 18,794 |
def MatchNormsLoss(anchor_tensors, paired_tensors):
"""A norm on the difference between the norms of paired tensors.
Gradients are only applied to the paired_tensor.
Args:
anchor_tensors: batch of embeddings deemed to have a "correct" norm.
paired_tensors: batch of embeddings that will be pushed to the n... | 02f62a90cf51547b4af6063ad13be1bb712dfe5a | 18,795 |
def get_ei(xx_tf, yn_tf, gp):
"""
:param xx_tf: A tensor giving the new point to evaluate at.
:param yn_tf: A tensor giving all previously observed responses.
:param gp: A gp used to predict. GP should be trained on the locations yn_tf was observed.
"""
N, P = gp.index_points.numpy().shape
... | af1b41e80a74d505161a5c9edc2334a6d4e691bf | 18,796 |
def authenticate_begin(username, **_):
"""
Begin authentication procedure
Variables:
username user name of the user you want to login with
Arguments:
None
Data Block:
None
Result example:
<WEBAUTHN_AUTHENTICATION_DATA>
"""
user = STORAGE.user.get(username, as_obj=... | 6a42bfd2aba2f17f7ee7ec892bf23ef2f0221ee0 | 18,797 |
def tempSHT31():
"""Read temp and humidity from SHT31"""
return sht31sensor.get_temp_humi() | 1e934ad3a467d48019ec91e18ffab4e8d4c473ae | 18,798 |
import requests
def dog(argv, params):
"""Returns a slack attachment with a picture of a dog from thedogapi"""
# Print prints logs to cloudwatch
# Send response to response url
dogurl = 'https://api.thedogapi.com/v1/images/search?mime_types=jpg,png'
dogr = requests.get(dogurl)
url = dogr.json(... | cb80426e6cab0aa2fc58b78baa0ff225d654f04a | 18,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.