content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def get_array_of_field_values_matching(field_names, matchop, collection_obj):
"""Returns an array with all values the given field takes in all documents
matched by the given Matchop in the given collection."""
push_dict = {field_name : "$" + field_name for field_name in field_names}
agg_pipe = [
... | 4c02826b2dc598c1ba3f12df467fcbb6283a1a2b | 633,566 |
def partition_label_unlabeled(train_data_vector,label_dict):
"""
To segregate training data into labeled and non labeled based on fraction
"""
for index in range(len(train_data_vector)):
if ("unknown" in label_dict.keys()):
if (train_data_vector[index][-1]==label_dict["unknown"]):... | c53e1c77275c24b58ae6ea5d8c83892cb5c0dd40 | 633,567 |
import re
def to_valid_key(name):
"""
convert name into a valid key name which contain only alphanumeric and underscores
"""
valid_name = re.sub(r'[^\w\s]', '_', name)
return valid_name | 458683acbad2fcd72cc39a586ae4c1d1fbf8cf73 | 633,568 |
def get_minimum(poly, search_range=None):
""" Get the minimum values of a polynomial.
parameters:
===========
- poly: np.poly1d instance
- search_range: list of size 2
Should contain the minimum and maximum search range in index 0 and 1 (respectively)
returns:
=======... | de8893b4c9ae6a134ae2d7e1e239ecc89bbe85e5 | 633,569 |
import math
def myround(x, base, choice=None):
"""
Round values to the nearest base
:type x: float
:param x: value to round
:type base: int
:param base: nearest number to round to
:type choice: str
:param choice: 'up' to round up, 'down' to round down, or None for nearest
"""
... | 82b75a0c3883a481645b590e5253e07c25086c93 | 633,570 |
import sys
def detect_codec(data: bytes, codecs: tuple = (('utf-32-le', 4),
('utf-16-le', 2))) -> tuple:
"""Attempt to detect codec of data. Returns codec string and corresponding
code point length."""
for values in codecs:
codec, cp_len = values
... | 009be4a0acf3340d1db3d67239fafc51768518f8 | 633,574 |
def fix_sqltype(sqltype):
"""Fix `sqltype` string. Force uppercase string and
change 'FLOAT' -> 'REAL'.
Parameters
----------
sqltype : str
Returns
-------
st : string
"""
st = sqltype.upper()
if st == 'FLOAT':
st = 'REAL'
return st | ffdb226a4fbed30f48344e2c1d6328be52e8bf70 | 633,576 |
def add_text_generate_args(parser):
"""Text generation arguments."""
group = parser.add_argument_group(title='text generation')
group.add_argument("--temperature", type=float, default=1.0,
help='Sampling temperature.')
group.add_argument("--greedy", action='store_true', default=F... | 0c1838ca868eb2685ce3a9dd5284b0892c889edc | 633,577 |
from typing import Callable
from typing import Iterable
def zip_with(func: Callable, *iters) -> Iterable:
"""`zip` all the iters and apply function `func` to each of them
"""
return map(func, zip(*iters)) | 9e0c1635d9f11b133fa54c47310125fa480b91b6 | 633,578 |
def decode_variable_integer(bytes_input: bytes):
"""
If the length is fitting in 7 bits it can be encoded in 1 bytes.
If it is larger then 7 bybitstes the last bit of the first byte indicates
that the length of the lenght is encoded in the first byte and the length
is encoded in the following bytes.... | ba770a3a1035d8b3e8df4f85c428b6729a20ab09 | 633,579 |
import torch
def get_corr_together(fake_ys, y):
"""
Args:
fake_ys (torch.Tensor): with shape (n_results, n_sample,).
y (torch.Tensor): with sample (n_sample,).
Returns:
corr (torch.Tensor): with shape (n_result,)
"""
# 转置不转置速度相同
fake_y_mean = torch.mean(fake_ys, dim... | a4984853f3032c8ac8f72b630eb17223e83fa4b9 | 633,580 |
import io
def txt_only_abstract_reader(filepath):
"""
Use this method to read ONLY an abstract from file
:param filepath:
:return: a list of abstract
"""
result = []
with io.open(filepath, "r", encoding="utf-8") as f:
lines = f.readlines()
for line in lines:
if ... | 9963ea064aa0f0cfb63a417bae4e275f74c2d9ac | 633,581 |
from pathlib import Path
import os
import sys
def check_target_type(target, filetype):
"""Validate path and file / directory type.
It also returns the appropritate fio command line parameter based on the
file type.
"""
keys = ["file", "device", "directory", "rbd"]
test = {keys[0]: Path.is_fi... | 5005a24d29beb8597a4567efeb47bab646eca77b | 633,582 |
def _king_black_limit(square):
"""
白方田字格限制
:param square:
:return:
"""
return square in [66, 67, 68, 75, 76, 77, 84, 85, 86] | 7e27a28b18fa745519340b41a5f9d88574aa4c0d | 633,583 |
def control_char_symbol(c: str) -> str:
"""Returns one of the Unicode Control Picture characters (e.g. '␛') for
the given single-character string with an ord() less than 32.
Raises ValueError for invalid strings.
"""
if len(c) != 1 or ord(c) >= 32:
raise ValueError('Argument must be a singl... | 55e95d6b1db5d1e65ea5011711f026684f1f58b5 | 633,584 |
import random
import torch
def random_channel_mask(stage_repeats=None, stage_out_channels=None, candidate_scales=None,
select_all_channels=False):
"""
candidate_scales = [0.2, 0.4, 0.6, 0.8, 1.0, 1.2, 1.4, 1.6, 1.8, 2.0]
"""
if stage_repeats is None:
stage_repeats = [4,... | 34cdc8684cf0421787168aa27ff12e223d6c11a2 | 633,586 |
def tf(tokens):
""" Compute TF
Args:
tokens (list of str): input list of tokens from tokenize
Returns:
dictionary: a dictionary of tokens to its TF values
"""
d = {}
for token in tokens:
if token in d:
d[token] += 1
else:
d[token] = 1
t... | aac14c2f771638467a151ec18b4d5366386b4a71 | 633,587 |
def sys_encoding():
"""Charset to use for --file <path>|- (stdin)"""
return 'utf8' | 70a61870803f8a77dd42f818f895138c13e2af9b | 633,588 |
def insert_timestamp_single_row_csv(header: bytes, rows_list: list, time_stamp: bytes) -> bytes:
""" Inserts the timestamp field into the header of a csv, inserts the timestamp
value provided into the first column. Returns the new header string."""
header_list = header.split(b",")
header_list.inser... | ac16af5d8e40598bfb271deb2bc81734022ac576 | 633,589 |
def converted_tests():
"""Example of pytest-json report output converted to Mig3 spec."""
return [{"module": "tests/test_converter.py", "test": "test_simple_convert"}] | 0727fc712a5a5fc035195e3416d9e70fee74455c | 633,591 |
def setup_1():
"""Setup test 1."""
list0 = [i for i in range(10)]
list1 = [i + 0.5 for i in range(5, 20)]
list1[3] = 8
return list0, list1 | fa0e35c302efb8fbb6173b8776d665651c66d997 | 633,592 |
import collections
def _make_skew_prows(grid):
"""
0 1 2 3 6 7 4 5, "right init"
"""
Ncore, Nrow, Ncol = grid
chips_per_pcol = Ncore * Nrow
out = []
for i in range(Ncol):
col = collections.deque(range(i * chips_per_pcol, (i + 1) * chips_per_pcol))
col.rotate(Ncore * i)
out += tuple(col)
re... | 7fe9e9e15efc183b108ab3d9d824d62674cddc02 | 633,593 |
def extract_by_index(a_list, indices):
"""
Creates a list that consists of the elements at the given indices of
the given list.
:param a_list: The list to get elements from.
:param indices: The indices to use to source elements.
:return: The selected list.
"""
retur... | 76d6594645985066df31a53059b5308c2338b494 | 633,594 |
def next_turn(events):
"""
list of (turn, move, returnvalue)
return returnvalue where turn is smallest, on tie move is largest
"""
return sorted(events, key=lambda tup: (tup[0], -tup[1]))[0][2] | d6610c7aa66fed8e58caf2a900fb8e9ddaee51a9 | 633,595 |
def index_to_factoradic(value, num_elem=None):
""" Convert the int:index to a factoradic representation in a list, indexed 0 to n-1
Args"
value: the integer to convert to mixed radix format
num_elem: Ignored. For API compatability with `factoradic_to_permutation`.
Returns:
"""
remai... | 33a9f39b0e7de304693f737f80868f66e3b65d90 | 633,597 |
def is_prime(integer):
"""Determines weather integer is prime, returns a boolean value"""
# add logic here to make sure number < 2 are not prime
for i in range(2, integer):
if integer % i == 0:
return False
return True | d4e8d54cb25006217bc47687e47ba72a0fefc23b | 633,598 |
def filter_noncruising(trip_list, keep_only_driving=False,
keep_all_fhv=True, silent=True):
"""Removes trips labeled as 'not_cruising' after classification.
trip_list [list]: a list of dicts in JSON format.
keep_only_driving [bool]: should segments not identified
as 'driving' be dropped fro... | 028c1d25f1827b8a8648d17f594461dd1266e85c | 633,599 |
def batch_get_similarity_matrix(ref, target):
"""
Get pixel-level similarity matrix.
:param ref: (batchSize, num_ref, feature_dim, H, W)
:param target: (batchSize, feature_dim, H, W)
:return: (batchSize, num_ref*H*W, H*W)
"""
(batchSize, num_ref, feature_dim, H, W) = ref.shape
ref = ref.... | edc516b0aba8990eb37839bf578a75be5f479f65 | 633,600 |
def fallbackSeries(requestContext, seriesList, fallback):
"""
Takes a wildcard seriesList, and a second fallback metric.
If the wildcard does not match any series, draws the fallback metric.
Example:
.. code-block:: none
&target=fallbackSeries(server*.requests_per_second, constantLine(0))
... | ff50bc21530e1ca7ce079132437dbdcd88f13886 | 633,601 |
import inspect
def get_class_property_names(obj: object):
"""Returns the names of all properties of a class."""
return [
p[0] for p in inspect.getmembers(type(obj), inspect.isdatadescriptor)
if not p[0].startswith("_")
] | b96413d4b17aef2f0b53b68528c394cd50c3cdaf | 633,602 |
def get_most_popular_drugs(nonzero_df):
"""
Get the top 3 drugs that are used by patients.
Input
-----
df: pandas.DataFrame
The dataframe containing patients with positive response to treatments
Returns
-------
popular_df: pandas.DataFrame
The dataframe containing t... | f77a8753e2ec3515a601fb67240ca2e9daeeb0ca | 633,603 |
def c_to_f(temp):
"""
Convert celcius temperature to fahrenheit.
"""
return temp * 1.8 + 32 | 101135ffd13f4d2d636305ea33968734cb1ebb07 | 633,604 |
import string
import secrets
def generate_password(length=12):
"""Generates a random password
Args:
length (int, optional): Length of the generated password. Defaults to 12.
Returns:
str: The output generated password
"""
req_str = string.ascii_letters + string.digits
secure... | 5ddf9c957a2ed994617f8650b51b49ee489d8d70 | 633,605 |
import yaml
def read_yaml(config_name, config_path):
"""
config_name:需要读取的配置内容
config_path:配置文件路径
"""
if config_name and config_path:
with open(config_path, 'r', encoding='utf-8') as f:
conf = yaml.safe_load(f.read())
if config_name in conf.keys():
return co... | 033e4781a1ca27ceba21cfd553db357024509570 | 633,606 |
def get_current_session(request, hproPk):
"""Get the current session value"""
retour = {}
base_key = 'plugit_' + str(hproPk) + '_'
for key, value in request.session.iteritems():
if key.startswith(base_key):
retour[key[len(base_key):]] = value
return retour | b4eee60a436076d3d489856825a2db48a3bb416c | 633,607 |
def p_second_half(spec, clip_left2, clip_right2, top, f21, pmax, p, f):
"""Interpolate the second half of the triangle"""
df2 = top / f21
diff = f[2] - p - 1.0
if not clip_left2:
spec[p] += (f21 - diff) * (diff + f21) * 0.5 * df2
else:
spec[p] += (diff + 0.5) * df2
p += 1
... | 9084183d1250a0fbe82f55f1999b548694100f24 | 633,608 |
def max_run(_b, _x):
"""Determine the length of the maximum run of b's in vector x.
Parameters
----------
b: int
Integer for counting.
x: array
Vector of integers.
Returns
-------
max: int
Length of maximum run of b's.
"""
# Initialize counter
_max ... | 3d0afdfd13bfe6f4c4b5009b115a33c7714f34c6 | 633,609 |
def mock_cavatica(mocker, settings):
""" Mocks out project setup functions """
settings.CAVATICA_HARMONIZATION_TOKEN = "testtoken"
settings.CAVATICA_DELIVERY_TOKEN = "testtoken"
cavatica = mocker.patch("creator.studies.schema.django_rq.enqueue")
return cavatica | d8be3763f260571a76f8ad9a2142674980cd0bfa | 633,610 |
import os
def test_env():
"""
Check if the environment has the right variables set
"""
unset = set()
for i in ('HOME', 'PATH', 'TERM'):
if not os.environ.get(i):
unset.add(i)
if unset:
variables = ', '.join('$%s' % i for i in unset)
print('ERROR: %s not set'... | f8a121627a1338ccbfcaefdff520ef1449df0231 | 633,611 |
import json
def translate(key, lang='fr'):
"""
Une fonction de traduction
"""
with open('langs.json') as fichier:
trans = json.load(fichier)
mot_cle = trans.get(key)
if mot_cle:
return mot_cle.get(lang) \
if mot_cle.get(lang) else mot_cle
else:
return key | bb90f058ecc78d43c2fb4f97b48cccc8031d5a0a | 633,612 |
def flatten_output_shape(input_shape, options=None):
"""Flatten operation input to output shape conversion"""
return (int(input_shape[0]), int(input_shape[1] * input_shape[2] * input_shape[3])) | a50f08ecbff91417cdc36176874ba8060abaf7ab | 633,613 |
def ssh_cmd_container_instance(detail) -> str:
"""SSH command to access a ecs2 instance by id."""
return f"TERM=xterm ssh {detail['ec2InstanceId']}" | 003255798f038fe9ac676549049e5c89792fa6fd | 633,615 |
def get_tmin_tmax(ct_idx, chop_times, sfreq):
"""
Get tmin and tmax for the chop interval based on the
time points given by chop_times.
Parameters:
-----------
ct_idx : int
Index corresponding to chop_times.
chop_times : list of float
List with the time points of when to cho... | 0e5446f121c5c5bce7d59697790b907bf1d1500f | 633,616 |
def uniform(destinations):
"""
Create a uniform distribution for given destinations.
destinations: iterable of states
"""
count = len(destinations)
mod = 100 % count
prob = 1/count
dist = {i: prob for i in destinations}
last = destinations[-1]
dist[last] = dist[last] + 0.01*mod
... | bd0896de68a0b6b41a0edbd8ef0ffc3b64afb289 | 633,617 |
import time
def datetime2ts(dt):
""" Convert a `datetime` object to unix timestamp (seconds since epoch).
"""
return int(time.mktime(dt.timetuple())) | 289c11c47d4cb0e9a6ea620fa5b40f81e4c5644d | 633,618 |
def sreprlow(s):
"""Squash unicode and return the repr() of string `s` as lower case."""
return repr(str(s)).lower() | 5fb91c45d05b075e488fa0b2f1084ed811538548 | 633,619 |
def file_from_list_of_images(file_list, current_file, request):
"""return filename from file_list depends of request
request: position on the list
"""
if file_list:
if request == "first":
file = file_list[0]
elif request == "previous":
position = file_list.index(c... | 0a24a0bcd19f8b3104f20ca896a40a7a3049de52 | 633,620 |
def FormatThousands(value):
"""Format a numerical value, inserting commas as thousands separators.
Args:
value: An integer, float, or string representation thereof.
If the argument is a float, it is converted to a string using '%.2f'.
Returns:
A string with groups of 3 digits before the decimal po... | df453e379924644c7a7822dff3d5a54e4a9f3276 | 633,621 |
import time
import subprocess
def run_command(cmd,argslist=None,dir='.'):
""" runs a command in the shell
cmd: executable
args: array of arguments
dir: the directory to run executable
returns: time(ms), subprocess object, stdout
"""
start_time = time.time()
if argslist... | 04e964863193a538a66ace9ec644ca99cd27cccf | 633,622 |
def get_ligand_filetype(ligand_filename):
"""Returns the filetype of ligand."""
if ".mol2" in ligand_filename:
return "mol2"
elif ".sdf" in ligand_filename:
return "sdf"
elif ".pdbqt" in ligand_filename:
return "pdbqt"
elif ".pdb" in ligand_filename:
return "pdb"
else:
raise ValueError("... | 0c56e63a314cb0994989c14180c7fd542181969d | 633,623 |
def list_of(type):
"""Return to_list such that to_list([x0, x1, ...]) returns
[type(x0), type(x1), ...].
"""
def to_list(x):
return [type(e) for e in x]
return to_list | 65c692a9a7a4473457aff5c658f48da569ed9f2d | 633,624 |
import sys
def validate_tagname(repo, tagname):
"""Try to find a given tagname in a repo's tags.
If no tagname is given, find the youngest tag.
Return a dict containing tag name and tag date
"""
print('Fetching tags...')
tags = repo.get_tags()
tag_list = []
for t in tags:
tag... | 40b495870ea00bf1dbca4e522b402a542c439051 | 633,626 |
def starfilter(pred, iterable):
"""
Analogous to starmap from the itertools module, but wrt. filter. Basic functionality only.
:param pred:
:param iterable:
:return:
"""
if pred is None:
return filter(None, iterable)
def new_pred(args):
return pred(*args)
return fi... | a5237d889da2e1c50b00ae222a545354c44d5280 | 633,627 |
def _check_value(value):
"""Convert the provided value into a boolean, an int or leave it as it."""
if str(value).lower() in ["true"]:
value = True
elif str(value).lower() in ["false"]:
value = False
elif str(value).isdigit():
value = int(value)
return value | b5dbc8925de7ea383529a7131d5d65bb1f7e88fc | 633,628 |
def getdiffmeta(diff):
"""get commit metadata (date, node, user, p1) from a diff object
The metadata could be "hg:meta", sent by phabsend, like:
"properties": {
"hg:meta": {
"date": "1499571514 25200",
"node": "98c08acae292b2faf60a279b4189beb6cff1414d",
"u... | 8bd27fc7cbf62d20b08e4f8aa65d4f0cef2d3e0b | 633,629 |
def mergesort(list, descending=False):
"""
Takes in a list as an argument, and sorts it using a "Merge Sort"-algorithm.
---
Args:
- list (list): The list to be sorted
- descending (bool): Set true if the list be sorted high-to-low. Default=False
Raises:
- TypeError:... | a13b242eb58a89163290e229e8d78fe87c4bf0d7 | 633,630 |
import argparse
def getCommandLineArgs():
""" Process the command line arguments """
parser = argparse.ArgumentParser(prog="ccvalidator",
description="Validate and determine the issuer of a given credit card number")
parser.add_argument("card_num", help="Credit card number")
return parser... | 9b1f61b0832ac419414176b2d321cdf0f7a00ed0 | 633,631 |
def GetUniqueSessionID(process_obj):
""" Create a unique session identifier.
params:
process_obj: lldb.SBProcess object refering to connected process.
returns:
int - a unique number identified by processid and stopid.
"""
session_key_str = ""
if hasattr(process_obj, "... | eff6214503bc63080aee39b3e142e9d131fa7ebd | 633,632 |
import re
from datetime import datetime
def clean_title_input(title, draft=False):
"""Convert a string into a valide Jekyll filename.
Remove non-word characters, replace spaces and underscores with dashes,
and add a date stamp if the file is marked as a Post, not a Draft.
Args:
title (string... | 80958f893641bd420f487077d009be4c3efec1dc | 633,633 |
def _find_node(state, node_id_or_label):
""" Finds a node according to its ID (if integer is
provided) or label (if string is provided).
:param node_id_or_label Node ID (if int) or label (if str)
:return A nodes.Node object
"""
if isinstance(node_id_or_label, str):
for n i... | 32a73b9e486994110e5ff812702cd4a6294fd7fb | 633,634 |
def _subsample( X, ind):
""" like X[ind,:] but works in case X has size (n,) """
if X.ndim == 1:
y = X[ind]
elif X.ndim == 2:
y = X[ind,:]
else:
raise ValueError("Expected 1D or 2D array")
return y | 6d9a3632fbe88acdf664fe919e93b14ac2933a86 | 633,635 |
def _make_task_name(cls, addons=None):
"""Makes a pretty name for a task class."""
base_name = ".".join([cls.__module__, cls.__name__])
extra = ''
if addons:
extra = ';%s' % (", ".join([str(a) for a in addons]))
return base_name + extra | 07cd75c4782cdfcc268720c5a411a9eb161a4a0c | 633,636 |
def _test2(num1, num2):
"""Sample function for TestCase.
Returns the supplied values.
Args:
num1: number 1
num2: number 2
Returns:
float: sum of number 1 and 2
"""
return float(num1) + float(num2) | 9d43da9a9864d367a54248386e78fe15f0977a37 | 633,637 |
import six
def collect_namespaces(root_spec):
"""Constructs a set of namespaces in a given ElementSpec.
Args:
root_spec: An `ElementSpec` for the root element in the schema.
Returns:
A set of strings specifying the names of all the namespaces that are present
in the spec.
"""
findable_namespac... | 5eba961e8aaa7f4a84279fd082b55fab66f7ce37 | 633,638 |
def school2nation(id_num):
"""
Takes school id, returns nation id of the school.
"""
if id_num < 97100000:
return id_num // 100000 * 10000
if id_num < 97200000:
return 7240000
if id_num < 97400000:
return 8400000
return 320100 | 74e7eb74b2adf1cd2c8855a1bcc35eddf38586e3 | 633,639 |
def peel_ptr_decl(decl_type_node):
""" Remove PtrDecl and ArrayDecl layer """
is_ptr_decl = False
peeled_decl_type_node = decl_type_node
while peeled_decl_type_node.__class__.__name__ == 'PtrDecl' or peeled_decl_type_node.__class__.__name__ == 'ArrayDecl':
is_ptr_decl = True
peeled_decl_type_node = peel... | 3195e2442975c8dae56ad3a754a850e4835d7849 | 633,640 |
import pandas
import numpy
def pandas_df_without_nan(df: pandas.DataFrame, value:object=None) -> pandas.DataFrame:
"""
Takes a pandas DataFrame, replaces the numpy.nan values with None.
Or with value specified with optional `value` kwarg.
"""
return df.replace({numpy.nan: value}) | cccdffd2421695bedbe40b3d890ffb3c4310c59c | 633,641 |
import math
def latitud_en_radianes(latitud):
"""
calcula la latitud en radianes
param: latitud: latitud de la estación
"""
return (math.pi * latitud)/180 | f82d286e93d38e8470262c64f321849e5a6ce385 | 633,642 |
def _get_query_string(args):
"""Return the query values given the arguments to a pymemcache command.
If there are multiple query values, they are joined together
space-separated.
"""
keys = ''
# shortcut if no args
if not args:
return keys
# pull out the first arg which will c... | 21acad5f484c91d0474b55bf2bc906826371a022 | 633,643 |
import string
import random
def nicepass(alpha=6,numeric=2):
"""
returns a human-readble password (say rol86din instead of
a difficult to remember K8Yn9muL )
"""
vowels = ['a','e','i','o','u']
consonants = [a for a in string.ascii_lowercase if a not in vowels]
digits = string.digits
#... | ec798b7f16baf8616397ab961a81d228d5b93a9f | 633,644 |
def pybb_posted_by(post, user):
"""
Check if the post is writed by the user.
"""
return post.user == user | 5bd87efee55d00af13b10be2247956408c42cb18 | 633,646 |
import torch
def shearx_grid(output_size, ulim=(-1, 1), vlim=(-5, 5), out=None, device=None):
"""Horizontal shear coordinate system.
Args:
output_size: (int, int), number of sampled values for the v-coordinate and u-coordinate respectively
ulim: (float, float), Cartesian y-coordinate limi... | 76682d670995b45140207029458855201d3207ed | 633,647 |
def block_schema_to_dict(schema):
"""Serializes block schema to dict.
Args:
schema: block schema to serialize into dict.
Returns:
dict: dict from BlockSchema.
"""
return dict(
schema_id=str(schema.id),
name=schema.name
) | 6554c825a6707995447363b4977658cd50511067 | 633,648 |
def classname(cls):
"""Create the class name str for __repr__"""
return '.'.join([cls.__class__.__module__, cls.__class__.__name__]) | c12290a6829eea08909ce722a43c31c9fc8373bf | 633,649 |
import os
def check_meta_ettus_path(mep):
"""
Check if mep is a valid path of a meta-ettus repository.
"""
return os.path.isdir(os.path.join(mep, 'meta-ettus-core')) | 3ecc583f12fbfad3961a4a213ddc982cd7af56d7 | 633,650 |
import pickle
def get_ibc_data(use_neutral=False,
use_subsampling=False,
return_subsampling_depths=False,
labels=(0, 1, 2)):
"""
Samples the annotated IBC data. This dataset can be described
more here. http://www.cs.umd.edu/~miyyer/ibc/.
This dataset... | 4571b6d42b2dca1c52fb5089e29047c17c64363f | 633,651 |
import os
import re
def get_all_sizes(folder, suffix='*'):
"""
will sort and list all the files by their sizes.
If some files have the same size, will list them together
Args:
----
folder: gs folder path
suffix: of a specific file type
Returns:
-------
dict(sizes:[paths... | 9effe955f4c49c3144b70d99e567b62e341a34b8 | 633,652 |
def tokens2options(tokens):
"""Split the list of tokens into the options it specifies, even if
there is a single option.
Arguments:
`tokens` -- the list of tokens to split, as provided by the tokenizer.
Returns:
A list of options, suitable for parsing.
"""
options = []
option = []
... | ac3ba1d2c21a3d2e7b14ec55091dce2f6397b866 | 633,653 |
import torch
def bce_loss(y, y_hat):
"""
Args:
y_hat: the prediction tensor
y: the label tensor
Return:
loss: scalar of loss
dJdy_hat: The gradient tensor of shape (batch_size, linear_2_out_features)
"""
loss = -(1.0/y.shape[1])*torch.sum(y * torch.log(y_ha... | f2e3bb7f9f0476a797f0996d7a07b29bab1f39f3 | 633,654 |
def dummy_annotation_txt_header(tmpdir_factory):
"""Create txt header."""
content = ("# A something \n"
"# orig_time : 42\n"
"# orig_time : 2002-12-03 19:01:11.720100\n"
"# orig_time : 42\n"
"# C\n"
"Done")
fname = tmpdir_factory.mkt... | 778fa90948c502e6ed9fffc91cb3b22ba78085b4 | 633,656 |
def traverse_keys(d, keys, default=None):
"""
Allows you to look up a 'path' of keys in nested dicts without knowing whether each key exists
"""
key = keys.pop(0)
item = d.get(key, default)
if len(keys) == 0:
return item
if not item:
return default
return traverse_keys(it... | 6b2586e0fff4527ccbd50c8d6f0a9626056b3043 | 633,657 |
def threshold_RMSE(upper_bound, lower_bound, q=3):
"""Compute threshold for RMSE metric.
Args:
upper_bound (int): Upper bound of regression outputs
lower_bound (int): lower bound of regression outputs
q (int): Quantification parameter
Returns:
threshold (float): The minimal... | 210036056c59d4a52fa9401a78529ee7c8d3b503 | 633,658 |
def TxtWrapBy(start_str, end, all):
"""
获取选取设备信息的索引,通过[]之间的字符去解析
:param start_str: 开始字符
:param: end: 结束字符
:param: all: 总字符串
:return: 返回相应解析的字符串
"""
start = all.find(start_str)
if start >= 0:
start += len(start_str)
end = all.find(end, start)
if end >= 0:
... | 7577a4b35b5b97c5801a99b0487d87a10d7fa7d1 | 633,659 |
def enum(*sequential):
"""
pseudo Enum type; Usage: EnumType=enum('key1','key2',...,)
"""
enums = dict(zip(sequential, range(len(sequential))))
return type('Enum', (), enums) | 25ed597429af0183c1ce2383e40b2de2b353526e | 633,660 |
from typing import List
def find_first_k_missing_positive(nums: List[int], k: int) -> List[int]:
"""
Time Complexity: O(N)
Space Complexity: O(1)
Parameters
----------
nums : List[int]
Input unsorted array.
k : int
Input number 'k'.
Returns
-------
List[int]
... | 6218c0a87e6c0ad18d18b7c1e8da49a812199e66 | 633,661 |
def capitalize_correct(phrase):
"""
Capitalizes words in a string, avoiding possessives being capitalized
"""
phrase = phrase.strip()
return " ".join(w.capitalize() for w in phrase.split()) | 3771dbd16bb21a03cf009d8301821545e0a03f95 | 633,662 |
def delete(path):
"""decorator which registers a class method as a DELETE handler"""
def decorator(f):
f._endpoint = path
f._methods = ['DELETE']
return f
return decorator | fdebc4b4290e1b502ac227b32bb4830c3601e3da | 633,663 |
def parseSecondsIntoReadableTime(seconds):
"""Generate a string based on seconds having the format "m:s:cs"."""
minutes = seconds / 60
absoluteMinutes = int(minutes)
seconds = (minutes - absoluteMinutes) * 60
absoluteSeconds = int(seconds)
m = str(absoluteMinutes)
if absoluteMinutes <= 9:
... | 88773b328018b8b6b05139dc8e8e57f9e387c97c | 633,664 |
def function_1_arg(first_argument):
"""one argument function"""
return first_argument | 0f143bf0a9fe0523b017b426090a3a3dad81065f | 633,665 |
import torch
def generate_grid(zmin, zmax, dz, device, ndim=2):
"""generate a 1- or 2-dimensional grid
Returns: Tensor, int
Tensor: The grid tensor with shape (k^2, 2),
where k=(zmax - zmin)/dz
int: k
"""
if ndim == 2:
x = torch.arange(zmin, zmax, dz)
k = x... | 680e115139ba3c249cde18b6532a39bd83164330 | 633,666 |
def remove_unknowns(vocab, sentence):
"""
assuming sentence is a list
"""
for i in range(len(sentence)):
if not sentence[i] in vocab:
sentence[i] = "<unk>"
return sentence | 1411b6eaacacff3ba277d4c81aadc603f6476b64 | 633,667 |
def trapezoid_area(base_short,base_long,height):
"""Usage: Find the area of a trapezoid"""
return ((base_short+base_long)/2)*height | a666bc4b2461753acd7f18b66280366b55185bf1 | 633,668 |
from typing import Dict
from typing import Any
from warnings import warn
def has_license_and_update(data: Dict[str, Any]) -> bool:
"""Check if license header exists anywhere in notebook and format.
Args:
data: object representing a parsed JSON notebook.
Returns:
Boolean: True if notebook contains the ... | 67f3f6d7b9f31961f138824482926dcf529f5409 | 633,670 |
import os
def getLoad():
"""Get the system load in 1m,5m and 10m. This is available under Linux or Darwin only."""
load = {}
system_load = os.getloadavg()
# check if system_load is None before adding it
if system_load is not None:
# In this tupple get the middle one
load.update({"1... | a9a9e9c722085dec27625856ef0b2b7e330248c6 | 633,671 |
def lookup_salt(email_address, db):
"""
lookup and return a user's password salt
"""
salt_dict = db.users.find_one(
{'email_address_lowercase': email_address.strip().lower(), 'salt': {'$exists': 1}},
{'salt': 1})
if salt_dict is not None:
return salt_dict['salt']
... | a40b04cc59154e069f0a6825eb7aae544cb73e9a | 633,672 |
from pkg_resources import get_distribution, DistributionNotFound
def distribution_version(name):
"""try to get the version of the named distribution,
returs None on failure"""
try:
dist = get_distribution(name)
except DistributionNotFound:
pass
else:
return dist.version | 08f437a02ea356abe821e635a5319f6bd324c204 | 633,673 |
def to_css_length(x):
"""
Return the standard length string of css.
It's compatible with number values in old versions.
:param x:
:return:
"""
if isinstance(x, (int, float)):
return '{}px'.format(x)
else:
return x | bb4dde6bb8288f3b7c11e89f56b1413f881abb86 | 633,674 |
def nD0_active(N, vzero, dr, L):
"""
Returns product of particle density n = N/L^2 and active diffusion constant
D_0 = vzero^2/2*dr.
Parameters
----------
N : int or float
Number of particles.
vzero : float
Self-propelling velocity.
dr : float
Rotation diffusion ... | 14ea2f249a68fd4dbdde94d72b94fc3d38009a68 | 633,675 |
def ishappy(n):
"""
Takes an input of a number to check if it is happy
Returns bool values True for a happy number and False for unhappy numbers
"""
cache=[1, 7, 10, 13, 19, 23, 28, 31, 32, 44, 49, 68, 70, 79, 82, 86, 91, 94, 97, 100, 103, 109, 129, 130, 133, 139,
167, 176, 188, 190, 192, 1... | 3670494f84e5fe1065e965dd126b99ba0fed8a88 | 633,676 |
def unsetbit(target, bit):
"""
Сбрасывает бит bit в 0 в байте target
"""
return target & ~ (1 << bit) | 271786ba73b76fadcafe4285c251c56cafbb8061 | 633,678 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.