content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
from typing import List
import itertools
def get_config_combination_list(settings, default=None) -> List:
"""
Given a list of hyperparameters return all combinations of that.
"""
keys = list(settings)
r = []
for values in itertools.product(*map(settings.get, keys)):
d = dict(zip(keys, ... | b291de2a711d819b570ef285cd6633a558d4855e | 589,647 |
import torch
def kl_divergence_bern_bern(z_pres_logits, prior_pres_prob, eps=1e-15):
"""
Compute kl divergence of two Bernoulli distributions
:param z_pres_logits: (B, ...)
:param prior_pres_prob: float
:return: kl divergence, (B, ...)
"""
z_pres_probs = torch.sigmoid(z_pres_logits)
kl... | 233639d2cee592e1b4a44878ad754e718a8c0fe0 | 589,650 |
def write_pos_numpy(pos, fn):
"""
Write the data to a .pos file (binary file type). See the
``read_pos_numpy'' function for more information on the .pos file format.
Parameters
----------
pos : Numpy array
The data to write
fn : str
The filename to which to write
Retur... | bd3e6383f24fde7d682e7d47136554fc8adb2435 | 589,652 |
def query_mission(id):
"""
Build the Query for a single mission
"""
query = f'''
{{
mission(id:"{id}") {{
id
name
manufacturers
description
website
}}
}}
'''
return query | 60d0fdf2bbea4307b901e6b2f3917a5dda7aa7a4 | 589,654 |
def triple_step_iterative(nb_of_steps):
"""
The most naive implementation, using 3 variables corresponding
to the 3 previous states, we calculate the next and update them
continuously until we've looped up to nb_of_steps.
"""
a, b, c = 0, 0, 1
for step in range(nb_of_steps):
temp_var... | 8a3d094c09d814bb37f90f9c85a2c2e8c6ac2c64 | 589,656 |
def length(iterable):
"""
Return number of elements in iterable. Consumes iterable!
>>> length(range(10))
10
:param iterable iterable: Any iterable, e.g. list, range, ...
:return: Length of iterable.
:rtype: int
"""
return sum(1 for _ in iterable) | 4c427353d42e578ce96cc7f57751d0cd5582e954 | 589,657 |
import random
import string
def random_string(length: int = 10) -> str:
"""Returns a random string of lowercase letters and digits with a given length.
Args:
length: output length
Returns:
a random string with length being `length`
"""
return "".join(
[random.choice(strin... | 6c76818b1d5500639ccfc1bc24da775dacf9be23 | 589,658 |
from typing import List
from typing import Union
def replace_many(
value: str,
substrings_to_replace: List[str],
replacement_substrings: Union[List[str], str]
) -> str:
"""
Function replace many substring at once.
Args:
value: String in which we want to replace the substri... | a6f9610ebd043cc1e292ee28a5c8adccda0de448 | 589,661 |
def find_linestarts(codeobj):
"""Finds the offsets in a bytecode which are the start a line in the source code.
Parameters
=========================================
codeobj (code): code object
Returns
=========================================
dict: a dictionary with offsets as the keys and ... | c39dda5b9e59e6550dc98bd0a9362bca9e24d9b1 | 589,668 |
def _standard_uuid(short: int) -> str:
"""Gets a 128-bit UUID from a ``short`` UUID.
Args:
short: a 16-bit or 32-bit UUID.
Returns:
A 128-bit UUID as a string.
"""
return f"{short:08x}-0000-1000-8000-00805f9b34fb" | b0282903c53e252c1aaf4fe3bc7ac0c91645cf07 | 589,669 |
from textwrap import dedent
def default_myst_include(root_file: str) -> str:
"""Return string which is a MyST include directive pointing to `root_file`,
located under `..` relative to `docs`. See:
https://myst-parser.readthedocs.io/en/latest/sphinx/use.html#howto-include-readme
"""
template_includ... | 0ea0347674620a5d3128660072fe442c52f3f6ce | 589,674 |
def snake_case(text):
"""Normalize text to snake_case"""
return text.strip().replace("-", "_").replace(" ", "_").lower() | 02814712881c3c0b4ee7d941f4e3e53536d01806 | 589,678 |
def make_list_if_string(item):
"""Put `item` into a list."""
if isinstance(item, str):
return [item]
return item | 5475822f4abf677aca5e6d14aef3a6c60082aea0 | 589,679 |
from typing import List
def factorize(n: int) -> List[int]:
"""Prime factorization
Factorize integer `n` with time complexity O(sqrt(n))
Args:
n: Integer to factorize.
Returns:
List of prime factors of `n`.
"""
res: List[int] = []
for i in range(2, int(n ** 0.5) + 1):
... | 975a8f835fbc4bb3dc4ce6ad49fbd1898ef7b0c3 | 589,681 |
from typing import Iterable
from typing import Iterator
def iter_(iterable: Iterable) -> Iterator:
"""Returns appropriate iterator for the given iterable.
This is mainly created because python's ``iter``
returns an iterable of keys instead of keys and values for ``dict``.
>>> tuple(iter_({1: "a", 2: ... | 0017a0c068045c185e8cefda4c78890bf4d93982 | 589,685 |
import re
def toxicity_check(word_list,text):
"""
Check words that are profane
Parameters
----------
word_list: set
set of words in english dictionary
text : str
output string from function pre-processing
Returns
-------
set
list of words that are prof... | b8311e893266e2e390cfb438f0aafc7e41d2b88c | 589,691 |
def aminoacidSMILES(amino):
"""
Obtain the SMILES representation of a particular amino acid
Arguments:
amino -- One-letter code of the amino acid
Return:
smiles -- 1D Chemical representation of the amino acid
"""
# Dictionary with the SMILES per amino acid
aminoacids ... | d2c4104ca2ba1a48a52f0846c976a3879654de47 | 589,692 |
def transpose(lst):
""" Transposes a matrix. """
return list(map(list, zip(*lst))) | af1e5e3bdca5201c34d0bd6a355d67b4d4bf2515 | 589,693 |
def per_100_diff(v1: float, v2: float, n_digits: int = 2) -> float:
"""Computes the percentage difference between two values and rounds it to a number of digits.
Args:
v1 (float): One value.
v2 (float): Other value.
n_digits (int, optional): Number of digits to round the result. Default... | c3626e90e75cfe7b196c91e7ef2d1f2fd14e1f78 | 589,695 |
def _validate_compatabilities(compatabilities, *args, **kwargs):
"""
Given a list of compatability functions, run the checks
:param compatabilities: a list of compatability functions to call
:param args: any arguments to pass to compatability functions
:param kwargs: any arguments to pass to compa... | 9c5decbfd0f603933e1f78288946fd3de0063161 | 589,702 |
def add_star(value: str, pvalue: float, star: bool) -> str:
"""
Add 1, 2 or 3 stars to a string base on the p-value
Adds 1 star if the pvalue is less than 10%, 2 if less than 5% and 3 is
less than 1%.
Parameters
----------
value : str
The formatted parameter value as a string.
... | a6cfa490ab1ad39f7c64b7fc88ab80606ee8e0e1 | 589,709 |
def prettify_fingerprint(fingerprint):
"""
Returns the fingerprint in its common pretty form::
XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX
"""
if fingerprint is None:
return 'NO FINGERPRINT'
chunks = [fingerprint[i:i + 4] for i in range(0, 32, 4)]
return '%s %s' % (' '.jo... | 4571f3a9d48952526e0c18590e066b3495d0c04a | 589,710 |
from typing import Dict
def merge_dicts_strict(d1: Dict, d2: Dict) -> Dict:
"""Merge two dicts in a strict manner, i.e. the second dict overwrites keys
of the first dict but all keys in the second dict have to be present in
the first dict.
:param d1: base dict which will be overwritten
:param d2: ... | 8f4cc9a16fee1573aabf6353fb1e45dbc9dcd9ce | 589,711 |
def opts_dict(opts):
"""
Convert an user_options style list to a dictionnary indexed by the long
option name.
"""
return dict([(x[0], x) for x in opts]) | a232acac470c1523f2c259c2a2fa9f9aa846977f | 589,714 |
def _transform_old_style_comments(annotation):
"""
Transform an old-style, targetless "comment" into one with a target.
If this annotation has a URI, but no targets and no references, then it's
an "old-style" comment or "page note". Detect this for old clients and
rewrite the annotation target prop... | ea4f9838741f02f192604515b3d60fc578a3f9ff | 589,717 |
from datetime import datetime
def to_utc_date(date):
"""Convert a datetime object from local to UTC format
>>> import datetime
>>> d = datetime.datetime(2017, 8, 15, 18, 24, 31)
>>> to_utc_date(d)
datetime.datetime(2017, 8, 16, 1, 24, 31)
Args:
date (`datetime`): Input datetime objec... | 2547139ebfb64dc1bce50a18299a2290c92c471d | 589,719 |
def check_integer(initial_number_of_balls):
"""
This function checks if the user's initial input is an integer or not.
If not: return False
If it is: return True
:param initial_number_of_balls: this is the variable saving the user's input
:return: True if the user puts in an integer
False if... | c6f248b741d185bd24d60b8d8d5db4e3ac913f0d | 589,722 |
def _add_objects_loose_loop(container, data):
"""Add loose objects to a container, within a for loop.
:param container: a Container
:param data: a dictionary where the key is an arbitrary identifier, and the value is a byte string.
:return: a dictionary where the keys are the object hash keys as return... | 37a96030e7c8e9ab77b420451f7523159552b4ee | 589,723 |
def validate_type(value, type_, name=None):
"""Validates that value is of the specified type.
Args:
value: The value to validate.
type_: The requested type.
name: The name of the argument being validated. This is only used to format
error messages.
Returns:
A valid value of type `type_`.
... | 1aac562e9b6a059a814ef1b253def10afa9f01a2 | 589,725 |
def deleteSymbol(command, mySymbols):
""" Check if command is to delete stock symbol (d | delete [SYM/#]). """
expression = command.strip().lower()
words = expression.split()
return (len(mySymbols) > 0 and ("d " in expression or "delete " in expression) and (words[0] == "d" or words[0] == "delete") and ... | 6bf36e11c3cc69221c8996b65e49f90b4d1791a1 | 589,726 |
def out_tconv(spatial, config):
"""
Calculate spatial output shape after transpose convolution.
Arguments:
spatial (tensor): spatial dimensions.
config (dict): module parameters.
"""
p, k, s = [config[k]
for k in ['padding', 'kernel_size', 'stride']]
p2 = p if isins... | f5e331d83c1d213487faa0371793de54f9ec38ea | 589,735 |
def Get_mte_status(cur, status):
"""
Perform and execute mysql command (select by M&TE status), obtain the all response from DB
# result = cur.fetchall() # This method fetches all rows from the last executed statement
# result = cur.fetchone() # This method return the first row of the result
:param... | fbdc714702817d28fcad76e2cb36c1d7a2615b56 | 589,736 |
def get_samples(distribution, num_samples, seed=None):
"""Given a batched distribution, compute samples and reshape along batch.
That is, we have a distribution of shape (batch_size, ...), where each element
of the tensor is independent. We then draw num_samples from each component, to
give a tensor of shape:
... | ab8d3b48c3767907c6f8b47a4108f3d15b5d02a6 | 589,738 |
def get_update_args(delta: dict, data: dict) -> dict:
"""
Change the updated field names to fit the pull-request update command.
Args:
delta (dict): Updated fields from XSOAR incident mirroring.
data (dict): Incident source fields from XSOAR incident mirroring.
Returns:
dict: Up... | f70228728b8ab67407650d76fa14bed585dc7564 | 589,744 |
def load_metadata(filename):
""" Loads transcriptions from metadata csv. """
with open(filename, encoding='utf-8') as f:
filepaths_and_text = [line.strip().split("|")[:2] for line in f]
return dict(filepaths_and_text) | b6527d9aeaeb14f5b52b266ab3f456b24ada29bc | 589,749 |
def sigmoid_grad(f):
"""
Computes the gradient for the sigmoid function
"""
return f * (1.0 - f) | 370db0e088b96aa0fd984749b322b5c27a15333a | 589,753 |
def site_to_key(site, state=""):
"""Convert site to key. `state` is added to end of key."""
if type(state) != str:
raise Exception("`state` must be a string.")
return ",".join([str(l) for l in site]) + state | c7655c4193b2077c11ef1b7b83fac3bc7588c857 | 589,755 |
def add_all(seq):
"""Add all of the elements of seq."""
i = 0
s = 0
while i < len(seq):
s += seq[i]
i += 1
return s | 46cdb88893d1bae4a27fa31e9e3a6ae92b1bd0e3 | 589,756 |
def get_condition_label(condition_id: str) -> str:
"""Convert a condition ID to a label.
Labels for conditions are used at different locations (e.g. ensemble
prediction code, and visualization code). This method ensures that the same
condition is labeled identically everywhere.
Parameters
----... | c4f338b8c735538b3be88021e0c20b9433d51741 | 589,759 |
def is_stranded(G, q):
"""Returns True iff `q` is stranded in `G`.
A vertex `q` in `G` is :dfn:`stranded` if there is no
edge starting at `q` or if there is no edge ending at `q`.
Parameters
----------
G : graph
q : vertex in `G`
Examples
--------
>>> G = nx.MultiDiGraph()
... | 3fb771a796ce257d986f3864613f76e5390d1da7 | 589,764 |
def num_frames(df):
"""Total number of frames."""
return df.index.get_level_values(0).unique().shape[0] | 57ac211bf182c8ccfe4aca5af5a728ab7c9cd1dd | 589,765 |
import json
import requests
def fetch_file_from_web(server_url, path, transform_func=json.loads):
"""Fetch file from a web server
The default behavior is to transform the response to a json.
"""
artifact_url = "{0}/{1}".format(server_url, path)
r = requests.get(artifact_url)
r.raise_for_statu... | ed2fcdd64612bb59d98f3ae290b39e9ac6110dc2 | 589,771 |
import typing
def parse_tags(tags_string: str) -> typing.List[str]:
"""
Parse the `Tags` section and get a list of tags.
:param tags_string: A string containing all tags, with comma as delimiter.
:return: A sorted list of stripped tags.
"""
tags = tags_string.split(',')
if not tags:
... | f7cb845152ad935b5be28822aa1d3a9acad6548e | 589,772 |
import hashlib
def sha256_bytes(data):
"""Computes sha256sum."""
hasher = hashlib.sha256()
hasher.update(data)
return hasher.hexdigest() | ee74361adec7277f7c872ab1622f85eb816d51a4 | 589,775 |
def issubtype(tcon1, tcon2):
"""
Check whether tcon1 <: tcon2
"""
return tcon2 in tcon1.supertypes | ae72afab2cd77028ac61392c45a871b8c4c6a4e6 | 589,776 |
import re
def remove_links(tweet):
"""Takes a string and removes web links from it"""
tweet = re.sub(r'http\S+', '', tweet) # remove http links
tweet = re.sub(r'bit.ly/\S+', '', tweet) # remove bitly links
tweet = tweet.strip('[link]') # remove [links]
tweet = re.sub(r'pic.twitter\S+','', twe... | 6555ad849b72863bdedc523c171356329585d86b | 589,779 |
def find_layer(arch, target_layer_name):
"""Find target layer to calculate CAM.
: Args:
- **arch - **: Self-defined architecture.
- **target_layer_name - ** (str): Name of target class.
: Return:
- **target_layer - **: Found layer. This layer will be hooked to g... | 29724c0c16983b534d6e578c9fadef819fb51b43 | 589,780 |
import copy
def _get_value(item, key):
"""Grabs a nested value within a dict
:param dict item: the dictionary
:param str key: the nested key to find
:returns: the value if found, otherwise None
"""
keys = key.split('.', 1)
if isinstance(item, dict):
if len(keys) == 2:
... | 7bf312a8f5ce0782c29ddc704951abf52f58ab35 | 589,781 |
import struct
def read_plain_double(fo):
"""Reads a 64-bit float (double) using the plain encoding"""
tup = struct.unpack("<d", fo.read(8))
return tup[0] | 63a385351608befca96f0861a68afc023f944fc4 | 589,782 |
def search_list(in_list, item):
"""Search for property in the input data
Parameters
----------
in_list : list
list of all the available properties
item : str
name of the property to search
Returns
-------
list
list of index of the searched property
"""
r... | 71a50ea5c7a3835b8e0b3d949596f3488bbb33fb | 589,785 |
def test_function_docs(arg):
"""
A function to test docs.
:param arg: An argument.
:return: A return value.
"""
return f"test_function_docs: {arg}" | 26fb8c907a308e50dd41c0421abe8718c01132f2 | 589,786 |
def add_old_flag(df):
"""
Mark all mechanisms which were originally evaluated in StatDP [1].
[1] Ding, Zeyu, Yuxin Wang, Guanhong Wang, Danfeng Zhang, and Daniel Kifer.
"Detecting Violations of Differential Privacy." In Proceedings of the 2018
ACM SIGSAC Conference on Computer and Communica... | 65170264e46d917aeb69d331054e7bdc23f3f774 | 589,787 |
import types
def _bind(method, instance):
"""Bind a method to an instance.
For details, see https://stackoverflow.com/a/37455782.
Args:
method (function): Method to be bound. Must accept ``self`` as first argument.
instance (SomeClass): An instantiated class.
Returns:
Method... | a961d7aff1f3ca6163842038d4098a29fd6ae0f0 | 589,788 |
def parse_route_name_and_version(route_repr):
"""
Parse a route representation string and return the route name and version number.
:param route_repr: Route representation string.
:return: A tuple containing route name and version number.
"""
if ':' in route_repr:
route_name, version =... | f2c7db91efd086a8910acc4ecda4bbd3b9578531 | 589,790 |
def make_mount_string(mount, project):
"""
Return mount and project string used to specify storages
"""
return "{mount}/{project}".format(mount=mount, project=project) | eaee7260ea040acf497e60607637c5963e373561 | 589,791 |
def conditional(data, c1, c2, out=None):
"""
Create a conditional probability table with counts
data
dataframe
c1
condition as string
c2
list of conditions as strings
out
output format. If None, counts are returned.
If a function is passed, it is applied t... | 3ce763a5d95f618ed656c1fc74467706e5600e22 | 589,798 |
def _nzt(bt, zt, bt1, bt2):
"""Evaluate appropriate z-location for countersunk hole."""
if (bt - 0.5) < zt <= 0.5:
zt1 = bt1 - 0.5 + (zt - bt + 0.5) * (1.0 - bt1) / (1.0 - bt)
zt2 = bt2 - 0.5 + (zt - bt + 0.5) * (1.0 - bt2) / (1.0 - bt)
else:
zt1 = bt1 - 0.5 + (zt - bt + 0.5) * bt1 /... | 45e8001e4c97aee269dbcf412786863c52328ebd | 589,801 |
def job_runner(job):
"""
Run a job. Called in a Process pool.
"""
return job.run() | 7c76225cc8d19e08231ba2973bee0ba7ff4827cc | 589,802 |
def play_tictactoe_turn(action, state):
"""
Play a single turn of tictac toe. Returns the next person's turn and the
new board_state given the input action.
Input:
action:
0-8, an index into the board array
state:
board_state:
(0,1,0,None,None... | df898b89ef847d2b65795687ef4ba0b1aedf0660 | 589,803 |
def read_fake_mapping(fake_genome_mapping_filename):
"""
:param fake_genome_mapping_filename: fake genome mapping file
:return: dict of fake position -> (chr, ref position)
"""
fake_map = {}
with open(fake_genome_mapping_filename) as (f):
for line in f:
fake_pos, ref_chr, ref... | aff7c16a96c41a1467c1f70f8f393b3808ae47d0 | 589,806 |
from typing import Set
from typing import List
def compare_sets(curr: Set[str], prod: Set[str]) -> List[str]:
"""
Compares two sets of values and returns a list of items with "+" or "-" prefix indicating
whether the value has been added or is missing in the second set compared to the first.
Args:
... | 2a98f53d6be1decc329ea93ec1f850f362910087 | 589,807 |
def determine_native_name(coreclr_args, base_lib_name, target_os):
""" Determine the name of the native lib based on the OS.
Args:
coreclr_args (CoreclrArguments): parsed args
base_lib_name (str) : root name of the lib
target_os (str) : os to run tests on
Return:
(str) : nam... | 133799258e71cabce110eeca6f4870442f284399 | 589,809 |
def bool_from_env_string(string: str) -> bool:
"""Convert a string recieved from an environment variable into a
bool.
'true', 'TRUE', 'TrUe', 1, '1' = True
Everything else is False.
:param string: The string to convert to a bool.
"""
if str(string).lower() == 'false' or str(string) == ... | adade99e2be55215fa22d56506ac47e651c11829 | 589,813 |
def RTrim(text):
"""Strip spaces from the right of the text"""
return str(text).rstrip() | 757f7631f1926b9f1ae51e4a6efc1b1354bb5df1 | 589,817 |
import torch
def cxcywh_to_ltrb(boxes, as_tuple=False):
"""(center_x, center_y, width, height) -> (left, top, right, bottom) (已测试)
:param boxes: shape(NUM/..., 4). (center_x, center_y, width, height)
:param as_tuple:
if True: return len(4 * shape(NUM/...,)). False: return shape(NUM/..., 4)
:... | ce3f134b2f43d71039e58a13addf3bb2d217b02a | 589,818 |
def weight_path(model_path):
""" Get path of weights based on path to IR
Params:
model_path: the string contains path to IR file
Return:
Path to weights file
"""
assert model_path.endswith('.xml'), "Wrong topology path was provided"
return model_path[:-3] + 'bin' | 99479ae821e5919aa40dc4c437c3854b0ec0f697 | 589,819 |
def off_diagonal(x):
""" Return a flattened view of the off-diagonal elements of a square
matrix.
"""
n, m = x.shape
assert n == m
return x.flatten()[:-1].view(n - 1, n + 1)[:, 1:].flatten() | 7b65257db38b281d5abd8132e940504aa6bea9c6 | 589,820 |
def sql_get_query_data(connection, query):
"""Runs SQL statement to get results of query specified, returned and pyodbc cursor.
Args:
connection: pyodbc.connect() object, Connection to use when selecting data
query: string, Valid select statement
Returns:
... | 416730d8bc021bf63e232a7aa251aefc29166a15 | 589,821 |
def sanitize_name(s,new_char='_'):
"""
Replace 'unsafe' characters in HTML link targets
Replaces 'unsafe' characters in a string used as a
link target in an HTML document with underscore
characters.
Arguments:
s (str): string to sanitize
replace_with (str): string to replace 'unsaf... | 33b87124adf2c1a4c41590be506daf8276cb3d70 | 589,823 |
def merge(f_list):
"""
Merge two polynomials into a single polynomial f.
Input:
[f0, f1] A list of two polynomials
Output:
f A polynomial
Format: Coefficient
"""
f0, f1 = f_list
n = 2 * len(f0)
f = [0] * n
for i in range(n // 2):
f[2 * i + 0] =... | bae2e187d624b585d10ba4d2ecfbb54e8e43235e | 589,824 |
def make_taw_list(taw_tup):
"""
makes a list of all the taws used
:param taw_tup: (begin_taw, end_taw, taw_step)
:return:
"""
# upack
begin_taw, end_taw, taw_step = taw_tup
taw_list = []
for i in range(0, ((end_taw - begin_taw) / taw_step)):
taw = begin_taw + (i * taw_step)
... | 2214bff4beefa5948b264b9b6738dec2411c4a97 | 589,827 |
def split_decimal(version_decimal):
"""Split a Decimal version number into numeric representations of its components.
Args:
version_decimal (Decimal): A Decimal containing an IATI version number.
Returns:
list of int: A list containing numeric representations of the Integer and Decimal com... | f1fda339b8339ce56f947fc66af49d16b6710e4e | 589,828 |
def escalar(datos, margen_adicional=0, minimos=None, maximos=None):
"""
Recibe datos cuyos valores se encuentran en el intervalo [minimos, maximos],
y los escala de forma que queden en el intervalor [0, 1].
Adicionalmente, puede especificarse un margen de seguridad, que amplía el
intervalo entre [m... | 0f2a6274600a57717ad937a3056deccccba5fb27 | 589,832 |
def rho_to_units(rho, ref_density=1250):
"""Convert dimensionless growth rate to real units for a growth process.
Returns
-------
density : number or numpy array (dtype float)
Time in units (hours, days, etc.)
Parameters
----------
rho : number or numpy array
... | 7fc34c72fa80f99d14ef5ab0c809b012fad45b05 | 589,833 |
import re
def parse_show_version(raw_result):
"""
Parse the 'show version' command raw output.
:param str raw_result: vtysh raw result string.
:rtype: dict
:return: The parsed result of the show version command in a \
dictionary of the form:
::
{
'version' : '',... | d6daf64f2b4cc669358662866fd298638dc8bfdd | 589,835 |
def linear_distance(a: float, b: float) -> float:
""" Returns the absolute difference between a and b """
return abs(a - b) | 78a0f50a64ee3396ac197d5b5bafb69f6cea67bd | 589,837 |
def get_total_time_intersect(target_duration_dict_a: dict, target_duration_dict_b: dict) -> int:
"""Return sum of durations for targets in A that are also in B"""
total_time = 0
for target in target_duration_dict_a.keys():
if target in target_duration_dict_b.keys():
total_time += target_... | 0dc649ad0faa4de0a2e0ad6415b1ee545a6914ac | 589,838 |
def get_stream_index(structure_pattern,structure_index):
"""
Translates the sequence of indices identifying an item in a hierarchy
to the index identifying the same item in the flattened data stream.
The structure indices must point to a value, not a list.
>>> get_stream_index('..[[[.]..].].',[0])
... | e97fe95d16b58a8f562c3bfb058ee106d944e289 | 589,839 |
import json
def context_from_json_file(file_name):
"""
Load a json file into a dictionary.
Parameters
----------
file_name: str
Path to the json file.
Returns
dict
Content of the file as dictionary.
"""
with open(file_name, encoding='utf-8') as json_file:
... | 47968c0eb0f267421006ddaebf15c8a4ef643c25 | 589,841 |
def getMedian(laundry):
"""
Gets the median item in the given list.
Args:
laundry (list): Items to get middle item from.
Returns:
(Any): The median item in the list.
"""
length = len(laundry)
if length == 0:
return None
median_index = int((length - 1) / 2)
... | eb5f35efe8805a9927034caa5e871d54057b8e7c | 589,842 |
def format_timestamp(timestamp):
"""Returns a string representing a python datetime in LDAP timestamp
format.
:param timestamp: An "aware" datetime object
:return: A timestamp in the format YYYYMMDDhhmmss-0700 (or -0800 in the winter)
"""
if timestamp.tzinfo is None or timestamp.tzinfo.utcoffse... | 73a06037a4305177eb644e5ec2ca798b9598a297 | 589,843 |
def common_prefix(key, node_id):
"""Find the common prefix between two hex digit numbers
Arguments:
key {Hex String}
node_id {Hex String}
Returns:
Integer -- Length of common prefix
"""
prefix = key
while node_id[:len(prefix)] != prefix and prefix:
prefix = ... | 442abc931b7210ed35475c48c01c76e252b7b87a | 589,850 |
import gzip
import json
def import_compressed_json(file_name):
"""Import gzip compressed JSON.
:param file_name: Name of file to be read e.g. dict.json.gz
:returns: JSON as a dictionary.
"""
with gzip.open(file_name, mode="rt") as f:
return json.load(f) | c9c4bca3c04a9a36cb33d5b172b6836ec044d5d5 | 589,856 |
def encryption(msg):
"""Encrypts the message that the user inputs to the chatbot.
Parameters
----------
msg : string
String that the user inputs.
Returns
-------
encoded : string
String containing the encoded message with 'Encoded Message: ' in front of it.
... | 6ce43c17e5091071630b864821c2d52242df31ec | 589,859 |
import uuid
def generate_stream_id(dtime):
"""
Get a string for use as a stream ID.
The idea is to create a stream ID that is largely human-readable
(hence the timestamp), and compact, but will not repeat if multiple packets
are generated within a small timespan (within reason).
To do this, w... | 6183a991dded82917fbd12ae5d712b6779e2099b | 589,865 |
import types
def code_object_replace(code: types.CodeType, **kwargs) -> types.CodeType:
"""
Return a copy of the code object with new values for the specified fields.
"""
try:
kwargs["co_consts"] = tuple(kwargs["co_consts"])
except ValueError:
pass
# Python 3.8+
if hasattr(... | 5c5d2a764f1a2237fc0358faae73bdb6c72a75d4 | 589,868 |
import math
def arctan_z_term(z, term_index):
"""
Generates each term in Gregory-Leibniz series for arctan(z)
"""
term_power = (term_index*2+1) # Each term is raised to this power, and also divided by this value
return (math.pow(z, term_power)/term_power)*((-1)**(term_index)) | 44bb0a822e0bd4c64de703ee0d0549c17046dfd8 | 589,875 |
import pickle
def load_fragGC_pickle(inFH):
"""Loading fragGC info assuming a pickled python object
produced by SIPSim fragGC.
Parameters
----------
inFH : file handle
Returns
-------
fragGC object
"""
fojb = pickle.load(inFH)
d = dict()
for x in fojb:
... | d044cabbd2149cc4cbcd1fdcf4c380b425a7b337 | 589,880 |
def samples_to_seconds(samples, rate):
"""Convert audio samples to seconds samples / samplerate."""
return samples / rate | d09b283d4b1553c6fa53b3c65cdf3c1b3496d93f | 589,881 |
def print_rolls_nicely(rolls):
"""
This function prints the rolls in a more understandable way.
"""
def format_roll(name, values):
"""
This function prints a line in a prefined way.
"""
return "{: <10} {}".format(name, " | ".join([str(item) for item in values]))
pr... | fb4c609b93bfb5513af3fe6c7449a190f42381c7 | 589,882 |
def convert_bytes_to_str(message):
"""Convert bytes to str phrase
"""
return message.decode('utf8', 'ignore') | 2406dc4124e1baec5752eb1b7eb90e79b915e0be | 589,884 |
def check_valid_role(role):
"""
Checks if the role is valid, return true if it is, and false otherwise.
"""
if role == 'patient' or role == 'administrator' or role == 'physician' or role == 'radiologist' or role == 'nurse' or role == 'technical support':
return True
else:
return Fals... | 9a3581b4dda734572e3a715b0c0d218732fa04ab | 589,885 |
def difference(array, *lists):
"""Creates a list of list elements not present in the other lists.
Args:
array (list): List to process.
lists (list): Lists to check.
Returns:
list: Difference of the lists.
Example:
>>> difference([1, 2, 3], [1], [2])
[3]
.... | 7b56db50e2844244fc2ce6d884d2ed26ac35471a | 589,888 |
def associate_by_user_id(backend, details, response, user=None, *args, **kwargs):
"""
Associate current auth with a user with the same Google user_id in the DB.
"""
if user:
return None
user_id = response.get('id')
if user_id:
# Try to associate accounts registered with the same... | 3781d5612cdcbd7f53d3f8257e5c04ec90a10246 | 589,896 |
def remove_arg(args, arg, has_param=False):
"""Removes the first instance of the specified arg from the list of args.
If the arg is present and has_param is set, also removes the parameter that follows
the arg.
:param list args: strings representing an argument list.
:param staring arg: argument to remove fr... | 7c3a2a24716090c72b051ead4ee6eb8b09e9b206 | 589,906 |
def value_in_list(answers, key, values):
"""Determine user's answer for the key is in the value list.
Args:
answer: Dict of user's answers to the questions.
key: question key.
values: List of values to check from.
"""
try:
value = answers[key]
return value in values
except KeyError:
re... | 8e1dd440063645e39419864ee7cc7563608c64c3 | 589,907 |
def isType(node, typename):
"""Return True if node.type() is typename or
any subclass of typename."""
return typename in node.nodeType(inherited=True) | 42eec0ef5109a91e4550d622a1cc53f4e6742d20 | 589,910 |
def apply_pct(record_list, win_pct):
"""
Inputs:
record_list (binary list) - list containing wins (1) and losses (0) in every possible unique permutation
win_pct (list) - list containing win percentage to be applied
Returns:
pcts_applied (list) - list with win/loss percentages appli... | b21e12d8c0e9388f9798078af614c00ce6b3b5cb | 589,922 |
from typing import Dict
def get_formatter(**kwargs) -> Dict[str,str]:
"""
Generates a formatter dict used for formatting filenames.
Takes in kwargs of Dict[str,Any].
Does not keep lists, dicts and bools.
Automatically filters out` .endswith('ated_at')` for animethemes-dl.
Also adds `{video_fil... | a925d8fce129c54dbbac4b7e0506f35127ac6d85 | 589,924 |
def match_type(obj, matchers):
"""Matches a given object using the given matchers list/iterable.
NOTE(harlowja): each element of the provided list/iterable must be
tuple of (valid types, result).
Returns the result (the second element of the provided tuple) if a type
match occurs, otherwise none i... | da9e4e4a9247f1cd2b5040b0585b3fe54fad7087 | 589,926 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.