content stringlengths 42 6.51k |
|---|
def _deep_get(instance, path):
"""
Descend path to return a deep element in the JSON object instance.
"""
for key in path:
instance = instance[key]
return instance |
def binomial_coeff_nested_conditionals(n, k):
"""Original rewritten using nested conditional expressions.
"""
return 1 if k==0 else 0 if n == 0 else (binomial_coeff_nested_conditionals(n-1, k) + binomial_coeff_nested_conditionals(n-1, k-1)) |
def clamp(value, min_value, max_value):
"""Clamps a value witin the bound [min_value, max_value]
Returns
-------
float
"""
if min_value > max_value:
raise ValueError("min_value must be bigger than max_value")
return float(min(max(value, min_value), max_value)) |
def append_reverse(n=int(1e4)):
"""Assemble list with `append` and `reverse`.
"""
L = []
for x in range(n):
L.append(x)
L.reverse()
return L |
def format_filesize(num, suffix='B'):
"""
See: https://stackoverflow.com/questions/1094841/reusable-library-to-get-human-readable-version-of-file-size
"""
for unit in ['', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi']:
if abs(num) < 1024.0:
return "%3.1f%s%s" % (num, unit, suffix)
num /= 1024.0
return "%.1f%s%s" % (num, 'Yi', suffix) |
def RL(text, cb=None):
"""Convenience function returning a readline test expectation."""
return {
"name": "readline",
"args": [],
"ret": text,
"cb": cb,
"cwd": None,
} |
def valid(node, min_value, max_value):
"""Iteratively validate BST"""
if node is None:
return True
if node.value <= min_value or node.value >= max_value:
return False
return valid(node.left, min_value, node.value) and valid(node.right, node.value, max_value) |
def getTriangleCentroid(x1, y1, x2, y2, x3, y3):
"""
Return the x and y coordinates of a triangle's centroid.
Parameters
----------
x1 : float
x coordindate of first point defining a triangle
y1 : float
y coordindate of first point defining a triangle
x2 : float
x coordindate of second point defining a triangle
y2 : float
y coordindate of second point defining a triangle
x3 : float
x coordindate of third point defining a triangle
y3 : float
y coordindate of third point defining a triangle
Returns
-------
x : float
x coordinate of triangle's centroid
y : float
y coordinate of a triangle's centroid
"""
x = (x1 + x2 + x3) / 3.0
y = (y1 + y2 + y3) / 3.0
return x, y |
def pocock_cutoff(K, alpha):
""" Returns the cutoff value for Pocock's Test
Arguments:
K: An integer less than 10.
alpha: The alpha level of the overall trial (0.01, 0.05 or 0.1).
Returns:
cutoff: The value of \(C_P(K, \alpha)\) for the study.
Note:
Since there is no closed source formula for the cutoff value, a lookup
table is used.
"""
if not isinstance(K, int) or K < 1 or K > 10:
raise ValueError('K must be an integer between 1 and 10.')
if alpha not in [0.01, 0.05, 0.1]:
raise ValueError('alpha must be 0.01, 0.05, or 0.1.')
cutoffs = {
"0.01": [2.576, 2.772, 2.873, 2.939, 2.986, 3.023, 3.053, 3.078, 3.099, 3.117],
"0.05": [1.960, 2.178, 2.289, 2.361, 2.413, 2.453, 2.485, 2.512, 2.535, 2.555],
"0.1": [1.645, 1.875, 1.992, 2.067, 2.122, 2.164, 2.197, 2.225, 2.249, 2.270],
}
return cutoffs[str(alpha)][K - 1] |
def playfair_deal_with_dups(text):
"""playfair can't deal with conseuctive letters being duplicated,
this adds in an X between conseuctive duplciated letters
Args:
text ([str]): plain text to get rid of dups
Returns:
[message]: list of text with the X's added where there are conseuctive duplicates
"""
message = list(text.strip())
for i in range(1,len(message)):
if message[i] == message[i-1]:
message.insert(i, "X")
return message |
def get_formatted_amount(order_amount):
"""
Returns the decimal order_amount in the format expected by RedSys.
Example: 20,00 -> 2000
"""
return int(round(float(order_amount) * 100)) |
def prep_available_bundle(device, npc):
"""
Prepare bundle query XML.
:param device: Hexadecimal hardware ID.
:type device: str
:param npc: MCC + MNC (see `func:bbarchivist.networkutils.return_npc`)
:type npc: int
"""
query = '<?xml version="1.0" encoding="UTF-8"?><availableBundlesRequest version="1.0.0" authEchoTS="1366644680359"><deviceId><pin>0x2FFFFFB3</pin></deviceId><clientProperties><hardware><id>0x{0}</id><isBootROMSecure>true</isBootROMSecure></hardware><network><vendorId>0x0</vendorId><homeNPC>0x{1}</homeNPC><currentNPC>0x{1}</currentNPC></network><software><currentLocale>en_US</currentLocale><legalLocale>en_US</legalLocale><osVersion>10.0.0.0</osVersion><radioVersion>10.0.0.0</radioVersion></software></clientProperties><updateDirectives><bundleVersionFilter></bundleVersionFilter></updateDirectives></availableBundlesRequest>'.format(device, npc)
return query |
def to_percentage(number):
"""
Formats a number as a percentage, including the % symbol at the end of the string
"""
return "{:.2%}".format(number) |
def unpack_singleton(x):
"""Gets the first element if the iterable has only one value.
Otherwise return the iterable.
# Argument
x: A list or tuple.
# Returns
The same iterable or the first element.
"""
if len(x) == 1:
return x[0]
return x |
def time_to_sample(time_, samplerate):
"""Return sample index closest to given time.
Args:
time (float): Time relative to the start of sample indexing.
samplerate (int): Rate of sampling for the recording.
Returns:
sample (int): Index of the sample taken nearest to ``time``.
"""
sample = int(time_ * samplerate)
return sample |
def all_equal(arg1,arg2):
"""
Return a single boolean for arg1==arg2, even for numpy arrays.
Uses all(arg1==arg2) for sequences, and arg1==arg2 otherwise.
"""
try:
return all(a1 == a2 for a1, a2 in zip(arg1, arg2))
except TypeError:
return arg1==arg2 |
def genpass(pwds_amount=1, paswd_length=8):
""" Returns a list of 'pwds_amount' random passwords, having length of 'paswd_length' """
import random
return [ ''.join([chr(random.randint(32, 126)) for _ in range(paswd_length)]) for _ in range(pwds_amount)] |
def last_not_in_set(seq, items):
"""Returns last occurrence of any of items in seq, or None.
NOTE: We could do this slightly more efficiently by iterating over s in
reverse order, but then it wouldn't work on generators that can't be
reversed.
"""
found = None
for s in seq:
if s not in items:
found = s
return found |
def normalize_judge_names(name):
"""Cleans up little issues with people's names"""
out = []
words = name.split()
for i, w in enumerate(words):
# Michael J Lissner --> Michael J. Lissner
if len(w) == 1 and w.isalpha():
w = '%s.' % w
# Michael Lissner Jr --> Michael Lissner Jr.
if w.lower() in ['jr', 'sr']:
w = '%s.' % w
# J. Michael Lissner --> Michael Lissner
# J. G. Lissner --> J. G. Lissner
if i == 0 and w.lower() in ['j.', 'j']:
next_word = words[i + 1]
if not any([len(next_word) == 2 and next_word.endswith('.'),
len(next_word) == 1]):
# Drop the word.
continue
out.append(w)
return ' '.join(out) |
def safe_eval(expression):
"""Safely evaluates a mathematical expression.
(Exists because I couldn't find a way to allow
CL parameters to be expressions - ideally needs
a better solution.)
Parameters
----------
expression: str
Mathematical expression in string to be evaluated.
"""
allowed_chars = "0123456789+-*(). /"
for char in expression:
if char not in allowed_chars:
raise Exception(f'Unsafe eval - allowed characters: {allowed_chars}')
return eval(expression) |
def merge_sort(arr):
"""
Returns the list 'arr' sorted in nondecreasing order in O(nlogn) time.
"""
r = len(arr)
if 1 < len(arr):
q = int(r/2)
L = merge_sort(arr[0:q])
R = merge_sort(arr[q:])
print(L,R)
i,j,k = 0,0,0
while i < len(L) and j < len(R):
if L[i] < R[j]:
arr[k] = L[i]
i = i+1
k = k+1
elif R[j] < L[i]:
arr[k] = R[j]
j = j+1
k = k+1
if i >= len(L):
while j < len(R):
arr[k] = R[j]
j = j+1
k = k+1
elif j >= len(R):
while i < len(L):
arr[k] = L[i]
i = i+1
k = k+1
print(arr,'\n')
return arr |
def path_join(p1: str, p2: str):
"""Helper to ensure there is only one '/' between two strings"""
return '{}/{}'.format(p1.rstrip('/'), p2.lstrip('/')) |
def is_numeric(obj):
"""
Checks to see object is numeric.
Args:
obj (object)
Returns:
Boolean
"""
try:
float(obj)
return True
except:
return False |
def triangle_number(nth):
"""Returns the nth triangular number"""
return nth * (nth + 1) / 2 |
def build_id(Z: int, A: int, state: str = "") -> int:
"""
Builds a canonical nuclide id from atomic number, atomic mass, and
and energy state.
Parameters
----------
Z : int
Atomic number.
A : int
Atomic mass.
state : str
energy state.
Returns
-------
int
Canonical nuclide id.
Examples
--------
>>> rd.utils.build_id(1,2)
10020000
>>> rd.utils.build_id(28,56,'m')
280560001
"""
if state != "":
if state == "m":
state_int = 1
elif state == "n":
state_int = 2
else:
raise ValueError(state + " is not a valid energy state.")
else:
state_int = 0
canonical_id = (Z * 10000000) + (A * 10000) + state_int
return canonical_id |
def add_with_saturation_bad(a, b, c=10):
"""
add_with_saturation add with saturation
"""
return min(a+b, c) |
def decode_number(value, float_factory): # type(string) -> (int)
"""
Decode string to integer and guess correct base
:param value: string input value
:return: integer
"""
value = value.strip()
if '.' in value:
return float_factory(value)
base = 10
if len(value) > 1 and value[1] == 'b': # bin coded
base = 2
value = value[2:]
if len(value) > 1 and value[1] == 'x': # hex coded
base = 16
value = value[2:]
return int(value, base) |
def find_duplicates(arr):
"""
find the duplicates in a list
:param arr: list to search
:return: list containing unique duplicate elements
"""
cache = {}
dupe = {}
for e in arr:
try:
cache[e] # raise an error if not found
dupe[e] = 1 # mark as a duplicate since we've previously seen one
except KeyError as err:
# the element has not been seen yet and is not a duplicate
cache[e] = 1
return list(dupe.keys()) |
def bearerAuthHeader(auth_string):
""" Build the bearer token authentication header of HTTP request.
: param auth_string: the authentication string containing the OAuth token.
: return: the 'Bearer token' authorization header.
"""
token = auth_string
auth_header = 'Bearer {0}'.format(token)
return auth_header |
def exercise_5(inputs): # DO NOT CHANGE THIS LINE
"""
This functions receives the input in the parameter 'inputs'.
Change the code, so that the output is sqaure of the given input.
Output should be the name of the class.
"""
output = inputs
return output # DO NOT CHANGE THIS LINE |
def rev_comp(seq: str) -> str:
"""
Generates the reverse complement of a sequence.
"""
comp = {
"A": "T",
"C": "G",
"G": "C",
"T": "A",
"B": "N",
"N": "N",
"R": "N",
"M": "N",
"Y": "N",
"S": "N",
"W": "N",
"K": "N",
"a": "t",
"c": "g",
"g": "c",
"t": "a",
"n": "n",
" ": "",
}
rev_seq = "".join(comp.get(base, base) for base in reversed(seq))
return rev_seq |
def toTupple(obj):
"""
Converts recursively to tuple
:param obj: numpy array, list structure, iterators, etc.
:return: tuple representation obj.
"""
try:
return tuple(map(toTupple, obj))
except TypeError:
return obj |
def lookup(name, namespace):
"""
Get a method or class from any imported module from its name.
Usage: lookup(functionName, globals())
"""
dots = name.count(".")
if dots > 0:
moduleName, objName = ".".join(name.split(".")[:-1]), name.split(".")[-1]
module = __import__(moduleName)
return getattr(module, objName)
else:
modules = [
obj
for obj in list(namespace.values())
if str(type(obj)) == "<type 'module'>"
]
options = [getattr(module, name) for module in modules if name in dir(module)]
options += [obj[1] for obj in list(namespace.items()) if obj[0] == name]
if len(options) == 1:
return options[0]
if len(options) > 1:
raise Exception("Name conflict for %s")
raise Exception("%s not found as a method or class" % name) |
def _amount(amount, asset='HBD'):
"""Return a steem-style amount string given a (numeric, asset-str)."""
assert asset == 'HBD', 'unhandled asset %s' % asset
return "%.3f HBD" % amount |
def format_ml_code(code):
"""Checks if the ML code ends with the string 'model = ' in its last line. Otherwise, it adds the string.
Args:
code (str): ML code to check
Returns:
str: code formatted
"""
return code[:code.rfind('\n')+1] + 'model = ' + code[code.rfind('\n')+1:] |
def find_common_left(strings):
"""
:param list[str] strings: list of strings we want to find a common left part in
:rtype: str
"""
length = min([len(s) for s in strings])
result = ''
for i in range(length):
if all([strings[0][i] == s[i] for s in strings[1:]]):
result += strings[0][i]
else:
break
return result |
def sao_anagramas(frase1, frase2):
"""
Funcao que identifica anagramas
:param frase1:
:param frase2:
:return: True se frase1 e frase2 sao anagramas e False caso contrario
"""
# eliminar espacos em branco
frase1 = frase1.replace(' ', '')
frase2 = frase2.replace(' ', '')
# comparar tamanho de cadeia com letras. Se for diferente, nao sao anagramas
if len(frase1) != len(frase2):
return False
# remover cada letra de frase1 de frase2, uma a uma da para fazer isso com
# dica: parar remover apenas uma lestra, utilize frase2.replate('a','',1)
for letra_de_1 in frase1:
frase2=frase2.replace(letra_de_1,'',1)
return len(frase2)==0 |
def mini_batch_weight(batch_idx: int, num_batches: int) -> float:
"""Calculates Minibatch Weight.
A formula for calculating the minibatch weight is described in
section 3.4 of the 'Weight Uncertainty in Neural Networks' paper.
The weighting decreases as the batch index increases, this is
because the the first few batches are influenced heavily by
the complexity cost.
Parameters
----------
batch_idx : int
Current batch index.
num_batches : int
Total number of batches.
Returns
-------
float
Current minibatch weight.
"""
return 2 ** (num_batches - batch_idx) / (2 ** num_batches - batch_idx) |
def unescape(s):
"""Excel save as tsv escaped all '"' chars - undo that!"""
if len(s) < 2:
return s
if s[0] == '"' and s[-1] == '"':
return s[1:-1].replace('""', '"')
return s |
def number_of_batches(total, sizeperc):
"""
:param data:
:param sizeperc: size of a batche expressed as a percentage of the total data
(between 0 and 1)
:return:
"""
if sizeperc > 1:
raise ValueError('sizeperc must be between 0 and 1')
if sizeperc < 0:
raise ValueError('sizeperc must be between 0 and 1')
b_size = max(int(total * sizeperc), 1)
return max(int(total/b_size), 1) |
def take(list_, index_list):
"""
Selects a subset of a list based on a list of indices.
This is similar to np.take, but pure python.
Args:
list_ (list): some indexable object
index_list (list, slice, int): some indexing object
Returns:
list or scalar: subset of the list
CommandLine:
python -m utool.util_list --test-take
SeeAlso:
ut.dict_take
ut.dict_subset
ut.none_take
ut.compress
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_list import * # NOQA
>>> list_ = [0, 1, 2, 3]
>>> index_list = [2, 0]
>>> result = take(list_, index_list)
>>> print(result)
[2, 0]
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_list import * # NOQA
>>> list_ = [0, 1, 2, 3]
>>> index = 2
>>> result = take(list_, index)
>>> print(result)
2
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_list import * # NOQA
>>> list_ = [0, 1, 2, 3]
>>> index = slice(1, None, 2)
>>> result = take(list_, index)
>>> print(result)
[1, 3]
"""
try:
return [list_[index] for index in index_list]
except TypeError:
return list_[index_list]
# if util_iter.isiterable(index_list):
# else: |
def safe_to_bool(input):
""" Safely convert user input to a boolean, throwing exception if not boolean or boolean-appropriate string
For flexibility, we allow case insensitive string matching to false/true values
If it's not a boolean or string that matches 'false' or 'true' when ignoring case, throws an exception """
if isinstance(input, bool):
return input
elif isinstance(input, str) and input.lower() == 'false':
return False
elif isinstance(input, str) and input.lower() == 'true':
return True
else:
raise TypeError(
'Input Object is not a boolean or string form of boolean!') |
def valid_distance(dist_m):
"""check that distance is:
* non-negative
* an integer
* devisable by 100
* above 3000
"""
if type(dist_m) != int:
return False
if 0 < dist_m < 3000:
return False
if dist_m % 100 != 0:
return False
return True |
def virtual_machine_names_to_container_names(configuration):
"""
convert virtual machine names to container names using configuration
Args:
configuration: user final configuration
Returns:
list of container name in array
"""
return [
"{0}_{1}".format(configuration[selected_module]["virtual_machine_name"], selected_module.rsplit("/")[1])
for selected_module in configuration
] |
def factor_size(value, factor):
"""
Factors the given thumbnail size. Understands both absolute dimensions
and percentages.
"""
if type(value) is int:
size = value * factor
return str(size) if size else ''
if value[-1] == '%':
value = int(value[:-1])
return '{0}%'.format(value * factor)
size = int(value) * factor
return str(size) if size else '' |
def maskify(cc):
"""return masked string"""
le = len(cc)
if le < 5:
return cc
else:
return "#" * (le - 4) + cc[le - 4:] |
def unescape_tokenized_text(s: str) -> str:
"""
Remove some escaped symbols introduces by moses tokenizer that are unneeded
"""
s = s.replace("'", "'")
s = s.replace(""", "\"")
s = s.replace("[", "[")
s = s.replace("]", "]")
return s |
def intersects(left, right):
"""
Returns true if two rectangles overlap
"""
(xl, yl, wl, hl) = left
(xr, yr, wr, hr) = right
return not ((xl + wl) < xr or xl > (xr + wr) or yl > (yr + hr) or (yl + hl) < yr) |
def ensure_iob2(tags):
"""Check that tags have a valid IOB format.
Tags in IOB1 format are converted to IOB2.
"""
tags = list(tags)
for i, tag in enumerate(tags):
if tag == 'O':
continue
split = tag.split('-')
if len(split) != 2 or split[0] not in ['I', 'B']:
return False
if split[0] == 'B':
continue
elif i == 0 or tags[i - 1] == 'O': # conversion IOB1 to IOB2
tags[i] = 'B' + tag[1:]
elif tags[i - 1][1:] == tag[1:]:
continue
else: # conversion IOB1 to IOB2
tags[i] = 'B' + tag[1:]
return tags |
def is_sorted(s: str) -> bool:
"""Is s a sorted string?"""
return list(s) == sorted(s) |
def collapse_list(l, empty = '.'):
"""
Concatena todas las cadenas de la lista en una sola lista
"""
collapsed = ''
for elt in l:
if elt == None:
collapsed = collapsed + empty
else:
collapsed = collapsed + elt
return collapsed |
def _gendesc(infiles):
"""
Generate a desc entity value.
Examples
--------
>>> _gendesc("f")
'coeff'
>>> _gendesc(list("ab"))
['coeff0', 'coeff1']
"""
if isinstance(infiles, (str, bytes)):
infiles = [infiles]
if len(infiles) == 1:
return "coeff"
return [f"coeff{i}" for i, _ in enumerate(infiles)] |
def number_of_differences(str1, str2):
"""
>>> str1 = str2 = 'ABABABABAB'
>>> assert(number_of_differences(str1, str2) == 0)
>>> str1, str2 = 'ABABABABAB', 'BABABABABA'
>>> assert(number_of_differences(str1, str2) == 10)
>>> str1, str2 = 'SOSSPSSQSSOR', 'SOSSOSSOSSOS'
>>> assert(number_of_differences(str1, str2) == 3)
"""
return sum(str1[i] != str2[i] for i in range(len(str1))) |
def general_calculation(table, targets):
"""Returns the sum of all targets unit values, if the id is unknown, add it as value 1"""
total = 0
for enemy in targets:
table.setdefault(enemy.type_id, 1)
total += table[enemy.type_id]
return total |
def compare_val(expected, got):
""" Compare values, throw exception if different. """
if expected != got:
raise Exception("expected '%s', got '%s'" % (expected, got))
return True |
def howmany(bit):
""" how many values are we going to pack? """
return 32
#number = (64+bit-1)/bit
#while((number * bit) % 8 != 0):
# number += 1
#return number |
def kernel_sigmas(n_kernels):
"""
get sigmas for each guassian kernel.
:param n_kernels: number of kernels (including exactmath.)
:param lamb:
:param use_exact:
:return: l_sigma, a list of simga
"""
bin_size = 2.0 / (n_kernels - 1)
l_sigma = [0.001] # for exact match. small variance -> exact match
if n_kernels == 1:
return l_sigma
l_sigma += [0.1] * (n_kernels - 1)
return l_sigma |
def line_segment_intersection(a, b, c, d):
"""Checks if two lines intersect.
Args:
a (list): Point 1 of Line 1
b (list): Point 2 of Line 1
c (list): Point 1 of Line 2
d (list): Point 2 of Line 2
Returns:
(bool) True if there is an intersection, otherwise False.
"""
c1 = (d[1] - a[1]) * (c[0] - a[0]) > (c[1] - a[1]) * (d[0] - a[0])
c2 = (d[1] - b[1]) * (c[0] - b[0]) > (c[1] - b[1]) * (d[0] - b[0])
c3 = (c[1] - a[1]) * (b[0] - a[0]) > (b[1] - a[1]) * (c[0] - a[0])
c4 = (d[1] - a[1]) * (b[0] - a[0]) > (b[1] - a[1]) * (d[0] - a[0])
return c1 != c2 and c3 != c4 |
def str2bool(v):
"""Function For converting unicode values to bool"""
print('Entering conversion function')
return v.lower() in ("yes", "true", "t", "1") |
def partition_names_by_comp(names):
"""Take an iterator of names and return a tuple of the form (namelist,
compmap) where namelist is a list of simple names (no dots) and compmap is
a dict with component names keyed to lists of variable names.
"""
simple = []
compmap = {}
for name in names:
parts = name.split('.', 1)
if len(parts) == 1:
simple.append(name)
else:
compmap.setdefault(parts[0], []).append(parts[1])
return (simple, compmap) |
def fix_desc(desc, units=None):
"""Clean up description column."""
full_desc = desc.strip()
if units and units != 'N/A':
if full_desc:
full_desc += ' (' + units + ')'
else:
full_desc = units
return full_desc |
def first_word(s):
"""Returns the first word in a string"""
return s.split()[0] |
def smallest_square(n: int):
"""
returns the smallest int square that correspond to a integer
example: smallest_square(65) returs 8 (8*8 = 64)
"""
n = abs(n)
i = 0
while i**2 <= n:
i += 1
if n - (i-1)**2 < i**2 - n:
return i - 1
else:
return i |
def convert_time(_time) -> str:
"""
Convert time into a years, hours, minute, seconds thing.
"""
# much better than the original one lol
# man I suck at docstrings lol
try:
times = {}
return_times = []
time_dict = {
"years": 31536000,
"months": 2628000,
"weeks": 604800,
"days": 86400,
"hours": 3600,
"minutes": 60,
"seconds": 1
}
for key, value in time_dict.items():
times[str(key)] = {}
times[str(key)]["value"] = int(_time // value)
_time %= value
for key, value in times.items():
if not value['value']:
continue
return_times.append("{0} {1}".format(value['value'], key))
return ' '.join(return_times) if return_times else '0 seconds'
except Exception:
return 'indefinitely' |
def lerp(x0, x1, t):
""" Linear interpolation """
return (1.0 - t) * x0 + t * x1 |
def channel_to_gauge_names(channel_names: list) -> list:
""" Replace the channel names with gauge locations. """
gauges = {"CH 1": "Main", "CH 2": "Prep", "CH 3": "Backing"}
return [gauges.get(ch, ch) for ch in channel_names] |
def explode_entity_name(entity_name: str) -> str:
""" replaces _ with space
"""
return entity_name.replace('_', ' ') |
def to_ascii(text):
"""
Force a string or other to ASCII text ignoring errors.
Parameters
-----------
text : any
Input to be converted to ASCII string
Returns
-----------
ascii : str
Input as an ASCII string
"""
if hasattr(text, 'encode'):
# case for existing strings
return text.encode(
'ascii', errors='ignore').decode('ascii')
elif hasattr(text, 'decode'):
# case for bytes
return text.decode('ascii', errors='ignore')
# otherwise just wrap as a string
return str(text) |
def dict_get_nested(d, key):
"""Get a (potentially nested) key from a dict-like."""
if '.' in key:
key, rest = key.split('.', 1)
if key not in d:
raise KeyError(key)
return dict_get_nested(d[key], rest)
else:
if key not in d:
raise KeyError(key)
return d[key] |
def is_printable(str1, codec='utf8'):
""" Returns True if s can be decoded using the specified codec """
try:
str1.decode(codec)
except UnicodeDecodeError:
return False
else:
return True |
def str_to_hexstr(s):
"""Convert a string into an hexadecimal string representation"""
if type(s) is not str:
s = chr(s)
return ":".join("{:02x}".format(ord(c)) for c in s) |
def solar_elevation_corrected_atm_refraction(
approx_atmospheric_refraction, solar_elevation_angle
):
"""Returns the Solar Elevation Corrected Atmospheric Refraction, with the
Approximate Atmospheric Refraction, approx_atmospheric_refraction and Solar
Elevation Angle, solar_elevation_angle."""
solar_elevation_corrected_atm_refraction = (
approx_atmospheric_refraction + solar_elevation_angle
)
return solar_elevation_corrected_atm_refraction |
def known_face_sentence(known_face_name):
"""
describe known person
Example:
Anuja is in front of you.
:param known_face_name: name of known person in the frame
:return: sentence descibing person
"""
return "%s in front of you" % (
known_face_name
) |
def break_words(stuff):
"""This function will break up words for us."""
words = stuff.split(" ")
return words |
def bigger_price(limit: int, data: list) -> list:
"""
TOP most expensive goods
"""
result = sorted(data, key=lambda k: k["price"], reverse=True)
return result[:limit] |
def _check_consistency_sizes(list_arrays) :
"""Check if all arrays in list have the same size
Parameters:
-----------
list_arrays: list of numpy arrays
Return
------
bool: True if all arrays are consistent, False otherwise.
"""
if len(list_arrays) == 0 :
return True
return all(myarray.size == list_arrays[0].size for myarray in list_arrays) |
def filter_folder_path(path):
""" This function will filter out \\..\\ or \\ at the begining. Also if path becomes empty, . will be used """
local_search_path = path
local_search_path = local_search_path.replace('\\..\\', '\\')
local_search_path = local_search_path.replace('/../', '/')
if local_search_path.startswith('/') or local_search_path.startswith('\\'):
local_search_path = local_search_path[1:]
if not local_search_path:
local_search_path = '.'
return local_search_path |
def _anharm_zpve_from_scaling(freq, scaled_freq):
""" Determine what the anharmonic ZPVE should be after scaling
"""
return (freq / 2.0) - (1.0 / 8.0) * (scaled_freq - freq) |
def _get_testm_tree(ind):
"""Generate a fake package with submodules
We need to increment index for different tests since otherwise e.g.
import_modules fails to import submodule if first import_module_from_file
imports that one
"""
return {
'dltestm%d' % ind: {
'__init__.py': '',
'dlsub1': {'__init__.py': 'var = 1'},
'dlsub2.py': 'var = 2'}
} |
def get_registry_for_env(environment: str) -> str:
"""
Mapping of container registry based on current environment
Args:
environment (str): Environment name
Returns:
str: Connect registry for current
"""
env_to_registry = {
"prod": "registry.connect.redhat.com",
"stage": "registry.connect.stage.redhat.com",
"qa": "registry.connect.qa.redhat.com",
"dev": "registry.connect.dev.redhat.com",
}
return env_to_registry[environment] |
def number_of_lottery_tickets_by_veet_units(veet_units):
"""
Function to calculate the number of lottery
tickets to assign for each participants based on veet units.
Args:
veet_units (int): count of veet units
"""
veet_units = int(veet_units)
max_ticket_to_assign = 15
veet_ticket_mapping = {1: 1, 2: 3, 3: 5}
veet_figures = list(veet_ticket_mapping.keys())
ticket_count = 0
while veet_units and veet_figures and ticket_count <= max_ticket_to_assign:
veet_unit = veet_figures.pop()
if veet_units >= veet_unit:
remaining_sale = veet_units // veet_unit
veet_units %= veet_unit
ticket_count += remaining_sale * veet_ticket_mapping[veet_unit]
return min(ticket_count, max_ticket_to_assign) |
def sort_012(arr):
"""
Given an input array consisting on only 0, 1, and 2, sort the array in a single traversal.
Args:
arr(list): List to be sorted
"""
if arr is None:
return arr
zero_index = 0
current_index = 0
two_index = len(arr) - 1
while current_index < len(arr) and current_index <= two_index:
if arr[current_index] == 0:
arr[current_index] = arr[zero_index]
arr[zero_index] = 0
zero_index += 1
current_index += 1
elif arr[current_index] == 2:
arr[current_index] = arr[two_index]
arr[two_index] = 2
two_index -= 1
else:
current_index += 1
return arr |
def get_file_list_based_on_suffix(file_list, suffix):
"""Get filenames ending with the given suffix."""
match_list = []
for fid in file_list:
fid = str(fid) # MW: To also allow fid to be of type pathlib.Path
if '~$' in fid:
# memory prefix when a file is open
continue
elif fid.endswith(suffix):
match_list.append(fid)
return match_list |
def remove_invalid_resource_name_charaters( # pylint: disable=invalid-name
str_to_process: str,
) -> str:
"""Remove characters that would be invalid in certain cases (e.g. DNS)."""
remove_these_chars = ["'", '"', "%", "$", "`"]
out_str = ""
for this_char in str_to_process:
if this_char in remove_these_chars:
continue
if this_char in [" ", "-"]:
out_str += "_"
continue
out_str += this_char
return out_str |
def utf8_decoder(s):
""" Decode the unicode as UTF-8 """
if s is None:
return None
return s.decode('utf-8') |
def observed_name(name):
"""Return `_name_observed`."""
return "_{}_observed".format(name) |
def remove_scale_offset(value, scale, offset):
"""Remove scale and offset from the given value"""
return (value * scale) - offset |
def touching(pos1, pos2):
""" tells you if two positions are touching """
if pos1[0] == pos2[0] and abs(pos1[1] - pos2[1]) == 1:
return True
if pos1[1] == pos2[1] and abs(pos1[0] - pos2[0]) == 1:
return True
return False |
def has_double_letters(text):
"""Check if text has any double letters"""
# Check if any two successive letters are the same,
# and return True if they are, of False if there aren't any.
for i in range(len(text) - 1):
if text[i] == text[i + 1]:
return True
return False |
def setlist(L):
""" list[alpha] -> set[alpha] """
# E : set[alpha]
E = set()
# e : alpha
for e in L:
E.add(e)
return E |
def get_data(payload_for_geo):
""" Returns the full timeseries data as from a DataCommons API payload.
Args:
payload_for_geo -> The payload from a get_stats call for a
particular dcid.
Returns:
The full timeseries data available for that dcid.
"""
if not payload_for_geo:
return {}
time_series = payload_for_geo.get('data')
if not time_series:
return {}
return time_series |
def http_error_handler(error):
"""Default error handler for HTTP exceptions"""
return ({"message": str(error)}, getattr(error, "code", 500)) |
def longest_increasing_subsequence(X):
"""Returns the Longest Increasing Subsequence in the Given List/Array"""
N = len(X)
P = [0] * N
M = [0] * (N+1)
L = 0
for i in range(N):
lo = 1
hi = L
while lo <= hi:
mid = (lo+hi)//2
if (X[M[mid]] < X[i]):
lo = mid+1
else:
hi = mid-1
newL = lo
P[i] = M[newL-1]
M[newL] = i
if (newL > L):
L = newL
S = []
k = M[L]
for i in range(L-1, -1, -1):
S.append(X[k])
k = P[k]
return S[::-1] |
def _package_variables(variables, check_type):
""" Removes token and customer id and adds check type to dict data
Removes the token from the dictionary that will be sent to NodePing
in JSON format as well as the customer id since these aren't a part
of the check data. Also adds the check type.
:type variables: dict
:param variables: Parameters that were passed in to the previous function
:type check_type: string
:param check_type: The type of NodePing check that will be created
:return: Variables that will be posted to NodePing
:rtype: dict
"""
variables.update({'type': check_type})
variables.pop('token')
variables.pop('customerid')
variables.pop('kwargs')
return variables |
def _check_preferred_compat_mode(preferred_mode, supported_modes):
"""Checks whether the LPAR's preferred mode is supported
:param preferred_mode: preferred compat mode of the LPAR
:param supported_modes: proc compat modes supported by the dest host
:returns: True if the preferred mode is supported and False otherwise
"""
if preferred_mode == 'default':
return True
return preferred_mode in supported_modes |
def lerp1d(a: float, b: float, r: float) -> float:
"""Returns a point interpolated from a to b, at r."""
return a + (b - a) * r |
def do_steps_help(cls_list):
"""Print out the help for the given steps classes."""
for cls in cls_list:
print(cls.help())
return 0 |
def replace_nones_in_dict(target, replace_value):
"""Recursively replaces Nones in a dictionary with the given value."""
for k in target:
if target[k] is None:
target[k] = replace_value
elif type(target[k]) is list:
result = []
for e in target[k]:
if type(e) is dict:
result.append(replace_nones_in_dict(e, replace_value))
else:
if e is None:
result.append(replace_value)
else:
result.append(e)
target[k] = result
elif type(target[k]) is dict:
replace_nones_in_dict(target[k], replace_value)
return target |
def range_spec(x, y):
""" range_spec """
for _ in range(1, 10, 3):
x = x + 1
return x + y |
def compare_config(module, kwarg_exist, kwarg_end):
"""compare config between exist and end"""
dic_command = {'isSupportPrmpt': 'lacp preempt enable',
'rcvTimeoutType': 'lacp timeout', # lacp timeout fast user-defined 23
'fastTimeoutUserDefinedValue': 'lacp timeout user-defined',
'selectPortStd': 'lacp select',
'promptDelay': 'lacp preempt delay',
'maxActiveNum': 'lacp max active-linknumber',
'collectMaxDelay': 'lacp collector delay',
'mixRateEnable': 'lacp mixed-rate link enable',
'dampStaFlapEn': 'lacp dampening state-flapping',
'dampUnexpMacEn': 'lacp dampening unexpected-mac disable',
'trunkSysMac': 'lacp system-id',
'trunkPortIdExt': 'lacp port-id-extension enable',
'portPriority': 'lacp priority', # interface 10GE1/0/1
'lacpMlagPriority': 'lacp m-lag priority',
'lacpMlagSysId': 'lacp m-lag system-id',
'priority': 'lacp priority'
}
rlist = list()
exist = set(kwarg_exist.keys())
end = set(kwarg_end.keys())
undo = exist - end
add = end - exist
update = end & exist
for key in undo:
if key in dic_command:
rlist.append('undo ' + dic_command[key])
for key in add:
if key in dic_command:
rlist.append(dic_command[key] + ' ' + kwarg_end[key])
for key in update:
if kwarg_exist[key] != kwarg_end[key] and key in dic_command:
if kwarg_exist[key] == 'true' and kwarg_end[key] == 'false':
rlist.append('undo ' + dic_command[key])
elif kwarg_exist[key] == 'false' and kwarg_end[key] == 'true':
rlist.append(dic_command[key])
else:
rlist.append(dic_command[key] + ' ' + kwarg_end[key].lower())
return rlist |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.