content stringlengths 42 6.51k |
|---|
def _format_time(seconds):
"""seconds: number
returns a human-friendly string describing the amount of time
"""
minute = 60.00
hour = 60.00 * minute
if seconds < 30:
return '{} ms'.format(int(seconds * 1000))
if seconds < 90:
return '{} seconds'.format(round(seconds, 2))
... |
def resolve_secrets(vault_client, rendered_template):
"""Parse a rendered template, extract any secret definitions, retrieve them
from vault and return them to the caller.
This is used in situations where direct Vault support is not available e.g.
Chronos.
"""
resolved_secrets = {}
secrets... |
def sanitize_filename(filename):
"""
Return a sanitized file path with certain characters replaced.
"""
return filename.replace(":", "_").replace("/", "_") |
def primitive_path(name):
"""Gets the relative path to the primitive file with the specified name.
Args:
name (str): The name of the primitive.
"""
return 'primitives/' + name + '.pc' |
def keywithmaxval(d):
""" a) create a list of the dict's keys and values;
b) return the key with the max value"""
v = list(d.values())
k = list(d.keys())
return k[v.index(max(v))] |
def pick_n(items, n):
"""Pick n items, attempting to get equal index spacing.
"""
if not (n > 0):
raise ValueError("Invalid number of items to pick")
spacing = max(float(len(items)) / n, 1)
spaced = []
i = 0
while int(i) < len(items) and len(spaced) < n:
spaced.append(items[i... |
def linear_dist_sphere(radius: float, surf_dist: float, depth_a: float, depth_b: float) -> float:
"""
The purpose of this function is to find the actual, linear distance between the hypocenter of
and earthquake and the bottom of a fracking well. It's a more general problem/solution, though:
retu... |
def train_get_surrounding_syms(s, position, featureprefix, lookright = True):
"""Get surrounding symbols from a list of chunks and position.
>>> s = ['<', u'a', u'b', u'u', u'_', u't', u'a', u'n', u'doka', '>']
>>> train_get_surrounding_syms(s, 4, 'in_')
set([u'nin_ta', u'nin_t', u'nin_tan', u'pin_u', u... |
def euclids_algorithm(m: int, n: int) -> int:
"""
Given unsigned int m, n. Find the highest common denominator.
:rtype: int
:param m: first number in question
:param n: second number in question
:return: Highest common denominator
"""
# Check if m is greater than n to skip the fi... |
def get_from_nested_dict(nested_dicts, path):
"""
Retrieves a value from a nested_dict.
Args:
path (str)
"""
value = nested_dicts
for key in path.split("/"):
if type(value) is dict:
value = value[key]
elif type(value) is list:
value = value[in... |
def FindByWireName(list_of_resource_or_method, wire_name):
"""Find an element in a list by its "wireName".
The "wireName" is the name of the method "on the wire", which is the raw name
as it appears in the JSON.
Args:
list_of_resource_or_method: A list of resource or methods as annotated by
the Api.... |
def count_vowels(string):
"""
#### returns amount of vowels in given string
#### Example:
x = count_vowels("The meaning of life, 42 to proof this, is this text"*3)
### print(x)
### 42
"""
vowels,counter = ("aeiou"),0
for i in string:
if i.lower() in vowels : counter+=1
... |
def get_entry_or_none(base: dict, target, var_type=None):
""" Helper function that returns an entry or None if key is missing.
:param base: dictionary to query.
:param target: target key.
:param var_type: Type of variable this is supposed to be (for casting).
:return: entry or None.
"""
if... |
def get_login_url(client_id: str, redirect_uri: str) -> str:
"""
Returns the url to the website on which the user logs in
"""
return f"https://login.live.com/oauth20_authorize.srf?client_id={client_id}&response_type=code&redirect_uri={redirect_uri}&scope=XboxLive.signin%20offline_access&state=<optional;... |
def ramp(e, e0, v0, e1, v1):
"""
Return `v0` until `e` reaches `e0`, then linearly interpolate
to `v1` when `e` reaches `e1` and return `v1` thereafter.
Copyright (C) 2017 Lucas Beyer - http://lucasb.eyer.be =)
"""
if e < e0:
return v0
elif e < e1:
return v0 + (v1-v0)*(e-e0)... |
def check_anagrams(a: str, b: str) -> bool:
"""
Two strings are anagrams if they are made of the same letters
arranged differently (ignoring the case).
>>> check_anagrams('Silent', 'Listen')
True
>>> check_anagrams('This is a string', 'Is this a string')
True
>>> check_anagrams('... |
def nl_capitalize(string: str):
""" Capitalize first character (the rest is untouched)
:param string:
:return:
"""
return string[:1].upper() + string[1:] |
def fill_valid_next_words(pos, word2index_y, last_word, bpe_separator, wrong_chars=[]):
"""
Searches all the valid words for a last_word and a list of wrong_chars to continue it
:param pos: Position on the hypothesis of the last word
:param word2index_y: Dictionary to convert words to indeces
:param... |
def to_lower(string: str) -> str:
"""
Converts :string: to lower case. Intended to be used as argument converter.
Args:
string: string to format
Returns:
string to lower case
"""
return string.lower() |
def solve(task: str) -> int:
"""Find number of steps required to jump out of maze."""
current_index = 0
steps = 0
data = [int(item) for item in task.strip().split("\n")]
while 0 <= current_index < len(data):
offset = data[current_index]
next_index = current_index + offset
if... |
def get_polygon_from_file_settings(settings):
"""
:param settings:
:return:
"""
try:
return settings['step'], settings['x_pos'], settings['y_pos']
except ValueError:
print('Not Valid Settings') |
def devide_zero_prefix_index(number):
"""
Split the zero prefix
"""
if not number.startswith("0"):
return None, int(number)
i = 0
while i < len(number):
if number[i] != "0":
break
i += 1
return number[0:i], 0 if i >= len(number) else int(number[i:]) |
def get_boundaries(bucket_names):
"""
Get boundaries of pandas-quantized features.
>>> bucket_names = ["whatever_(100.0, 1000.0)", "whatever_(-100.0, 100.0)"]
>>> get_boundaries(bucket_names)
[(100.0, 1000.0), (-100.0, 100.0)]
"""
boundaries = []
for bucket_name in bucket_names:
... |
def get_bond_from_num(n: int) -> str:
"""Returns the SMILES symbol representing a bond with multiplicity
``n``. More specifically, ``'' = 1`` and ``'=' = 2`` and ``'#' = 3``.
:param n: either 1, 2, 3.
:return: the SMILES symbol representing a bond with multiplicity ``n``.
"""
return ('', '=', ... |
def query_data(data_to_process, query_type=None):
"""Query data.
"""
if query_type == 'lines':
lines = 0
for _, contents in data_to_process.items():
if isinstance(contents, bytes):
text = contents.decode('utf-8')
else:
text = contents
... |
def never_swap(doors, past_selections):
"""
Strategy that never swaps when given a chance.
"""
return past_selections[-1] |
def session_device(request, var, Session="auth_device"):
"""
Set a Session variable if logging in via a subacc
This will be linked to a decorator to control access to
sections of the site that will require the master account to be used
:param request:
:param session: default is auth_device
:... |
def dimensions_to_resolutions(value):
"""
## dimensions_to_resolutions
Parameters:
value (list): list of dimensions (e.g. `640x360`)
**Returns:** list of resolutions (e.g. `360p`)
"""
supported_resolutions = {
"256x144": "144p",
"426x240": "240p",
"6... |
def odds(p):
"""Computes odds for a given probability.
Example: p=0.75 means 75 for and 25 against, or 3:1 odds in favor.
Note: when p=1, the formula for odds divides by zero, which is
normally undefined. But I think it is reasonable to define Odds(1)
to be infinity, so that's what this function do... |
def comp_1st(n):
"""takes a binary number (n) in string fomat
returns the 1's complement of the number"""
n=str(n)
result=[]
for digit in n:
a=str(1-int(digit))
result.append(a)
return "".join(result) |
def parse_dependencies_unix(data):
""" Parses the given output from otool -XL or ldd to determine the list of
libraries this executable file depends on. """
lines = data.splitlines()
filenames = []
for l in lines:
l = l.strip()
if l != "statically linked":
filenames.appe... |
def roundu(x: int, y: int, z: int) -> int:
"""Run calculation, round up, and return result."""
w = x * y / z
iw = int(w)
if iw - w != 0:
return iw + 1
return iw |
def sanitize_bool_for_api(bool_val):
"""Sanitizes a boolean value for use in the API."""
return str(bool_val).lower() |
def PS_custom_get_process(v):
"""convert string to proper float value, for working with the PS 120-10 """
return float(v[1:]) * 1e-2 |
def secureCompare(s1, s2):
"""Securely compare two strings"""
return sum(i != j for i, j in zip(s1, s2)) == 0 |
def get_age_distribution_max(selectpicker_id: str) -> int:
"""
:param selectpicker_id:
:return:
"""
min_values = {
"0": 18,
"1": 25,
"2": 35,
"3": 45,
"4": 55,
"5": 99
}
return min_values.get(selectpicker_id, 99) |
def _to_bgr(rgb):
"""excel expects colors as BGR instead of the usual RGB"""
if rgb is None:
return None
return ((rgb >> 16) & 0xff) + (rgb & 0xff00) + ((rgb & 0xff) << 16) |
def trim_spaces(s: str) -> str:
"""Trims excess spaces
Examples:
>>> trim_spaces(' pretty')
'pretty'
>>> trim_spaces(' CHEDDAR CHEESE')
'CHEDDAR CHEESE'
>>> trim_spaces(' salt ')
'salt'
"""
return ' '.join(_ for _ in s.split(' ') if _) |
def header_line_to_anchor( line ):
"""
duplicate (approximately) the GitLab algorithm to make a header anchor
"""
s1 = line[3:].strip().replace( '=', '' )
s2 = ' '.join( s1.split() )
s3 = s2.lower()
return s3 |
def _in_tag(text, tag):
"""Extracts text from inside a tag.
This function extracts the text from inside a given tag.
It's useful to get the text between <body></body> or
<pre></pre> when using the validators or the colorizer.
"""
if text.count('<%s' % tag):
text = text.split('<%s' % tag... |
def get_comma_sep_string_from_list(items):
"""Turns a list of items into a comma-separated string."""
if not items:
return ''
if len(items) == 1:
return items[0]
return '%s and %s' % (', '.join(items[:-1]), items[-1]) |
def get_numeric_ratio(s):
"""
gets the ratio of numeric characters to the total alphanumerics
:type s: str
:rtype: float or NoneType
"""
num_numeric = 0
num_alphabetic = 0
if len(s) == 0:
return None
else:
for character in s:
if character.isnumeric():
num_numeric += 1
elif character.isalpha():
... |
def romanFromInt(integer):
"""
Code taken from Raymond Hettinger's code in Victor Yang's "Decimal
to Roman Numerals" recipe in the Python Cookbook.
>>> r = [romanFromInt(x) for x in range(1, 4000)]
>>> i = [intFromRoman(x) for x in r]
>>> i == [x for x in range(1, 4000)]
True
"""
co... |
def make_vars(spec):
"""Returns configurable variables for make"""
return f"AZURE_REGION={spec['region']} RESOURCE_GROUP_NAME={spec['resource_group']} STORAGE_ACCOUNT_NAME={spec['storage_acc_name']} FUNCTION_APP_NAME={spec['app_name']} APPINSIGHTS_NAME={spec['app_insights_name']}" |
def u_init(x, y, xmin, xmax, ymin, ymax):
"""
initial condition
"""
center = (
.75*xmin + .25*xmax,
.50*ymin + .50*ymax
)
radius = 0.1
height = 0.5
return 1 + height * ((x-center[0])**2+(y-center[1])**2 < radius**2) |
def _indent(s, amount):
"""
Indents string `s` by `amount` doublespaces.
"""
pad = ' ' * amount
return '\n'.join([pad + i for i in s.splitlines(False)]) |
def __operator(x, w, c, noise):
"""
Operator is used to generate artificial datasets
:param w:
:param c:
:param noise:
:return:
"""
return x * w + c + noise |
def generate_network_url(project, network):
"""Format the resource name as a resource URI."""
return 'projects/{}/global/networks/{}'.format(project, network) |
def _AdditionalCriteriaAllPassed(additional_criteria):
"""Check if the all the additional criteria have passed.
Checks for individual criterion have been done before this function.
"""
return all(additional_criteria.values()) |
def rgb(red, green, blue):
"""
Make a tkinter compatible RGB color.
"""
return "#%02x%02x%02x" % (red, green, blue) |
def gradient_descent(x0, grad, step_size, T):
"""run gradient descent for given gradient grad and step size for T steps"""
x = x0
for t in range(T):
grad_x = grad(x)
x -= step_size * grad_x
return x |
def only_source_name(full_name):
"""Helper function that strips SNAPPY suffixes for samples."""
if full_name.count("-") >= 3:
tokens = full_name.split("-")
return "-".join(tokens[:-3])
else:
return full_name |
def equal_probs(num_values):
"""Make an array of equal probabilities."""
prob = 1.0 / num_values
probs = [prob for i in range(num_values)]
return probs |
def csv_to_set(x):
"""Convert a comma-separated list of strings to a set of strings."""
if not x:
return set()
else:
return set(x.split(",")) |
def nsubset(dictionary, keys):
"""Creates a new dictionary from items from another one. The 'n' stands
for 'negative', meaning that the keys form an excluded list. All keys
from the other dictionary will be extracted except for the ones explicitly
indicated. The original dictionary is left untouched.
... |
def lazy_value(value):
"""
Evaluates a lazy value by calling it when it's a callable, or returns it unchanged otherwise.
"""
return value() if callable(value) else value |
def range_ranges(ranges):
"""
Return int array generated starting on the smallest range start to the
highest range end.
"""
ranges = [n for r in ranges for n in range(r[0], r[-1] + 1)]
return sorted(list(set(ranges))) |
def serialize(tokens):
"""
Serialize tokens:
* quote whitespace-containing tokens
* escape semicolons
"""
ret = []
for tok in tokens:
if " " in tok:
tok = '"%s"' % tok
if ";" in tok:
tok = tok.replace(";", "\;")
ret.append(tok)
return " ... |
def get_voltage_extremes(voltages):
""" Finds and returns the minimum and maximum voltages measured in the
ECG signal.
:param voltages: List of voltage measurements
:return: Tuple containing min and max voltages (floats)
"""
return min(voltages), max(voltages) |
def heatCapacity_f1(T, hCP):
"""
heatCapacity_form1(T, hCP)
slop vapor & solid phases: T in K, heat capaity in J/mol/K;
heat capacity correlation
heat capacity = A + B*T + C/T^2
Parameters
T, temperature
hCP, A=hCP[0], B=hCP[1], C=hCP[2]
A, B, and C are regression coe... |
def display_scoped_map_with_bombs(scope, element_id, data, bombs, fills):
"""Renders a map with a close-up look to the scope the country belongs to.
Args:
scope -> datamaps scope instance.
element_id -> ID for the DOM element where the map is going to render.
This element should contain the follo... |
def to_binary(int_value: int):
"""
This method converts an int to its binary representation.
:param int_value: The int value to convert.
:return: The binary representation as str.
"""
# The implementation does not build on to_numeral
# because the native Python conversion is faster
resu... |
def typed(var, types):
"""
Ensure that the "var" argument is among the types passed as the "types" argument.
@param var: The argument to be typed.
@param types: A tuple of types to check.
@type types: tuple
@returns: The var argument.
>>> a = typed('abc', str)
>>> type(a)
<type '... |
def get_namespace(title):
"""Parses a Wiktionary page title and extracts the namespace from it.
Parameters
----------
title : str
The page title to parse.
Returns
-------
str or None
The namespace, in text, of the given title, or None for the
main namesp... |
def validate_number(num, low, high):
"""
Takes user input as a string and validates that it is
an integer between low and high
"""
try:
num = int(num)
except ValueError:
return False
if num < low or num > high:
return False
return True |
def translate_version_str2int(version_str):
"""Translates a version string in format x[.y[.z[...]]] into a 000000 number.
Each part of version number can have up to 99 possibilities."""
import math
parts = version_str.split('.')
i, v, l = 0, 0, len(parts)
if not l:
return v
while i <... |
def add_segment_final_space(segments):
"""
>>> segments = ['Hi there!', 'Here... ', 'My name is Peter. ']
>>> add_segment_final_space(segments)
['Hi there! ', 'Here... ', 'My name is Peter.']
"""
r = []
for segment in segments[:-1]:
r.append(segment.rstrip() + " ")
r.append(segme... |
def do_prepend(value, param='/'):
"""Prepend a string if the passed in string exists.
Example:
The template '{{ root|prepend('/')}}/path';
Called with root undefined renders:
/path
Called with root defined as 'root' renders:
/root/path
"""
if value:
return '%s%s' % (... |
def get_group(yaml_dict):
"""
Return the attributes of the light group
:param yaml_dict:
:return:
"""
group_name = list(yaml_dict["groups"].keys())[0]
group_dict = yaml_dict["groups"][group_name]
# Check group_dict has an id attribute
if 'id' not in group_dict.keys():
prin... |
def message_prefix(file_format, run_type):
"""Text describing saved case file format and run results type."""
format_str = ' format' if file_format == 'mat' else ' format'
if run_type == ['PF run']:
run_str = run_type + ': '
else:
run_str = run_type + ':'
return 'Savecase: ' + file_... |
def mean(X):
""" Calculate mean of a list of values.
Parameters
----------
X : a list of values
"""
return sum(X) / float(len(X)) |
def is_term(uri):
"""
>>> is_term('/c/sv/kostym')
True
>>> is_term('/x/en/ify')
True
>>> is_term('/a/[/r/RelatedTo/,/c/en/cake/,/c/en/flavor/]')
False
"""
return uri.startswith('/c/') or uri.startswith('/x/') |
def target_name_conversion(targetname):
"""
NAME:
target_name_conversion
PURPOSE:
to convert targetname to string used to plot graph
INPUT:
targetname (string)
OUTPUT:
converted name (string)
HISTORY:
2017-Nov-25 - Written - Henry Leung (University of Toro... |
def choices_from_dict(source, prepend_blank=True):
"""
Convert a dict to a format that's compatible with WTForm's choices.
It also optionally prepends a "Please select one..." value.
Example:
# Convert this data structure:
STATUS = OrderedDict([
('unread', 'Unread'),
('open', 'O... |
def euclidean_gcd(a,b):
"""Euclidean Algorithm to find greatest common divisor.
Euclidean algorithm is an efficient method for computing
the greatest common divisor (GCD) of two integers (numbers),
the largest number that divides them both without a remainder [Wiki].
Args:
a (int): T... |
def concat(arrays):
"""
Concatenates an array of arrays into a 1 dimensional array.
"""
concatenated = arrays[0]
if not isinstance(concatenated, list):
raise ValueError(
"Each element in the concatenation must be an instance "
"of `list`."
)
if len(arrays)... |
def clean_row(review):
"""
Cleans out a review and converts to list of words.
Currently only removes empty elements left after removing some punctuations.
Args:
review(str): The review in string format.
Returns:
List of words in the accepted review, cleaned.
"""
return [word... |
def prepend_xpath(pre, xpath, glue=False):
"""Prepend some xpath to another, properly joining the slashes
"""
if (not pre) or xpath.startswith('//'):
# prefix doesn't matter
return xpath
if pre.endswith('./'):
if xpath.startswith('./'):
return pre[:-2] + xpath
... |
def get_label(genotype_type):
"""
Get genotype label for a type of genotype
:param genotype_type: Genotype in string
:return: Integer label for the type
"""
if genotype_type == "Hom":
return 0
elif genotype_type == "Het":
return 1
elif genotype_type == "Hom_alt":
... |
def remove_hyphens(s):
"""
:param s:
:return:
"""
return ' - '.join([x.replace('-', ' ') for x in s.split(' - ')]) |
def join_authors(list):
"""Joins pubmed entry authors to a single string"""
return ", ".join([x["name"] for x in list]) |
def transit_mask(time, t0, duration, porb):
"""
Mask out transits
Args:
t0 (float): The reference time of transit in days.
For Kepler data you may need to subtract 2454833.0 off this
number.
duration (float): The transit duration in hours.
porb (float): The p... |
def expand_dic(vid_vidx, l_vid_new):
"""Expands a dictionnary to include new videos IDs
vid_vidx: dictionnary of {video ID: video idx}
l_vid_new: int list of video ID
Returns:
- dictionnary of {video ID: video idx} updated (bigger)
"""
idx = len(vid_vidx)
for vid_new in l_vid_new:
... |
def dot_prod(a, b):
"""
Calculates the dot product of two lists with values
:param a: first list
:param b: second list
:return: dot product (a . b)
"""
return sum([i*j for (i, j) in zip(a, b)]) |
def PNT2QM_Pv4(XA,chiA):
""" TaylorT2 2PN Quadrupole Moment Coefficient, v^4 Phasing Term.
XA = mass fraction of object
chiA = dimensionless spin of object """
return -25.*XA*XA*chiA*chiA |
def round_to_second(time):
"""Rounds a time in days to the nearest second.
Parameters
----------
time: int
The number of days as a float.
Returns
-------
float
The number of seconds in as many days.
"""
return(round(time * 86400)/86400.0) |
def divisors(number, primes):
"""Finds number of divisors of a number using prime factorization."""
prime_factors_pow = []
if number < 2:
prime_factors_pow.append(0)
for p in primes:
if p > number:
break
n = 0
while number % p == 0:
n += 1
... |
def zero_plentiful3(arr):
"""."""
four_plus = 0
res = []
for char in arr:
if char == 0:
res.append(char)
if char != 0:
if len(res) >= 4:
four_plus += 1
for x in res:
res.pop()
if len(res) < 4 and len(... |
def find_download_urls(release_page_body):
"""
find_download_urls is parse and grep tarfind_urls.
:param release_page_body:
"""
file_urls = []
if isinstance(release_page_body, list):
for paresr in release_page_body:
file_urls.extend(find_download_urls(paresr))
elif isin... |
def base62_encode(num: int) -> str:
"""
http://stackoverflow.com/questions/1119722/base-62-conversion
"""
alphabet = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
if num == 0:
return alphabet[0]
arr = []
base = len(alphabet)
while num:
num, rem = divmo... |
def encode_varint(number: int) -> bytes:
"""
Encode varint into bytes
"""
# Shift to int64
number = number << 1
buf = b""
while True:
towrite = number & 0x7F
number >>= 7
if number:
buf += bytes((towrite | 0x80,))
else:
buf += bytes((to... |
def minimal_roman(value):
"""
Return minimal form of value in roman numeral
"""
tmp = ''
# First the thousands
quot = value//1000
res = value%1000
for i in range(quot):
tmp += 'M'
# Second the centuries
quot = res//100
res = res%100
if quot==9:
tmp +... |
def op_inv(x):
"""Finds the inverse of a mathematical object."""
if isinstance(x, list):
return [op_inv(a) for a in x]
else:
return 1 / x |
def convert_nt(nt: int) -> float:
""" Convert a nucleotide position/width to a relative value.
Used to calculate relative values required for polar plots.
Args:
nt: position/width in nucleotides
Returns:
relative value
"""
return (nt * 6.29) / 16569 |
def get_attributes(attrs):
"""return attributes string for input dict
format: key="value" key="value"...
spaces will be stripped
"""
line = ''
for i,j in attrs.items():
s = ''
# Caution! take care when value is list
if isinstance(j,list):
for k in j: s += k + ... |
def _unmangle_name(mangled_name, class_name):
"""Transform *mangled_name* (which is assumed to be a
"_ClassName__internal" name) into an "__internal" name.
:arg str mangled_name:
a mangled "_ClassName__internal" member name
:arg str class_name:
name of the class where the (unmangled) name... |
def get_gender_it(word, context=""):
"""
In Italian to define the grammatical gender of a word is necessary
analyze the article that precedes the word and not only the last
letter of the word.
"""
gender = None
words = context.split(' ')
for idx, w in enumerate(words):
if w == w... |
def join_germanic(iterable, capitalize=True, quoteChars="\"", concat="'"):
"""Like "".join(iterable) but with special handling, making it easier to just concatenate a list of words.
Tries to join an interable as if it was a sequence of words of a generic western germanic language. Inserts a space between each ... |
def _label_tuple_to_text(label, diff, genes=None):
"""
Converts the variant label tuple to a string.
Parameters
----------
label : tuple(str)
A tuple of (chrom, pos, ref, alt).
diff : float
The max difference score across some or all features in the model.
genes : list(str) ... |
def maybe_int(string):
"""Convert string to an integer and return the integer or None."""
try:
return int(string)
except ValueError:
return None |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.