content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import struct
import os
def parse_zip(fp):
"""
Parse the zip file headers at fp
:param fp: the file pointer from which to parse the zip file
:return: A tuple of local files, directory headers, and end of central directory
The local files are dictionary where the keys are the local ... | fec86690c7959f325907d249b1752e705248401d | 652,566 |
def monthdelta(date, delta):
"""
Get the date relevant to the delta from today's date
"""
m, y = (date.month+delta) % 12, date.year + ((date.month)+delta-1) // 12
if not m:
m = 12
d = min(date.day, [31, 29 if y%4==0 and not y%400==0 else 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][m-1])
... | 8c37b4c9792f1c9eb87ac57aaf459bf09a0d1fe3 | 652,567 |
def get_virtual_network_info(**output_dict):
"""
Get the VLAN information including name,
the svip ip, netmask, size, and starting IP
"""
out_dict = {}
response_json = output_dict['ListVirtualNetworks']
# print(json.dumps(response_json, sort_keys=True, indent=4))
for virtnet in respo... | e35a8335528e80577a2c07c074f0e224d45334cc | 652,568 |
from typing import OrderedDict
import copy
def build_argument_tree(items):
"""
Given a dictionary of lists, builds a tree structure representing
all possible combinations of the values from these lists.
Arguments:
items: Dictionary of lists, looking like this:
{
... | 44514f7d221aedf1b96218472f94f2af9079d717 | 652,569 |
from calendar import isleap
import datetime
def datetime_from_numeric(numdate):
# borrowed from the treetime utilities
# https://github.com/neherlab/treetime/blob/de6947685fbddc758e36fc4008ddd5f9d696c6d3/treetime/utils.py
"""convert a numeric decimal date to a python datetime object
Note that this onl... | 849825381df7cacf33bb94bd22cbfd027a79f804 | 652,570 |
def get_feature_dict(params):
"""
Creates a dictionnary that maps the feature to their position in X
"""
feature_dict = params['feature_dict']
for key, value in feature_dict.items():
if len(value) > 1:
feature_dict[key] = tuple(range(value[0], value[1]))
return feature_dict | 7853ec659cb14a369b98025344ff8bbca24294fb | 652,571 |
import re
def sha_from_desc(desc):
""" Extract the git SHA embedded in the description field """
m = re.match(".*\[SHA ([A-Za-z0-9]{7})[\]!].*", desc)
if m:
return m.groups()[0] | 8f8a598c3bba0aba8d0786d4d4d2737e1bc4d8df | 652,572 |
import os
def getList(folder, key1="", key2="", key3=""):
"""get the list of files in the folder containing key1 and key2"""
L = os.listdir(folder)
L = [v for v in L if (key1 in v) and (key2 in v) and (key3 in v)]
return L | 77eff2f5c8a2d22f66d164fd505ad51df2b8ee83 | 652,573 |
from functools import reduce
import operator
def multiply(__iterable):
"""Return the multiplication of a 'start' value (default: 1) plus an iterable
of numbers
When the iterable is empty, return the start value. This function is intended
specifically for use with numeric values and may reject non-num... | b200c3d9aeb0c288686802ed0485bdf8fb0e1554 | 652,574 |
def find_irreducible_prefix(brackets):
"""Find minimal prefix of string which is balanced (equal Ls and Rs).
Args:
brackets: A string containing an equal number of (and only) 'L's and 'R's.
Returns:
A two-element tuple.
The first element is the minimal "irreducible prefix" of
`brackets`, which ... | fa8bd7998550de63f9fea9523424b198bfc96a45 | 652,575 |
def _extract_node_text(node):
"""Extracts `text` and `content-desc` attribute for a node."""
text = node.get('text')
content = node.get('content-desc', [])
all_text = [text, content] if isinstance(content, str) else [text] + content
# Remove None or string with only space.
all_text = [t for t in all_text if... | 66800ba5ab924fc0641a6a725069e3899fee39ef | 652,576 |
def filter_reports_by_table(reports, tables=None, skip_tables=None):
"""
:type reports list[indexdigest.utils.LinterEntry]
:type tables str
:type skip_tables str
:rtype: list[indexdigest.utils.LinterEntry]
"""
if tables:
return [
report for report in reports
i... | 50ea7b02ccedec1a336f32a0816ce828f60dd311 | 652,577 |
def moreFunc(y, z):
"""
@description: basic multiplication function
"""
val = y * z
return val | 14ae042751d2d8e83fc7419cfe1dc19498d6e4bb | 652,578 |
def substitute(message, substitutions=[[], {}], depth=1):
"""
Substitute `{%x%}` items values provided by substitutions
:param message: message to be substituted
:param substitutions: list of list and dictionary.
List is used for {%number%} substitutions and dictionary for
{%name%} subs... | 4a46c46faf1848f1c7e437fed956e21cfdd3a813 | 652,579 |
def encodeDict(items):
""" Encode dict of items in user data file
Items are separated by '\t' characters.
Each item is key:value.
@param items: dict of unicode:unicode
@rtype: unicode
@return: dict encoded as unicode
"""
line = []
for key, value in items.items():
item = u'%... | 2cd39fc638753c943bae28cac22ad4cce3259862 | 652,580 |
import random
def rescale_image(img, scale):
"""Rescales the image.
Args:
img (list) the current state of the feature vis image.
scale (bool) true, if image should be randomly scaled.
Returns:
list: the rescaled image.
"""
if scale:
# factors are selected based on th... | 2e1bd47dca83b43e9baa65690b80d5809bace5b4 | 652,581 |
import math
def rotationFromQuaternion(q):
"""Convert quaternion to euler-axes-angle (vrml)."""
v = [0.0, 0.0, 0.0, 0.0]
v[3] = 2.0 * math.acos(q[0])
if (v[3] < 0.0001):
# if v[3] close to zero then direction of axis not important
v[0] = 0.0
v[1] = 1.0
v[2] = 0.0
el... | c60130eec3e5a4fa8fc3079a6046e3b9b56707e7 | 652,582 |
import typing
def find_section_in_list(
section: typing.List[typing.Any], action: typing.Dict[str, typing.Any], key: str
) -> int:
"""
Find index of section in list
:param section: list, where we want to search
:param action: action dictionary
:param key: the key marker
:return: index of s... | b958b06472020aac57b53bdf29873ca2d3ffba1e | 652,583 |
import os
import pathlib
def find_unity():
"""Search for Unity.exe
find_unity() -> str
"""
for v in os.environ.values():
if v.endswith("Unity.exe"):
return v
unity_root = pathlib.Path(os.environ['PROGRAMFILES']) / "Unity/Editor"
if unity_root.exists():
for f in uni... | 0666cc2719be583d57bba285137187852adc19e5 | 652,584 |
def readImageFileFromDisk(filename):
"""
Convert digital data to binary format
:param filename: file to convert
:return: binary data content of specified file
"""
with open(filename, 'rb') as file:
binaryData = file.read()
return binaryData | cb6aad78775dfef4229d3a04b6f7545c65ebd5b2 | 652,585 |
def get_version():
""" Get version of %MODULE% package. """
return "0.0.1" | 8d80f085fac3358c6ca1ac2a21a0ba471a63b38d | 652,586 |
import torch
def variable_delay(phase, audio, buf_size):
"""delay with variable length
Args:
phase (torch.Tensor): 0~1 0: no delay 1: delay=max_length (batch, n_samples)
audio (torch.Tensor): audio signal (batch, n_samples)
buf_size (int) : buffer size in samples = max delay length... | ecf92e0857909f0d4509a8d933df701d926dfa73 | 652,587 |
def get_order_category(order):
"""Given an order string, return the category type, one of:
{"MOVEMENT, "RETREATS", "DISBANDS", "BUILDS"}
"""
order_type = order.split()[2]
if order_type in ("X", "D"):
return "DISBANDS"
elif order_type == "B":
return "DISBANDS"
elif order_type ... | 08c276c6080a47b6170e211f5c63f3163eedf3a6 | 652,588 |
import re
def pre_process(s):
"""
clean strings before processing
:param s:
:return:
"""
if type(s) != str:
return s
s = re.sub('\n', ' ', s)
s = re.sub('-', '', s)
s = re.sub('/', ' ', s)
s = re.sub("'", '', s)
s = re.sub(",", '', s)
s = re.sub(":", ' ', s)
... | ecbaa520de863e845449c82ed6d9944be8b3e9bf | 652,589 |
import random
def powerlaw_sequence(n,exponent=2.0):
"""
Return sample sequence of length n from a power law distribution.
"""
return [random.paretovariate(exponent-1) for i in range(n)] | aa394a74e92c1c3f1f59a56d55a585e7d0c8bdd4 | 652,591 |
import functools
import time
def timer(function):
""" A decorator that makes the decorated *function* return its execution time."""
@functools.wraps(function)
def wrapper(*args, **kwargs):
t1 = time.time()
result = function(*args, **kwargs)
t2 = time.time()
print(" @time '... | 216b6ce5aa91f78fe16b62e2fc4af92e3268d863 | 652,592 |
def cli(ctx, history_id, dataset_id, file_path, use_default_filename=True):
""".. deprecated:: 0.8.0 Use :meth:`~bioblend.galaxy.datasets.DatasetClient.download_dataset` instead.
Output:
"""
return ctx.gi.histories.download_dataset(history_id, dataset_id, file_path, use_default_filename=use_default_f... | 9ce95eb3489894095d410dacaac34807b253f071 | 652,593 |
def derive_version_from_namespace(root):
"""Simplistic version detection of XML document from ETree object root."""
not_found = ''
versions = (
'http://docs.oasis-open.org/csaf/ns/csaf-cvrf/v1.1/cvrf',
'http://docs.oasis-open.org/csaf/ns/csaf-cvrf/v1.2/cvrf',
)
if root is None:
... | c23439a2295b1382726626cf2cca750f7db9cc14 | 652,594 |
def make_album(artist_name, album_title):
"""Returns the name of the album and it's title."""
album_discription = f"{artist_name}, {album_title}"
return album_discription.title() | 947dc8bd649728321642e42a7fa68544282254ba | 652,595 |
def distance_between(origin_x, origin_y, destination_x, destination_y):
"""Takes origin X,Y and destination X,Y and returns the distance between them"""
return ((origin_x - destination_x)**2 + (origin_y - destination_y)**2)**.5 | 98b3fa8499c149f4c162f2b40eb58da8b36596ee | 652,596 |
def basic_data_context_config_dict(basic_data_context_config):
"""Wrapper fixture to transform `basic_data_context_config` to a json dict"""
return basic_data_context_config.to_json_dict() | febc522b59deb4b6920a56941a5f439ae5c90475 | 652,598 |
def str_is_num10(a_str):
"""通过int(a_str, 10)测试字符串数字是否是10进制"""
# noinspection PyBroadException
try:
int(a_str, 10)
return True
except:
return False | 20ccfc10d7c119597bfded3807cd9269691c63ce | 652,599 |
def split_elem_def(path):
"""Get the element name and attribute selectors from an XPath path."""
path_parts = path.rpartition('/')
elem_spec_parts = path_parts[2].rsplit('[')
# chop off the other ']' before we return
return (elem_spec_parts[0], [part[:-1] for part in elem_spec_parts[1:]]) | 63394c8a1ecf5d4e2fbeb1f7f3b58f4c386b29e2 | 652,600 |
def __make_selected_courses_string(courses):
"""Creates a string of comma separated string of course names.
Used for user printout to indicate what courses the script is going to query
Args:
courses (listof Course): list of canvasapi course objects - specified by id in .csv file
Returns:
... | 68a8b9ca6c2fcb243fd31a9ea912961d7a9395e9 | 652,601 |
def _normalize_target_module(source_module, target_module, level):
""" Normalize relative import, to absolute import if possible.
Parameters
----------
source_module : str or None
Name of the module where the import is written.
If given, this name should be absolute.
target_module :... | 7f6ce7688a5e5f8116419074c7cafc94ef794996 | 652,602 |
import copy
def ApplyFunToRadii(fiber_bundle, fun):
"""
Applies function to fibers radii
Parameters
----------
fiber_bundle : [(,4)-array, ...]
list of fibers
fun : function
Returns
-------
res : [(,4)-array, ...]
translated fiber_bundle
"""
fiber_bundle ... | fd904747954dc7b894cf6e086c1843f98b9ece27 | 652,604 |
from typing import Dict
from typing import Tuple
def get_floors(source_matrix: Dict, vertices_names: Tuple, source_floor=()) -> Tuple:
"""
Calculates the graph floors (levels) to order it.
:param source_matrix:
:param vertices_names:
:param source_floor:
:return:
"""
#print('source_flo... | 2e09e50159bf5d0c50dc81b06530ac1c5131469a | 652,605 |
def get_file_info_from_url(url: str, spec_dir: str):
"""
Using a url string we create a file name to store said url contents.
"""
# Parse a url to create a filename
spec_name = url.replace('https://raw.githubusercontent.com/', '')\
.replace('.yml', '')\
.replace... | 229de0038d0b0249a68a7e4c058f76f972296fac | 652,606 |
from typing import Dict
def reciprocal_cycle_length(n: int) -> int:
"""Returns the length of the recurring cycle in the decimal fraction part
of 1/n for some natural number n.
"""
# perform long division for 1/n
remainders: Dict[int, int] = {}
dividend = 1
digit_count = 0
while di... | 50626930f13a2789cc240ad78dd2a5ca7862390b | 652,607 |
def make_idx(*args, dim, ndim):
"""
Make an index that slices exactly along a specified dimension.
e.g. [:, ... :, slice(*args), :, ..., :]
This helper function is similar to numpy's ``_slice_at_axis``.
Parameters
----------
*args : int or None
constructor arguments for the slice o... | 78f432d18e6107b0aed9d68f60b6e088e795dedf | 652,608 |
def Luhn (number):
""" function Luhn validates a number against the Luhn checksum formula
- function call: Luhn (number)
number has to be an integer, digits only
- output: True | False
source: https://en.wikipedia.org/wiki/Luhn_algorithm
Press q to exit. """
result = False
... | 8872dfcbbfca221c5a36732974226c5a5db0ec9e | 652,609 |
from typing import Iterable
from typing import Any
def contains(collection: Iterable, entity: Any) -> bool:
"""Checks whether collection contains the given entity."""
return entity in collection | 7688428427e056ed24830b2fd9c3ba34be02e84b | 652,610 |
import pickle
def load(filename):
"""
Load posterior object from pickle file.
Args:
filename (string): full path to pickle file
"""
with open(filename, 'rb') as f:
post = pickle.load(f)
for key,val in post.params.items():
if val is None:
del post.params[ke... | 35909bae8d14cea146bd138cf5bfdfcb03c5c4f1 | 652,611 |
from pathlib import Path
def extract_sequence(fasta: Path, target_contig: str) -> str:
"""
Given an input FASTA file and a target contig, will extract the nucleotide/amino acid sequence
and return as a string. Will break out after capturing 1 matching contig.
"""
sequence = ""
write_flag = Fal... | 547ba39dc3658e6c28c77012eba79393c01690ee | 652,612 |
import random
def shuffle_sequence(seq):
""" shuffles a sequence given as string """
l = list(seq)
random.shuffle(l)
return ''.join(l) | 2669bd9d849d551cafe0661d13da92b1a1d169de | 652,613 |
def hex2int(value, w=0):
"""
This will convert data into hex to int
Author : Prudvi Mangadu (prudvi.mangadu@broadcom.com)
:param value:
:param w:
:return:
"""
return int("0x{}".format(value), w) | 7d2b12ccbbc26868916367fda414f2df65384dc3 | 652,614 |
def obter_pos_c(pos):
"""
obter_pos_c: posicao -> str
Recebe uma posicao e devolve a componente coluna da posicao.
"""
return pos['c'] | f1df4cc2416ed0a6f5cab5bb72b0fe8392a132e0 | 652,615 |
def interval_len(aInterval):
"""Given a 3 column interval, return the length of the interval """
return aInterval[2] - aInterval[1] + 1 | ea4aca73d330852f41cc66a77e93b49c595cac68 | 652,616 |
def isColorBar(ax):
"""
Attempt to guess whether an input matplotlib
``Axes`` is home to a ``colorbar`` object.
**Parameters**
ax
An Axes instance.
**Returns**
A boolean value of ``True`` if the x xor y axis
satisfies all of the foll... | 18941944084fcfa2dce424de290557df59cc9ffb | 652,618 |
def get_emoji(hashtag):
"""Return a helpful emoji bashed on the hashtag of the earning report."""
if "miss" in hashtag:
return "🔴"
return "🟢" | d9cdcee7d0d3aa5b6b040fe29abf8d688ebdef9c | 652,619 |
from typing import List
def find_occurrences_in_text(text: List[List[List[str]]],
researched_tokens: List[str]) -> List[str]:
"""
Find occurrences of given tokens in a given text.
Each occurrence has the following format: <chapter>-<line>-<half-line>-<word>.
>>> text = r... | 9c19223fc21660fdf01fc1566177899b4f2427e5 | 652,620 |
import argparse
def parse_args():
"""Parses arguments for script."""
ap = argparse.ArgumentParser(
description='Plots histograms and saves image residuals' + \
' where objects are detected.')
ap.add_argument('-f', '--framerange', nargs=2, default=(0,0),
meta... | 4f2f18ed3ac618d251132922be18776365acc676 | 652,621 |
def test_fake_group(group_no, groups):
"""
Does tag span many groups? If so we'll create pseudo group of groups.
Return the number of groups and total number of posts if true. Otherwise,
return 0, 0
:param: group_no: Group number within groups list
:param: groups: List of
:return: Tru... | 445f8a40cf06cd800fa87b05a7fe16e6a1dcf0dc | 652,622 |
def read_reco2vol(volumes_file):
"""Read volume scales for recordings.
The format of volumes_file is <reco-id> <volume-scale>
Returns a dictionary { reco-id : volume-scale }
"""
volumes = {}
with open(volumes_file) as volume_reader:
for line in volume_reader.readlines():
if l... | 8914f0f8351f3340fa3382c7dad00c61ce0aa154 | 652,623 |
import os
def load_stopwords(directory):
"""
Loads stopwords from the project directory.
"""
filename = os.path.join(directory, "processed", "stopwords.txt")
if not os.path.isfile(filename):
raise FileNotFoundError(f"The file '{filename}' does not exist.")
return [
line.strip(... | 6b9ec08145be16919630edac7824491b4aa0e622 | 652,624 |
def create_option_response(option):
"""
"""
return {
'option': option['option'],
'value': option['display']
} if option else None | 6a1b3e2aa786e525ad649405b75825f83bb9d9dd | 652,625 |
def isLineStacked(index) :
"""
Returns true if the data identified by this (multi)index should be stacked when using the Graph option "Stacked chart" and "Line type:Script"
"""
return True | d656bbcc0892074e2ef5f6015ad69c537b231368 | 652,627 |
def closest_pair(point_list):
"""Gets the closest pair of points from a list of points."""
return point_list[0], point_list[1] | daab93a662daa2e8aa18d2b1bca7d2fd333f0e0b | 652,628 |
def lower_keys(x):
"""converts the payload dict keys to all lowercase to match schema
Args:
x:payload
"""
if isinstance(x, dict):
return dict((k.lower(),v) for k, v in x.items())
else:
return "msg_fromat_incorrect" | d5a34884267dacd7c1080ffb1a4ac7708124044a | 652,629 |
import re
def sanitize_xpath(value: str):
"""
Sanitize/canonize the XPath value
:param value:
:return:
"""
value = re.sub(r'.*?}(F\d+_\d+?)\[\d+](.*)', r'\1\2', value)
value = re.sub(r'(\[)|(])|(/Q{.*?})', '', value)
value = value.strip(' \n')
return value | 8a7df4d80ca4a908b17476040f5c4cb4cbb8675a | 652,630 |
from typing import List
from functools import reduce
def transpose_alt(matrix: List[str]):
"""Transposes a matrix.
Transposes a matrix in a more geeky way as it uses a long one-liner.
*(It's a one-liner metaphorically speaking of course as for
readability reasons it's been split up into multiple line... | e73799c634a9901ed94ff7ebe042e8fe6386e985 | 652,631 |
import argparse
def get_args():
""" get args"""
parser = argparse.ArgumentParser(description='get ecolite train dataset')
parser.add_argument('dataset', type=str, default="ucf101",
choices=['ucf101', 'hmdb51', 'kinetics', 'something', 'jhmdb'])
parser.add_argument('modality', t... | b774ee634e9403f420a9d67f22efc7fe73401d05 | 652,633 |
def _owens_t_regions(h, a):
"""Returns a list of Tensors describing the region of computation."""
# We assume h >= 0, 0 <= a <= 1
# Regions 1-7 that use T1.
regions = []
is_in_region1 = (h <= 0.06) & (a <= 0.025)
is_in_region1 = is_in_region1 | (h <= 0.02) & (a <= 0.09)
regions.append(is_in_region1)
i... | 05b58954dfcf78eaedfe09cc6d6708a97cec3e98 | 652,634 |
import collections
def extract_corefRelations(etreeRoot, d):
"""
:param etreeRoot: ECB+ XML root
:return: dictionary with annotaed events in ECB+ (event_dict)
:return:
"""
relations_dict_appo = collections.defaultdict(list)
relations_dict = {}
for elem in etreeRoot.findall('Relations... | f8ae9ae0ad97d0e6e0e65830aab0c146aa60c10c | 652,635 |
def p_conditional_to_joint(P):
"""
given conditional probability matrix P, return approximiation of joint distribution probability
"""
return (P + P.T) / (2. * P.shape[0]) | e5687d796eb5103c4aa6fbd27c7b83da56294a0c | 652,636 |
def PowersetList(initial_set):
"""Computes the power set of a given set.
If the input is null, it returns the empty set.
"""
# The power set of the empty set has one element, the empty set.
result = [[]]
if initial_set:
for x in initial_set:
result.extend([subset + [x] for subset in result])
r... | 017e375c3ba0df006444e52d1799c4f020479a40 | 652,637 |
from typing import List
def get_list_of_colormaps() -> List[str]:
"""Return the list of avalaible colors"""
return [
"autumn",
"bone",
"colorcube",
"cool",
"copper",
"flag",
"gray",
"hot",
"hsv",
"jet",
"lines",
"p... | 619291144831b4eaaaf8ae0caa54e94077c4bed5 | 652,638 |
def ReduceLROnPlateauConfig(argument_parser):
"""
Set CLI arguments
:param argument_parser: argument parser
:type argument_parser: ```ArgumentParser```
:returns: argument_parser
:rtype: ```ArgumentParser```
"""
argument_parser.description = """Reduce learning rate when a metric has sto... | b626ff014360eda76c4e587b608387a261fa5a59 | 652,639 |
def bdev_nvme_opal_revert(client, nvme_ctrlr_name, password):
"""Revert opal to default factory settings. Erase all data.
Args:
nvme_ctrlr_name: name of nvme ctrlr
password: password
"""
params = {
'nvme_ctrlr_name': nvme_ctrlr_name,
'password': password,
}
retu... | a3521b6f4266b56204e30e3ba6ed22e6130f4f23 | 652,640 |
import argparse
from pathlib import Path
def parse_args():
"""Parse input arguments."""
parser = argparse.ArgumentParser(description="Map csv to COCO json")
parser.add_argument("-id", "--deepfake_image_path", type=Path, help="Path to the jpg image files for deepfake.")
parser.add_argument("-ld", "--d... | fe78d744c5c5e08194fb10ee9e0ca4ede3b2c06b | 652,641 |
def default_boosts():
"""Generate dictionary with default boost levels."""
boost_dict = {}
boost_dict["atk"] = 0
boost_dict["def"] = 0
boost_dict["spa"] = 0
boost_dict["spd"] = 0
boost_dict["spe"] = 0
return boost_dict | 110fa352afda91dd9bdc2dca9c222825fae61c83 | 652,643 |
def url(classes):
"""get URL property (u-*) names
"""
return [c.partition("-")[2] for c in classes if c.startswith("u-")] | 685de8f7feacf4de5856e29b5c1aad75d8df7f30 | 652,644 |
from zipfile import ZipFile
import os
def unzip_files(zip_filename_list):
"""
Unzipping the datasets
parameters
----------
zip_filename_list : the list of file names to unzip under the data folder
"""
folder_names = []
for file in zip_filename_list:
# paths
... | bed10668819c8e994397b2cfeed1285138a87e81 | 652,646 |
import requests
def api(url):
"""
This function consumes an api for word's countries names and their capital cities
"""
request_data = requests.get(url)
status_code = request_data.status_code
data = request_data.json()
return data | 1104a5753eb620b322881f231b93e450f46f95dc | 652,647 |
import hashlib
def sha256(path):
"""Return the sha256 digest of a file."""
h = hashlib.sha256()
with open(path, 'rb') as f:
for chunk in iter(lambda: f.read(8192), b''):
if not chunk: break
h.update(chunk)
return h.hexdigest() | 97ec85f000ff9db7dbdbffab78ede1dd3b12fc65 | 652,648 |
import yaml
def jinja_filter_toyaml_dict(value) -> str:
"""Jinjafilter to return a dict as a Nice Yaml.
Args:
value (dict): value to convert
Returns:
Str formatted as Yaml
"""
return yaml.dump(value, default_flow_style=False) | eb3506fd00a9a36390037436a38de36a9ccbe343 | 652,649 |
import sys
def outputs_match_1D(actual, expected):
"""Compare two 3D-arrays (in format as in expected_valid_output) and
see if they match. The reason we need this function instead of just ==
is that the module is allowed to output anything when the expected
value is None (i.e. we expect garbage)."""
stderr = ... | b09f6d6b10cf21c749ae6a236d2d9cc68b8820fe | 652,650 |
import configparser
def get_required_packages():
"""
Returns the packages used for install_requires
This used to pin down every package in Pipfile.lock to the version, but that, in turn, broke
downstream projects because it was way too strict.
Now, this simply grabs all the items listed in the `... | 9450c7917dd511d1adcd0c08f4b4203273433238 | 652,651 |
def peak_position_comparisons(unknown_peaks, known_compound_peaks,
known_compound_list,
association_matrix):
"""This function takes in an association matrix and turns the numbers
given by said matrix into a text label."""
#Handling errors in input... | b7aa3430fafbca61b2922dc2847b8d1b25a8f2e8 | 652,652 |
def packet_size():
"""Constant packet size of 1000 bytes."""
return 1000 | d1e58318141401771e66d291d64539817238d7a4 | 652,653 |
def pow3(x, c, a, alpha):
"""pow3
Parameters
----------
x : int
c : float
a : float
alpha : float
Returns
-------
float
c - a * x**(-alpha)
"""
return c - a * x**(-alpha) | b231bc11ee060023691ef0908cd81898733ab97f | 652,654 |
from bs4 import BeautifulSoup
def extractsms(htmlsms) :
"""
extractsms -- extract SMS messages from BeautifulSoup tree of Google Voice SMS HTML.
Output is a list of dictionaries, one per message.
"""
msgitems = [] # accum message items here
# Extract all conversations by searching ... | 464254147fd21426cf00715ec8af2f0daad974b4 | 652,655 |
def clean_list(list):
""" cleans a list of all extraneous characters """
clean_list = []
try:
for element in list:
clean_list.append(element.strip())
except Exception:
return -1
return clean_list | e6a0739344aea8e48de7c72b666b213894c7a2b4 | 652,656 |
def point_sub(a, b):
""" Subtract two 2d vectors
(Inline this if you can, function calls are slow)
"""
return (a[0] - b[0], a[1] - b[1]) | 208cfc0b533b706bd258c954a39cbb3c75b304cb | 652,657 |
def minibatch_fn(net, loss_fn, optimizer, batch):
"""
Trains network for a single batch.
Args:
net (torch network)
ANN network (nn.Module)
loss_fn (torch loss)
loss function for SGD
optimizer (torch optimizer)
optimizer for SGD
batch (torch.Tensor)
... | 2e4cc7ae929efe08a0b8ffb23521f6b29a4e559c | 652,658 |
import hmac
def constant_time_compare(val1: str, val2: str) -> bool:
"""Return True if the two strings are equal, False otherwise."""
return hmac.compare_digest(val1.encode('utf8'), val2.encode('utf8')) | b22ef33cf38e92e1bd346a6e9c0a397eaef8c9d3 | 652,659 |
import hashlib
def control_sum(fpath):
"""Returns the control sum of the file at ``fpath``"""
f = open(fpath, "rb")
digest = hashlib.sha512()
while True:
buf = f.read(4096)
if not buf:
break
digest.update(buf)
f.close()
return digest.digest() | 050d30cc92d1379fc89be716f31909531284b3f4 | 652,660 |
def is_retweet(tweet):
"""リツイートであるかを確認する
Parameters
----------
tweet : tweepy.models.Status
ツイートオブジェクト
Returns
-------
bool
リツイートかどうかの真偽値
"""
return hasattr(tweet, "retweeted_status") | 0de6d6de849d207d88a258cb1970dc04ae4fe3e4 | 652,661 |
import sys
def quote_string_define_value(value):
""" Quote the value used in a -D name=value compiler define in a
command line safe way.
This function makes sure that the string value is quoted in
way that survives the command line interface used for talking
to compilers.
""... | 7f23279c59db693f229ce997c8eb7eaf6d107a3f | 652,662 |
from typing import List
import re
def get_participants_twitter_ids_in_one_page(participation_table_list) -> List[str]:
"""1ページ内のテーブルからtwitterユーザidを取得し、リストを作成する
Args:
participation_table_list ([type]): BeautifulSoupのオブジェクト。ルートにテーブルを持っている
Returns:
IdList: ページ内のtwitterユーザidのリスト
"""
... | 6d45142457e6fd98548c59f46acda9458f1eb75c | 652,663 |
def is_paragraph_head(span):
"""Returns if sentence is the first sentence of a paragraph."""
sents = span.doc.sents
spar = span._.paragraph
res = 1
for s in sents:
if s._.paragraph == spar:
if s.start < span.start:
res = 0
return res | 3ff7509329a18d1c464e7a53bbde2be7b4a9579d | 652,664 |
def _get_vf_default_style(ttfont):
"""Return the name record string of the default style"""
default_fvar_val = ttfont['fvar'].axes[0].defaultValue
name_id = None
for inst in ttfont['fvar'].instances:
if inst.coordinates['wght'] == default_fvar_val:
name_id = inst.subfamilyNameID
return ttfont['name... | ee35a70de1a40d4f915c94a31d53a288c6bbf16b | 652,666 |
def QtoMatrix16(q):
"""
QtoMatrix3x3
"""
w, x, y, z = q[0], q[1], q[2], q[3]
return (1 - y * y - z * z,
2 * x * y - 2 * z * w,
2 * x * z + 2 * y * w,
0,
2 * x * y + 2 * z * w,
1 - x * x - z * z,
2 * y * z - 2 * x * w,
... | dcd798864da9250ee65a08119881c30fe1a28cc2 | 652,667 |
def tenant_is_enabled(tenant_id, get_config_value):
"""
Feature-flag test: is the given tenant enabled for convergence?
:param str tenant_id: A tenant's ID, which may or may not be present in the
"convergence-tenants" portion of the configuration file.
:param callable get_config_value: config k... | 00c90b9a0c58aeca4a9cddc64fac41d93ce8c1d6 | 652,668 |
def get_defined_pipeline_classes_by_key(module, key):
"""Return all class objects in given module which contains given key in its name."""
return [
cls for name, cls in module.__dict__.items()
if isinstance(cls, type) and key in name
] | 55a3dd6a0bfeaa2fea49e6193f39438c2abaf0be | 652,669 |
def calc_bits(offset, size):
"""
Generates the string of where the bits of that property in a register live
Parameters
----------
offset : int,
size : int,
Returns
----------
ret_str : str, the string
"""
# Generate the register bits
if size == 1:
ret_str ... | b28c5de3d22957102e264c97f3d31376bc0ade59 | 652,670 |
import re
def _get_python_info_rename(path):
""" Figure out the name of the package, without the version for renaming the directory.
Why do all this? Well, (1) it's tricky to figure the boundary between package name and version
for some packages, and this approach removes the guesswork, (2) sometimes you... | c213d9ec3d037524bb6afd9c0be1884a3196fd03 | 652,672 |
def sf_pytest_cli_orgname(request):
"""Helper to see what org the user has asked for"""
return request.config.getoption("--org") | ccae111433512503d31e4ed96b4d60bb8a734593 | 652,673 |
def _convert_units(self, val):
"""
Convert the text value into a common unit. In this case, we're converting to mm.
:param val:
:return:
"""
val = str(val)
if val[-2:] == "mm":
# As-is
return val[:-2]
elif val[-2:] == "cm":
return str(float(val[:-2]) * 10.0)
... | 27117ed7f7b0c508c834bc7e2837897e7eaf81ec | 652,674 |
def set_color_mask(A, M, c):
""" Given image array A (h, w, 3) and mask M (h, w, 1),
Apply color c (3,) to pixels in array A at locations M
"""
for i in range(3):
A_i = A[:,:,i]
A_i[M]=c[i]
A[:,:,i] = A_i
return A | 3e113d168d1a6d5321628a7cc099e67c770f601c | 652,675 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.