content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import os
def load_requirements(path: str) -> list:
"""Load requirements from the given relative path."""
with open(path, encoding="utf-8") as file:
requirements = []
for line in file.read().split("\n"):
if line.startswith("-r"):
dirname = os.path.dirname(path)
... | 021ddf0e89d94cc52b4de88b8bd3c629543a39de | 673,067 |
def select_zmws(zmws, min_requested_bases):
"""
>>> select_zmws([], 0)
([], 0)
>>> select_zmws([], 10)
([], 0)
>>> select_zmws([('zmw/1', 1), ('zmw/2', 2), ('zmw/3', 5), ('zmw/4', 7), ('zmw/5', 10), ('zmw/6', 15)], 10)
(['zmw/1', 'zmw/2', 'zmw/3', 'zmw/4'], 15)
>>> select_zmws([('zmw/1',... | 106cfba09496a25e2376e92e5747a4e3d13f9f2f | 673,068 |
def preprocess(sample):
"""Preprocess a single sample."""
return sample | b34a59ce5ac2f372940d9ea47fdf8870e63aef06 | 673,069 |
def point_on_rectangle(rect, point, border=False):
"""
Return the point on which ``point`` can be projecten on the
rectangle. ``border = True`` will make sure the point is bound to
the border of the reactangle. Otherwise, if the point is in the
rectangle, it's okay.
>>> point_on_rectangle(Rect... | 761d3cd918b353e18195f8817292b9c2c9ec4f40 | 673,070 |
def sort_priority2(values, group):
"""
Similar to set_priority but it returns a boolean indicating if any higher-priority items
were seen at all.
"""
found = False
def helper(x):
# The nonlocal statement makes it clear when data is being assigned out of a closure into
# another ... | f5713810d48fdeead9f59f96bfaa8f3a3e4b0545 | 673,071 |
def for_teuthology(f):
"""
Decorator that adds an "is_for_teuthology" attribute to the wrapped function
"""
f.is_for_teuthology = True
return f | a4fe41f957efe8cf2f5e3bf41428e004f136bfa8 | 673,072 |
import os
def match_prefix(pathname, prefix):
"""
Check if a pathname has the expected prefix.
:param pathname: The pathname of a file or directory (a string).
:param prefix: The pathname of a directory expected to contain
the given `pathname` (a string).
:returns: :data:`True`... | 4f65d60630a73a832c764911ccc4d560c78b88b0 | 673,073 |
def filter_to_demo_indicators(df):
"""Remove columns that don't pretain to demographic indicators (Occupied units,
renter occupied units, owner occupied units which come 200 ACS PUMS Data but are
Housing Security and Quality category indicators"""
df = df.drop(
df.filter(regex="P25pl|LTHS|HSGrd|... | c660db13a79e8bf8d387b0ae3805484ac0b410ed | 673,074 |
import pickle
def loadpfile(path: str) -> list:
"""
Loads whatever object is contained in the pickle file.
Args:
path: file path
Returns:
some object
"""
return pickle.load(open(path, 'rb')) | 7a40b5ebe276ffa8efbaa54f642b3a69ac109d15 | 673,075 |
import argparse
import sys
def get_args():
"""Parse arguments from CLI"""
parser = argparse.ArgumentParser()
parser.add_argument(
'--config',
action='store_true',
help='Create `requirements.json` file'
)
parser.add_argument(
'--delete',
type=str,
hel... | 05aadacf588ef93b176314f6974214a00c855c5f | 673,076 |
def single_number(nums):
"""
Given an array of integers, every element appears twice except for one. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
Args:
nums: list[int]
Returns:
int
"... | 96b9146bf93a3704bec638ac5be2c8bbf956387b | 673,077 |
def bin_search(query, data):
""" Query is a coordinate interval. Binary search for the query in sorted data,
which is a list of coordinates. Finishes when an overlapping value of query and
data exists and returns the index in data. """
i = int(round(len(data)/2)) # binary search prep
lower, upper = 0, len(data)... | 355a270b1fb4b2fea75ec699c081b2a3fa064aab | 673,078 |
def con_celsius_to_kelvin(degree_celsius):
"""
Parameters
----------
degree_celsius : float
temperature in Celsius
Returns
-------
degree_kelvin : float
temperature in Kelvin
"""
degree_kelvin = degree_celsius + 273.15
return degree_kelvin | b0c6e9d486779458775baeaa70cfd7dff3adc6fc | 673,079 |
def update_output_tab2(value):
"""
:return: Minimum number of games selected
output text on tab 2 based on slider input.
"""
return "Min Ratings: {}".format(value) | f6697a0e4e448490c8365792dfa07ffa24434342 | 673,080 |
def _nsec_to_usec_round(nsec: int) -> int:
"""Round nanoseconds to microseconds"""
return (nsec + 500) // 10 ** 3 | c273bea9a4c04478ea3b391682a33fbbbdf5b731 | 673,081 |
def segment_sentences(text, delimiters = None):
"""
"""
if delimiters is None:
delimiters = ['?', '!', ';', '?', '!', '。', ';', '…', '\n']
#
text = text.replace('...', '。。。').replace('..', '。。')
#
# 引用(“ ”)中有句子的情况
# text = text.replace('"', '').replace('“', '').replace('”', '')
... | db18ddedef6aa92b6cec42142c0614b8501cb87f | 673,082 |
def launch():
""" Called when the user launches the skill without specifying what they want
"""
return "<speak>sample welcome text</speak>" | 221c880d5afd97e2b5893f0aa35b94d3b43780df | 673,083 |
def possui_par(numeros):
"""Verifica se a lista possui pelo menos um número par.
"""
return False | 0ba3fc2f61c6af410e05b263b509af066076b710 | 673,084 |
def _ord(i):
"""Converts a 1-char byte string to int.
This function is used for python2 and python3 compatibility
that can also handle an integer input.
Args:
i: The 1-char byte string to convert to an int.
Returns:
The byte string value as int or i if the input was already an
... | 5635e7e6dcf58017b0a8170d3afb78a474eb90ad | 673,085 |
def _compute_temp_terminus(temp, temp_grad, ref_hgt,
terminus_hgt, temp_anomaly=0):
"""Computes the (monthly) mean temperature at the glacier terminus,
following section 2.1.2 of Marzeion et. al., 2012. The input temperature
is scaled by the given temperature gradient and the elev... | 155379cdaf8e5aedc5769da20330d752179ffe11 | 673,086 |
import torch
def sample_descriptors_epi(keypoints, descriptors, s, normalize=True, align_corner=False):
"""Samples descriptors at point locations"""
b, c, h, w = descriptors.shape
keypoints = keypoints - s / 2 + 0.5
keypoints /= torch.tensor([(w * s - s / 2 - 0.5), (h * s - s / 2 - 0.5)], device=key... | d0b7a27fa1ac794686f09b4df9b4cdecfdfd8070 | 673,087 |
def check_movie_in_tweet(movie, full_text):
""" Verifica se um filme foi mencionado no tweet. """
if movie['title'] in full_text:
if (movie['words_count'] <= 2) and (movie['score'] < 10.0):
return False
if (movie['words_count'] <= 3) and (movie['score'] < 9):
return False... | 01bb250ffc302be730bad29cd77f37392383c6e2 | 673,088 |
def featuretype_filter(feature, featuretype):
"""
Only passes features with the specified *featuretype*
"""
if feature[2] == featuretype:
return True
return False | ccd56ed0f5273af8bfa0365a93d54f8457b13b0b | 673,089 |
def as_latex(ordinal):
"""
Convert the Ordinal object to a LaTeX string.
"""
if isinstance(ordinal, int):
return str(ordinal)
term = r"\omega"
if ordinal.exponent != 1:
term += f"^{{{as_latex(ordinal.exponent)}}}"
if ordinal.copies != 1:
term += rf"\cdot{as_latex(ord... | 6df43f0a1250879f56900bb2d70e2edece3628e3 | 673,090 |
import re
def filter_comments(string):
"""Remove from `string` any Python-style comments ('#' to end of line)."""
comment = re.compile(r'(^|[^\\])#.*')
string = re.sub(comment, '', string)
return string | b4a50d09061b05f8582625a3a0602acb27a97605 | 673,091 |
def apply_scale_offset(field_def, field_value):
"""From the FIT SDK release 20.03.00
The FIT SDK supports applying a scale or offset to binary fields. This
allows efficient representation of values within a particular range and
provides a convenient method for representing floating point values in
... | 45b6486c8d24ca7ae7a0fd9cd878c10143c50581 | 673,092 |
def size_index(user):
"""Set the index of the current partition.
Arguments
---------
user: "Dictionary containing user's answers"
Returns
-------
"Integer of the current partition index"
"""
index = 0
if 'swap_size' in user:
index = 3
elif 'root_size' in use... | 7c2494aeeaf6926dfa390df0dde93410b2a9c1f2 | 673,094 |
def apply_ants_transform_to_point(transform, point):
"""
Apply transform to a point
ANTsR function: `applyAntsrTransformToPoint`
Arguments
---------
point : list/tuple
point to which the transform will be applied
Returns
-------
tuple : transformed point
... | 87ebb8c562c3b3c8ed297efac652a452f708f3e3 | 673,095 |
def _generate_short_name(name):
"""Get composer short name"""
name_parts = name.split(" ")
lname = name_parts.pop()
initials = "".join([f"{name[0]}." for name in name_parts])
return f"{initials} {lname}".strip() | e0eab31cc5c8df1e9a6f5a3971a65f1155931df1 | 673,096 |
import string
def remove_punctuation(input_string):
"""Remove the punctuations in input string.
Parameters
----------
input_string : string
String to remove punctuations.
Returns
-------
output_string : string
String without punctuations.
"""
out_st... | 61e0e1a0e7921aaa84b7db3f582b43a382fdab18 | 673,097 |
import re
def is_strong_password(password):
"""Determines whether a string is a strong password or a weak password.
Args:
password: The string to be tested for password strength.
Returns:
A boolean value indicating whether the password is strong or weak.
"""
char_length = re... | 3e1d1736ec4f9a02979903d39394f23558b6f5a9 | 673,098 |
def MigrateUSBPDSpec(spec):
"""Migrate spec from old schema to newest schema.
Args:
spec: An object satisfies USB_PD_SPEC_SCHEMA.
Returns:
An object satisfies USB_PD_SPEC_SCHEMA_V3.
"""
if isinstance(spec, int):
return {
'port': spec
}
if isinstance(spec, (list, tuple)):
return... | 1491f5d956d6ce9fa833322995b49166e2508691 | 673,099 |
def what_versions_sync(pg_versions, gh_versions, pg_versions_gh):
""" versions to add, update, delete.
"""
to_add = gh_versions - pg_versions
to_update = pg_versions_gh & gh_versions
to_delete = pg_versions_gh - gh_versions
return to_add, to_update, to_delete | b40eecbb277d6742287563d1ea5b1d8a300621af | 673,100 |
import glob
import os
def get_filenames(data_dir, ext):
"""Return a list of filenames.
Args:
is_training: A boolean denoting whether the input is for training.
data_dir: path to the the directory containing the input data.
Returns:
A list of file names.
"""
return glob.gl... | b731d1b1408a4908714e2ed4bd98c9733ffa7c20 | 673,101 |
def series_circuit_UA(*args):
"""
Calculates the total U*A-value for a series circuit of two or more U*A
values.
Parameters:
-----------
UA : float, int, np.ndarray
U*A value (heat conductivity) in [W/K] for each part of the series
circuit. If given as np.ndarray, all arrays hav... | 354ca1ca4f5f5e706d1c07618896d5a73c2853b9 | 673,102 |
def _merge_fix(d):
"""Fixes keys that start with "&" and "-"
d = {
"&steve": 10,
"-gary": 4
}
result = {
"steve": 10,
"gary": 4
}
"""
if type(d) is dict:
for key in d.keys():
if key[0] in ('&', '-'):
... | 381287054aeb04959a96c90f22a50f3321d5ab1e | 673,103 |
def handle_name(name: str) -> str:
"""使用引号包裹有空格的文件名"""
if ' ' in name:
name = "'" + name + "'"
return name | d48f12ad56eb70e5216e25c9571edfb481a39eaf | 673,104 |
import os
import sys
def ScriptDir():
"""Get the full path to the directory containing the current script."""
script_filename = os.path.abspath(sys.argv[0])
return os.path.dirname(script_filename) | b5348fc10873edb8db28ee8055b27c9b9f32f090 | 673,105 |
def mesh_dual(mesh, cls=None):
"""Construct the dual of a mesh.
Parameters
----------
mesh : :class:`compas.datastructures.Mesh`
A mesh object.
cls : Type[:class:`compas.datastructures.Mesh`], optional
The type of the dual mesh.
Defaults to the type of the provided mesh obje... | e9ff14953137fe3e8685cdd9d6aab33e96fd5320 | 673,106 |
from pathlib import Path
def transformPath(string, location, tokens):
"""Transforms a ParseResult into a Path"""
path = ""
for handle in tokens.path[0].split("/"):
if "@" in handle:
node, address = handle.split("@")
path += "/%s@%x" % (node, int(address))
elif handl... | 8e3041f0ba6d7ea02716b200c819c9c04493a5d0 | 673,107 |
def update_quotes(char, in_single, in_double):
"""
Taken from: https://github.com/jkkummerfeld/text2sql-data
:param char:
:param in_single:
:param in_double:
:return:
"""
if char == '"' and not in_single:
in_double = not in_double
elif char == "'" and not in_double:
i... | 5c9a26d56dbb026b4e01f8a98014e97e5314ecc1 | 673,108 |
import os
import re
import fnmatch
def load_bidsignore(bids_root):
"""Load .bidsignore file from a BIDS dataset, returns list of regexps"""
bids_ignore_path = os.path.join(bids_root, ".bidsignore")
if os.path.exists(bids_ignore_path):
with open(bids_ignore_path) as f:
bids_ignores = f.... | 0ad1ebc648b4510f1688da64065e892c08e66039 | 673,109 |
import requests
import json
def site_catalog(site):
"""
Returns a dictionary of CWMS data paths for a particular site
Arguments:
site -- cwms site name, example TDDO
Returns:
json.loads(r.text) -- dictionary of available site data
"""
url = r'http:... | 229c56cd5d472125695d4a91c95f5966736ea72e | 673,110 |
def split_node_lists(num_jobs, total_node_list=None, ppn=24):
"""
Parse node list and processor list from nodefile contents
Args:
num_jobs (int): number of sub jobs
total_node_list (list of str): the node list of the whole large job
ppn (int): number of procesors per node
Retur... | 9ec3f14b1eedcd8d741be2b38f93791968268c39 | 673,111 |
def convert_datepicker_to_isotime(date_picker_format):
"""the date_picker_format argument comes from the html forms and it should looks like this: MM/DD/YYYY.
We want to transform them into our standart ISO format like this :
YYYY-MM-DDThh:mm:ss.ms
"""
try:
year = date_picker_format.sp... | ae1992ee055236a2aeebfe02ddd8740c462f0983 | 673,112 |
def handle(req):
"""handle a request to the function
Args:
req (str): request body
"""
print(req)
return "ok" | 07332c2a618fb7c3b46c8395caf5966473ea0159 | 673,113 |
def undo_keypoint_normalisation(normalised_keypoints, img_wh):
"""
Converts normalised keypoints from [-1, 1] space to pixel space i.e. [0, img_wh]
"""
keypoints = (normalised_keypoints + 1) * (img_wh/2.0)
return keypoints | fc7760b4e1b3318ea73812bdc88b9fb7e87be358 | 673,115 |
def suite_in_func(x):
"""
>>> suite_in_func(True)
(42, 88)
>>> suite_in_func(False)
(0, 0)
"""
y = z = 0
if x: y = 42; z = 88
return y, z | 842684bacef553585e41bc51bb251c936b3eba31 | 673,116 |
def overflow_wrap(keyword):
"""``overflow-wrap`` property validation."""
return keyword in ('normal', 'break-word') | 1ade3dd7bcf7eec54006ccf44622540b0a56a79b | 673,117 |
def output_aws_credentials(awscreds, awsaccount):
"""
Format the credentials as a string containing the commands to define the ENV variables
"""
aws_access_key_id = awscreds["data"]["access_key"]
aws_secret_access_key = awscreds["data"]["secret_key"]
shellenv_access = "export AWS_ACCESS_KEY_ID=%... | c09c4a26ac9b91c6d2de863c3f37ddca21d21375 | 673,118 |
import os
def make_datafile(path_a,filelist_a,path_b,filelist_b):
"""Assembly the datafile name to analyze
Parameters
----------
path_a : str
Path of the files corresponding to the reference library
filelist_a : list of str
List of the filenames of the different replicates from ... | c96b68f0396abdd28fb6c30696143b918a0639a2 | 673,119 |
from typing import Match
def _get_match():
"""Return a Match object."""
return Match() | 9179a90e3d4ffcc19fd400973ec1e4bf29b0c53f | 673,120 |
def get_phase_refr_index(wlen):
"""Get the phase refractive index for ice as a function of wavelength.
See: https://wiki.icecube.wisc.edu/index.php/Refractive_index_of_ice#Numerical_values_for_ice
or eqn 3 in https://arxiv.org/abs/hep-ex/0008001v1
Parameters
----------
wlen
Wavelength ... | 1c8a6000f7c8f9900ed495ae29998bf7e0b656e8 | 673,121 |
from pathlib import Path
def get_github_api_token(tok):
"""
Fetch github personal access token (PAT) for gist api request using POST
Parameters
----------
tok : str
PAT if passed as string, else None and will be fetched
"""
if not tok:
tok_path = Path.home() / ".jupyter_to_... | cbe35a5ef3e5db5bd6538fe30b906eb47946b51f | 673,122 |
def squeeze_axes(shape, axes, skip='XY'):
"""Return shape and axes with single-dimensional entries removed.
Remove unused dimensions unless their axes are listed in 'skip'.
>>> squeeze_axes((5, 1, 2, 1, 1), 'TZYXC')
((5, 2, 1), 'TYX')
"""
if len(shape) != len(axes):
raise ValueError("... | ca359ee31ecf3000d9afc7afd1ebbf779ce528a3 | 673,124 |
def read_padding(fp, size, divisor=2):
"""
Read padding bytes for the given byte size.
:param fp: file-like object
:param divisor: divisor of the byte alignment
:return: read byte size
"""
remainder = size % divisor
if remainder:
return fp.read(divisor - remainder)
return b'... | fdb1e87123125cc3b0e9d1b60b5b7d112bd56235 | 673,125 |
def get_array_int(values):
"""
Simply returns the value given as an int
:param values: list of int of values to return
:return: list of int ot test
"""
assert isinstance(values, (tuple, list))
for v in values:
assert isinstance(v, int)
return list(values) | 0a932f6c2005696979c47a594bef12e4eb39aec3 | 673,128 |
def extractDetails(remoteException):
"""Extract the details of an xml-rpc exception error message"""
try:
details = remoteException.faultString or remoteException.message
details = details.split(":", 2)[-1].replace("'>", "").lstrip()
except AttributeError:
details = str(remoteExcepti... | 5cc9fd0ece9e702843a710a29d03288b61c40cfd | 673,129 |
def fileopen(fun):
""" Open read-only filehandle if first argument is string
This function can be used to decorate functions that expect a filehandle as
the first argument. If the first argument is a string, it is assumed to be
the path to the input file, and the file is opened in read mode.
Args:... | bbe8e4260d88a8ffe05fd98f82f54bedc8bcb99f | 673,130 |
def preprocess_baseline2(segment_df, rush_hour):
"""
Preprocess the segment data considering the weather and the rush hour
Algorithm:
Preprocess segment_df to add a new column of rush hour
split the dataframe with groupby(segment_start, segment_end, weather, rush_hour)
Define the new dataframe
... | b3a3a4ed4096b6c2424023d2adad2fb2a176d71a | 673,131 |
def str_remove(string, index, end_index=None):
"""Remove a substring from an existing string at a certain from-to index range."""
end_index = end_index or (index + 1)
return "%s%s" % (string[:index], string[end_index:]) | b9e2913835bbad96520f20eccead1d40a89b8039 | 673,133 |
def m_coef(h_septum):
"""
Calculates the specific coefficient for calculation the heigth ligth layer of liquid equation.
Parameters
----------
h_septum : float
The heigth of drain septum, [m]
Returns
-------
m_coef : float
The specific coefficient for this equation [dimen... | efc247919fa737bfefb889f2641787a68db89e93 | 673,134 |
import os
import mmap
def count_lines(filename):
"""Fast line count for files"""
filename = str(filename) # conver path objects
if not os.path.exists(filename):
raise ValueError(f'No such file: {filename!r}')
if os.path.getsize(filename) == 0:
return 0
with open(str(filename), ... | 75e859818c7024ae467b6bca0398bae6fc0654c0 | 673,135 |
def get(conn, uri, access_token=None):
"""
HTTP GET request with an optional authorization header with the access_token
"""
if access_token:
headers = {'authorization': '%s %s' % (access_token['token_type'], access_token['access_token'])}
else:
headers = {}
conn.request('GET', ur... | 3cf381d355652c6d984442e035cba45a8879658c | 673,136 |
def all_true(iterable):
""" Helper that returns true if the iterable is not empty and all its elements evaluate to true. """
items = list(iterable)
return all(items) if items else False | 4a6344abb72393c31883908627529aa6434f44cf | 673,139 |
import unicodedata
import string
import re
def preprocess_names(name, output_sep=' ', firstname_output_letters=1):
"""
Function that outputs a person's name in the format
<last_name><separator><firstname letter(s)> (all lowercase)
>>> preprocess_names("Samuel Eto'o")
'etoo s'
>>> pre... | 8ee4e3a487ef6e1603f8822a14354db621336f76 | 673,140 |
def get_domain_from_fqdn(fqdn):
""" Returns domain name from a fully-qualified domain name
(removes left-most period-delimited value)
"""
if "." in fqdn:
split = fqdn.split(".")
del split[0]
return ".".join(split)
else:
return None | 2a2bd0c67af39dc1949cab1f51fce4593e43d992 | 673,142 |
def flatten(scores, labels):
"""
Flattens predictions in the batch (binary case)
"""
return scores.view(-1), labels.view(-1) | 355e721560f0906d1fbe4f2a31ebfa13b267641c | 673,143 |
def GetPartitionsByType(partitions, typename):
"""Given a partition table and type returns the partitions of the type.
Partitions are sorted in num order.
Args:
partitions: List of partitions to search in
typename: The type of partitions to select
Returns:
A list of partitions of the type
"""
... | 58dd5b960f5332fca31a92de9f9a546a550c47ea | 673,144 |
import sys
def CreateCustomNamespace():
"""Namespace for sandbox environment"""
ns = dict()
try:
builtin_dict = __builtins__.__dict__
except AttributeError:
builtin_dict = __builtins__
ns["__builtins__"] = builtin_dict.copy()
ns["sys"] = sys
return ns | 2c0c08e9f35de9346f11e138acc66844d88bea3c | 673,145 |
def parse_response(message):
""" parse the http response """
result = message.decode()
return result | 66163ee29d1e213b2de7532861551f8f3443ffbe | 673,146 |
import re
def extract_information_of_cars(car_list):
"""Extract information for each car in the car list"""
# information of cars will be stored as list
cars = []
# get information of each car in the list
for car in car_list:
title = car.find("h2", class_="listing-row__title")
ti... | 5f69c2d6ae242da8f4ed28517c1bf599a546298e | 673,148 |
def is_admin(user):
"""
:param user:
:return True, (str): if user is admin
:return False, (str): is user is not admin
"""
if 'isAdmin' in user and user['isAdmin'] is True:
return True, None
return False, 'user is not authorized' | 3bc491d333d59f70c3fe1f1561c4a25c6dbdb54f | 673,149 |
def dict_max(*ds):
"""Take the maximum of dictionaries.
Args:
*ds (dict): Dictionaries.
Returns:
dict: `max(*ds)`.
"""
if not all([set(d.keys()) == set(ds[0].keys()) for d in ds[1:]]):
raise ValueError("Dictionaries have different keys.")
return {k: max([d[k] for d in d... | b24dddc5b5b670818b7dab38d959dcfa1e3f97ee | 673,150 |
def _batch_normalization(input_variable, name, mode_switch,
alpha=0.5, strict=True):
"""Based on batch normalization by Jan Schluter for Lasagne"""
raise ValueError("NYI")
G_name = name + '_G'
B_name = name + '_B'
list_of_names = [G_name, B_name]
if not names_in_graph(li... | f8dccc1e8edfa1aca0bb2075ade61543b04f58b2 | 673,151 |
import pandas
def is_pandas_df(o):
"""Is object o a pandas dataframe?"""
return isinstance(o, pandas.DataFrame) | 6f7bc3a966addf3c02eaf44b1d5a2152e0d87a89 | 673,152 |
from typing import List
from typing import Any
import collections
def _create_ngrams(tokens: List[Any], n: int) -> collections.Counter:
"""Creates ngrams from the given list of tokens.
Args:
tokens: A list of tokens from which ngrams are created.
n: Number of tokens to use, e.g. 2 for bigrams.
Returns... | 759da5a3179a3805ff84437aff7d52f620bb3bfc | 673,154 |
def split_group(name):
"""Split item name containing ``'/'`` into tuple of group/subname.
Examples:
- an input of ``'foo/bar'`` results in ``('foo', 'bar')``
- an input of ``'foo/bar/baz'`` results in ``('foo/bar', 'baz')``
"""
return tuple(reversed([x[::-1] for x in name[::-1].split("/", 1)]... | 99433ba2fe04bed360c204952b5394c4d22d6162 | 673,155 |
from typing import Mapping
def format_geodetic_target(location: Mapping) -> str:
"""creates command string for a geodetic target"""
return "g:{lon},{lat},{elevation}@{body}".format(**location) | 600b235bbfe4dd2d3779500d1decd687dd5f277f | 673,156 |
def is_valid_tfprof_tracefilename(filename: str) -> bool:
"""
Ensure that the tracefilename has a valid format.
$ENV_BASE_FOLDER/framework/tensorflow/detailed_profiling/$START_TIME_YYYYMMDDHR/$STEP_NUM/plugins/profile/$HOSTNAME.trace.json.gz
The filename should have extension trace.json.gz
"""
... | 0a67e35400c2f0591c8825ae840a29f45e4949cf | 673,157 |
import asyncio
async def preprocessor(input_data: str):
"""Simple feature processing that converts str to int"""
await asyncio.sleep(0.1) # Manual delay for blocking computation
return int(input_data) | f32deb8fa261f7ab72a024e056a41025f1cdf9b2 | 673,158 |
def _power_of_two(value):
"""Returns whether the given value is a power of two."""
return (value & (value - 1)) == 0 | b7493be7fc11cf92ad73fcdffda462aaa60ce623 | 673,159 |
def main_weapon_parts_position(main):
"""
主武器 配件信息
:param main:
:return:
"""
# 50 像素 小方块
parts_size = 42
# 武器和配件的距离 y
parts_distance_y = main[2] + 155
parts1 = (1316, 1316 + parts_size, parts_distance_y, parts_distance_y + parts_size)
parts2 = (1419, 1419 + parts_size, parts_... | 28771d6dffd7a205e7d2e82afb0b4bbed1829c9e | 673,160 |
def snake_to_camel(s: str) -> str:
"""Convert string from snake case to camel case."""
fragments = s.split('_')
return fragments[0] + ''.join(x.title() for x in fragments[1:]) | 5593e29ed345861dd0bada4a163c5006042a9fdb | 673,162 |
from numpy.random import standard_normal, random
from numpy import sqrt, less_equal, clip
def inv_gaussian(mu=1., _lambda=1., shape=None):
"""
Generate random samples from inverse gaussian.
"""
mu_2l = mu / _lambda / 2.
Y = mu * standard_normal(shape) ** 2
X = mu + mu_2l * (Y - sqrt(4 * _... | 66030cb8e132cced004f7812bb5c9baf04a0fcfb | 673,163 |
def extract_verts_in_range(gui, total_vertices, start_index, stop_index):
"""
Extracts vertices falling into a specified window of index values.
Args:
gui (GUIClass)
total_vertices (list): every vertex identified for the current input file
start_index (int)
stop_index (int)
"""
verts_in_range = []
... | 4ee4617af400779939391978b3af5023add8b045 | 673,164 |
def _get_norm_procedure(norm, parameter):
"""
Returns methods description of the provided `norm`
Parameters
----------
norm : str
Normalization procedure
Returns
-------
procedure : str
Reporting procedures
"""
if parameter not in ('sample_norm', 'gene_norm'):
... | ef1f16cffedafb90675239823aec52791c5d2fae | 673,165 |
from typing import Dict
from typing import Union
from typing import List
import json
import base64
def extract_syft_metadata(data: str) -> Dict[str, Union[str, List[str], bytes]]:
"""
Parse metadata from the syft output string
:param data: syft SBOM json string
:type data: str
:return: dict with ... | f375a7bcd1ad3e6df9e83befb0c0d7abd7db0f98 | 673,167 |
from typing import List
def bubble_sort_r(arr: List[int]) -> List[int]:
"""regular bubble sort"""
for i in range(len(arr) - 1):
for j in range(len(arr) - i - 1):
if arr[j] > arr[j + 1]:
arr[j], arr[j + 1] = arr[j + 1], arr[j]
return arr | 6a046ef01cda8329c6c4efdf6cbf5b45266a6675 | 673,168 |
def button(label: str) -> str:
"""Get en HTML button."""
return f'<button class="btn btn-primary" type="submit">{label}</button>' | d87e6f4ea1a5e87e0cfe73462b741e7f6b7fcd95 | 673,169 |
def getMObjectByMDagPath(dagPath):
"""
Retrieves an MObject from the given MDagPath.
:type dagPath: om.MDagPath
:rtype: om.MObject
"""
return dagPath.node() | 019b6c47f6b65582cb46a846987b53b27ee0e325 | 673,170 |
from typing import List
from typing import Tuple
def split_series(
series: List,
*,
reserved_ratio: float = 0.2,
test_ratio: float = 0.5,
) -> Tuple[List, List, List]:
"""
Split a series into 3 parts - training, validation and test.
Parameters
----------
series
a time seri... | 1e8e249f6c156f48071a1ca5892e47ea19dd00e1 | 673,171 |
def han(phi, Vclay, Peff=20.0):
"""
Vp and Vs relationhips using Han's empirical relations.
Vp = A + B*phi + C*Vclay
Either one of phi or Vclay may be an array, the other must be a constant.
"""
# Han fit coefficients for water saturated shaley sandstones
Vp_coef = {}
Vp_coef['5'] =... | e4c420c69fe0808ce0d32032baa9f86177c188d0 | 673,172 |
import fcntl
import os
def tty_nonblocking(fd):
"""set non-blocking attribute to a terminal fd."""
old_fl = fcntl.fcntl(fd.fileno(), fcntl.F_GETFL)
fcntl.fcntl(fd, fcntl.F_SETFL, old_fl | os.O_NONBLOCK)
return old_fl | 8f5c10e1dc4e6efc37897598b960cae8904303ce | 673,173 |
import os
def mkdir(dir_path):
"""make directory if dir_path not exist
Args:
dir_path (string): directory absolute path
Returns:
state: if successfully created directory return True,
nontheless return False
Examples:
>>> File.mkdir("/home/directory/test")
... | c29974acdbd94b2f0895ea46cf95966194518fb6 | 673,174 |
def remove_polygon_empty_row_if_polygon_exists(solution_df):
"""[summary]
Args:
solution_df ([type]): [description]
Returns:
[type]: [description]
"""
df = solution_df.reset_index(drop=True)
polygon_empty_rows = df[df.geometry == 'POLYGON EMPTY']
idxs_to_remove = []
f... | 6ef0e365efacae207d50b409aab8a5b18294d2cf | 673,175 |
def convert_args_dict_to_list(dict_extra_args):
""" flatten extra args """
list_extra_args = []
if 'component_parallelism' in dict_extra_args:
list_extra_args += ["--component_parallelism",
','.join(dict_extra_args['component_parallelism'])]
if 'runtime_config' in dict_extra_args:
... | 618db4df137c1a3214134b5783f887125cc97f33 | 673,176 |
import uuid
import base64
def nice():
"""
Returns a randomly generated uuid v4 compliant slug which conforms to a set
of "nice" properties, at the cost of some entropy. Currently this means one
extra fixed bit (the first bit of the uuid is set to 0) which guarantees the
slug will begin with [A-Za-... | 2e8c5fef173f50af4f9bd6b3377e59015c56d5ff | 673,177 |
import datetime
def group_datetime(d, interval):
"""Group datetime in bins."""
seconds = d.second + d.hour * 3600 + d.minute * 60 + d.microsecond / 1000
k = d - datetime.timedelta(seconds=seconds % interval)
return datetime.datetime(k.year, k.month, k.day, k.hour, k.minute, k.second) | bba4a6a8eb789af7f8825cb4c4e8fc8073892dd2 | 673,178 |
import re
def regex_match(pattern):
"""A curried regex match. Gets a pattern and returns a function that expects a text to match the pattern with.
>>> regex_match(r"phone:(\d*)")("phone:1234567").group(1) # noqa: W605
'1234567'
"""
def regex_match_inner(text):
return re.match(pattern, ... | ae466d108291fecc1cca985c0caa9d98c75e3d0a | 673,180 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.