content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import math
def hm_sim_str(s1, s2):
"""字符串的汉明距离"""
if s1 is None or s2 is None:
return -999.9
if len(s1) != len(s2):
raise ValueError("Not same length:`s1`, `s2`")
return math.log(sum(el1 == el2 for el1, el2 in zip(s1, s2)) / len(s1)) | 23932d89aeb3c0d7be9648fe24118548af5a593f | 672,724 |
def combine_bytes(reorder):
"""Combine list of bytes into one binary sequence"""
o = b''
for r in reorder:
o += r
return o | 8014302a48e839edf4fcb6a1cd8f978d5bfa92e5 | 672,725 |
import os
def is_path_root(path: str) -> bool:
"""Returns whether or not the given (host) path is the root of the filesystem."""
real_path = os.path.realpath(path)
parent_real_path = os.path.realpath(os.path.join(real_path, '..'))
return real_path == parent_real_path | a0d1703de53366f465814422492a131fd76d37d5 | 672,726 |
def adjust_error_on_warning_flag(flag, step, language):
"""
Adjust a given compiler flag according to whether this is for configure or make.
"""
assert language in ('c', 'c++')
assert step in ('configure', 'make')
if language == 'c' and flag in ('-Wreorder', '-Wnon-virtual-dtor'):
# Skip... | 112bfe55f6bbd77ef2ac5aa70ec23d56f46bacd0 | 672,727 |
import os
def get_local_path(level, lesson, type_file):
"""Return a file path to a file
"""
filename = 'level%slesson%s.%s' % (level, lesson, type_file)
return os.path.join('TTMIK', str(level), str(lesson), filename) | 94a321636df764ac0eb1573539742bf0e2ec1924 | 672,728 |
def x_to_ab(x, p, q):
"""
Given some integer x mod pq, returns the CRT representation (x mod p, x mod q)
(CRT -> Chinese Remainder Theorem).
"""
return x % p, x % q | 2d8d5c4cb60c490e04f9d3bec47652afc2ee9638 | 672,729 |
import os
def countINDIR(INDIR):
"""
Description
-----------
Returns list = [0, total number of files in INDIR].
"""
n_files = sum([len(files) for r, d, files in os.walk(INDIR)])
counting = [0, n_files] # [number of processed files, total number of files]
return counting | 18c5ea164b576a92799c4e1dde70e4357b7256ad | 672,730 |
def is_number(num):
"""Checks if num is a number"""
try:
float(num)
except ValueError:
return False
return True | 28e5d8d96e324bd2690f06a7681999f37b1d42af | 672,732 |
def ok_for_raw_triple_quoted_string(s, quote):
"""
Is this string representable inside a raw triple-quoted string?
Due to the fact that backslashes are always treated literally,
some strings are not representable.
>>> ok_for_raw_triple_quoted_string("blah", quote="'")
True
>>> ok_for_raw_tr... | bb86e5720ec91a5ce0e15ce342563cfa03ba6319 | 672,733 |
import json
def read_fps(json_file_path):
"""
Open json file, read the fps the data was recorded at.
input: json file path
output: int (fps)
"""
with open(json_file_path) as f:
data = json.load(f)
fps = data['fps'][0]
return fps | 28d55b554b339d49920cf046230fd77b1c6ca2e3 | 672,734 |
import importlib
def global_members(modulename):
"""A decorator that exposes Enum members as global variables."""
module = importlib.import_module(modulename)
def inner(the_enum):
# Iterating over the enum doesn't include aliases.
for name, member in the_enum.__members__.items():
... | e26c0ff9fe168d14bf20f7e006ecbac3d3c078e2 | 672,735 |
def approximate_boundary_mean(g, n1, n2):
"""Return the boundary mean as computed by a MomentsFeatureManager.
The feature manager is assumed to have been set up for g at construction.
"""
return g.feature_manager.compute_edge_features(g, n1, n2)[1] | 889617cdc63fe738788ef864102a5a2231374a46 | 672,736 |
def separate_artists_list_by_comparing_with_another(
another_artists_list, compared_artist_list
):
"""
Input: Two list of artists_id
Return two lists containing:
- Every artist in compared_artist_list that are in another_artists_list
- Every artist in compared_artist_list that are not in anothe... | 330fae7901e4600a0ecfad00b9f55db6a0358a36 | 672,737 |
def _is_items(lst):
"""Is ``lst`` an items list?
"""
try:
return [(a, b) for a, b in lst]
except ValueError:
return False | 1a8362cd5c91dd799469682d729d2f9c735dd795 | 672,738 |
from typing import List
def get_drop_columns_binary(categoricals: List[str], columns: List[str]) -> List[str]:
"""
Selects the columns which can be dropped for one-hot-encoded dfs without drop_first.
Is mainly needed to transform into drop_first encoding
Parameters
----------
categoricals: n... | b20ce71b7b44ac48f3850e58223d58ec871623fd | 672,739 |
def process_predictions(lengths, target, raw_predicted):
"""
Removes padded positions from the predicted/observed values and
calls inverse_transform if available.
Args:
lengths: Lengths of the entries in the dataset.
target: Target feature instance.
raw_predicted: Raw predicted/... | 7bdebe64779bd2972ba9e1f6549193c033a81ccb | 672,740 |
def get_start_end_from_string(start_end):
""" 111.222 => 111, 222 """
start, end = start_end.split(".")
start = int(start)
end = int(end)
return(start, end) | 43af0d52c492b083be01a97aeca8999ba78e3bdc | 672,742 |
def get_weighted_mean(distribution: list, weights: list) -> float:
"""
:param distribution: list of int or float to calculate the weighted mean
:param weights: weights list
:return: the weighted mean of distribution list
"""
numerator = sum([distribution[i] * weights[i] for i in range(len(distri... | a9f67af2c1e492348dc2693531b3641e0decbc5b | 672,743 |
import logging
import sys
def read_image_from_file(args):
"""
Reads in a text file that has a list of docker images to save too file.
:param args:
:return:
"""
try:
with open(args.filename, "r") as img_file:
img_list = img_file.readlines()
if img_list:
... | 8a6f1b8d1983421ab755de236755c8607212733e | 672,744 |
import json
import os
def get_macro_values():
"""
Parse macro environment JSON into dict. To make this work use the icpconfigGetMacros program.
Returns: Macro Key:Value pairs as dict
"""
macros = json.loads(os.environ.get("REFL_MACROS", ""))
macros = {key: value for (key, value) in macros.ite... | 42b25bb590c62a3990a0491d98e78c2ec258234a | 672,745 |
import os
def get_file_base_name(path):
"""
To get base file name based on the path
:param path:
:return:
"""
try:
name = os.path.basename(path).split('.')[0]
return name
except ValueError as e:
raise ValueError("When to get file path: {} with error: {}".format(path... | 9eaee78aac3620df62e5c07072bdb34b13ba6d5f | 672,746 |
from typing import Counter
def part2(template: str, insertions: dict):
"""Part 2 cannot possibly work in the same way as part 1, the increasing
length of string quickly reaches a point where memory management gets
to be the controlling factor.
Instead, we know that there are a fixed number... | 721bcf7d3d608134ee2479e277621cf99ceeb389 | 672,747 |
from typing import List
def cross_over(input_data: List, value: int):
"""return true if input_data crossed over value otherwise false"""
return input_data[-1] > value > input_data[-2] | 94a60dcb1ade37825812c307f70091cff0643822 | 672,748 |
def check_strand(read, strand):
"""
check the read strand to remove of opposite reads,
this is only suitable for fr-firststrand library
"""
if strand == '+':
if read.is_paired:
if read.is_read1 and read.is_reverse:
return True
elif read.is_read2 and n... | 4127b5c687f39fbb86ae6f296c0eada907198506 | 672,749 |
import random
def sa(*args):
"""
Shepperd and MacDonell's standardized error.
SA = 1 - MAR/MARp0
:param args: [actual, predicted, vector]
:return: SA
"""
mar = abs(args[0] - args[1])
mar_p0 = sum([abs(random.choice(args[2])-args[0]) for _ in range(1000)])/1000
return mar/mar_p0 | c55ed4605ed4751e67e2ab8aa24253b1f89ab207 | 672,750 |
def sub_loop(regex, repl, text):
"""
In ``text``, substitute ``regex`` by ``repl`` recursively. As long
as substitution is possible, ``regex`` is substituted.
INPUT:
- ``regex`` -- a compiled regular expression
- ``repl`` -- replacement text
- ``text`` -- input text
OUTPUT: substitu... | 2ee0d7decdb5abc63b8a44cc1012dd47fd2993dd | 672,751 |
def prod_nadate_process(prod_df, prod_col_dict, pnadrop=False):
"""
Processes rows of production data frame for missing time-stamp
info (NAN).
Parameters
----------
prod_df: DataFrame
A data frame corresponding to production data.
prod_df_col_dict: dict of {str : str}
A d... | 20381ef0cbeabae67d738f17ecd349513006e81e | 672,752 |
def transf_yukovski(a, t):
"""Dado el punto t (complejo) y el parámetro a
a de la transformación proporciona el punto
tau (complejo) en el que se transforma t."""
tau = t + a ** 2 / t
return tau | fb55e4032d6900dccba6290411c6f5ce0199af5e | 672,754 |
import re
def norm_url_prefix(url):
"""Normalize the url prefix."""
url = re.sub(r'[/\\]+', '/', url).rstrip('/')
if url != '' and not url.startswith(''):
url = '/' + url
if url == '/_api':
raise ValueError('URL prefix of a storage cannot be `/_api`.')
return url | 70a4be52110b4272095f9214387ad08a434c0e0e | 672,755 |
def construct_name(user):
""" Helper function for search. Not used in requests."""
name = []
if 'fname' in user.keys():
name.append(user['fname'])
if 'lname' in user.keys():
name.append(user['lname'])
return ' '.join(name) | 00f565a31fbd3b4e927bf553a25344525b0386a7 | 672,756 |
def wrap_seq_string(seq_string, n=60):
"""Wrap nucleotide string (seq_string) so that each line of fasta has length n characters (default n=60)
Args:
seq_string (str): String of DNA/protein sequence
n (int): Maximum number of characters to display per line
Returns:
(str): String o... | 6987d3066b8907ad6ec44a374a3d86c6a2bb7b4c | 672,757 |
def jib(foot, height):
"""
jib(foot,height) -> area of given jib sail.
>>> jib(12,40)
240.0
"""
return (foot*height)/2 | 5097252deffe96f8d4fc32e5f26b8be3cadcd1cc | 672,758 |
import textwrap
def _GetNextConfigParam():
"""Generate R22ParamGetNextConfigParam() C function source."""
return textwrap.dedent('''
R22Parameter R22ParamGetNextConfigParam(R22Parameter param,
R22Memory mem) {
int32_t index = (int32_t)param;
ass... | 7a5a2dec4034f68275f8740560a3eed8b4d18f15 | 672,759 |
import os
def generateResultFilename(inputFileName):
"""
Generate a result file name based on the input name
:param inputName: name of the processed file
:return alreadyExists: returns True if the file already exists
:return resultFile: name of the output file
"""
alreadyExists = False
... | bf44658abedf6ec873824ea13f9ca47cdc666ec1 | 672,760 |
import random
def high_or_low(lower=1, upper=100):
"""This function takes two inputs from main, the upper or lower bound of a random number based on user input,
it defaults to a number between 1 and 100, and it returns a random number within the given range"""
computer_guess = random.randint(lower, upper)... | 16a934851b300bb7469fde5a0ed937a960bc7bab | 672,761 |
def sizeCayley(gen,edges):
"""
Returns the number of nodes in a Cayley Tree.
"""
size = 1
for x in range(1,gen+1):
size += (edges * (edges - 1)**(x - 1))
return size | 2fb49041f6ffd5b283f44a3fd208aeb8e9ae1503 | 672,762 |
def _mac_to_oid(mac):
"""Converts a six-byte hex form MAC address to six-byte decimal form.
For example:
00:1A:2B:3C:4D:5E converts to 0.26.43.60.77.94
Returns:
str, six-byte decimal form used in SNMP OIDs.
"""
fields = mac.split(':')
oid_fields = [str(int(v, 16)) for v in fiel... | 5bf5d6a1b3e5bf3afcf8d00553e668d8d8fd2309 | 672,764 |
import os
def countFilesOfType(top, extension):
"""inputs: top: a String directory
extension: a String file extension
returns a count of files with a given extension in the directory
top and its subdirectories"""
count = 0
filenames = [x[2] for x in os.walk(top)]... | 817cd20c65c71ae28a491e519959b17813f7333c | 672,765 |
import os
import json
def to_json(*path):
"""buils a full path and reads it as json"""
with open(os.path.join(*path), 'r') as f:
return json.load(f) | 5a50177ccbd1fb47cb83605ac692ac3bbc180aa6 | 672,766 |
def inputs(self):
"""get input vars needed at runtime, in the order as the values that should
be passed to :meth:`__call__`
:setter: Set the order of input vars, which must be created by
:func:`.make_arg`. None could also given, and in such case only keyword
arguments would be allowed for :... | a41d903308b44c8d945dd3649c6028b75ae71b3e | 672,767 |
def get_amr_line(input_f):
"""
Read the file containing AMRs. AMRs are separated by a blank line.
Each call of get_amr_line() returns the next available AMR (in one-line form).
Note: this function does not verify if the AMR is valid
"""
cur_amr = []
has_content = False
for line in input... | 60e22230748f9b849b460b465415a82d0af7c909 | 672,768 |
def read_obs(obs_file):
"""
Function to read in observation data from text file
each line should be formatted as "T ill V J"
"""
f = open(obs_file, 'r' )
f.readline() # there's a header with column labels
obs_T, obs_ill, obs_V, obs_J = [], [], [], []
for line in f:
l=line.s... | 40b2bd9d56e85ebbfe86f1221104e6c1fd194934 | 672,769 |
import torch
def get_generator_input_sampler():
"""
初始生成器(generator)数据分布:采用均匀分布(Uniform), 而非随机噪声, 以保证 Generator必须以非线性方法生成目标数据分布
:return: 生成size为([m, n]), 范围为(0, 1)样本
"""
# 均匀分布
# torch.rand(m, n)
# lambda表达式:匿名函数, lambda 参数: 返回值
return lambda m, n: torch.rand(m, n) | e8a6ca193db973d34e3f241b60160fa7222ecb1a | 672,770 |
def fake_answer_questionnaire(input_str, answer_options, multiple_choice_questions):
"""Imitates the ability of a self-aware model to answer questions about itself, as in answer_questionnaire subtask
Args:
input_str: String. The model's input, containing a question about the model
answer_option... | 1d459c52b7b949bfed2ad7cf18c489db58a4387e | 672,771 |
import math
def make_jc_matrix(t, a=1.):
"""
Returns Juke Cantor transition matrix
t -- time span
a -- mutation rate (sub/site/time)
"""
eat = math.exp(-4*a/3.*t)
r = .25 * (1 + 3*eat)
s = .25 * (1 - eat)
return [[r, s, s, s],
[s, r, s, s],
[s, s, r, s],... | 12f0c30732db909930201ba7ff26c78c38ea4f4a | 672,772 |
import re
def _urlify_name(name):
"""Converts a name or title into something we can put into a URI.
This is designed to only be for one way usage (ie. we can't use the
urlified names to figure out what photo or photoset we are talking about).
"""
return re.sub(r'\W+', '-', name).strip('-') or... | 9d38ec55376a9a380b5615a84b80aafb084518f1 | 672,773 |
def Cornfeld_mean(*variables):
"""Return the mean of a sample using Cornfeld's method.
Input: *float (all variables as arguments)
Output: int
"""
return (max(variables) + min(variables)) / 2 | ac0477938f7edcb729c76039e83a268749ec7b3c | 672,774 |
def make_name(variable, anon="anonymous_variable"):
"""
If variable has a name, returns that name. Otherwise, returns anon.
Parameters
----------
variable : tensor_like
WRITEME
anon : str, optional
WRITEME
Returns
-------
WRITEME
"""
if hasattr(variable, 'n... | 5201568e5caa38e1c6233609f335b8bea155c5fd | 672,775 |
def actual_train(model_dir, train_dir, epochs=100, init="uniform", dict_arg=None):
"""Put a placeholder."""
return {
"model_dir": model_dir.as_posix(),
"train_dir": train_dir.as_posix(),
"epochs": 7,
"init": init,
"dict_arg": dict_arg,
} | b1cea34753d5e32ac21cbfdc1925e5b2578b55e2 | 672,776 |
def action2config(action, enc_end=3, dec_block=3, dec_len=5):
"""reconstruct action"""
enc_config = action[:enc_end]
dec_config = []
start = enc_end
for _ in range(dec_block):
dec_config.append(action[start : start + dec_len])
start = start + dec_len
return enc_config, dec_config | 88b4c20933910360ae63be5a5867bfb5d883fa48 | 672,777 |
def parse_ipmi_sdr(output):
"""Parse the output of the sdr info retrieved with ipmitool"""
hrdw = []
for line in output:
items = line.split("|")
if len(items) < 3:
continue
if "Not Readable" in line:
hrdw.append(('ipmi', items[0].strip(), 'value', 'Not Reada... | 7525b21926ced8dc44f4730c283432b869905786 | 672,778 |
import numpy
def _get_histogram(input_values, num_bins):
"""Computes histogram.
B = number of bins
:param input_values: 1-D numpy array of input values.
:param num_bins: Number of bins.
:return: lower_bin_edges: length-B numpy array of lower bin edges.
:return: upper_bin_edges: length-B nump... | 7f8411f25fcc2d21df9f82812af71c24ccbacd2d | 672,779 |
from pathlib import Path
def repository(tmp_path: Path) -> Path:
"""Fixture for a repository."""
path = tmp_path / "repository"
path.mkdir()
(path / "marker").write_text("Lorem")
return path | d334be1f1bda43f3c7c46c8b79dd3024029618a9 | 672,780 |
def rnaseq_variant_calling(samples, run_parallel):
"""
run RNA-seq variant calling using GATK
"""
samples = run_parallel("run_rnaseq_variant_calling", samples)
return samples | c728a8b6bc6d502876b3d43239c99373ecb71ae6 | 672,781 |
def latest_actions_only(items):
"""Keep only the most recent occurrence of each action, while preserving the order"""
used = set()
res = []
for item in reversed(items):
if item not in used:
res.append(item)
used.add(item)
return reversed(res) | 56e8dd5b0b2bfab2da91c1070252ba6574f50fed | 672,782 |
def planet(armageddon):
"""Return a default planet (exponential atmosphere)"""
return armageddon.Planet() | 2f5f3b1dbd4b88d1362d8670a4bb9aebb1753e8a | 672,783 |
def mult_with_submatrix(A, columns, x):
"""Computes :math:`b = A[:, I] x`
"""
A = A[:, columns]
return A @ x | 7b2c9eab55a18f4c0de13cc0cbe6038f7fb0c573 | 672,784 |
def set_cover(X, subsets):
"""
This algorithm finds an approximate solution
to finding a minimum collection of subsets
that cover the set X.
It is shown in lecture that this is a
(1 + log(n))-approximation algorithm.
"""
cover = set()
subsets_copy = list(subsets)
while True:
S = max(subsets_co... | afbcded0a24e1bffcad4e6c01f844edcef673fb7 | 672,786 |
def _validate_float(value):
""" Convert an arbitrary Python object to a float, or raise TypeError.
"""
if type(value) is float: # fast path for common case
return value
try:
nb_float = type(value).__float__
except AttributeError:
raise TypeError(
"Object of type ... | 5cd57b9b557ef5c3a56365152eb95fbea2a8b098 | 672,787 |
def degree_sequence(creation_sequence):
"""
Return degree sequence for the threshold graph with the given
creation sequence
"""
cs = creation_sequence # alias
seq = []
rd = cs.count("d") # number of d to the right
for i, sym in enumerate(cs):
if sym == "d":
rd -= 1
... | da70884b8d36447d59898a9abed1db6313998774 | 672,788 |
def lr_lin_reduction(learning_rate_start = 1e-3, learning_rate_stop = 1e-5, epo = 10000, epomin= 1000):
"""
Make learning rate schedule function for linear reduction.
Args:
learning_rate_start (float, optional): Learning rate to start with. The default is 1e-3.
learning_rate_stop (float, op... | 75809150725bcaa8216dfec8958957101dfc01b2 | 672,789 |
def split_conn_port(connection):
"""Return port number of a string such as 'port0' as an
integer, or raise ValueError if format is invalid"""
try:
return int(connection.split('port', 1)[1])
except (ValueError, IndexError):
msg = "port string %s does not match format 'port<N>' for integer... | 60ea8508920158a99fda3fa69c9b0c2bdd221919 | 672,790 |
def tail(list, n):
""" Return the last n elements of a list """
return list[:n] | bef68bbe0f4fc3ace24306ba6e01c6c1dd9aab8c | 672,791 |
import numpy
def argextrema(this_array, axis=None):
"""Get the location of the extrema
Arguments:
this_array: numpy array to get the extrema location from
axis: axis to search along
Returns:
argmin: argmin of this array
argmax: argmax of this array
"""
argextr = (... | 652418c1113ae7ca69d8f092fb11269952855b01 | 672,792 |
def find_top2_clusters(clusters):
"""
:INPUT: clustering.labels_
:OUTPUT: tuple of two lists, each contain a cluster
:
"""
dic={}
for i, num in enumerate(clusters):
if num == -1:
continue
if num in dic.keys():
dic[num].append(i)
else:
... | 8e666a52bcecd785235b4fca2c190a73b56b286b | 672,793 |
import torch
def categorical_focal_loss(y_true, y_pred):
"""
Reference: https://github.com/umbertogriffo/focal-loss-keras
Softmax version of focal loss.
m
FL = SUM -alpha * (1 - p_o,c)^gamma * y_o,c * log(p_o,c)
c=1
where m = number of classes, c = class and o = observa... | d5a9224dbfedaf10f9f27fb3872b2178bd6e7b5b | 672,794 |
import pickle
def get_pickle(bucket, pickle_path):
"""
REQUIRES: bucket a valid client side reference to storage bucket
pickle_path a valid path in Firebase storage with an
existing byte representation of a model
ENSURES: Returns a loaded model that can be interacted with in p... | 0597593595b6c2b365d3bdcffeccce0071babb13 | 672,795 |
def ghost_api_clean_bluegreen_app(apps_db, app):
"""
Removes the 'blue_green' document from the current app
"""
orig_bluegreen_conf = app.get('blue_green')
if orig_bluegreen_conf:
update_res = apps_db.update_one({'_id': app['_id']}, {'$unset': {'blue_green': ''}})
if not update_res.... | 4d78949b89631e13b930ea22ba0ca3275314a6f4 | 672,796 |
def compute_loss(logits, target, criterion):
"""
logits shape: [seq-len, batch-size, output_dim]
target shape: [batch-size, seq-len]
"""
loss = criterion(logits, target)
return loss | 791bfeab27b8264b4d72331c2b43cd22f6f4d480 | 672,797 |
def getBookList(genres: list, dict: dict) -> list:
"""Returns a list of book dictionaries"""
bookData = []
# Get list of all books
for genre in genres:
for book in dict[genre]:
book.update({'generes':genre}) #re inserts genre into dictionary
bookData.append(book)
retu... | 56ae7207084f7c9cad4d636952e777874a0638e9 | 672,798 |
def convert_string_to_numeric(value):
"""Break up a string that contains ";" to a list of values
:param value: the raw string
:return: a list of int/float values
"""
if ';' in value:
return list(map(convert_string_to_numeric, value.split(';')))
try:
return int(value)
finall... | 040b5440e68f2ae1d7bcf83df2ddd73ec3e892d5 | 672,799 |
import pickle
def get_pickleable_etype(cls, loads=pickle.loads, dumps=pickle.dumps):
"""Get pickleable exception type."""
try:
loads(dumps(cls))
except Exception: # pylint: disable=broad-except
return Exception
else:
return cls | f6b6b15c0ad49c26bebc2f4d919458abdf30228c | 672,800 |
def configuration(self):
"""Configuration based on self.params"""
return {self.__class__.__name__.lower(): self.params} | 4214bf189548e9c636c5db33bc862d291aa1b945 | 672,801 |
import re
def format_value(s, format_str):
""" Strips trailing zeros and uses a unicode minus sign.
"""
if not issubclass(type(s), str):
s = format_str % s
s = re.sub(r'\.?0+$', '', s)
if s[0] == "-":
s = u"\u2212" + s[1:]
return s | a56efef0002f885f47bd8203ff7df80aa83b889b | 672,802 |
def _add(a: int, b: int) -> int:
"""Add two numbers together.
Args:
a (int): First number.
b (int): Second number.
Returns:
int: A sum of two numbers.
"""
return a + b | 60372a3916a7337b1bdd401de0165bc46fabeee3 | 672,803 |
def _parse_list_file(path):
"""
Parses files with lists of items into a list of strings.
Files should contain one item per line.
"""
with open(path, 'r') as f:
items = [i for i in f.read().split('\n') if i != '']
return items | 2c1203cd76e6b4382d8407d5d4197a2b8489f92a | 672,804 |
def first_elem(s):
""" Extracts first element of pandas Series s, or returns s if not a series. """
try:
return s.iloc[0]
except AttributeError:
return s | 6b6bcf84c07ced25d797bc022d4713543deaeafb | 672,806 |
import glob
def get_images(path):
"""
Checks the folder for images
:param path: The folder in which we will check for images
:return: An array of all images found
"""
path = path
images = glob.glob(path + "**/**/**/*.jpg", recursive=True)
images.extend((glob.glob(path + "**/**/**/*.png... | dcb805a010af1c277f54b9dee1342b3eb6207d69 | 672,807 |
from itertools import chain, repeat
from typing import Iterable
from typing import Iterator
def ncycles(it: Iterable, n: int) -> Iterator:
"""
Returns the sequence elements n times
>>> [*ncycles(range(3), 3)]
[0, 1, 2, 0, 1, 2, 0, 1, 2]
"""
return chain.from_iterable(repeat(it, n)) | f6d4f5f14615dd2d170922a349bb3f0f4b6e4c0d | 672,809 |
import uuid
def generate_unique_id():
"""
Generates and returns a unique id string.
:return: Unique ID
:rtype: String
"""
return str(uuid.uuid1()) | f4fef6f139c129c35d9c7ce571302db5d31a94e6 | 672,810 |
import re
def get_audio_paths(dataset_root_path, lst_name):
"""Extract audio paths."""
audio_paths = []
with open(dataset_root_path / "scoring" / lst_name) as f:
for line in f:
audio_path, lang = tuple(line.strip().split())
if lang != "nnenglish":
continue
... | fb7256c994d928462152f6c9d85480d4b4a0d918 | 672,811 |
def product_interval(list1, list2):
"""Helper implementing combination of all intervals for any two interval lists.
"""
new_list=list()
for m in range(len(list1)):
for n in range(len(list2)):
new_list.append(list1[m]+list2[n])
return new_list | 841ea2554f02aca84f06cde58c180773a7e57ef9 | 672,812 |
def foreground_color(bg_color):
"""
Return the ideal foreground color (black or white) for a given background color in hexadecimal RGB format.
"""
bg_color = bg_color.strip('#')
r, g, b = [int(bg_color[c:c + 2], 16) for c in (0, 2, 4)]
if r * 0.299 + g * 0.587 + b * 0.114 > 186:
return '... | ae41ce30e820c160f1c9c88dd34496905f6a3bd6 | 672,813 |
def filter_tree(tree, ranks, ancestors):
"""Return a filtered version of the tree & ranks dict.
NOTE: Does NOT preserve the original dict order.
"""
count = len(tree)
wanted = {a: a for a in ancestors} # new tree
reject = set()
while tree:
taxid, parent = tree.popitem()
if ... | 831471e3efdc8219c9bb8d6f1b36b12e2e5f6ec5 | 672,814 |
def count_trajectories(n: int) -> int:
"""
The Grasshopper is in position 1.
The Grasshopper may jump to +1, +2 or +3.
How many possible trajectories does the grasshopper have to get to position n?
If n<=1, consider that the Grasshopper has 0 possible trajectory.
>>> count_trajectories(0)
0... | d9c0127e2a21346872783d6b4b9ea44fc2bde285 | 672,815 |
def jwt_key():
"""Provide a fernet key value."""
return "mVk0ZaJdN2akNwLRpxmuuUOTLgB75n5kxB6KZvDwEWo=" | fe833adeb92e66991abdfc48fb863e79fad4e2be | 672,816 |
import requests
def get_request(url, max_tries=10):
""" Get JSON data from BiGG RESTful API.
Args:
url (str): url request
max_tries (int): maximum number of communication attempts (default: 10)
Returns:
dict: json data
"""
resp, data = None, None
for i in range(max_... | 3a8752538cef2f33e4c3979e92f8a69d3c2c3d13 | 672,817 |
def ubfx(value, lsb, width):
"""Unsigned Bitfield Extract"""
return (value >> lsb) & ((1 << width) - 1) | bba3b92deea9105acc6554d235230711d1979c5f | 672,818 |
def interleaved2complex(data):
"""
Make a complex array from interleaved data.
"""
return data[..., ::2] + 1j * data[..., 1::2] | 78d7eeb385232757f4feddc757b6766ef91b1c23 | 672,819 |
import inspect
import gc
def gc_objects_by_type(tipe):
"""
Return a list of objects from the garbage collector by type.
"""
if isinstance(tipe, str):
return [o for o in gc.get_objects() if type(o).__name__ == tipe]
elif inspect.isclass(tipe):
return [o for o in gc.get_objects() if ... | 9f2baa59818b4e495703fbda3b095e46dde97b2a | 672,820 |
def positive_int_from_str(string, base=0):
"""
Accept a string.
Return as a positive integer if possible,
else raise
"""
try:
maybe = int(string, base=base)
except:
raise ValueError
if abs(maybe) != maybe:
raise ValueError
return maybe | 23e3681f7cd793924c6845cac392991a97383bb0 | 672,821 |
def operating_system(os):
"""
Property: PatchBaseline.OperatingSystem
"""
valid_os = [
"WINDOWS",
"AMAZON_LINUX",
"AMAZON_LINUX_2",
"UBUNTU",
"REDHAT_ENTERPRISE_LINUX",
"SUSE",
"CENTOS",
"DEBIAN",
"ORACLE_LINUX",
]
if os no... | a467aaaedccc08e09c64ad75a3ea028af20a63b5 | 672,822 |
from typing import Optional
from typing import List
def _nt_quote_args(args: Optional[List[str]]) -> List[str]:
"""Quote command-line arguments for DOS/Windows conventions.
Just wraps every argument which contains blanks in double quotes, and
returns a new argument list.
"""
# Cover None-type
... | 6939cb7d8e0b967d9bb629fc8785a42d130fd683 | 672,823 |
def sign_extend(value: int, orig_size: int, dest_size: int) -> int:
"""
Calculates the sign extension for a provided value and a specified destination size.
:param value: value to be sign extended
:param orig_size: byte width of value
:param dest_size: byte width of value to extend to.
:return:... | 2b3b545f5b7362f1a67bb95ce82265132f050c6f | 672,824 |
def check_number_v1(number):
"""Проверка числа для игры FizzBuzz.
Проверка на делимость "в лоб". Встречается повторяющийся код.
:param number: проверяемое число.
:type number: int
:return: строка 'FizzBuzz', если число кратно 3 и 5,
строку 'Fizz', если число кратно 3,
строк... | 1861e0fd5856814e56c28420186fae1d009b04f9 | 672,825 |
def _compute_params(t):
"""
Takes a timeseries and computes the parameters needed for the fast
lomb scargle algorithm in gatspy
"""
t_min, t_max, n = t[0], t[-1], len(t)
dt = (t_max - t_min) / float(n - 1)
min_freq = 1. / (t_max - t_min)
d_freq = 1. / (2 * dt * len(t))
return min_fre... | 68aabaf8611e3e536aaf4211c9f3912ab58f2b1e | 672,826 |
def identity(*args):
"""
Return whatever is passed in
Examples
--------
>>> x = 1
>>> y = 2
>>> identity(x)
1
>>> identity(x, y)
(1, 2)
>>> identity(*(x, y))
(1, 2)
"""
return args if len(args) > 1 else args[0] | e0ffb84b8685c562d9b05c4880553d4b8ea9678c | 672,827 |
def ascii_to_string(s):
""" Convert the array s of ascii values into the corresponding string. """
return ''.join(chr(i) for i in s) | 229d6a05da43c5016b6de8d3c1724ff9ac5b6e05 | 672,828 |
def _convert_to_index_name(s):
"""Converts a string to an Elasticsearch index name."""
# For Elasticsearch index name restrictions, see
# https://github.com/DataBiosphere/data-explorer-indexers/issues/5#issue-308168951
# Elasticsearch allows single quote in index names. However, they cause other
# p... | 4ce052c19e97ed0d528890f3a444e05b88344753 | 672,829 |
import re
def _close_elements(vistr: str) -> str:
"""Close elements NO_TITLE CRLF LF"""
# pylint: disable=cell-var-from-loop
for element in [
"NO_TITLE",
"FONT",
"LF",
"CRLF",
"SAME_AS_LABEL",
"append",
]:
vistr = re.subn(
f"<{element... | 78085c142f44a95392572588ac177f857e6f42ca | 672,831 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.