content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def prepares_return(data_filter, total_values):
"""
Funcção que prepara o array final com os valores totais por cliente
:param data_filter:
:param total_values:
:return total_values:
"""
for number in total_values:
for record in data_filter:
if number['source'] == record[... | feed5eeaea5b8d19de3818f2267bae2a156fea69 | 30,678 |
def getbinlen(value):
"""return the bit length of an integer"""
result = 0
if value == 0:
return 1
while value != 0:
value >>= 1
result += 1
return result | 523772f1c5eb856bff831e1565b2ff47fc19b2ff | 30,679 |
import pandas
def binary_feature(df, feat_col, value, binary_feature_col_name=None, concat=False):
"""
Given a dataframe, feature column name and value to check, return a series of binary responses 1 and 0
1 if the value in the feature column to check is present, 0 if otherwise
binary_feature
"""
... | 6215c422a74c6bf6d95308f014164279c478c40e | 30,680 |
def calculate_mean(some_list):
"""
Function to calculate the mean of a dataset.
Takes the list as an input and outputs the mean.
"""
return (1.0 * sum(some_list) / len(some_list)) | d0374fc5321f6caa05f546e274490e906bf60106 | 30,681 |
def __compress(list_events):
"""
Compress a list of events,
using one instantiation for the same key/value.
Parameters
--------------
list_events
List of events of the stream
Returns
--------------
:param list_events:
:return:
"""
compress_dict = {}
i = 0
... | 79d5fbef74be3db5296a631ee50757dabab2e897 | 30,682 |
def merge_media(forms, arg=None):
"""Merge media for a list of forms
Usage: {{ form_list|merge_media }}
* With no arg, returns all media from all forms with duplicates removed
Usage: {{ form_list|merge_media:'media_type' }}
* With an arg, returns only media of that type. Types 'css' an... | e4885524e3ac6c8598f485f55fa915b6a4874001 | 30,683 |
import re
def split_filenames(text):
"""Splits comma or newline separated filenames
and returns them as a list.
"""
names = [name.strip()
for name in re.split(r'[\n,]', text)]
return list(filter(None, names)) | 85d53b77a81d6c1133068932a510ff3c9087a3cd | 30,684 |
def _item_prop(name, default=None, setdefault=None, hint=False):
"""Create a property that fetches a value from the dictionary.
We implement getter, setter and deleter here. Whilst we may not want users
to do all of those things it is not our job to prevent users from doing
something stupid. Our goal i... | dd6bfbdae4e4a7ab38b971a51246b2f69bead56d | 30,685 |
import json
def list_generator_op(parallelism: int) -> str:
"""Generate list for parallel"""
# JSON payload is required for ParallelFor
return json.dumps([x for x in range(parallelism)]) | adade4d6afc2eeac6867da14b5f25e8f9b49317c | 30,686 |
def counter_count(string):
"""String's counter() method is used."""
return {i: string.count(i) for i in string} | f92985bf8f5d9895b426b61ad810e2cd81c4e400 | 30,687 |
import torch
def accuracy(output_1, target, topk=(1,)):
"""Computes the precision@k for the specified values of k"""
#view() means resize() -1 means 'it depends'
global total_re
with torch.no_grad():
batch_size = target.size(0)
#print("batch_size",batch_size)
maxk = max(topk) #... | b0ed9919d2aebb7cdc208afe69db6c4c5a2b6ff4 | 30,689 |
from typing import Dict
def _is_import_finished(log: Dict) -> bool:
"""Returns whether the import has finished (failed or succeeded)."""
return log['state'] not in ('QUEUED', 'RUNNING') | 4dbb9ee522b210781bbc25542dd1ab86dc0cd397 | 30,690 |
from typing import Dict
def _query_dict_to_qs(dic: Dict[str, str]) -> str:
"""
{'k1': 'v1', 'k2': 'v2'} -> ?k1=v1&k2=v2
"""
if not dic:
return ''
return '?' + '&'.join(f'{k}={v}' for k, v in dic.items()) | 27e9d7de3da75a9ed589d2a40a00b6cc2461afcd | 30,691 |
def extents_overlap(a_extent, b_extent):
"""Test if two extents overlap"""
if (a_extent.xmin > b_extent.xmax or
a_extent.xmax < b_extent.xmin or
a_extent.ymin > b_extent.ymax or
a_extent.ymax < b_extent.ymin):
return False
else:
return True | 09f30e3982fd139b4208501236c2a0fc4a413b96 | 30,693 |
def create_logdir(dataset, label, rd,
allow_zz, score_method, do_spectral_norm):
""" Directory to save training logs, weights, biases, etc."""
model = 'alad_sn{}_dzz{}'.format(do_spectral_norm, allow_zz)
return "train_logs/{}/{}/dzzenabled{}/{}/label{}/" \
"rd{}".format(dataset,... | 97c00c376ab0a70032932577f84d745bc01061da | 30,695 |
def get_high_lows_lookback(high, low, lookback_days):
"""
Get the highs and lows in a lookback window.
Parameters
----------
high : DataFrame
High price for each ticker and date
low : DataFrame
Low price for each ticker and date
lookback_days : int
The number of ... | d24905db2ae2425f7d57e3af503802c597d0c212 | 30,698 |
import glob
import os
def get_latest_file(filetype, detector=None, disregard_known_files=False):
"""
This function gets the latest modified file of filetype. This function will look into the calwebb_spec2_pytests
directory for the given file.
Args:
filetype: string, name/type of file type, e.g... | 1a6874e6173bdb02c5724408acf8de327efcbdda | 30,699 |
def dG_to_flux_bounds(dG_min, dG_max, infinity=1000, abstol=1e-6):
""" Convert standard Gibbs energy range to reaction flux bounds.
Args:
dG_min (float): minimum standard Gibbs energy
dG_max (float): maximum standard Gibbs energy
infinity (float): value to represent infinity (default: 1... | 85fabd94e2ba74a3accba873cde3bdc0398dd1d1 | 30,703 |
def _get_weights(model, features):
"""
If the model is a linear model, parse the weights to a list of strings.
Parameters
----------
model : estimator
An sklearn linear_model object
features : list of str
The feature names, in order.
Returns
-------
list of str
... | f26947922505cb3c06f1421238fdcde11064a686 | 30,705 |
import socket
def is_port_available(port: int, udp: bool = False) -> bool:
"""Checks whether a specified port is available to be attached to.
From `podman_compose <https://github.com/containers/podman-compose/blob/devel/podman_compose.py>`_.
Args:
port (int): The port to check.
udp (bool... | a963ad45477fc43bca1a356c6b76f8995f7df60b | 30,706 |
from pathlib import Path
def mask_workdir(location: Path, stacktrace: str, placeholder="$BLUEPRINT_DIR"):
"""
replaces real workdir with placeholder
"""
return stacktrace.replace(str(location), placeholder) | ffae80fa247c440472cf45c49e14ea9a700a44f5 | 30,707 |
def remove_character_at(str, idx):
"""Removes the character from str at index idx, returning the remaining string
str, int -> str
>>> remove_character_at("boats", 2)
'bots'
"""
return str[:idx] + str[idx+1:] | abc7bedb33c5c9e024dd8cf5830f3b3ee8b08f42 | 30,708 |
def cal_cluster_centers(df, fuzzy_matrix, n_sample, c, m):
"""
param df: 数据集的特征集,不包含标签列
param fuzzy_matrix: 隶属度矩阵
param c: 聚类簇数量
param m: 加权指数
"""
# *字符称为解包运算符
# zip(*fuzzy_amtrix) 相当于将fuzzy_matrix按列展开并拼接,但并不合并!
# list(zip(*fuzzy_amtrix)) 包含 列数 个元组。
fuzzy_mat_ravel = list(zip(*fu... | c1971b9bc1b5b48e0222cd2798da3477db9c95ad | 30,709 |
import os
def _find_entry_in_tree(repository, identifier, tree):
""" Finds a nearest-match entry in the given tree. This simply means that
the file extension can be optionally ignored.
"""
def is_dir_match(segment, entry, segments):
""" Used to decide whether or not the given segment matches... | 6403fe10026984e9d0dd9b1e3c96365567fb1a89 | 30,710 |
def remove_outlier(df_in, col_name, k=1.5):
"""remove outlier using iqr criterion (k=1.5)"""
q1 = df_in[col_name].quantile(0.25)
q3 = df_in[col_name].quantile(0.75)
iqr = q3-q1 # Interquartile range
fence_low = q1 - k * iqr
fence_high = q3 + k * iqr
df_out = df_in.loc[(df_in[col_name] >= fe... | fe519cdf339138dbff57fe183949ed0fd98b6e3f | 30,711 |
import argparse
def setup_parser():
"""Setup the command line argument parser"""
parser = argparse.ArgumentParser()
parser.add_argument('-c', '--config', help='Path to the configuration file')
return parser | a6346332f700326aa83de32b69ca68bd72327f8b | 30,713 |
def round_builtin():
"""round: Round a number to a given precision."""
return "short pi {}".format(round(3.1415, 2)) | d414d170cd615814bbd06b1d3045b24a1463cb96 | 30,716 |
def get_multi_label_options(defaults=None):
"""Multi-label-related options
"""
if defaults is None:
defaults = {}
options = {
# Multi-label labels. If set, only the given labels are expanded
'--labels': {
'action': 'store',
'dest': 'labels',
... | c4d3eb4b7859980ecbefb9f7d6c46948c398b92a | 30,718 |
def coll_fn_extract(data):
"""
DataLoader装载数据集使用, 判优, 过滤,打包
(
[
"editor 's note : in our behind the scenes series , cnn correspondents share their experiences in covering news and analyze the stories behind the events . here , soledad o'brien takes users inside a jail whe... | a7ae18629879552b5e5674e794a05dbeeef8d9e5 | 30,719 |
import os
def mkname(name):
"""
Returns a possible non-conflicting name able to be created in current directory.
"""
num = 0
name = str(name)
new_n = name[:]
old_n = new_n
while os.path.exists(new_n):
old_n = new_n
num += 1
new_n = name + str(num)
return(new... | a75eace5ba25b219d77b25e1755d1eb4b2594b34 | 30,720 |
def token2word_embeddings(data, pooling="max"):
"""Pool subword bert embeddings into word embeddings"""
assert pooling in ["first", "max", "sum", "avg"]
if pooling == "first":
# embeddings (bs, max_n_tokens, h_dim)
embeddings = data["bert_embeddings"]
indices = data["bert_indices"].... | 0ef59a11270ae3bb858d43020ac920b3a809bc15 | 30,721 |
import math
def calculate_number_of_bins_half(data):
"""The number of bins will be the half of the data size."""
return int(math.ceil(len(data) / 2.0)) | 5e162a05e9040a37f204b4a4d702c34e50ac9374 | 30,722 |
def get_scope(field):
"""For a single field get the scope variable
Return a tuple with name:scope pairs"""
name = field['name']
if 'scope' in field['field']:
scope = field['field']['scope']
else:
scope = ''
return (name, scope) | 1b931ec1a7c5a629fe6b39034c23fd02568ed5a7 | 30,724 |
import random
def generate_quality():
"""Generate Quality Code."""
quality_codes = ["A01", "A02", "A03", "A04"]
return random.choice(quality_codes) | d3f2eb0253ebb4d3db1c86dbd2685f2e302cbff9 | 30,725 |
import numpy
def error_estimation_simplex(vertex_vector_h, vertex_chi_sq_h, func):
"""
Error estimation.
Calculations according to
ANALYTICAL CHEMISTRY, VOL. 60, NO. 8, APRIL 15, 1988
notations
---------
theta_i = vertex_vector[i, :]
chi_sq_i = vertex_chi_sq[i]
"""
# ... | 319803a40639c58183239a24497b38d749f59ebd | 30,726 |
import torch
def quantile_features(density, q_vals):
"""
Input
- density: tensor of shape [n_samples]
- q_vals: list of numbers between 0 and 1 with the quantiles to use
Output
- quartile_sigs: tensor of shape [len(q_vals)]
"""
q_vals = torch.tensor(q_vals, dtype=density.dtype... | f720125b43250403a6164b7a94bd97f25cfea422 | 30,727 |
def And(s1, s2):
""" And(s1, s2) returns a new selector that selects a node only if BOTH
s1, and s2 select the node."""
return lambda x: s1(x) and s2(x) | 2de67c6b7109bf6b12c187f85bf8ca4483289156 | 30,728 |
import toml
def load_config_data():
""" Loads all config data from the duck_bot_config.toml file. """
return toml.load("duck_bot_config.toml") | b7cb1c28c5cd8b0399b3f2555ca09a677df7416b | 30,730 |
def get_cell(caves, row, col):
"""Get (row, col) cell in caves."""
return caves[row][col] | 743068c3be8e0e60b56cc8f0c9c99a0cea07e4c2 | 30,731 |
from typing import Callable
from typing import Any
from typing import Iterable
def first_order_frequencies(method: Callable[[list[Any], list[float], int], Iterable[Any]],
iterations: int,
population_size: int,
sample_size: int,
... | e03af41b83ad80a1f4313975d920c0c5efd815e0 | 30,732 |
def taux_gc(seq):
"""
Le taux de "GC" dans la séquence ADN.
"""
return ((seq.count('G') + seq.count('C')) / len(seq)) * 100 | d517f1b2dcde0ca2bb14648d2c40f58d52b43fec | 30,733 |
def check_within_range(dframe, lower_bound, upper_bound):
"""
Helper function to check if all values in a dataframe
are within given range (values inclusive) lower_bound, upper_bound
"""
out_of_range = 0
for col in dframe.columns:
within_range = dframe[col].between(lower_bound, upper_bo... | d81414f7ca11c514dd7348ee8f3013a472df932c | 30,735 |
def namebunch(abunch, aname):
"""give the bunch object a name, if it has a Name field"""
if abunch.Name == None:
pass
else:
abunch.Name = aname
return abunch | d3a32d578ef604760d1f5adb009c96de519f0ec3 | 30,737 |
def get_ranking13():
"""
Return the ranking with ID 13.
"""
return [
("a5", 0.868655),
("a6", 0.846338),
("a4", 0.812076),
("a3", 0.789327),
("a2", 0.718801),
("a1", 0.300742),
] | 8fd076f8d385600e10cc3a4610638a7dc30a0055 | 30,738 |
def convert_bytes_to_bits(byte_value):
""" Convert input bytes to bits """
return byte_value * 8 | e6cda98e84b133dc48a19ebc3e98e79bd577bf47 | 30,740 |
def for_object(permissions, obj):
"""
Only useful in the permission handling. This filter binds a new object to
the permission handler to check for object-level permissions.
"""
# some permission check has failed earlier, so we don't bother trying to
# bind a new object to it.
if permissions... | b843b2a4c2f13bb01d54c52d2bdf63d6047176c2 | 30,742 |
def mode(nums):
"""Return most-common number in list.
For this function, there will always be a single-most-common value;
you do not need to worry about handling cases where more than one item
occurs the same number of times.
>>> mode([1, 2, 1])
1
>>> mode([2, 2, 3, 3, 2])
... | 6421a27a545dcc000923842b88137e46ea0a0a5e | 30,744 |
def _callify(meth):
"""Return method if it is callable,
otherwise return the form's method of the name"""
if callable(meth):
return meth
elif isinstance(meth, str):
return lambda form, *args: getattr(form, meth)(*args) | df0e323d77d1e62cc89bbac84b3cf24a6d2e6f02 | 30,747 |
import numpy
def get_freq_array(bandwidth, n_chans):
"""
Create an array of frequencies for the channels of a backend
@param bandwidth : bandwidth
@type bandwidth : float
@param n_chans : number of channels
@type n_chans : int
@return: frequency of each channel in same units as bandwidth
"""
re... | 0f3ab851be519498765d7b579f13c44e3d751c3f | 30,752 |
import random
def _drawRandom(nbToDraw, maxValue, exclusion=None):
"""Draws random numbers from 0 to maxValue.
Args:
nbToDraw (int): number of numbers to draw
maxValue (int): max value for the numbers to draw
exclusion (set): numbers to exclude
"""
numbers = set()... | 24e44dc52cce7722bb1074b747457fc160912664 | 30,753 |
import copy
def _set_logger_name(config_in, package_name):
"""Replace config yml's logger package-name with the real package name"""
config = copy.deepcopy(config_in)
config['loggers'][package_name] = config['loggers'].pop('package-name')
return config | 12b7e33a6655fffd472d19545779d4ee325895cd | 30,757 |
def getPubSubAPSConfiguration(notifierID, config):
"""
Returns the Apple push notification settings specific to the pushKey
"""
try:
protocol, ignored = notifierID
except ValueError:
# id has no protocol, so we can't look up APS config
return None
# If we are directly ta... | bdadd793af1cb17f18401ab1938ac7a7517b67b5 | 30,760 |
def get_bound(atom, bound=None):
"""
Return appropriate `bound` parameter.
"""
if bound is None:
bound = atom.bound
if bound is None:
raise ValueError('either atom must be in bound '
+ 'mode or a keyword "bound" '
+ 'argument must be ... | f9223945011fbc056db170a943cf33fb09662920 | 30,761 |
def finding_gitlab_forks(fork_user):
"""
fork_user: Takes a repository to user_count dictionary map
purpose: calculates how much gitlab forks are there among all the forks
"""
total_forks = 0
gitlab_forks = 0
gitlab_url = []
for fu in fork_user:
total_forks += 1
if 'h... | 192cbc4f4dda4d086ddeb20243f9b3a605edad96 | 30,762 |
import sys
import unicodedata
def normalize_path(path):
"""normalize paths for MacOS (but do nothing on other platforms)"""
# HFS+ converts paths to a canonical form, so users shouldn't be required to enter an exact match.
# Windows and Unix filesystems allow different forms, so users always have to enter... | df3295c47e30b54edb2d74959d8dbaa114aa9773 | 30,763 |
def argmax(d):
"""d (dict)"""
max_value = max(d.values())
max_key = -1
for key, value in d.items():
if value == max_value:
max_key = key
return max_key | a47869475a3369f2f6a6b623533c0875b8062a50 | 30,764 |
import typing
import math
def normalized(x: float, y: float) -> typing.Tuple[float, float]:
"""
Returns a unit vector version of x, y
"""
magnitude = math.hypot(x, y)
if magnitude == 0:
return 0, 0
return x / magnitude, y / magnitude | fe6079a0e1335977fa831b64a340f5e7747d763f | 30,765 |
import math
def solve_tangent_angle(distance, radius):
"""
Helper function to calculate the angle between the
centre of a circle and the tangent point, as seen from
a point a certain distance from the circle.
:Parameters:
distance: float
Distance of point from centre of ... | 6db4a340f50d0fd426dbae3e2248624cc3c50563 | 30,766 |
def fullname(o):
"""获取对象的类名"""
module = o.__class__.__module__
if module is None or module == str.__class__.__module__:
cls_name = o.__class__.__name__
else:
cls_name = module + '.' + o.__class__.__name__
if cls_name == 'type':
cls_name = o.__base__.__module__ + '.' + o.__ba... | 1b4672add4a4ea8e5e7e9e539c596847e4d04bde | 30,767 |
from typing import OrderedDict
def collect(iterable, key=None, value=None):
"""Collect elements by key, preserving order."""
if key is None:
key = lambda element: element
if value is None:
value = lambda element: element
odict = OrderedDict()
for element in iterable:
odict.... | 94bd28567ed1ef4069fb617e837c4ba02ff24ae4 | 30,768 |
def get_word_list_from_data(text_df):
"""
将数据集中的单词放入到一个列表中
"""
word_list = []
# text_df.iterrows()返回一个列表,包含了所有数据的系你想
# [(行号,内容), (行号,内容), (行号,内容), (行号,内容)......]
for i, r_data in text_df.iterrows():
word_list += r_data['text'].split(' ')
# 包含数据集里所有词语的列表
return word_list | d66a5db21b0cd6e899f562ccb77b28c64ccad69d | 30,769 |
def round_f(d):
"""
取精度
"""
return d | d4622be3edc72f066fb5f3ba8a992fd70278ef68 | 30,770 |
import uuid
def _obtain_signed_blob_storage_urls(self, workspace_id, id_count=1, blob_path=None):
"""Obtain a signed blob storage url.
Returns:
[dict]: blob storage urls
[dict]: blob storage ids
"""
blob_url = f'{self.HOME}/{self.API_1}/project/{workspace_id}/signed_blob_url'
if ... | e6fa3e492930162ff7963ce0a8aedc2d91bd3583 | 30,773 |
import re
def gettime_s(text):
"""
Parse text and return a time in seconds.
The text is of the format 0h : 0.min:0.0s:0 ms:0us:0 ns.
Spaces are not taken into account and any of the specifiers can be ignored.
"""
pattern = r'([+-]?\d+\.?\d*) ?([mμnsinh]+)'
matches = re.findall(pattern, te... | 49f315b9f92dc04eea450f7d8b93a7f9bd08da14 | 30,774 |
def convert_openlayers_roi_to_numpy_image_roi(roi: list, image_height: int) -> list:
"""In both openlayers and numpy, the same roi format applies
Args:
roi (list): roi in format [x, y, width, height]
image_height (int): height of the original image from which the roi is cropped
Returns:
... | 6fe3247b0b1dcc7a9f9da23cbde1e42d71199d88 | 30,775 |
def _adjust_map_extent(extent, relocate=True, scale_ratio=1):
"""
Adjust the extent (left, right, bottom, top) to a new staring point and
new unit. extent values will be divided by the scale_ratio
Example:
if scale_ratio = 1000, and the original extent unit is meter, then the
unit is ... | ee1d6c4195daab7cc8473b05f334357d25b5b7b5 | 30,776 |
def parseArgs(args, aliases={}):
""" takes all options (anything starting with a -- or a -) from `args`
up until the first non-option.
short options (those with only one dash) will be converted to their long
version if there's a matching key in `shortOpts`. If there isn't, an
KeyError is raised."""
... | f749a9f59834922342efe00be200230fc820bf54 | 30,777 |
def pkcs_unpad_encryption(bytestring, block_length):
"""Takes a PKCS1.5 block and returns the message"""
correct_length_bytestring = bytestring.rjust(block_length, b"\x00")
if correct_length_bytestring[:2] != b"\x00\x02":
raise ValueError(
f"Bytestring isn't PKCS1.5 formatted: {correct_l... | 2753c4f30df006a88f31aa55b69d95326da8203f | 30,779 |
def fbexp(db, dp, rhog, rhos, umf, us):
"""
Bed expansion factor for calculating expanded bed height of a bubbling
fluidized bed reactor. See equations 14.7 and 14.8 in Souza-Santos [1]_.
Parameters
----------
db : float
Diameter of the bed [m]
dp : float
Diameter of the bed... | c78b94639f1d6835ee490636e85d49f04b09ebe1 | 30,780 |
import getpass
import os
def get_user_name():
"""
Returns the user name associated with this process, or raises an
exception if it fails to determine the user name.
"""
try:
return getpass.getuser()
except Exception:
pass
try:
usr = os.path.expanduser( '~' )
... | 3a9e66bc4026d7ec41dd6365593e23e234e461ae | 30,781 |
from typing import List
def write_floats_10e(vals: List[float]) -> List[str]:
"""writes a series of Nastran formatted 10.3 floats"""
vals2 = []
for v in vals:
v2 = '%10.3E' % v
if v2 in (' 0.000E+00', '-0.000E+00'):
v2 = ' 0.0'
vals2.append(v2)
return vals2 | 7e2f9b1a9e4560d3d9194c18601d22a57ed0811e | 30,782 |
def dup_integrate(f, m, K):
"""
Computes the indefinite integral of ``f`` in ``K[x]``.
Examples
========
>>> from sympy.polys import ring, QQ
>>> R, x = ring("x", QQ)
>>> R.dup_integrate(x**2 + 2*x, 1)
1/3*x**3 + x**2
>>> R.dup_integrate(x**2 + 2*x, 2)
1/12*x**4 + 1/3*x**3
... | 0f1981d699c4c80b61d4f0aececa1ccc4601712b | 30,783 |
from typing import Dict
import torch
def inputs_to_cuda(inputs: Dict[str, torch.Tensor]):
"""
Move tensors in the inputs to cuda.
Args:
inputs (dict[str, torch.Tensor]): Inputs dict
Returns:
dict[str, torch.Tensor]: Moved inputs dict
"""
if not torch.cuda.is_available():
... | 1c67e915463ea04b2df03f3697a2eb83dedb07a2 | 30,784 |
def pruneNullRows(df):
"""
Removes rows that are all nulls.
:param pd.DataFrame df:
This is done in place to avoid storage problems with large dataframes.
:return pd.DataFrame:
"""
return df.dropna(axis=0, how='all') | af0a34bed71f937d6ff970f521d5f82720fffdc9 | 30,785 |
def load_ed25519_vectors(vector_data):
"""
djb's ed25519 vectors are structured as a colon delimited array:
0: secret key (32 bytes) + public key (32 bytes)
1: public key (32 bytes)
2: message (0+ bytes)
3: signature + message (64+ bytes)
"""
data = []
for line in vec... | 618ea06c408d131664bbfe0b4350fee5e6a3edd0 | 30,786 |
from bs4 import BeautifulSoup
def parse_html(html: str) -> BeautifulSoup:
"""Parse the HTML with Beautiful Soup"""
return BeautifulSoup(html, features="html.parser") | 8e10667747f24b9f9790b2b512bc9d5635ec7cd9 | 30,787 |
import hashlib
def convert_email(email):
""" MD5 hash the email address """
email = email.strip().encode('utf-8').lower()
return hashlib.md5(email).hexdigest() | a556147ffb9111b6001c4d76f6cd82c3442e115e | 30,788 |
def get_n_lines(fin: str, size: int = 65536) -> int:
"""Given a filename, return how many lines (i.e. line endings) it has.
:param fin: input file
:param size: size in bytes to use as chunks
:return: number of lines (i.e. line endings) that `fin` has
"""
# borrowed from https://stackoverflow.com... | 0259c71681a9779e3df311ff03010262ded8f058 | 30,790 |
def uniformize_points(p1, p2, p3, p4):
"""
Orders 4 points so their order will be top-left, top-right,
bottom-left, bottom-right.
A point is a list/tuple made of two values.
:param p1:
:param p2:
:param p3:
:param p4:
:return:
"""
pts = [p1, p2, p3, p4]
pts.sort(key=lamb... | d51dd6a3c1524b2efc1df49bd5abdcf9ab0ef7ab | 30,792 |
def correct_text(key, text):
"""
矫正OCR后的文字
:param key:
:param text:
:return:
"""
if key == 'title1':
return text.replace('<>', '').replace('母', '').replace('团', '')
elif key == 'title2':
if text and text[0] == 7:
text = text.replace('7', 'Z')
return te... | a7a28b7d4f9e57e960c59428523dd3006e9050f3 | 30,793 |
import os
def get_download_filename( rule_response ):
"""
Parameters
----------
rule_response : dict
Returns
-------
str
"""
filename = 'download'
if 'name' in rule_response:
filename = rule_response.get( 'name' )
else:
download_path = rule_response.get( 'download' )
filename = os.path.basename( d... | 35b449e02cca22275c55225d2550060ac289d0c5 | 30,794 |
import re
def exact_match(single_line, single_line_compare):
"""
Look for an exact match within the compare parameter
@:return: Boolean value indicating a match was found or not.
"""
# Text could contain characters that are used for regex patterns
pattern = re.escape(single_line)
matches =... | f4a654ffeca7f4e8fbc96f6097e11a9c7d9ee34b | 30,795 |
def auth_token(pytestconfig):
"""Get API token from command line"""
return pytestconfig.getoption("token") | 419a0e617f242ac9b657b7b397e8b06e447a7efe | 30,796 |
import struct
def msg_request_pack(index, begin, length):
"""<len=0013><id=6><index><begin><length>
b'\x00\x00\x00\r\x06\x00\x00\x00\x00\x00\x00\x80\x00\x00\x00@\x00'
0, 32768, 16384 (5 byte prefix_len + msg_id prepended - not sure if it should be handled here)
"""
return (
bytes([0, 0, 0,... | 6346f2b3c9aee678ab5017fd00ad11dba32d3794 | 30,797 |
def conv_params(sz_in: int, sz_out: int):
"""Solves for filter_size, padding and stride per the following equation,
sz_out = (sz_in - filter_size + 2*padding) / stride + 1
Attempts to find a solution by iterating over various filter_size, stride and padding
in that order. If no solution is foun... | 86c1a2437231d2fb6515a6581719d3568cdee813 | 30,799 |
def get_model_io_names(model):
"""Gets names of the input and output nodes of the model
Args:
model (keras Model): model to parse
Returns:
inputs (list): names of all the input nodes
outputs (list): names of all the output nodes
"""
num_inputs = len(model.inputs)
num_o... | b8bc93bd2bf01597b16eaee5bc0f1a210e185dbe | 30,800 |
def find_package_data():
"""Find abiflows package_data."""
# This is not enough for these things to appear in an sdist.
# We need to muck with the MANIFEST to get this to work
package_data = {'abiflows.fireworks.tasks': ['n1000multiples_primes.json']
}
return package_data | 06549d7b20adce373bdf06dfc82684ec281eb15f | 30,802 |
def pascal(n):
"""
pascal: Method for computing the row in pascal's triangle that
corresponds to the number of bits. This gives us the number of layers
of the landscape and the number of mutants per row.
Parameters
----------
n : int
row of pascal's triangle to compute
Returns... | 66c6a9946a730186feda3fee04c75dd32d4312ad | 30,805 |
def get_value(input_data, field_name, required=False):
"""
Return an unencoded value from an MMTF data structure.
:param input_data:
:param field_name:
:param required:
:return:
"""
if field_name in input_data:
return input_data[field_name]
elif required:
raise Excep... | 3e4ec623528f279a61b5ad9897935a5fda8af2d1 | 30,806 |
def seconds_to_string(seconds):
"""
Format a time given in seconds to a string HH:MM:SS. Used for the
'leg time/cum. time' columns of the table view.
"""
hours, seconds = divmod(int(seconds), 3600)
minutes, seconds = divmod(seconds, 60)
return f"{hours:02d}:{minutes:02d}:{seconds:02d}" | 23db1370e887a9dad3d6dbd40bc2f25c244f1f77 | 30,807 |
def bateria(pcell_nom, vdc_sist, vdc_bc, nbat_p):
"""
Para calcular la potencia de la batería
vdc_sist: Usually is 12, 24 or 48 V for
large sistems.
"""
nbat_s = vdc_sist/vdc_bc
Pbat_nom = round(nbat_p*nbat_s*pcell_nom,2)
nbat = nbat_s*nbat_p
return P... | 54f8c2ad935c3cbda00dd57c4357d39d4c8b4757 | 30,808 |
def get_slice(img, indices):
"""
return image slice by index array
"""
return img[indices[0]:indices[1], indices[2]:indices[3], indices[4]: indices[5]] | bb2c602d56cc874e0e82c32aacc3b8d5b36d4e35 | 30,810 |
def py2tcl(pystr):
"""
Converts openseespy script to tcl
Returns
-------
"""
# new = '\n'.join(pystr.split()[1:]) # removes the import line
new = pystr.replace('(', ' ')
new = new.replace(')', ' ')
new = new.replace('opy.', '')
new = new.replace(',', '')
new = new.replace(... | 9e5e35d78a03a1c36eb599c5036419fb4e34649e | 30,811 |
def get_min_max(arr):
"""
Return a tuple(min, max) out of list of unsorted integers.
Args:
arr(list): list of integers containing one or more integers
Returns:
(int, int): A tuple of min and max numbers.
"""
if len(arr) == 0:
return None, None
min_number = max_number ... | d7cd2304092c766bfd0ffcb2235e7ad0c6428e61 | 30,814 |
def size_for(s):
"""
This function takes a string representing an amount of bytes and converts
it into the int corresponding to that many bytes. The string can be a plain
int which gets directly converted to that number of bytes or can end in a specifier
such as 100k. This indicates it is 100 kiloby... | 3e88f0555f0ab1b06432d87c5ebca7f33b24d1c7 | 30,816 |
def _estimateNormedOutsideTemperature(data):
""" When the normed outside temperature for a given region is'nt known,
this method will estimate it as follows:
- the two day mean temperatures are calculated for
. reference year
. extreme winter year
- the normed outside te... | ead03331a33b1c1492ccbff3cf53466686de484c | 30,817 |
import warnings
def igraph_info(g, census=False, fast=False):
"""Return summary dict of igraph properties"""
with warnings.catch_warnings():
warnings.simplefilter('ignore')
out = dict()
out["vertices"] = g.vcount()
out["edges"] = g.ecount()
out["density"] = 2*g.ec... | cc458be0dc77a6a2b107d7672832d20233842b8d | 30,819 |
def _is_whitenoise_installed() -> bool:
"""
Helper function to check if `whitenoise` is installed.
"""
try:
return True
except ModuleNotFoundError:
pass
return False | 3732d32de4fae1d9f65baeb481c9eb6a6dcdd7bd | 30,820 |
import os
def folder_search(input_folder,file_name):
"""
Scans a folder an returns a list of the paths to files that match the requirements. The matching is litteral.
*Previously named Foldersearch*
Warning:
It is just returning rigidly the files that **exaclty** match the path entered. Prefe... | 94fc3e47c3b434174e298917b63a197d9c7c7a09 | 30,821 |
def sanitize_version_number(version):
"""Removes common non-numerical characters from version numbers obtained from git tags, such as '_rc', etc."""
if version.startswith('.'):
version = '-1' + version
version = version.replace('_rc', '.')
return version | 4627ce6ad06046b575da3a272e8d8acc41183000 | 30,822 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.