content stringlengths 39 9.28k | sha1 stringlengths 40 40 | id int64 8 710k |
|---|---|---|
def get_passive_outcome(df, trial, sample):
"""Get data for a replay.
Parameters
----------
df : pandas.DataFrame
Data to be replayed
trial, sample : int
Indices into the data for which to fetch actions
Returns
-------
outcome : int
magnitude of the outcome to b... | e54e2e7e9dbbc7759a2a4284cfd4af88f5037793 | 233,001 |
import torch
def get_avg_global_features(points, mask, features, model):
"""obtain the avg pooling global features
Args:
points ([type]): points_batch
mask ([type]): points mask
features ([type]): point features
model ([type]): the loaded model
Returns:
[type]: retu... | 8a3f91c7f8ddbcb8aab32bff21d2dafaa19c68ef | 451,622 |
def manhattan_dist(pose1, pose2):
""" Returns manhattan distance between two poses """
return abs(pose1[0] - pose2[0]) + abs(pose1[1] - pose2[1]) | 9c4de9944febd48d6226e752f21dbdfb75555b81 | 592,287 |
import inspect
import logging
def verify_parameters(code, kwargs, err_message):
"""
Used to verify the that the parameters in kwarg match the signature of the code.
:param code: The code fragment's that has the signature to check.
:param kwargs: The kwargs to look for
:param err_message: An error ... | cd3c3542c41bb7ba0d3f8d7f250f44d743acb0a9 | 16,667 |
def _parse_input_list(input_list: str) -> list[str]:
"""
Converts a CSV list of assets IDs into a list of parsed IDs (but not Asset objects)
"""
return [fqn_id for fqn_id in input_list.split(",") if fqn_id != "" and fqn_id != ":"] | 280bb0e110be0f1230533acfa0f8ae4f3f2ac7af | 679,503 |
def global_usage_count(main=False):
"""
Returns global usage query
Args:
category (str): category name
main (bool): optional in order to account only for file used in main namespaces
"""
query = """
SELECT /* SLOW_OK */
COUNT(page.page_title) AS total_usa... | 4493b3a63b2fbe2e2824403a1db2705ad38cd14b | 179,597 |
def list_to_lower(string_list):
"""
Convert every string in a list to lower case.
@param string_list: list of strings to convert
@type string_list: list (of basestring)
@rtype: list (of basestring)
"""
return [s.lower() for s in string_list] | 35097ddb6a665c50851bf6c98b60e9de88fb147b | 661,563 |
from typing import Union
from typing import List
from pathlib import Path
def new_dirs(dir_paths: Union[str, List[str]]) -> List[str]:
"""
初始化文件夹,检验文件夹的存在状态,并返回准备好的文件夹路径。
Args:
dir_paths: 字符串类型的全路径,可以为单个路径,也可以放入列表中,批量创建。
Returns:
包含创建的文件夹路径字符串的list
"""
if isinstance(dir_paths... | 2a0a819a6771b22ee7ae4170cb0b42a8e1f59b52 | 595,329 |
from bs4 import BeautifulSoup
import re
def strip_spacing_from_soup(soup: BeautifulSoup, strip=False, verbose=None) -> BeautifulSoup:
"""
Strip excess white spaces near punctuation marks, e.g. fix ' .' and ' ,'
Args:
soup (BeautifulSoup, Tag, NavigableString): any soup
Returns:
soup (... | bead3244eb20ec188946bdbee06b444a6099d33f | 381,551 |
def _get_type_to_speed(cfs):
"""Given a list of charging functions, returns an object whose keys
are the CS types and values are speed rank.
Speed rank is a CS type's (0-indexed) position in the ordered list of fastest CS types.
"""
# compute max charge rates by type
result = [{
'cs_ty... | ca866af02fb39f31779de1bd7b3e6267c363b5b8 | 57,733 |
def quantumespresso_magnetic_code(aiida_local_code_factory):
"""Get a quantumespresso_magnetic code.
"""
quantumespresso_magnetic_code = aiida_local_code_factory(
executable='diff', entry_point='quantumespresso_magnetic')
return quantumespresso_magnetic_code | 913c8efc7bb2d1851c743754ea04df44c06ce6d7 | 85,876 |
def merge_aux(subperm, perm_list):
"""
Auxiliary function for merging subpermutations.
Args:
subperm (tuple):
perm_list (list)
Returns:
(tuple) list with subpermutation merged (if successful) and a flag
that is set to True if merge was successful and False otherwise.
... | 50bd179deebaba92a8ede9a9a833523208d1cb80 | 226,887 |
def fetch_mga_scores(mga_vec,
codon_pos,
default_mga=None):
"""Get MGAEntropy scores from pre-computed scores in array.
Parameters
----------
mga_vec : np.array
numpy vector containing MGA Entropy conservation scores for residues
codon_pos: list of ... | 9761bb4c8174e16916bfbb37bf715ad4cc85ec14 | 324,731 |
def feature_value_match_dict_from_column_names(column_names,
prefix=None, suffix=None,
col_name_to_feature_vals_delimiter='_match_for_____',
feature_vals_delimiter='_'):
"""G... | 72de4e16f2854a90f12b06b1f7a29d844ad7b265 | 88,584 |
import calendar
def tuple_to_secs(tuple):
""" Convert time tuple to UTC seconds. """
return calendar.timegm(tuple) | 4a55f6927d4b8f6b36c6d4a4aca33abf9b4c019d | 132,144 |
def read(path):
"""Read the file as one giant string."""
with open(path, "r", encoding="utf-8") as in_file:
return in_file.read() | 5538aaced99bc68c6b0c31b7e9a80f2adeb58a8c | 496,428 |
import time
def time_it(func):
"""
Run a function and return the time it took to execute in seconds.
"""
def timed_func(*args, **kwargs):
start_time = time.time()
func(*args, **kwargs)
end_time = time.time()
return end_time - start_time
timed_func.__name__ = func.__... | a25f6798ea0f40cd795036c2ef42f40f7b0be691 | 158,740 |
import base64
def base64_to_int(b: str) -> int:
""" Returns a int from a base64 string """
return int.from_bytes(base64.b64decode(b), 'big') | 1021d5f5bcff85ae1a0b6943f08b656eb54d7c48 | 322,868 |
def safedel_message(key):
"""
Create safe deletion log message.
:param hashable key: unmapped key for which deletion/removal was tried
:return str: message to log unmapped key deletion attempt.
"""
return "No key {} to delete".format(key) | 4bbc5b6a5a2bdeef1cfc535aa16fe1256f93fc17 | 249,749 |
import codecs
def load_data(train_file):
"""
Return list of dataset given train_file and gs_file
Value: [(sa:str, sb:str, score:float)]
"""
with codecs.open(train_file, 'r', encoding='utf8') as f:
data = []
for idx, line in enumerate(f):
line = line.strip().split('\t')
... | 218077e06a0850460404ed92ac4dbb6229225f3b | 162,952 |
from time import sleep
def test_re_auth(relay, mini_sentry):
"""
Tests that managed non-processing relays re-authenticate periodically.
"""
relay_options = {"http": {"auth_interval": 1}}
# count the number of times relay registers
original_check_challenge = mini_sentry.app.view_functions["ch... | 415084bd47ba59f370362abc3a7a07be9bd74e49 | 515,292 |
def anisotropy_from_intensity(Ipar, Iper):
"""
Calculate anisotropy from crossed intensities values.
"""
return (Ipar - Iper)/(Ipar + 2*Iper) | 6e9d2c211394193e0b9d00e79af523f91e9bd6f9 | 474,451 |
def fstarBen(mh, m1, f0, beta, gamma):
"""
Stellar mass to halo mass ratio as a function of halo mass.
Fitting function from Moster et al.
"""
mstar = 2.0 * f0 * 10.0 ** mh / ((10.0 ** mh / 10.0 ** m1) ** (-beta) + (10.0 ** mh / 10.0 ** m1) ** gamma)
fstar = mstar / 10.0 ** mh
return fstar | e54bb55468ce78c53ba380b08ad99ed61424c306 | 549,430 |
def clean(data, parameters):
"""
Cleans a dictionary to only includ valid parameters and non empty values.
"""
# Only take valid parameters.
data = {key: data.get(key) for key in parameters}
# Remove empty parameters.
data = {key: value for key, value in data.items() if value is not None}
... | c421f3df0220764af81c0226d8b9430063d141e3 | 326,544 |
def get_func_name(func_str):
"""
Get function name, ie removes possible return type
"""
name = func_str.split(' ')[-1]
return name | 50b88f2d575aa0d6a8067db21cc674b1d60bed00 | 379,173 |
def limit_string_length(string, max_len=50):
"""Limit the length of input string.
Args:
string: Input string.
max_len: (int or None) If int, the length limit. If None, no limit.
Returns:
Possibly length-limited string.
"""
if max_len is None or len(string) <= max_len:
return string
else:
... | bd7a96ac6e0da2f4f042c4034e92925272e3c861 | 353,800 |
def sum_book_score(book_idx_list, book_score_list):
"""
Helper function to get sum of book scores
Args:
book_idx_list: List of Book Index
, book_score_list: List of Book Scores
Returns:
sum of book scores
"""
return sum(book_score_list[book_idx] for book_idx in book... | 0bbae7a7b7c885e83f2bb60dd5aebc2d8e88ef5b | 193,985 |
def interpolateLinear(
y1, #
y2, #
x # weighting [0..1]. 0 would be 100 % y1, 1 would be 100 % y2
):
"""
simple linear interpolation between two variables
@param y1
@param y2
@param x weighting [0..1]: 0 would be 100 % y1, 1 would be 100 % y2
@return the interpolated value
"""
return y1 * (1.0 - x) + y... | d2193b8fe313ccc61853407fa75169ca4bf5771f | 246,571 |
def client_superuser(client, admin):
"""Provides a client with a logged in superuser. """
client.force_login(admin)
return client | 2433b52f5e9dbaedf73195d77e9015be158a262e | 72,387 |
def cfg_val_or_none(cfg, key):
"""Look up key in the 'cfg' dictionary. If not found, returns None."""
return cfg[key] if key in cfg else None | b5b59fe5aa29ac4974b5a3dd5bee901d4d019d70 | 364,322 |
import re
def change_to_count_endpoint(endpoint):
"""Utility function to change a normal endpoint to a ``count`` api
endpoint. Returns the same endpoint if it's already a valid count endpoint.
Args:
endpoint (str): your api endpoint
Returns:
str: the modified endpoint for a count endp... | 19d5931449cd8a1c5e2fd1f864a55c47c392645f | 462,936 |
def execute_commands_on_linux_instances(client, commands, instance_ids):
"""Runs commands on remote linux instances
:param client: a boto/boto3 ssm client
:param commands: a list of strings, each one a command to execute on the instances
:param instance_ids: a list of instance_id strings, of the instanc... | d6938ef7f7ec16d0cb4554f7efdd82ab381ba20f | 416,094 |
def simplify_keys(mapping: dict[str, str]) -> dict[str, str]:
"""
Simplify/deduplicate dict keys, to reduce variations in similarly-named keys
Example::
>>> simplify_keys({'my_namepace:Super_Order': 'Panorpida'})
{'superfamily': 'Panorpida'}
Returns:
dict with simplified/dedupl... | 5de6cea495d7ab7abf19c4e2487cb53813ef48b8 | 485,884 |
def _covcalc(a, b, wc):
"""
Calculates the covariance from a * b^t
:param a: The `a` matrix
:type a: torch.Tensor
:param b: The `b` matrix
:type b: torch.Tensor
:return: The covariance
:rtype: torch.Tensor
"""
cov = a.unsqueeze(-1) * b.unsqueeze(-2)
return (wc[:, None, None]... | 76d6c2d2c368135557478a9afee43183d8840052 | 141,176 |
def is_power_of_two(n):
"""Check whether `n` is an exponent of two
>>> is_power_of_two(0)
False
>>> is_power_of_two(1)
True
>>> is_power_of_two(2)
True
>>> is_power_of_two(3)
False
>>> if_power_of_two(16)
True
"""
return n != 0 and ((n & (n - 1)) == 0) | b5fdbabb959f224018b57c2244bbfe93780ece1c | 643,762 |
def _read_file(fname):
"""
Args:
fname (str): Name of the grammar file to be parsed
Return:
list: The grammar rules
"""
with open(fname) as input_file:
re_grammar = [x.strip('\n') for x in input_file.readlines()]
return re_grammar | 9e6fba0bf76f3170a3d26a73ba6bac3c9c8c34be | 672,566 |
def read_single_param_file(src, typename=int):
"""Read a file with one value
This function can be used to read files in Kaldi which
has parameter values stored in them. E.g. egs/info/num_archives.
Pass the typename in advance to return the value without errors.
Args:
src: the path to file ... | 0b5d4b210f0032e25ea16fe79278a0fe27fb63ad | 235,546 |
import re
def parsePlasClass(filename):
""" Parse the file into lists of edge names, lengths, and PlasClass scores
"""
with open(filename) as f:
names = []
lengths = []
scores = []
name = ''
for line in f:
splt = line.strip().split('\t')
ed... | 0481c203c03b87c2fd2a69d29f7cafabc876389e | 598,035 |
def find(label, equiv):
"""
Finds the root label in equivalence classes of labels
Parameters:
label -> int
Value of a labelled pixel, to traverse for finding the root label
equiv -> dict
Contains equivalence classes for each label
Return:
minVal -> int
The root label
"""
minVal = min(equiv... | 48199c10487c0867499e743e6ffbf04c6b9312a0 | 504,491 |
import torch
def calc_regression_acc(predictions, targets, thld=None):
"""Calculate accuracy when treating regression as binary classification.
Args:
predictions (torch.Tensor): The predicted mean. A mean greater than zero
will be considered a postive prediction.
targets (torch.Te... | ffd4df24d1dbcc69176ad46f2d198460de3fc222 | 396,997 |
import heapq
def heapmerge(*inputs):
"""Like heapq.merge(), merges multiple sorted inputs (any iterables) into a single sorted output, but provides more convenient API:
each input is a pair of (iterable, label) and each yielded result is a pair of (item, label of the input) - so that it's known what input a g... | 580ec9f2f0793f8907390f5c7f8eebf4ac539b59 | 701,533 |
def parse_port(arg):
"""Parse port argument and raise ValueError if invalid"""
if not arg:
return None
arg = int(arg)
if arg < 1 or arg > 65535:
raise ValueError("invalid port value!")
return arg | 5c746f858c0d2ddf78cc6b0069e765132de20469 | 301,324 |
import typing
def parse_xlsx(worksheet) -> typing.List[typing.List]:
"""Parse the Excel xlsx file at the provided path.
Args:
worksheet: An openpyxl worksheet ready to parse
Returns: List of values ready to write.
"""
# Convert the sheet to a list of lists
row_list = []
for r in ... | ef7494a0720a21fdfc99e378132f811effed0e51 | 97,923 |
def _prepare_pylint_args(args):
"""
Filter and extend Pylint command line arguments.
--output-format=parsable is required for us to parse the output.
:param args: list of Pylint arguments.
:returns extended list of Pylint arguments.
"""
# Drop an already specified output format, as we nee... | 0b25072e4b203ccd3a320d7d60178d6d51a456b9 | 114,965 |
import random
def create_neg_relations(entities, rels_between_entities, rel_type_count, neg_rel_count):
""" Creates negative relation samples, i.e. pairs of entities that are unrelated according to ground truth """
neg_unrelated = []
# search unrelated entity pairs
for i1, _ in enumerate(entities):
... | 4a8897b3055cf74106852b64944bb76c67674f71 | 650,678 |
from typing import Any
def sanitize_path(x: Any) -> str:
"""Converts `x` to string and replaces any occurrence of "/" with "_"."""
return str(x).replace("/", "_") | a162ffd127451e8e1cb4b6b937b1ea61a1373932 | 393,482 |
def read_file(path, file):
"""
reading .txt file and return its content as string
:param path: path to file
:param file: file (.txt)
:return: file_content as string
"""
file_name = str(path) + str(file)
with open(file_name + '.txt', 'r') as myfile:
file_content = myfile.read()
... | 374aa549c808d0e50fa42d133b9115eeca07ee91 | 265,652 |
def parse_vertices(vertices_str):
"""
Parse vertices stored as a string.
:param vertices: "x1,y1,x2,y2,...,xn,yn"
:param return: [(x1,y1), (x1, y2), ... (xn, yn)]
"""
s = [float(t) for t in vertices_str.split(',')]
return zip(s[::2], s[1::2]) | 58be48099272a9f9d5251666a0670a0c2b7e1f16 | 283,082 |
import math
def polysum(n, s):
"""
n: Number of sides
s: Length of each side
returns: sum of the area and square of the perimeter of the regular polygon
"""
area = (0.25*n*s*s)/math.tan(math.pi/n)
perimeter = n*s
sum = area + perimeter**2
return round(sum,4) | d2e7be6f8f02c7b5d481a08fed7f35aa8aa1c411 | 624,464 |
def split_all(s, chars):
"""Split on multiple character values.
>>> split_all('a_b_c_d', '_. ')
['a', 'b', 'c', 'd']
>>> split_all('a b c d', '_. ')
['a', 'b', 'c', 'd']
>>> split_all('a.b.c.d', '_. ')
['a', 'b', 'c', 'd']
>>> split_all('a_b.c d', '_. ')
['a', 'b', 'c', 'd']
>>>... | 76cd3d5823dec479984ddd570b4162ab11bffec1 | 594,624 |
def check_power_of_2(number: int) -> bool:
"""Checks if given argument represents power of 2.
Args:
number: is checked for power of 2.
Returns:
If number represents power of 2 - True, owervise False.
"""
return (number != 0) and ((number & (number - 1)) == 0) | a26de28dd170eed97fc73b48ae22f6309656ea1c | 398,764 |
def child_or_children(value):
""" Return num followed by 'child' or 'children' as appropriate """
try:
value = int(value)
except ValueError:
return ''
if value == 1:
return '1 child'
return '%d children' | a22be46a3fd1086dac116c187189204b5ea1a6db | 30,864 |
def _is_file_relevant(file_name: str, problem_name: str, graph_type: str, p_depth: int):
"""Check if a filename provided matches the description of a problem instance."""
return problem_name in file_name and "p=" + str(p_depth) in file_name and graph_type in file_name | 3cd9072c1b1be92392511e4a7952e4bb453f4206 | 384,037 |
def is_changed(local: dict, remote: dict) -> bool:
""" Determine if a locally defined monitor has changed from a remote version
Excludes silenced config from the check if the monitor may be muted to avoid unmuting any monitors accidentally
:param local: A dictionary representing the locally defined monitor
... | a7b0a08bf6b60fd520c2535bd8a3cfc96420a44c | 248,011 |
import re
def strip_interface_speed(speed):
"""Converts symbol interface speeds to a more common notation. Example: 'speed10gig' -> '10g'"""
if isinstance(speed, list):
result = [re.match(r"speed[0-9]{1,3}[gm]", sp) for sp in speed]
result = [sp.group().replace("speed", "") if result else "unk... | 1662ba127e37af207715d9fc5a9bdec924c0b781 | 305,370 |
import unicodedata
def remove_non_ascii_chars(s):
"""
Removes non-ascii characters from specified (unicode) string.
Basically following examples from http://bit.ly/2umENUv and
http://bit.ly/2sFScdQ.
"""
# latin-1 characters that don't have a unicode decomposition
CHAR_REPLACE = {
0... | 12a469ee95853817d8f1addcd3fedfeb43a4c0cc | 550,767 |
def _unwrap_response(resp):
"""Get the actual result from an IAM API response."""
for resp_key, resp_data in resp.items():
if resp_key.endswith('_response'):
for result_key, result in resp_data.items():
if result_key.endswith('_result'):
return result
... | 3902c3f9f78d256e697fe2a3ffa3de9a89f980be | 106,503 |
def strip_suffix(s, suffix):
"""Remove suffix frm the end of s
is s = "aaa.gpg" and suffix = ".gpg", return "aaa"
if s is not a string return None
if suffix is not a string, return s
:param str s: string to modify
:param str suffix: suffix to remove
:rtype: Optional[str]=None
"""
i... | 8ca0579d68bcb22c7c139583122ab281f79ce9f8 | 554,890 |
def count_files_dir(path):
"""count number of files recursivly in path."""
# IN pathlib path
num_f_dest = 0
for f in path.glob("**/*"):
if f.is_file():
num_f_dest += 1
return num_f_dest | 88da56f91c6afb8d87390e0da4d644991273cb09 | 125,106 |
def mass_to_richness(mass, norm=2.7e13, slope=1.4):
"""Calculate richness from mass.
Mass-richness relation assumed is:
mass = norm * (richness / 20) ^ slope.
Parameters
----------
mass : ndarray or float
Cluster mass value(s) in units of solar masses.
norm : float, optional
... | f048fc823db8df4d8b5e448a80a6244bcb5fab31 | 192,859 |
def store_by_id(obj_list):
"""returns a dict where the objects are stored by their object id"""
result_dict = {}
for obj in obj_list:
obj_id = obj.get('_source', {}).get('id', False)
if obj_id:
result_dict[obj_id] = obj
return result_dict | 26da665a2255a1002c8cb6eb90d933d066d96724 | 539,018 |
def convert_string_to_list(_string, separator=','):
"""
splits the string with give separator and remove whitespaces
"""
return [x.strip() for x in _string.split(separator)] | 47aa94e2678ab179310220a6c1e97b3fcd013b0a | 329,290 |
import requests
def do_gossip(known_nodes):
"""
The gossip algorithm - pull.
All the known nodes are checked for collecting the available chains.
:return: True if our chain was replaced, False if not
"""
collected_chains = []
# Pull: Collect the blockchains from the neighbours
for nod... | f543db7dba5ae7b6ef6f762ebc277310ad9a1f83 | 407,040 |
import math
def add_radians(a, b):
"""Adds two radian angles, and adjusts sign +/- to be closest to 0
Parameters:
:param float a: Angle a
:param float b: Angle b
Returns: The resulting angle in radians, with sign adjusted
:rtype: float
"""
return (a + b + math.pi) % (2 * ma... | 43f33ba646899e2431fee4967335b8a724cad194 | 46,289 |
def labels_to_onehot(labels, classes):
""" Convert a list of labels (integers) into one-hot format.
Parameters
----------
labels : list
A list of integer labels, counting from 0.
classes : int
Number of class integers.
Returns
-------
list
List of one-hot lists... | 886f7ccc954ffb86cc97db131b5108484ec40fa3 | 593,208 |
def contains_entry(entry_list, entry):
"""
Function for filtering duplicate entries in a list.
Args:
entry_list (list): List of Pymatgen ComputedEntry objects.
entry (ComputedEntry): the Pymatgen ComputedEntry object of
interest.
Returns:
bool
"""
for ent in... | 8e716b6549988a23f6ba38edae405b7cf717ed27 | 133,936 |
def draw_frame(surface, rect, color_fill, color_border, border=1):
"""
Creates and draws a rect with a frame. Returns the inside rect object.
returns a pygame.Rect() object, which is the filled area inside the frame
- surface: the pygame surface to draw this on
- rect: pygame.Rect() object for the o... | 2b37a96beb6d1c4d0aa184e677f6c8528b90193e | 641,806 |
def parse_response(response):
"""
:param response: output of boto3 rds client describe_db_instances
:return: an array, each element is an 3-element array with DBInstanceIdentifier, Engine, and Endpoint Address
Example:
[
['devdb-ldn-test1', 'mysql', 'devdb-ldn-test.cjjimtutptto.eu-we... | edaa4abbb695adb06c43dc93d70178bc10a82445 | 701,633 |
def ordinal(num : int) -> str:
"""
Return the ordinal of a number
For example, 1 -> 1st , 13 -> 13th , 22 -> 22rd
"""
remainder = num % 100
if remainder in (11, 12, 13):
return str(num) + "th"
else:
suffixes = ["th", "st", "nd", "rd", "th", "th", "th", "th", "th", "th"]
... | 59540556844ca7e9eaa9da134edd5ca6de08910b | 354,263 |
import csv
import re
def lookup_county(county_code, office_code):
""" Maps county numbers from a docket number (41, 20, etc.) to county
names.
The MDJ Docket search requires a user to select the name of the county
to search. We can get the name of the county from a Docket Number, but it
is not s... | 45ac7b4bb351da113beed57336300be40588d461 | 232,813 |
def get_word_times(word, sen):
"""
统计word在sen出现的次数
:param word: 要统计的单词,是一个字符串
:param sen: 句子, 是一个字符串列表
:return: 返回该单词在句子中出现的次数
"""
times = 0
for i in sen:
if word == i:
times += 1
return times | 239e1a86f9f397aeb2a9bf750ce236a121416346 | 300,379 |
def template_class(this_object):
"""Dump the object's class."""
cls = this_object.__class__
return '<code>%s</code>' % str(cls) | fe54a334d20cc1811f51c8768e08ebb54b61db4b | 104,842 |
def replace_multiple(string, replacements={}):
"""Replaces multiple strings inside a string.
Args:
string (str): String to replace.
replacements (dict): Custom replacements for the string.
Examples:
>>> print(replace_multiple('Replace this ".',
... r... | 9e182971669ef3cfb66bcc84379bae04965981a2 | 346,374 |
def tochar(v):
"""Check and convert value to a character"""
if isinstance(v, str) and len(v) == 1:
return v
else:
raise ValueError('Expected a character, but found %s' % v) | e406db33807ca0f25e5b348924226b58fcf04da3 | 659,945 |
def to_f(c):
"""Convert Celsius to Fahrenheit"""
return round(c * 9 / 5.0 + 32, 1) | 1bc2e1c8f3641e8d6d24caf61c54ec69a490525e | 360,267 |
def secret_test_function(context, secrets: list = []):
"""Validate that given secrets exists
:param context: the MLRun context
:param secrets: name of the secrets that we want to look at
"""
context.logger.info("running function")
for sec_name in secrets:
sec_value = context.get_secret(... | c4a32a89ce35ee994688bfeca9d06deb69d1d81a | 182,369 |
def extract_roles(x, roles):
"""
x is [N, B, R, *shape]
roles is [N, B]
output is [N, B, *shape]
"""
N, B, R, *shape = x.shape
assert roles.shape == (N, B)
return (x.reshape(N*B, R, *shape)[range(N*B), roles.reshape(N*B)]).reshape(N, B, *shape) | bfa71ca85245fdaa3a16acb68ea8038d21ee580f | 274,211 |
def retrieve_hidden_word(full_word, found_letter):
"""This function returns a hidden word.
The hidden letters are marked with an asterisk *."""
hidden_word = ""
for letter in full_word:
if letter in found_letter:
hidden_word += letter
else:
hidden_word += "*"
... | 6eb142fe1e04dfd2d53785e21117bc70f773e898 | 619,944 |
def is_finish(lst: list) -> bool:
"""
To be used with the filter function, keep only the bouts that
did NOT go the distance in a 3 or 5 round bout.
NB: This will also get rid of doctor stoppages between rounds.
"""
if (
(lst[2] == "3" and lst[3] == "5:00") or
(lst[2] == "5" and l... | 8182515499f7a262853c70b9265a7154183607e1 | 451,236 |
def max_element(l):
"""
Returns the maximum element of a given list of numbers.
"""
max_ = None
for x in l:
if max_ is None or x > max_:
max_ = x
return max_ | 1596f33f0bb91839fbcaf2613892bf90fafd6afd | 697,432 |
def script_path(script, test_name=__name__):
"""Returns a fully qualified module path based on test_name."""
return '{test_path}.{script}'.format(test_path=test_name, script=script) | 23ddb5e11ddaa1f85cc571442b0cda74c412cbe5 | 226,183 |
import base64
def b64str_to_img_file(src, saveto, urlsafe=False):
"""
Re-generate image file from any Base64 string generated by img_to_base64_str(), and save it to disk.
:param src: The string you want to decode.
:param saveto: Specify the path of generated file to save to.
:param urlsafe: Trigge... | b97168a46c5f111e3b0c8d33b647aab538176151 | 531,932 |
from datetime import datetime
def get_latest_year() -> int:
"""
Returns the last year if we are not in december yet otherwise
returns the current year.
"""
today = datetime.now()
if today.month < 12:
return today.year - 1
return today.year | 6cd7b36948de39546659bb4a56e113e7e365b68b | 124,055 |
def clip(val, min_val, max_val):
""" Clip value in between specified values. """
if val > max_val:
return max_val
if val < min_val:
return min_val
return val | 86c6d34c4f407cd0d0c8b2778546510c0083dbb7 | 222,725 |
def zaction(op, inv):
"""
Return a function
f: (G, Z) -> G
g, n |-> g op g op ... (n-1 times) ... op g
If n is zero, it returns identity element. If n is negative, it
returns |n|-1 times op on the inverse of g.
"""
def f(g, n):
result = op(g, inv(g)) # identity
... | a75f061221ce28b03f3bcc4ddbbc6985f20339b2 | 29,376 |
import requests
import time
def check_id_permitted(identifier: str, retries: int = 5) -> bool:
"""Check a user provided identifier is permitted
This ID is expected to be a valid URL
Parameters
----------
identifier : str
identifier URL candidate
Returns
-------
bool
... | bece0a3d2e8717ac05aabd809969bedd9ba4ecbc | 205,524 |
import re
def parse_chromosome(s):
"""
Parse and normalize a chromosome string, which may be prefixed with 'chr'.
"""
match = re.fullmatch(r'(?:chr)?([1-9]|1\d|2[0-2]|x|y|xy|mt?)', s, re.IGNORECASE)
if not match:
raise ValueError(f'Failed to match chromosome against {s}')
return matc... | 9b072b204a2da120e2fae9d2fe7c36e15ca858dc | 139,225 |
from pathlib import Path
def strip_extension(path):
"""Function to strip file extension
Parameters
----------
path : string
Absoluate path to a slide
Returns
-------
path : string
Path to a file without file extension
"""
p = Path(path)
return str(p.with_suffi... | b05adb2a37b65e027504f3c85c9c44161f21d126 | 580,415 |
def isNan(x):
"""check for nan by equating x to itself"""
return not x == x | f01ec6a5a5d04113d9c7c1630131802e412ade77 | 603,333 |
def get_note_type(syllables, song_db) -> list:
"""
Function to determine the category of the syllable
Parameters
----------
syllables : str
song_db : db
Returns
-------
type_str : list
"""
type_str = []
for syllable in syllables:
if syllable in song_db.motif:
... | 621448603581a56af22ec9c559f9854c62073318 | 698,749 |
def add_outputs_from_dict(
api_current_dict: dict,
fields_to_keep: list
) -> dict:
"""
Filters a dict and keeps only the keys that appears in the given list
:param api_current_dict: the origin dict
:param fields_to_keep: the list which contains the wanted keys
:return: a dict based o... | bfe251de9a8f2634b7777b1e2a89e6071b213ce1 | 599,786 |
import textwrap
def strip_comment_marker(text):
""" Strip # markers at the front of a block of comment text.
"""
lines = []
for line in text.splitlines():
lines.append(line.lstrip('#'))
text = textwrap.dedent('\n'.join(lines))
return text | 2c14db3bd25d19f1cdaad8aeab8d847974bf3213 | 222,378 |
def white_space(keyword):
"""``white-space`` property validation."""
return keyword in ('normal', 'pre', 'nowrap', 'pre-wrap', 'pre-line') | 5e05ce4bb616d7046548c7a548ca8cb47859b19b | 219,960 |
import asyncio
def create_checked_task(coro_or_future):
"""
Wrapper for `asyncio.ensure_future` that always propagates exceptions.
"""
def raise_any_exc(task):
return task.result()
task = asyncio.ensure_future(coro_or_future)
task.add_done_callback(raise_any_exc)
return task | f1c0df2858bacf679ff07de28463b677d33d40bd | 625,361 |
def remove_last_range(some_list):
"""
Returns a given list with its last range removed.
list -> list
"""
return some_list[:-1] | ea2063c901d3aaf67caad97f1760f6fb6afb31c1 | 9,228 |
import time
def datetime2ts(dt):
""" Convert a `datetime` object to unix timestamp (seconds since epoch).
"""
return int(time.mktime(dt.timetuple())) | 289c11c47d4cb0e9a6ea620fa5b40f81e4c5644d | 633,618 |
def _format_return_message(results):
"""
Formats and eliminates redundant return messages from a failed geocoding result.
:param results: the returned dictionary from Geoclient API of a failed geocode.
:return: Formatted Geoclient return messages
"""
out_message = None
if 'message' in resul... | a02f2277378b1c5b5f12ae2a00bb229d514860da | 280,261 |
def compose(*fs):
"""
Functional compositions of one or more functions. Eg. compose(f1, f2, f3, f4).
The innermost function:
- may take arbitrary (including zero) positional arguments.
- should produce one output value
The remaining functions (if there are more than one argument to compose):... | 5e950e920a740ef79f86f782abefa55a88a8258b | 336,829 |
def absolute_limits(nova_client):
"""Return the absolute limits as a dictionary."""
limits = nova_client.limits.get()
return dict([(limit.name, limit.value) for limit in list(limits.absolute)]) | ab9f17650c32e951d323ad7cd36b3c4c152de06e | 529,978 |
def snake_to_camel(name):
"""convert a snake-cased string to camel-cased"""
return name[0].lower() + "".join(
"_" + ch.lower() if ch.isupper() else ch
for ch in name[1:]) | e528d448e46e3a493a586b45cde1ce198ab3e000 | 613,667 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.