content
stringlengths 42
6.51k
|
---|
def get_facets_values(facet, header):
"""extracts facets values from the contents attribute"""
values = {}
if type(facet) is str:
values.update({header[0]: facet})
elif type(facet) is list:
values.update({k:v for k,v in zip(header, facet)})
return values
|
def _prepare_response_data(message, data=None):
"""Prepare response output.
Returns a simple dict containing a key `message` and optionally a key `data`.
"""
output = {"message": message}
if data is not None:
output["data"] = data
return output
|
def LCS(value: str) -> bytes:
"""
pack a string into a LCS
"""
return b'\x84' + str.encode(value) + b'\x00'
|
def reverse_complement(seq):
"""
Returns reverse complement of seq, with
any non-ACTG characters replaced with Ns
"""
transform = {'A': 'T',
'T': 'A',
'C': 'G',
'G': 'C',
'N': 'N'}
try:
comp = [transform[e] for e in seq]
except KeyError: # non-ATCGN characters in seq
seq = [e if e in "ACTGN" else "N" for e in seq]
comp = [transform[e] for e in seq]
rev_comp = comp[::-1]
rev_comp_string = ''.join(rev_comp)
return rev_comp_string
|
def params_schedule_fn_constant_09_01(outside_information):
"""
In this preliminary version, the outside information is ignored
"""
mdp_default_gen_params = {
"inner_shape": (7, 5),
"prop_empty": 0.9,
"prop_feats": 0.1,
"start_all_orders": [
{"ingredients": ["onion", "onion", "onion"]}
],
"display": False,
"rew_shaping_params": None
}
return mdp_default_gen_params
|
def initialize_tensor_board(dimensions, value):
"""
Initializes board with 0s.
Parameters:
dimensions (tuple): dimensions of the board
Returns: an nD board
"""
# Base case
if len(dimensions) == 1:
return [value for i in range(dimensions[0])]
# Iterative case
return [initialize_tensor_board(dimensions[1:], value) for j in range(dimensions[0])]
|
def create_callback_data(*args):
"""Crea una stringa a partire dai vlaori (arbitrari) in entrata, che verranno separati da ;"""
return ";".join(str(i) for i in args)
|
def fun1(n):
"""
sum up to n using recursion
:param n:
:return:
"""
if n == 0:
return 0
else:
return n + fun1(n - 1)
|
def readable_timedelta(days):
"""
Return a string of the number of weeks and days included in days.
Arguments:
days {int} -- number of days to convert
Returns:
{str} -- "{} week(s) and {} day(s)"
"""
# insert your docstring here
weeks = days // 7
remainder = days % 7
return "{} week(s) and {} day(s)".format(weeks, remainder)
|
def dereference_dict(name:str):
"""
Function to get dictionary to dereference
output labels as numbers (from the model)
to output labels as names.
Need name of dataset of which to dereference
"""
if name == "kauto5cls":
kauto_dict = {
0 : "woosan-song",
1 : "comsnip-winnow",
2 : "whimbr1-song",
3 : "eugplo-call",
4 : "eugplo-song"
}
return kauto_dict
|
def encode_proto_bytes(val: str) -> bytes:
""" Encodes a proto string into latin1 bytes """
return val.encode('latin1')
|
def sea_sick(sea):
"""getin sick."""
sick = 0
for i in range(len(sea) - 1):
if sea[i] != sea[i + 1]:
sick += 1
if sick > len(sea) * .2:
return "Throw Up"
return "No Problem"
|
def bdd_vars(bdd_vars, variables, skin, data_base_path):
""" Inject bdd_vars so they becomes available in play
fixture """
bdd_vars['data_base_path'] = data_base_path
return bdd_vars
|
def list_of_words(text):
"""Convert paragraph of " " and "\n" delimited words into a list of words"""
lines = text.strip().split("\n")
single_line = " ".join(lines)
words = single_line.split(" ")
return words
|
def subtract(a, b):
""" Subtracts b from a. """
return [a[0] - b[0], a[1] - b[1]]
|
def remove_extra_zeroes(number: str) -> str:
"""
Remove all zeroes from the end of the string
:param number:
:return:
"""
index = None
for i in range(-1, len(number) * -1, -1):
if number[i] == '0':
index = i
else:
break
if index is not None:
return number[0:index]
return number
|
def is_reserved_name(name):
"""Tests if name is reserved
Names beginning with 'xml' are reserved for future standardization"""
if name:
return name[:3].lower() == 'xml'
else:
return False
|
def gen_harmonies(n_streams, base_freq=200, ratio=[1,4,5,6]):
"""Generate harmonies for as many streams as needed. Obviously limited by range of reasonable frequencies.
Used during weights sonification.
Args:
base_freq: Basic frequency to build on.
ratio: List with ratios for frequencies. Should start with 1.
n_streams: Number of streams to build the harmonies for.
"""
mul_base = 1
n_ratio = len(ratio)-1
all_harms = []
for stream in range(n_streams+1):
#add new octave harmonies when more streams are needed
if stream % n_ratio == 0:
#adjust frequency to be multiple of base frequency
freq = base_freq * mul_base
mul_base += 1
#generate harmonies
harms = [freq * ratio[i] / ratio[1] for i in range(1, len(ratio))]
#print(harms)
all_harms += harms
#return as many streams as needed
return all_harms[:n_streams]
|
def _extract_problem_info(source):
"""Split the logpath to identify test problem, data set, etc.
Args:
source (Cockpit or str): ``Cockpit`` instance, or string containing the
path to a .json log produced with ``Cockpit.write``, where
information will be fetched from.
Returns:
[dict]: Dictioniary of logpath, testproblem, optimizer, etc.
"""
if isinstance(source, str):
# Split logpath if possible
try:
dicty = {
"logpath": source + ".json",
"optimizer": source.split("/")[-3],
"testproblem": source.split("/")[-4],
"dataset": source.split("/")[-4].split("_", 1)[0],
"model": source.split("/")[-4].split("_", 1)[1],
}
except Exception:
dicty = {
"logpath": source + ".json",
"optimizer": "",
"testproblem": "",
"dataset": "",
"model": "",
}
else:
# Source is Cockpit instance
dicty = {
"logpath": "",
"optimizer": source._optimizer_name,
"testproblem": "",
"dataset": "",
"model": "",
}
return dicty
|
def selection_sort(arr):
""" Selection Sort
Complexity: O(n^2)
"""
for i in range(len(arr)):
minimum = i
for j in range(i+1, len(arr)):
# "Select" the correct value
if arr[j] < arr[minimum]:
minimum = j
# Using a pythonic swap
arr[minimum], arr[i] = arr[i], arr[minimum]
return arr
|
def TransformIf(r, expr):
"""Disables the projection key if the flag name filter expr is false.
Args:
r: A JSON-serializable object.
expr: A command flag filter name expression. See `gcloud topic filters` for
details on filter expressions. The expression variables are flag names
without the leading *--* prefix and dashes replaced by underscores.
Example:
The "table(name, value.if(NOT short_format))" format will list a value
column if the *--short-format* command line flag is not specified.
Returns:
r
"""
_ = expr
return r
|
def spaced_str(input_list):
"""takes a list containing floats and creates a string of its entries such that each float value is separated
by a space. such a string is often used in urdfs - helper function for urdf creation
"""
# todo: nicer doc and comment
assert isinstance(input_list, list), "input_list has to be a list"
string = ""
for elem in input_list:
string = string + str(elem) + " "
# remove last space
string = string[:-1]
return string
|
def count_keys(n):
"""Generate outcome bitstrings for n-qubits.
Args:
n (int): the number of qubits.
Returns:
list: A list of bitstrings ordered as follows:
Example: n=2 returns ['00', '01', '10', '11'].
"""
return [bin(j)[2:].zfill(n) for j in range(2**n)]
|
def checkIfErrorJSONResponse(retval):
"""
Checks if the JSON returned is of the calss ErrorJSONReponse
"""
return retval.__class__.__name__ == "ErrorJSONResponse"
|
def get_patterns_per_repository(repo):
"""
Get all unique patterns in the repository.
Keyword arguments:
repo -- object containing properties of the repo
"""
dynamic_count = 0
if 'DYNAMIC-PATTERN' in repo['uniquePatterns']:
dynamic_count += repo['uniquePatterns']['DYNAMIC-PATTERN']
return len(repo['uniquePatterns']) + dynamic_count
|
def rev_seq(nuc, nuc_type='dna'):
"""Return the complement of each nucleotide"""
if nuc == 'A':
if nuc_type == 'rna':
return 'U'
elif nuc_type == 'dna':
return 'T'
else:
return 'T'
elif nuc == 'T':
return 'A'
elif nuc == 'C':
return 'G'
elif nuc == 'U':
return 'A'
else:
return 'C'
|
def set_cover(universe, subsets):
"""Find a family of subsets that covers the universal set"""
elements = set(e for s in subsets for e in s)
# Check the subsets cover the universe
if elements != universe:
return None
covered = set()
cover = []
# Greedily add the subsets with the most uncovered points
while covered != universe:
subset = max(subsets, key=lambda s: len(s - covered))
cover.append(subset)
covered |= subset
return cover
|
def process_hits(page, args, dbname):
""" Processes each hit in a scroll search and proposes changes
in the array returned """
changes = []
if 'hits' in page and 'hits' in page['hits']:
for hit in page['hits']['hits']:
doc = hit['_id']
body = {}
if args.obfuscate:
body['body'] = hit['_source']['body'].replace(args.obfuscate, "...")
body['subject'] = hit['_source']['subject'].replace(args.obfuscate, "...")
body['from'] = hit['_source']['from'].replace(args.obfuscate, "...")
if args.targetLID:
body['list_raw'] = args.targetLID
body['list'] = args.targetLID
if args.makePrivate:
body['private'] = True
if args.makePublic:
body['private'] = False
if not args.dryrun:
changes.append({
'_op_type': 'delete' if args.deleteEmails else 'update',
'_index': dbname,
'_type': 'mbox',
'_id': doc,
'doc': body
})
else:
changes.append({}) # Empty action for counting if dryrun, so we never accidentally run it.
return changes
|
def _gen_parabola(phase: float, start: float, mid: float, end: float) -> float:
"""Gets a point on a parabola y = a x^2 + b x + c.
The Parabola is determined by three points (0, start), (0.5, mid), (1, end) in
the plane.
Args:
phase: Normalized to [0, 1]. A point on the x-axis of the parabola.
start: The y value at x == 0.
mid: The y value at x == 0.5.
end: The y value at x == 1.
Returns:
The y value at x == phase.
"""
mid_phase = 0.5
delta_1 = mid - start
delta_2 = end - start
delta_3 = mid_phase ** 2 - mid_phase
coef_a = (delta_1 - delta_2 * mid_phase) / delta_3
coef_b = (delta_2 * mid_phase ** 2 - delta_1) / delta_3
coef_c = start
return coef_a * phase ** 2 + coef_b * phase + coef_c
|
def dec_hex(getal):
"""
convert dec characters to their hex representative
"""
return bytes([int(getal)])
|
def split_line(line, parsers, sep=" "):
"""Split a line into pieces and parse the strings."""
parts = [part for part in line.split(sep) if part]
values = [parser(part) for parser, part in zip(parsers, parts)]
return values if len(values) > 1 else values[0]
|
def deep_copy(to_copy, rows, cols):
"""Need i say?
"""
clean_mtx = []
for i in range(rows):
row = []
for j in range(cols):
row.append(to_copy[i][j])
clean_mtx.append(row)
return clean_mtx
|
def binary_search_return_first_invariant(arr, low, high, key):
"""
maintain invariant of arr[low] < key <= arr[high]
"""
if arr[low] >= key:
return low
if arr[high] < key:
return high + 1
while low + 1 < high:
mid = (low + high) // 2
if arr[mid] < key:
low = mid
else:
high = mid
# in the end low + 1 = high and arr[low] < mid <= arr[high] => return high
return high
|
def is_img_shape(shape):
"""Whether a shape is from an image."""
try:
return len(shape) == 3 and (shape[-3] in [1, 3])
except TypeError:
return False
|
def disabling_button(n_clicks):
"""
Disabling the button after its being clicked once
"""
if n_clicks >= 1:
return {'display':"none"}
|
def isascii(w):
"""Is all characters in w are ascii characters"""
try:
w.encode('ascii')
return True
except UnicodeError:
return False
|
def to_list(*args):
"""
Input:
args - variable number of integers represented as strings, e.g. to_list("15353", "025")
Output:
lst - a Python array of lists of strings, e.g. [[1,5,3,5,3],[0,2,5]]
"""
lst = []
for string in args:
lst.append([int(digit) for digit in string])
return lst
|
def get_min_remaining_length(traces):
"""
Minimum remaining length (for sequential, parallel cut detection)
Parameters
--------------
traces
Traces
"""
min_len_traces = []
min_rem_length = []
for x in traces:
if len(x) == 0:
min_len_traces.append(0)
else:
min_len_traces.append(len(x[0]))
min_rem_length.append(0)
min_rem_length[-1] = 0
min_rem_length[-2] = min_len_traces[-1]
j = len(traces) - 3
while j >= 0:
min_rem_length[j] = min_rem_length[j + 1] + min_len_traces[j + 1]
j = j - 1
return min_len_traces, min_rem_length
|
def targets_to_labels(targets):
"""Returns a set of label strings for the given targets."""
return set([str(target.label) for target in targets])
|
def map_getattr(classInstance, classFunc, *args):
"""
Take an instance of a class and a function name as a string.
Execute class.function and return result
"""
return getattr(classInstance, classFunc)(*args)
|
def count_common_prefix(str_seq, prefix):
""" Take any sequence of strings, str_seq, and return the count of
element strings that start with the given prefix.
>>> count_common_prefix(('ab', 'ac', 'ad'), 'a')
3
>>> count_common_prefix(['able', 'baker', 'adam', 'ability'], 'ab')
2
>>> count_common_prefix([], 'a')
0
>>> count_common_prefix(['a', 'a', 'ab'], 'a')
3
>>> count_common_prefix(['a', 'a', 'ab'], '')
3
"""
# Hint: use string method str.startswith
count = 0 # initialize to 0
for elem in str_seq: # iterate over all elements in str_seq
if elem.startswith(prefix):
count += 1 # increment count if elem starts with the prefix
return count
|
def Dedup(seq):
"""Return a sequence in the same order, but with duplicates removed."""
seen = set()
result = []
for s in seq:
if s not in seen:
result.append(s)
seen.add(s)
return result
|
def n_palavras_diferentes(lista_palavras):
"""
Essa funcao recebe uma lista de palavras e devolve o numero de palavras
diferentes utilizadas.
"""
freq = dict()
for palavra in lista_palavras:
p = palavra.lower()
if p in freq:
freq[p] += 1
else:
freq[p] = 1
return len(freq)
|
def scale_simulation_fit(simulated_value, actual_value, number_individuals, total_individuals):
"""
Calculates goodness of fit for the provided values, and scales based on the total number of individuals that exist.
The calculation is 1 - (abs(x - y)/max(x, y)) * n/n_tot for x, y simulated and actual values, n, n_tot for metric
and total
number of individuals.
:param simulated_value: the simulated value of the metric
:param actual_value: the actual value of the metric
:param number_individuals: the number of individuals this metric relates to
:param total_individuals: the total number of individuals across all sites for this metric
:return: the scaled fit value
"""
return (
(1 - (abs(simulated_value - actual_value)) / max(simulated_value, actual_value))
* number_individuals
/ total_individuals
)
|
def config_section_data():
"""Produce the default configuration section for app.config,
when called by `resilient-circuits config [-c|-u]`
"""
config_data = u"""[fn_ip_void]
ipvoid_base_url=https://endpoint.apivoid.com
ipvoid_api_key=<your-api-key>
"""
return config_data
|
def bounce_out(t):
"""Bounce out. Amplitude of bounce decreases."""
if t < 0.36363636363636365:
return 7.5625 * t * t
elif t < 0.7272727272727273:
return 7.5625 * (t - 0.5454545454545454) ** 2 + 0.75
elif t < 0.9090909090909091:
return 7.5625 * (t - 0.8181818181818182) ** 2 + 0.9375
else:
return 7.5625 * (t - 0.9545454545454546) ** 2 + 0.984375
|
def _sort_key_max_confidence(sample):
"""Samples sort key by the max. confidence."""
max_confidence = float("-inf")
for inference in sample["inferences"]:
if inference["confidence"] > max_confidence:
max_confidence = inference["confidence"]
return max_confidence
|
def is_same_len(*args):
"""
>>> is_same_len(1, 'aaa')
Traceback (most recent call last):
...
TypeError: object of type 'int' has no len()
>>> is_same_len([1], ['aaa'])
True
>>> is_same_len([1, 'b'], ['aaa', 222])
True
>>> is_same_len([1, 'b', 3], ['aaa', 222, 'ccc'])
True
>>> is_same_len([], ['aaa'])
False
>>> is_same_len([1], ['aaa', 222])
False
>>> is_same_len([1, 'b'], ['aaa'])
False
>>> is_same_len([1], ['aaa'], [111])
True
>>> is_same_len([1, 'b'], ['aaa', 222], [111, 'BBB'])
True
>>> is_same_len([1, 'b', 3], ['aaa', 222, 'ccc'], [111, 'BBB', 333])
True
>>> is_same_len([], ['aaa'], [111])
False
>>> is_same_len([1], ['aaa', 222], [111, 'BBB'])
False
>>> is_same_len([1, 'b'], ['aaa'], [111, 'BBB'])
False
>>> is_same_len([1, 'b'], None)
Traceback (most recent call last):
...
TypeError: object of type 'NoneType' has no len()
>>> is_same_len(None, ['aaa'])
Traceback (most recent call last):
...
TypeError: object of type 'NoneType' has no len()
>>> is_same_len(None, None)
Traceback (most recent call last):
...
TypeError: object of type 'NoneType' has no len()
>>> is_same_len([1, 'b'], None, ['aaa', 222])
Traceback (most recent call last):
...
TypeError: object of type 'NoneType' has no len()
>>> is_same_len(None, ['aaa'], [111])
Traceback (most recent call last):
...
TypeError: object of type 'NoneType' has no len()
>>> is_same_len(None, None, [111, 'BBB'])
Traceback (most recent call last):
...
TypeError: object of type 'NoneType' has no len()
>>> is_same_len(None, None, None)
Traceback (most recent call last):
...
TypeError: object of type 'NoneType' has no len()
>>> is_same_len([1], None, ['aaa', 222])
Traceback (most recent call last):
...
TypeError: object of type 'NoneType' has no len()
>>> is_same_len(None, ['aaa'], [])
Traceback (most recent call last):
...
TypeError: object of type 'NoneType' has no len()
>>> is_same_len(None, ['aaa'], [111, 'BBB'])
Traceback (most recent call last):
...
TypeError: object of type 'NoneType' has no len()
"""
if len(args) == 0: return True
len0 = len(args[0])
return all([len(x) == len0 for x in args])
|
def zscore_den(observed, expected, N, denom):
"""
Computes zscore with precomputed denominator.
:param observed:
:param expected:
:param N:
:param denom:
:return:
"""
x = float(observed - expected) / float(N)
return x / denom
|
def config_get(from_,what_):
""" Returns value what_ from_ """
from_=from_.replace(' ','')
d = from_[from_.index(what_+'=')+1+len(what_):].split('\n')[0]
return d
|
def check_for_winner(board):
"""
Searches through the boards and returns the id of the board if anyone has a full row or a full column.
If no winner were found, it returns -1.
"""
# First check if someone has a full row
count = 5
for j, row in enumerate(board):
for k, n in enumerate(row):
if n is True:
count-= 1
if count < 1:
return True
else:
count = 5
# If not, check if anyone has a full collumn
count = 5
for j in range(5):
for k in range(5):
if board[k][j] is True:
count -=1
if count < 1:
return True
else:
count = 5
# If no winner was found, return -1
return False
|
def is_wind(text: str) -> bool:
"""Returns True if the text is likely a normal wind element"""
# Ignore wind shear
if text.startswith("WS"):
return False
# 09010KT, 09010G15KT
if len(text) > 4:
for ending in ("KT", "KTS", "MPS", "KMH"):
if text.endswith(ending):
return True
# 09010 09010G15 VRB10
if not (
len(text) == 5
or (len(text) >= 8 and text.find("G") != -1)
and text.find("/") == -1
):
return False
return text[:5].isdigit() or (text.startswith("VRB") and text[3:5].isdigit())
|
def flatten(l):
"""
Flattens the list l.
:param l: list
:return: flattened list.
"""
return [item for sublist in l for item in sublist]
|
def boolean_type(text):
"""Custom Parse Type to parse a boolean value.
The same values are parsed as YAML does:
http://yaml.org/type/bool.html
Plus 0 and 1
"""
text = text.lower()
return text == "1" or text.startswith("y") or text == "true" or text == "on"
|
def check_required_modules(required_modules, verbose=True):
""" Function checks for Python modules which should be "importable"
before test suite can be used.
@return returns True if all modules are installed already
"""
import imp
not_installed_modules = []
for module_name in required_modules:
try:
imp.find_module(module_name)
except ImportError:
# We also test against a rare case: module is an egg file
try:
__import__(module_name)
except ImportError as exc:
not_installed_modules.append(module_name)
if verbose:
print("Error: %s" % exc)
if verbose:
if not_installed_modules:
print("Warning: Module(s) %s not installed. Please install "
"required module(s) before using this script."
% (', '.join(not_installed_modules)))
if not_installed_modules:
return False
else:
return True
|
def int_of_string_opt(s, base=10):
"""
Convert string to integer without raising exceptions
:param s: integer string
:param base: numbering base
:return: integer value or None on failure
"""
try: return int(s, base)
except: return None
|
def stringifyRequestArgs(args):
"""Turn the given HTTP request arguments from bytes to str.
:param dict args: A dictionary of request arguments.
:rtype: dict
:returns: A dictionary of request arguments.
"""
# Convert all key/value pairs from bytes to str.
str_args = {}
for arg, values in args.items():
arg = arg if isinstance(arg, str) else arg.decode("utf-8")
values = [value.decode("utf-8") if isinstance(value, bytes)
else value for value in values]
str_args[arg] = values
return str_args
|
def _text(x: float, y: float, text: str, fontsize: int = 14):
"""Draw SVG <text> text."""
return f'<text x="{x}" y="{y}" dominant-baseline="middle" ' \
f'text-anchor="middle" font-size="{fontsize}px">{text}</text>'
|
def century(year):
"""
Given a year, return the century it is in
:param year:
:return:
"""
if year % 100 == 0:
return year // 100
return (year // 100) + 1
|
def get_figshare_project_data(initial_data, headers, resources):
"""
Get all top level figshare projects.
Parameters
----------
initial_data: list
List of all top level projects
headers: dict
The authorization header that Figshare expects
resources: list
A list of resources to append to
Returns
-------
A list of resources.
"""
for project in initial_data:
resources.append({
"kind": "container",
"kind_name": "project",
"container": None,
"id": project['id'],
"title": project['title']
})
return resources
|
def good_str(x):
"""Returns a safe (escaped) version of the string.
str -- The string"""
return repr(str(x))[1:-1]
|
def to_minutes(s):
"""
Convert a time specification on the form hh:mm to minutes.
>>> to_minutes('8:05')
485
"""
h, m = s.split(':')
return int(h) * 60 + int(m)
|
def strip_illegal_characters(name):
"""
Strip characters that the APIC deems are illegal
:param name: String to remove the illegal characters
:return: String with the illegal characters removed
"""
chars_all_good = True
for character in name:
if character.isalnum() or character in ('_', '.', ':', '-'):
continue
chars_all_good = False
name = name.replace(character, '')
if chars_all_good:
return name
return strip_illegal_characters(name)
|
def col_labels(matrix_dim):
"""
Return the column-stacked-matrix-basis labels based on a matrix dimension.
Parameters
----------
matrix_dim : int
The matrix dimension of the basis to generate labels for (the
number of rows or columns in a matrix).
Returns
-------
list of strs
"""
if matrix_dim == 0: return []
if matrix_dim == 1: return [''] # special case - use empty label instead of "I"
return ["(%d,%d)" % (j, i) for i in range(matrix_dim) for j in range(matrix_dim)]
|
def _tuple_slice(tup, start, end):
"""get sliced tuple from start and end."""
return tup[start:end]
|
def flatten_nested_lists(L):
""" Each element of L could be a list or any object other than a list. This function
returns a list of non-list objects, where the internal lists or lists_of_lists
have been 'flattened'.
"""
ret = []
for elem in L:
if isinstance(elem, list):
ret.extend(flatten_nested_lists(elem))
else:
ret.append(elem)
return ret
|
def selection_collision(selections, poolsize):
"""
Calculate the probability that two random values selected from an arbitrary
sized pool of unique values will be equal. This is commonly known as the
"Birthday Problem".
:param int selections: The number of random selections.
:param int poolsize: The number of unique random values in the pool to choose from.
:rtype: float
:return: The chance that a collision will occur as a percentage.
"""
# requirments = sys
probability = 100.0
poolsize = float(poolsize)
for i in range(selections):
probability = probability * (poolsize - i) / poolsize
probability = (100.0 - probability)
return probability
|
def get_values_multicol(columns_to_query_lst, columns_to_update_lst, query_values_dict_lst ):
"""
makes flat list for update values.
:param columns_to_query_lst:
:param columns_to_update_lst:
:param query_values_dict_lst:
:return values: list of user-given values for multirow query with first params to
query and then params to update. E.g ['col2query1','col2update1','col2query2','col2update2']
"""
values = []
for dict_row in query_values_dict_lst:
for col in columns_to_query_lst:
values.append(dict_row['where'][col])
for col in columns_to_update_lst:
values.append(dict_row['update'][col])
return values
|
def generic_layer_dict_maker() -> dict:
"""Just a function that puts all of the standard layer definitions and
their corresponding allowed amino acids into a convenient dictionary.
As of versions > 0.7.0, made layers more restrictive. Old definitions
for helices were:
"core AND helix": 'AFILVWYNQHM',
"boundary AND helix_start": 'ADEHIKLNPQRSTVY',
"boundary AND helix": 'ADEHIKLNQRSTVYM'
As of versions > 0.8.0, made layers slightly less restrictive. Old
definitions for helices were:
"core AND helix": 'AILVYNQHM',
"boundary AND helix_start": 'ADEHKNPQRST',
"boundary AND helix": 'ADEHKNQRST'
Args:
None
Returns:
layer_dict (dict): The dict mapping standard layer definitions to
their allowed amino acids.
"""
layer_dict = {"core AND helix_start": 'AFILVWYNQSTHP',
"core AND helix": 'AFILVYNQHM',
"core AND loop": 'AFGILPVWYDENQSTHM',
"core AND sheet": 'FILVWYDENQSTH',
"boundary AND helix_start": 'ADEHIKLNPQRSTV',
"boundary AND helix": 'ADEHIKLNQRSTVM',
"boundary AND loop": 'ADEFGHIKLNPQRSTVY',
"boundary AND sheet": 'DEFHIKLNQRSTVY',
"surface AND helix_start": 'DEHKPQR',
"surface AND helix": 'EHKQR',
"surface AND loop": 'DEGHKNPQRST',
"surface AND sheet": 'EHKNQRST',
"helix_cap": 'DNSTP'}
return layer_dict
|
def versionString(version):
"""Create version string."""
ver = [str(v) for v in version]
numbers, rest = ver[:2 if ver[2] == '0' else 3], ver[3:]
return '.'.join(numbers) + '-'.join(rest)
|
def adaptive_name(template, host, index):
"""
A helper function for interface/bridge name calculation.
Since the name of interface must be less than 15 bytes. This util is to adjust the template automatically
according to the length of vmhost name and port index. The leading characters (inje, muxy, mbr) will be shorten if necessary
e.g.
port 21 on vms7-6 -> inje-vms7-6-21
port 121 on vms21-1 -> inj-vms21-1-121
port 121 on vms121-1 -> in-vms121-1-121
"""
MAX_LEN = 15
host_index_str = '-%s-%d' % (host, int(index))
leading_len = MAX_LEN - len(host_index_str)
leading_characters = template.split('-')[0][:leading_len]
rendered_name = leading_characters + host_index_str
return rendered_name
|
def num_to_one(x: int) -> int:
"""Returns +1 or -1, depending on whether parm is +ve or -ve."""
if x < 0:
return -1
else:
return 1
|
def chop_at_now(ttlist):
"""Chop the list of ttvalues at now.
"""
ttlist = list(ttlist)
if not ttlist:
return []
first = ttlist[0]
now = first.__class__()
return [ttval for ttval in ttlist if ttval <= now]
|
def convert_types(input_dict):
"""Convert types of values from specified JSON file."""
# Eval `type` and `element_type` first:
for key in input_dict.keys():
if input_dict[key]['type'] == 'tuple':
input_dict[key]['type'] = 'list'
for el_key in ['type', 'element_type']:
if el_key in input_dict[key].keys():
input_dict[key][el_key] = eval(input_dict[key][el_key])
# Convert values:
for key in input_dict.keys():
if 'default' in input_dict[key].keys() and input_dict[key]['default'] is not None:
if 'element_type' in input_dict[key].keys():
if input_dict[key]['type'] == list:
for i in range(len(input_dict[key]['default'])):
input_dict[key]['default'][i] = input_dict[key]['element_type'](input_dict[key]['default'][i])
else:
input_dict[key]['default'] = input_dict[key]['type'](input_dict[key]['default'])
return input_dict
|
def join_name(*parts):
"""Joins a name. This is the inverse of split_name, but x == join_name(split_name(x)) does not necessarily hold.
Joining a name may also be subject to different schemes, but the most basic implementation is just joining all parts
with a space.
"""
return " ".join(parts)
|
def fetch_extra_data(resource):
"""Return a dict with extra data retrieved from CERN OAuth."""
person_id = resource.get("cern_person_id")
return dict(person_id=person_id)
|
def welcome():
"""List all available api routes"""
return(
f"Available Routes:<br/>"
f"Precipitation: /api/v1.0/precipitation<br/>"
f"Stations: /api/v1.0/stations<br/>"
f"Temperatures: /api/v1.0/tobs<br/>"
f"Temperature stat start date (yyyy-mm-dd): /api/v1.0/yyyy-mm-dd<br/>"
f"Temperature stat from start to end dates(yyyy-mm-dd): /api/v1.0/yyyy-mm-dd/yyyy-mm-dd"
)
|
def unify_quotes(token_string, preferred_quote):
"""Return string with quotes changed to preferred_quote if possible."""
bad_quote = {'"': "'", "'": '"'}[preferred_quote]
allowed_starts = {
'': bad_quote,
'f': 'f' + bad_quote,
'r': 'r' + bad_quote,
'u': 'u' + bad_quote,
'b': 'b' + bad_quote
}
if not any(
token_string.startswith(start)
for start in allowed_starts.values()):
return token_string
if token_string.count(bad_quote) != 2:
return token_string
if preferred_quote in token_string:
return token_string
assert token_string.endswith(bad_quote)
assert len(token_string) >= 2
for prefix, start in allowed_starts.items():
if token_string.startswith(start):
chars_to_strip_from_front = len(start)
return '{prefix}{preferred_quote}{token}{preferred_quote}'.format(
prefix=prefix,
preferred_quote=preferred_quote,
token=token_string[chars_to_strip_from_front:-1])
|
def h2_style():
"""
h2 style
"""
return {
"border-color" : "#99A1AA",
"background-color" : "#CCEECC"
}
|
def problem9(solution):
"""Problem 9 - Special Pythagorean triplet"""
# Find a^2 + b^2 = c^2 for a < b < c
a = 1
while a <= solution/3:
b = a + 1
while b <= solution/2:
c = solution - (a+b)
if c <= b:
break
if (a * a) + (b * b) == (c * c):
return a * b * c
b += 1
a += 1
# Not Found
return -1
|
def flatten_twdict(twlist: list):
"""
create flat list of tweet text from list of dict or list of list
:param twlist: list of dict
:return:
"""
templst: list = []
for twthis in twlist:
if isinstance(twthis, dict):
templst.append(twthis['text'])
elif isinstance(twthis, list):
templst.append(" ".join([str(x) for x in twthis]))
else:
templst.append(twthis)
return templst
|
def edgesToVerts(s):
""" Turn a list of edges into a list of verticies """
o = set()
for e in s:
o.add(e[0])
o.add(e[1])
return o
|
def _is_ethernet(port_data):
"""Return whether ifIndex port_data belongs to an Ethernet port.
Args:
port_data: Data dict related to the port
Returns:
valid: True if valid ethernet port
"""
# Initialize key variables
valid = False
# Process ifType
if 'ifType' in port_data:
# Get port name
name = port_data['ifName'].lower()
# Process ethernet ports
if port_data['ifType'] == 6:
# VLAN L2 VLAN interfaces passing as Ethernet
if name.startswith('vl') is False:
valid = True
# Return
return valid
|
def maybe_int(string):
"""
Returns the integer value of a string if possible,
else None
"""
try:
return int(string)
except ValueError:
return None
|
def update_params(original_return, add_params):
"""Insert additional params to dicts."""
if isinstance(original_return, list):
original_return = [{**i, **add_params} for i in original_return]
elif isinstance(original_return, dict):
original_return.update(add_params)
return original_return
|
def find_all_simulations(flist, sim):
"""
Finds all simulations in the list given.
:param flist:
:param sim:
:return: [list]
"""
if not flist:
return None
else:
matches = []
for fs in flist:
if fs.startswith(sim):
matches.append(fs)
return matches
|
def get_ref(name, prop='selfLink'):
""" Creates reference to a property of a given resource. """
return '$(ref.{}.{})'.format(name, prop)
|
def bytify(n=0, size=1, reverse=False, strict=False):
"""
Returns bytearray of at least size bytes equivalent of integer n that is
left zero padded to size bytes. For n positive, if the bytearray
equivalent of n is longer than size and strict is False the bytearray
is extended to the length needed to fully represent n. Otherwise if strict
is True or n is negative it is truncated to the least significant size bytes.
Big endian is the default.
If reverse is true then it reverses the order of the bytes in the resultant
bytearray for little endian with right zero padding.
"""
if n < 0 or strict:
n = n & (2 ** (size * 8) - 1)
b = bytearray()
count = 0
while n:
b.insert(0, n & 0xFF)
count += 1
n >>= 8
if (count < size):
b = bytearray([0]*(size-count)) + b
if reverse:
b.reverse()
return b
|
def derive_config_dict(config_obj):
"""Get the config dict from the obj
:param config_obj: The config object
:type config_obj:
:return:
:rtype:
"""
if config_obj:
config_dict = dict(config_obj.__dict__)
config_dict.pop("_sa_instance_state")
return config_dict
else:
return config_obj
|
def parse_number(value):
"""
Try converting the value to a number
"""
try:
return float(value)
except ValueError:
return None
|
def remove_nondigits(string_arg):
"""
Removes all non-digits (letters, symbols, punctuation, etc.)
:param str:
:return: string consisting only of digits
:rtype: str
"""
return ''.join(filter(lambda x: x.isdigit() or x == '.', string_arg))
|
def tamper(payload, **kwargs):
"""
Replaces (MySQL) instances like 'CONCAT(A, B)' with 'CONCAT_WS(MID(CHAR(0), 0, 0), A, B)' counterpart
Requirement:
* MySQL
Tested against:
* MySQL 5.0
Notes:
* Useful to bypass very weak and bespoke web application firewalls
that filter the CONCAT() function
>>> tamper('CONCAT(1,2)')
'CONCAT_WS(MID(CHAR(0),0,0),1,2)'
"""
if payload:
payload = payload.replace("CONCAT(", "CONCAT_WS(MID(CHAR(0),0,0),")
return payload
|
def as_list(x, length=1):
"""Return x if it is a list, else return x wrapped in a list."""
if not isinstance(x, list):
x = length*[x]
return x
|
def parse_none_results(result_dict):
"""
Replace `None` value in the `result_dict` to a string '-'
"""
for key, value_list in result_dict.items():
for i in range(len(value_list)):
if value_list[i] is None:
result_dict[key][i] = '-'
return result_dict
|
def attr_populated(obj, attr):
"""Return True if attr was populated in obj from source JSON."""
return not not getattr(obj, '_populated_' + attr, False)
|
def autodoc_skip_member(app, what, name, obj, skip, options):
"""Skips undesirable members.
"""
# N.B. This should be registerd before `napoleon`s event.
# N.B. For some reason, `:exclude-members` via `autodoc_default_options`
# did not work. Revisit this at some point.
if "__del__" in name:
return True
# In order to work around #11954.
if "__init__" in name:
return False
return None
|
def _union_lists(lists):
"""
Return a list that contains of all the elements of lists without
duplicates and maintaining the order.
"""
seen = {}
return [seen.setdefault(x, x)
for l in lists for x in l
if x not in seen]
|
def local_ports(servers_list) -> "list[int]":
"""Maps given JSON servers array into a server ports list using "port" property."""
return [game_server["port"] for game_server in servers_list]
|
def selection_sort(integers):
"""Search through a list of Integers using the selection sorting method.
Search elements 0 through n - 1 and select smallest, swap with element at
index 0, iteratively search through elements n - 1 and swap with smallest.
"""
integers_clone = list(integers)
for index in range(len(integers_clone) - 1, 0, -1):
max_position = 0
for location in range(1, index + 1):
if integers_clone[location] > integers_clone[max_position]:
max_position = location
temp = integers_clone[index]
integers_clone[index] = integers_clone[max_position]
integers_clone[max_position] = temp
return integers_clone
|
def sanitize_html(text):
"""Prevent parsing errors by converting <, >, & to their HTML codes."""
return text\
.replace('<', '<')\
.replace('>', '>')\
.replace('&', '&')
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.