content stringlengths 42 6.51k |
|---|
def handle_events(selection, events, selectors):
"""Execute functions corresponding to the selector contained in selection."""
results = []
for k, v in selectors.items():
if v in selection:
results.append(events[k]())
selection.remove(v)
return [res for res in results if res] |
def ordered_json(json_dict):
"""Creates a ordered json for comparison"""
if isinstance(json_dict, dict):
return sorted((k, ordered_json(v)) for k, v in json_dict.items())
if isinstance(json_dict, list):
return sorted(ordered_json(x) for x in json_dict)
return json_dict |
def makePrettySize(size): # copied from https://github.com/zalando/PGObserver
""" mimics pg_size_pretty() """
sign = '-' if size < 0 else ''
size = abs(size)
if size <= 1024:
return sign + str(size) + ' B'
if size < 10 * 1024**2:
return sign + str(int(round(size / float(1024)))) + ' kB'
if size < 10 * 1024**3:
return sign + str(int(round(size / float(1024**2)))) + ' MB'
if size < 10 * 1024**4:
return sign + str(int(round(size / float(1024**3)))) + ' GB'
return sign + str(int(round(size / float(1024**4)))) + ' TB' |
def get_offset(args):
"""Get the page offset, validating or returning 0 if None or invalid."""
offset = args.get('offset', '0')
if offset.isdigit():
return int(offset)
else:
return 0 |
def set_bit(value, offset):
"""Set a bit at offset position
:param value: value of integer where set the bit
:type value: int
:param offset: bit offset (0 is lsb)
:type offset: int
:returns: value of integer with bit set
:rtype: int
"""
mask = 1 << offset
return int(value | mask) |
def add_to_mean(current_mean, n, new_value, decimals=2):
"""
This function can be used when wanting to know the new mean of a list
after adding one or more values to it.
One could use this function instead of recalculating the new mean by
adding all the old values with the new one and dividing by n (where n is
the new total number of items in the list).
Args:
current_mean: Mean of the list pre-new value.
n: Number of items in the list pre-new value.
new_value: An int, float, or list of ints and/or flots of the new value(s)
decimals: (optional) number of decimal points (default is 2)
Returns:
A float object denoting the new mean.
Examples:
>>> add_to_mean(20, 4, 10)
18.0
>>> add_to_mean(40, 4, (10, 12))
30.33
>>> add_to_mean(0, 3, (10, -10, 0))
0.0
>>> add_to_mean(50, 0, 5)
Traceback (most recent call last):
...
ValueError: Current n must be an integer greater than 0.
>>> add_to_mean(16, 8, ('5')) # doctest: +ELLIPSIS
Traceback (most recent call last):
...
TypeError: add_to_mean() requires the new value(s) ... ints and/or floats.
"""
old_sum = current_mean * n
# sanity check the provided n
if n <= 0 or not isinstance(n, int):
raise ValueError('Current n must be an integer greater than 0.')
if isinstance(new_value, (int, float)):
new_sum = old_sum + new_value
return(round(new_sum / (n + 1), decimals))
elif type(new_value) in [list, tuple]:
new_sum = old_sum + sum(new_value)
return(round(new_sum / (n + len(new_value)), decimals))
else:
raise TypeError('add_to_mean() requires the new value(s) to be an int, '
'float, or a list or tuple of ints and/or floats.') |
def addext(name_str, ext_str):
"""Add a file extension to a filename
:param name_str: The filename that will get the extension
:param ext_str: The extension (no leading ``.`` required)
:returns: The filename with the extension
"""
if not ext_str:
return name_str
return name_str + "." + ext_str |
def remove_const(argtype):
"""Remove const from argtype"""
if argtype.startswith('const'):
return argtype.split('const ')[1]
return argtype |
def flatten_lists_all_level(list_of_lists: list) -> list:
"""
Wrapper to unravel or flatten list of lists to max possible levels
Can lead to RecursionError: maximum recursion depth exceeded
Default = 1000, To increase (to say 1500): sys.setrecursionlimit(1500)
"""
if not isinstance(list_of_lists, list):
return list_of_lists
elif len(list_of_lists) is 0:
return []
elif isinstance(list_of_lists[0], list):
return flatten_lists_all_level(list_of_lists[0]) + flatten_lists_all_level(list_of_lists[1:])
else:
return [list_of_lists[0]] + flatten_lists_all_level(list_of_lists[1:]) |
def merge(ll, rl):
"""Merge two lists.
:param ll: left list
:param rl: right list
:return: new list with ll and rl in ascending order.
"""
merged = []
l_idx, r_idx = 0, 0
while l_idx < len(ll) or r_idx < len(rl):
if l_idx < len(ll):
# Right index reached the end or left item is lower
if r_idx >= len(rl) or ll[l_idx] <= rl[r_idx]:
merged.append(ll[l_idx])
l_idx += 1
if r_idx < len(rl):
# Left index reached end or right item is lower
if l_idx >= len(ll) or rl[r_idx] <= ll[l_idx]:
merged.append(rl[r_idx])
r_idx += 1
# print('merged:', merged)
return merged |
def primary_schema(search_path):
"""Return the first schema in the search_path.
:param str search_path: PostgreSQL search path of comma-separated schemas
:return: first schema in path
:raise: ValueError
"""
search_path = search_path.strip()
if not search_path:
schemas = None
else:
schemas = search_path.split(',')
if not schemas:
raise ValueError('search_path must be non-empty')
return schemas[0].strip() |
def set_array(input_data, array):
"""Return data wrapped in array if if array=True."""
if array:
return [input_data]
return input_data |
def _strip_shell(cmd):
"""Strip a (potentially multi-line) command.
For example
$ foo \
> --bar baz \
> --quux 10
would becomes `foo --bar baz --quux 10`.
"""
parts = []
for line in cmd.strip().split("\n"):
without_console = line.lstrip("$> ").rstrip("\\ ")
parts.append(without_console)
return " ".join(parts) |
def reward(total_reward, percentage):
"""
Reward for a problem with total_reward done to percentage.
Since the first a few test cases are generally very easy, a linear
approach will be unfair. Thus, the reward is given in 20:80 ratio.
The first 50% gives 20% of the reward, and the last 50% gives 80%
of the reward.
Thus, if percentage <= 0.5, then the percentage of reward given is:
0.2 * (percentage / 0.5) = 0.4 * percentage
And if percentage >= 0.5, then the weighed percentage is:
0.2 + 0.8 * ((percentage - 0.5) / 0.5)) = 1.6 * percentage - 0.6
"""
percentage /= 100
if percentage <= 0.5:
weighed_percentage = 0.4 * percentage
else:
weighed_percentage = 1.6 * percentage - 0.6
return round(total_reward * weighed_percentage) |
def cleanup_test_name(name, strip_tags=True, strip_scenarios=False):
"""Clean up the test name for display.
By default we strip out the tags in the test because they don't help us
in identifying the test that is run to it's result.
Make it possible to strip out the testscenarios information (not to
be confused with tempest scenarios) however that's often needed to
identify generated negative tests.
"""
if strip_tags:
tags_start = name.find('[')
tags_end = name.find(']')
if tags_start > 0 and tags_end > tags_start:
newname = name[:tags_start]
newname += name[tags_end + 1:]
name = newname
if strip_scenarios:
tags_start = name.find('(')
tags_end = name.find(')')
if tags_start > 0 and tags_end > tags_start:
newname = name[:tags_start]
newname += name[tags_end + 1:]
name = newname
return name |
def divide_by(array_list, num_workers):
"""Divide a list of parameters by an integer num_workers.
:param array_list:
:param num_workers:
:return:
"""
for i, x in enumerate(array_list):
array_list[i] /= num_workers
return array_list |
def clip_path(filepath):
"""
Clip path to get file name
"""
fileslist = filepath.split('/')
return fileslist[-1] |
def check_qcs_on_files(file_meta, all_qcs):
"""Go over qc related fields, and check for overall quality score."""
def check_qc(file_accession, resp, failed_qcs_list):
"""format errors and return a errors list."""
quality_score = resp.get('overall_quality_status', '')
if quality_score.upper() != 'PASS':
failed_qcs_list.append([file_accession, resp['display_title'], resp['uuid']])
return failed_qcs_list
failed_qcs = []
if not file_meta.get('quality_metric'):
return
qc_result = [i for i in all_qcs if i['@id'] == file_meta['quality_metric']['@id']][0]
if qc_result['display_title'].startswith('QualityMetricQclist'):
if not qc_result.get('qc_list'):
return
for qc in qc_result['qc_list']:
qc_resp = [i for i in all_qcs if i['@id'] == qc['@id']][0]
failed_qcs = check_qc(file_meta['accession'], qc_resp, failed_qcs)
else:
failed_qcs = check_qc(file_meta['accession'], qc_result, failed_qcs)
return failed_qcs |
def remapE24(digit1, digit2):
"""The E24 series which includes E12 and E6 as subsets has a few values
which do not map exactly to the mathematical values."""
e24_digit2 = digit2
if (digit1 == 2 and digit2 == 6
or digit1 == 3 or digit1 == 4):
e24_digit2 += 1
elif digit1 == 8:
e24_digit2 -= 1
return e24_digit2 |
def except_keys(dic, keys):
"""Return a copy of the dict without the specified keys.
::
>>> except_keys({"A": 1, "B": 2, "C": 3}, ["A", "C"])
{'B': 2}
"""
ret = dic.copy()
for key in keys:
try:
del ret[key]
except KeyError:
pass
return ret |
def checkfname(fname, extension):
"""
Check if string ends with given extension
========== ===============================================================
Input Meaning
---------- ---------------------------------------------------------------
fname String with file name
extension Extension that fname should have
========== ===============================================================
========== ===============================================================
Output Meaning
---------- ---------------------------------------------------------------
fname String with the original fname and added extension if needed
========== ===============================================================
"""
extL = len(extension)
if len(fname) <= extL or fname[-extL:] != extension:
fname = fname + "." + extension
return fname |
def get_subdict(adict, keys):
"""
Get a sub-dictionary of `adict` with given `keys`.
"""
return dict((key, adict[key]) for key in keys if key in adict) |
def weekday_name(day_of_week):
"""Return name of weekday.
>>> weekday_name(1)
'Sunday'
>>> weekday_name(7)
'Saturday'
For days not between 1 and 7, return None
>>> weekday_name(9)
>>> weekday_name(0)
"""
day = {
1:"Sunday",
2:"Monday",
3:"Tuesday",
4:"Wednesday",
5:"Thursday",
6:"Friday",
7:"Saturday",
}
return day.get(day_of_week,None) |
def dir2text(mydir):
"""Convert a direction to its plain text equivalent"""
if mydir is None:
return "N"
mydir = int(mydir)
if mydir >= 350 or mydir < 13:
return "N"
elif mydir >= 13 and mydir < 35:
return "NNE"
elif mydir >= 35 and mydir < 57:
return "NE"
elif mydir >= 57 and mydir < 80:
return "ENE"
elif mydir >= 80 and mydir < 102:
return "E"
elif mydir >= 102 and mydir < 127:
return "ESE"
elif mydir >= 127 and mydir < 143:
return "SE"
elif mydir >= 143 and mydir < 166:
return "SSE"
elif mydir >= 166 and mydir < 190:
return "S"
elif mydir >= 190 and mydir < 215:
return "SSW"
elif mydir >= 215 and mydir < 237:
return "SW"
elif mydir >= 237 and mydir < 260:
return "WSW"
elif mydir >= 260 and mydir < 281:
return "W"
elif mydir >= 281 and mydir < 304:
return "WNW"
elif mydir >= 304 and mydir < 324:
return "NW"
elif mydir >= 324 and mydir < 350:
return "NNW" |
def topo_classes_subsets_defined_by_state_count(topo_classes_with_counts):
""" Input: List: [x_i,x_2,...,x_n]; x_i = [t_i,c_i] = [topo_class_hash_i, count_of_states_i]
Output: [ y_1,y_2,...,y_n]; y_i= [t_1,t_2,...t_n]; t_i= topo_class_hash;
yi is constrained by sum(c_i)<= fixed amount
"""
max_node_count = 50000
sets_of_topo_classes = []
current_set_topo_classes = []
current_set_size = 0
for [topo_class,size] in topo_classes_with_counts:
if size + current_set_size <= max_node_count or (current_set_size == 0 and size >= max_node_count):
current_set_topo_classes.append(topo_class)
current_set_size = current_set_size + size
else:
sets_of_topo_classes.append(current_set_topo_classes)
current_set_topo_classes = [topo_class]
current_set_size = size
if current_set_topo_classes:
sets_of_topo_classes.append(current_set_topo_classes)
return sets_of_topo_classes |
def compute_line_intersection_point(x1, y1, x2, y2, x3, y3, x4, y4):
"""
Compute the intersection point of two lines.
Taken from https://stackoverflow.com/a/20679579 .
Parameters
----------
x1 : number
x coordinate of the first point on line 1. (The lines extends beyond this point.)
y1 : number:
y coordinate of the first point on line 1. (The lines extends beyond this point.)
x2 : number
x coordinate of the second point on line 1. (The lines extends beyond this point.)
y2 : number:
y coordinate of the second point on line 1. (The lines extends beyond this point.)
x3 : number
x coordinate of the first point on line 2. (The lines extends beyond this point.)
y3 : number:
y coordinate of the first point on line 2. (The lines extends beyond this point.)
x4 : number
x coordinate of the second point on line 2. (The lines extends beyond this point.)
y4 : number:
y coordinate of the second point on line 2. (The lines extends beyond this point.)
Returns
-------
tuple of number or bool
The coordinate of the intersection point as a tuple ``(x, y)``.
If the lines are parallel (no intersection point or an infinite number of them), the result is False.
"""
def _make_line(p1, p2):
A = (p1[1] - p2[1])
B = (p2[0] - p1[0])
C = (p1[0]*p2[1] - p2[0]*p1[1])
return A, B, -C
L1 = _make_line((x1, y1), (x2, y2))
L2 = _make_line((x3, y3), (x4, y4))
D = L1[0] * L2[1] - L1[1] * L2[0]
Dx = L1[2] * L2[1] - L1[1] * L2[2]
Dy = L1[0] * L2[2] - L1[2] * L2[0]
if D != 0:
x = Dx / D
y = Dy / D
return x, y
else:
return False |
def stringify(value):
"""
Escapes a string to be usable as cell content of a CSV formatted data.
"""
stringified = '' if value is None else str(value)
if ',' in stringified:
stringified = stringified.replace('"', '""')
stringified = f'"{stringified}"'
return stringified |
def bottom_up_decomposite_n(n: int):
"""
bottom-up method for dynamic programming
"""
m = dict()
for i in range(n+1):
m[(i,i)] = 0
for i in range(1, int(n/2)+1):
for j in range(i, n-i+1):
total = 0
if j <= i:
total = 0
else:
for k in range(i, j):
if j - k < k:
total = 1
break
total += 1 + m[(j-k, k)]
m[j, i] = total
total = 1
for i in range(1, int(n/2)+1):
total += m[n-i, i] + 1
return total |
def shiftchunk(chunks, c, which, incr):
"""Shifts the 'which' endpoint of chunk 'c' by 'incr'.
"""
ret = [ch[:] for ch in chunks]
ret[c][which] += incr
last = ret[c][which]
if which == 1:
for w in range(c+1, len(ret)):
oldi, oldj = i, j = ret[w]
if i < last:
i = last
if j < i:
j = i
#print '%s (%s,%s) -> (%s,%s)' % (w, oldi, oldj, i, j)
last = j
if (i, j) == (oldi, oldj): break
ret[w] = [i,j]
else:
for w in range(c-1, -1, -1):
oldi, oldj = i, j = ret[w]
if j > last:
j = last
if i > j:
i = j
#print '%s (%s,%s) -> (%s,%s)' % (w, oldi, oldj, i, j)
last = i
if (i, j) == (oldi, oldj): break
ret[w] = [i,j]
return ret |
def lamb_blasius(re):
"""
Calculate friction coefficient according to Blasius.
Parameters
----------
re : float
Reynolds number.
Returns
-------
lamb : float
Darcy friction factor.
"""
return 0.3164 * re ** (-0.25) |
def sign(x):
"""Sign indication of a number"""
return 1 if x > 0 else -1 if x < 0 else 0 |
def time_to_kobo(y, m, d='01', h='00', mi='00', s='00'):
"""Format timestamp for Kobo."""
y = str(y)
m = str(m)
d = str(d)
h = str(h)
mi = str(mi)
s = str(s)
return y + '-' + m + '-' + d + 'T' + h + ':' + mi + ':' + s + 'Z' |
def dict_union(*dicts, merge_keys=['history', 'tracking_id'], drop_keys=[]):
"""Return the union of two or more dictionaries."""
from functools import reduce
if len(dicts) > 2:
return reduce(dict_union, dicts)
elif len(dicts) == 2:
d1, d2 = dicts
d = type(d1)()
# union
all_keys = set(d1) | set(d2)
for k in all_keys:
v1 = d1.get(k)
v2 = d2.get(k)
if (v1 is None and v2 is None) or k in drop_keys:
pass
elif v1 is None:
d[k] = v2
elif v2 is None:
d[k] = v1
elif v1 == v2:
d[k] = v1
elif k in merge_keys:
d[k] = '\n'.join([v1, v2])
return d
elif len(dicts) == 1:
return dicts[0] |
def is_empty_file(file_field):
"""
Return True if the given file field object passed in is None or has no filename
Args:
file_field (django.db.models.FileField or None): A file field property of a model object
Returns:
bool: True if the given file field object passed in is None or has no filename
"""
return file_field is None or not file_field.name |
def odds(p):
"""
definition of odds ratio, without Laplace correction
:param p: probability
:param n: number of training instances
:param k: cardinality of y
:return: odds ratio
"""
assert 0 <= p <= 1, "Probability out of [0, 1]!"
y = p / (1 - p)
return y |
def get_winner(board):
""" finds out if there is a winner and who won """
def who_won(in_a_row, board_size, cur_player):
"""
a function private to get_winner() (yes you can do this. Cool huh!?)
that tells get_winner if it has a winner
"""
if in_a_row == board_size:
return 1 if cur_player == 'X' else 2
else:
return 0
def test_row_col(board, rows):
""" private function to test the rows and columns """
for i in range(len(board)):
cur_player = board[i][0] if rows else board[0][i]
in_a_row = 0
for j in range(len(board)):
symbol = board[i][j] if rows else board[j][i]
if (not symbol == '-') and (symbol == cur_player):
in_a_row += 1
else:
break
winner = who_won(in_a_row, len(board), cur_player)
if not winner == 0:
return winner
return 0
def test_diagonal(board, normal):
""" private function to test the two diagonals """
cur_player = board[0][0] if normal else board[0][len(board)-1]
in_a_row = 0
for i in range(len(board)):
symbol = board[i][i] if normal else board[i][len(board)-1-i]
if (not symbol == '-') and (symbol == cur_player):
in_a_row += 1
else:
break
winner = who_won(in_a_row, len(board), cur_player)
if not winner == 0:
return winner
return 0
# test rows
winner = test_row_col(board, True)
if not winner == 0:
return winner
# test cols
winner = test_row_col(board, False)
if not winner == 0:
return winner
# test diagonal from top left to bottom right
winner = test_diagonal(board, True)
if not winner == 0:
return winner
# test diagonal from top right to bottom left
winner = test_diagonal(board, False)
if not winner == 0:
return winner
return 0 |
def get_full_class_path(o):
"""Returns the full class path of an object"""
module = o.__class__.__module__
if module is None or module == str.__class__.__module__:
return o.__class__.__name__ # Avoid reporting __builtin__
else:
return module + '.' + o.__class__.__name__ |
def matrix_divided(matrix, div):
"""matrix """
if (not isinstance(matrix, list) or matrix == [] or
not all(isinstance(row, list) for row in matrix) or
not all((isinstance(col, int) or isinstance(col, float))
for col in [num for row in matrix for num in row])):
raise TypeError("matrix must be a matrix (list of lists) of "
"integers/floats")
if not all(len(row) == len(matrix[0]) for row in matrix):
raise TypeError("Each row of the matrix must have the same size")
if type(div) != int and type(div) != float:
raise TypeError("div must be a number")
if div == 0:
raise ZeroDivisionError("division by zero")
j = list(map(lambda x: list(map(lambda y: round(y / div, 2), x)), matrix))
return j |
def factorial_loop(number):
""" loop factorial """
result = 1
for x in range(2, number+1, 1):
result *= x
return result |
def get_properties(value):
"""
Converts the specified value into a dict containing the NVPs (name-value pairs)
:param value:
:return:
"""
rtnval = None
if isinstance(value, dict):
# value is already a Python dict, so just return it
rtnval = value
elif '=' in value:
# value contains '=' character(s), so split on that to
# come up with NVPs
properties = value.split('=')
if properties:
rtnval = {properties[0]: properties[1]}
if rtnval is None:
# Couldn't tell what the delimiter used in value was, so just
# return a dict with value as the value, and 'Value' as the key
rtnval = {'Value': value}
return rtnval |
def get_micro_secs(real_str: str) -> int:
"""
If there is a decimal point returns fractional part as an integer in units
based on 10 to minus 6 ie if dealing with time; real_str is in seconds and any factional
part is returned as an integer representing microseconds. Zero returned if no factional part
:param real_str: A string with optional fraction
:return: decimal part as integer based on micro units eg microseconds
"""
try:
p1, p2 = real_str.split(".")
except ValueError:
return 0
if p2:
p2 = f"{p2:0<6}"
return int(p2)
return 0 |
def classify(instruction):
"""Classify instruction.
Return name of instruction handler and arguments.
"""
if instruction in (0x00e0, 0x00ee):
return f"op_{instruction:04x}",
opcode = instruction >> 12
if 0 <= opcode <= 2:
return f"op_{opcode}nnn", instruction & 0x0fff
if 3 <= opcode <= 4:
x = instruction & 0x0f00
kk = instruction & 0x00ff
return f"op_{opcode}xkk", x >> 8, kk
if opcode == 5:
# if instruction & 0xf00f == 0x5000
if instruction & 0x000f == 0:
x = instruction & 0x0f00
y = instruction & 0x00f0
return "op_5xy0", x >> 8, y >> 4
if 6 <= opcode <= 7:
x = instruction & 0x0f00
kk = instruction & 0x00ff
return f"op_{opcode}xkk", x >> 8, kk
if opcode == 8:
function = instruction & 0x000f
x = instruction & 0x0f00
y = instruction & 0x00f0
if 0 <= function <= 7:
return f"op_8xy{function}", x >> 8, y >> 4
if function == 0xe:
return f"op_8xye", x >> 8, y >> 4
if opcode == 9:
if instruction & 0x000f == 0:
x = instruction & 0x0f00
y = instruction & 0x00f0
return "op_9xy0", x >> 8, y >> 4
if 0xa <= opcode <= 0xb:
return f"op_{opcode:1x}nnn", instruction & 0x0fff
if opcode == 0xc:
x = instruction & 0x0f00
kk = instruction & 0x00ff
return "op_cxkk", x >> 8, kk
if opcode == 0xd:
x = instruction & 0x0f00
y = instruction & 0x00f0
n = instruction & 0x000f
return "op_dxyn", x >> 8, y >> 4, n
if opcode == 0xe:
function = instruction & 0x00ff
x = instruction & 0x0f00
if function == 0x9e:
return "op_ex9e", x >> 8
if function == 0xa1:
return "op_exa1", x >> 8
if opcode == 0xf:
function = instruction & 0x00ff
if function in (0x07, 0x0a, 0x15, 0x18, 0x1e, 0x29, 0x33, 0x55, 0x65):
x = instruction & 0x0f00
return f"op_fx{function:02x}", x >> 8
return "", |
def stringize(contents):
"""Convert contents into a valid C string, escaped if necessary"""
contents = str(contents).rstrip().lstrip().replace('\\', '\\\\')
contents = contents.replace('"', '\\"')
return contents |
def is_pos_idx(arg: int) -> bool:
"""Return True if arg matches positional index notation"""
if not isinstance(arg, int):
return False
return bool(0 <= arg <= 63) |
def version_param(params):
"""Return the value of the HTTP version parameter, or `None` if no
version parameter is supplied.
"""
for k, v in params.items():
if k.lower() == "version":
return v |
def c_to_k(t_c):
"""Convert Celsius to Kelvin."""
if t_c is None:
return None
return t_c + 273.15 |
def get_img_extension(path: str) -> str:
"""
Parse the path and return the image's extension (replacing jpg to jpeg with accordance with EPUB spec)
"""
path_list = path.rsplit(".", 1)
if len(path_list) == 2:
ext = path_list[1]
else:
ext = "jpeg"
if ext == "jpg":
ext = "jpeg"
return ext |
def remove_stop_words(string, stop_words):
"""Sanitize using standard list comprehension"""
return ' '.join([w for w in string.split() if w not in stop_words]) |
def check_win(word, guessed):
"""Returns True if every letter in word has been guessed, else False"""
for letter in word:
if letter not in guessed:
return False
return True |
def intify_keys(d):
"""Convert string keys in a dictionary to integers"""
return {int(k): v for k, v in d.items()} |
def indexes(dic, keys=None):
""" index dictionary by multiple keys
Parameters
----------
dic : dict
keys : list
Examples
--------
>>> d = {1:{"a":"A"},2:{"b":"B"}}
>>> indexes(d,[1,'a'])
'A'
"""
keys = [] if keys is None else keys
assert hasattr(dic, 'keys')
new = dic.copy()
old_key = None
for key in keys:
if not hasattr(new, 'keys'):
raise KeyError('No indexes after: {}'.format(old_key))
old_key = key
new = new[key]
return new |
def default(row, index) -> str:
"""If a index out of range occurs return a empty string."""
if len(row) > index:
return row[index]
return '' |
def sum_of_args(*args, **kwargs):
"""Sums the args, and returns a copy of kwargs with the sum of args added to each value.
>>> sum_of_args(1,2,3, a=0, b=10)
{'a': 6, 'b': 16}
"""
t = sum(args)
return {k: t + v for k, v in kwargs.items()} |
def get_index(i,j,num_of_nodes):
"""
give the row and column index, return the location in a matrix
"""
return (i*num_of_nodes+j) |
def initialize_float_from_method_call(floatPtr, instance, mayThrowOnFailure):
"""Internal function to try converting 'instance' to a float.
Args:
floatPtr - a PointerTo(float) that we're supposed to initialize
instance - something with a __float__method
mayThrowOnFailure - if True, then we shouldn't swallow the exception
Returns:
True if floatPtr is initialized successfully, False otherwise.
"""
try:
res = instance.__float__()
if isinstance(res, float):
floatPtr.initialize(res)
return True
else:
return False
except Exception: # noqa
if mayThrowOnFailure:
raise
return False |
def pkg_mount_type_to_string(_type):
"""
Converts the PKG_MOUNT_
TYPE_* contstants to a human readable string.
"""
if _type == 0:
return "UNKNOWN"
elif _type == 1:
return "AMBIG"
elif _type == 2:
return "TH"
elif _type == 3:
return "SMT"
else:
return "*ERR(%s)*" % str(_type) |
def format_float(numpy_float):
"""
Converts a numpy64 type to a formatted string.
Ex: Input => numpy64(99999.6577) Output => '99,999.658'
@param nupmy64 numpy_float: this is a first param
@return: this is a description of what is returned
"""
python_float = numpy_float
if not isinstance(python_float, float):
python_float = numpy_float.item() # numpy method to convert to float
return f'{round(python_float, 3):,}' |
def ternary_search(f, l, r, min_=True, maxiter=100, tol=1e-6):
"""Optimize f(x) using the ternary search
f(x) is unimodal (only one optima) in a [l, r]
"""
i = 0
while r - l > tol and i < maxiter:
# split (r - l) in 3 parts
a = (l * 2 + r) / 3 # l + 1/3 * (r - l)
b = (l + 2 * r) / 3 # l + 2/3 * (r - l)
# f(x) either increasing or min on [a,b]
if f(a) < f(b) and min_:
# [b, r] is no longer of interest
r = b
# decreasing or max
elif f(a) >= f(b) and not min_:
r = b
else:
# [a, l] is no longer of interest
l = a
i += 1
return (l + r) / 2 |
def get_elements(element=None, filename=None):
"""Get values for selected element from xml file specified in filename"""
if filename is None or element is None:
return []
import xml.dom.minidom
import xml.parsers.expat
try:
dom = xml.dom.minidom.parse(filename)
except IOError:
return []
except xml.parsers.expat.ExpatError:
return []
values = dom.getElementsByTagName(element)
return values |
def bracket_sub (sub, comment=False):
""" Brackets a substitution pair.
Args:
sub (tuple): The substitution pair to bracket.
comment (bool): Whether or not to comment the bracketed pair.
Returns:
tuple: The bracketed substitution pair.
"""
if comment:
return ('\(\*\s*\{\{\\s*' + sub[0] + '\\s*\}\}\s*\*\)', sub[1])
else:
return ('\{\{\\s*' + sub[0] + '\\s*\}\}', sub[1]) |
def quick_clean(raw_str):
"""
args:
- raw_str: a string to be quickly cleaned
return
- the original string w/ all quotes replaced as double quotes
"""
return raw_str.replace("''", '" ').replace("``", '" ').strip() |
def get_names(rec_list):
"""
Gets the sequnece IDs from a sequence record list, returns a comma separated string of IDs
"""
return ", ".join([r["rec"].id for r in rec_list]) |
def consider(string, font=None):
"""
Error for command prompt
Count=If count is needed, then you have to change countError to something else than None:
assign countError to variable put before loop, which equals 1.
After the warning you have to implement the incrementation of this variable
"""
txt = u"\n [**CONSIDER**]> {}\n\n".format(string)
if font:
txt += u"\\\\\\\\\\\\\\\ *FILE NAME: {}*\n".format(
font.path.split("/")[-1])
return txt |
def validSpanishNumber(phone):
"""
Function intended to ensure phone is in spanish format:
*** start w/ 9/8/6/7
*** total 9 numbers in format XXX XXX XXX
"""
try:
if len(phone) != 11:
return False
for i in range(11):
if i in [3,7]:
if phone[i] != ' ':
return False
elif not phone[i].isnumeric():
return False
return True
except Exception as e:
print(e)
return False |
def save_class(cls):
"""
Save given class as a string.
:type cls: type
:rtype: str
"""
return '{0.__module__}.{0.__name__}'.format(cls) |
def get_indicators(confidence, weights):
"""Takes a confidence number and a map from weights (confidences) to words with that weight. Returns a set of all words which have a confidence higher that <confidence>"""
sorted_weights = weights.keys()
sorted_weights = sorted(sorted_weights, reverse=True)
indicators = set()
for w in sorted_weights:
if w > confidence:
for word in weights[w]:
indicators.add(word)
return indicators |
def get_event_ends(T_part, n_repeats):
"""get the end points for a event sequence, with lenth T, and k repeats
- event ends need to be removed for prediction accuracy calculation, since
there is nothing to predict there
- event boundaries are defined by these values
Parameters
----------
T_part : int
the length of an event sequence (one repeat)
n_repeats : int
number of repeats
Returns
-------
1d np.array
the end points of event seqs
"""
return [T_part * (k+1)-1 for k in range(n_repeats)] |
def init_game(n_rows, n_columns, red_discs, yellow_discs):
"""Init an empty game with some initial moves.
Game is a 2D grid indexed from top left (0,0) to bottom right.
"""
game = [[" " for _ in range(n_columns)] for _ in range(n_rows)]
for x, y in red_discs:
game[x][y] = "R"
for x, y in yellow_discs:
game[x][y] = "Y"
return game |
def delegate(session_attributes, slots):
"""
Directs Amazon Lex to choose the next course of action based on the bot configuration.
"""
return {
'sessionAttributes': session_attributes,
'dialogAction': {
'type': 'Delegate',
'slots': slots
}
} |
def duration_to_string(duration):
"""
Converts a duration to a string
Args:
duration (int): The duration in seconds to convert
Returns s (str): The duration as a string
"""
m, s = divmod(duration, 60)
h, m = divmod(m, 60)
return "%d:%02d:%02d" % (h, m, s) |
def hpa_to_mmhg(pressure: int) -> int:
"""
Converts pressure in hpa to mmhg
Args:
pressure: pressure to convert
Returns: pressure in mmhg
"""
return int(pressure * 0.75006156130264) |
def human_seconds(seconds, display='.2f'):
"""
Given `seconds` seconds, return human readable duration.
"""
value = seconds * 1e6
ratios = [1e3, 1e3, 60, 60, 24]
names = ['us', 'ms', 's', 'min', 'hrs', 'days']
last = names.pop(0)
for name, ratio in zip(names, ratios):
if value / ratio < 0.3:
break
value /= ratio
last = name
return f"{format(value, display)} {last}" |
def deep_get(target_dict, key_list, default_value=None):
"""
Get a value from target_dict entering in the nested keys. If keys does not exist, it returns None
Example target_dict={a: {b: 5}}; key_list=[a,b] returns 5; both key_list=[a,b,c] and key_list=[f,h] return None
:param target_dict: dictionary to be read
:param key_list: list of keys to read from target_dict
:param default_value: value to return if key is not present in the nested dictionary
:return: The wanted value if exist, None otherwise
"""
for key in key_list:
if not isinstance(target_dict, dict) or key not in target_dict:
return default_value
target_dict = target_dict[key]
return target_dict |
def strip_indentation_whitespace(text):
"""Strips leading whitespace from each line."""
stripped_lines = [line.lstrip() for line in text.split("\n")]
return "\n".join(stripped_lines) |
def key2str(target):
"""
In ``symfit`` there are many dicts with symbol: value pairs.
These can not be used immediately as \*\*kwargs, even though this would make
a lot of sense from the context.
This function wraps such dict to make them usable as \*\*kwargs immediately.
:param target: `Mapping` to be made save
:return: `Mapping` of str(symbol): value pairs.
"""
return target.__class__((str(symbol), value) for symbol, value in target.items()) |
def document_keys(doc) :
"""Returns formatted strings of document keys.
"""
keys = sorted(doc.keys())
s = '%d document keys:' % len(keys)
for i,k in enumerate(keys) :
if not(i%5) : s += '\n '
s += ' %s' % k.ljust(16)
return s
#return '%d doc keys:\n %s' % (len(keys), '\n '.join([k for k in keys])) |
def color_pixel(index):
"""
Color the vertex by its index. Note the color index must lie between
0-255 since gif allows at most 256 colors in the global color table.
"""
return max(index % 256, 1) |
def update_vocab(vocab):
"""Add relevant special tokens to vocab."""
vocab_size = len(vocab)
vocab["<unk>"] = vocab_size
vocab["<s>"] = vocab_size + 1
vocab["</s>"] = vocab_size + 2
return vocab |
def _patch_qichat_script(code):
""" Apply modifications to old version qichat script
to make it correspond to new behavior format files
"""
# for now, nothing to do more than the lstrip() made upper
return code |
def _is_bare_mapping(o):
"""Whether the object supports __getitem__ and __contains__"""
return (
hasattr(o, '__contains__') and callable(o.__contains__) and
hasattr(o, '__getitem__') and callable(o.__getitem__)
) |
def convert_to_bool(value_str: str) -> bool:
"""
Converts string values to their boolean equivalents.
:param value_str: Value string.
:return: The boolean value represented by `value_str`, if any.
:raise: A ValueError if it is not possible to convert the value string to bool.
"""
conversion_dict = {"true": True, "t": True, "y": True, "false": False, "f": False, "n": False}
try:
return conversion_dict[value_str.lower()]
except KeyError as e:
raise ValueError(f"Not a boolean value: {value_str}") from e |
def svg_icons_context_processor(request):
"""
Provide an empty set, that will be filled with the name of the icon, that was embedded.
This is relevant for the svg_icon template tag.
"""
return {"_embedded_svg_icons": set()} |
def split_package_name(p):
"""Splits the given package name and returns a tuple (name, ver)."""
s = p.split('==')
if len(s) == 1:
return (s[0], None)
else:
return (s[0], s[1]) |
def has_no_jump(bigram, peaks_groundtruth):
"""
Tell if the two components of the bigram are same or successive in the sequence of valid peaks or not
For exemple, if groundtruth = [1,2,3], [1,1] or [2,3] have no jump but [1,3] has a jump.
bigram : the bigram to judge
peaks_groundtruth : the list of valid peaks
Return boolean
"""
assert len(bigram) == 2
if len(set(bigram)) == 1:
return True
sorted_groundtruth = sorted(peaks_groundtruth)
sorted_peaks = sorted(list(bigram))
begin = sorted_groundtruth.index(sorted_peaks[0])
end = begin+len(sorted_peaks)
return sorted_peaks == sorted_groundtruth[begin:end] |
def compare_range(value, window):
"""
Compare value with nagios range and return True if value is within boundaries
:param value:
:param window:
:return:
"""
incl = False
if window[0] == '@':
incl = True
window = window[1:]
if ":" not in window:
start = 0
stop = window
else:
bits = window.split(':')
start = bits[0]
stop = bits[1] if bits[1] else '~'
start = None if start == '~' else float(start)
stop = None if stop == '~' else float(stop)
if start is not None and ((incl and value <= start) or (not incl and value < start)):
return False
if stop is not None and ((incl and value >= stop) or (not incl and value > stop)):
return False
return True |
def mean(num_lst):
"""
Calculates teh mean of a list of numbers
Parameters
----------
num_lst : list of int or float
List of numbers to calculate the average of
Returns
-------
float of the average/mean of num_lst
Examples
--------
>>> mean([1, 2, 3, 4, 5])
3.0
"""
return sum(num_lst) / len(num_lst) |
def _merge_yaml(ret, data, profile=None):
"""
Merge two yaml dicts together at the misc level
"""
if 'misc' not in ret:
ret['misc'] = []
if 'misc' in data:
for key, val in data['misc'].items():
if profile and isinstance(val, dict):
val['nova_profile'] = profile
ret['misc'].append({key: val})
return ret |
def numberOfChar(stringList):
""" Returns number of char into a list of strings and return a int """
return sum(len(s) for s in stringList) |
def DataSpeedUnit(speed):
"""
Convert data speed to the next
best suited data size unit
by Max Schmeling
"""
units = ['bps', 'Kbps', 'Mbps', 'Gbps']
unit = 0
while speed >= 1024:
speed /= 1024
unit += 1
return '%0.2f %s' % (speed, units[unit]) |
def _get_links(previous, nexts, children):
"""Returns graphs edges between two subgraphs."""
links = {}
for n in previous:
next_children = []
if n not in nexts:
next_children = [c.name for c in children.get(n, []) if c in nexts]
if len(next_children) > 0:
links[n.name] = next_children
return links |
def mockServerAnswer(word: str, guess: str) -> str:
"""Function for development purposes"""
ans = ''
for letter in word:
if letter == guess:
ans = ans + '1'
else:
ans = ans + '0'
return ans |
def _desktop_escape(s):
"""Escape a filepath for use in a .desktop file"""
escapes = {' ': R'\s', '\n': R'\n', '\t': R'\t', '\\': R'\\'}
s = str(s)
for unescaped, escaped in escapes.items():
s = s.replace(unescaped, escaped)
return s |
def generate_bounding_box_values(latitude, longitude, delta=0.01):
"""
Calculate a small bounding box around a point
:param latitude: decimal latitude
:param longitude: decimal longitude
:param float delta: difference to use when calculating the bounding box
:return: bounding box values in the following order: lower longitude, lower latitude,
upper longitude, upper latitude
:rtype: tuple
"""
flt_lat = float(latitude)
flt_lon = float(longitude)
lat_lower = flt_lat - delta
lon_lower = flt_lon - delta
lat_upper = flt_lat + delta
lon_upper = flt_lon + delta
return lon_lower, lat_lower, lon_upper, lat_upper |
def validate_and_build_instance_fleets(parsed_instance_fleets):
"""
Helper method that converts --instance-fleets option value in
create-cluster to Amazon Elastic MapReduce InstanceFleetConfig
data type.
"""
instance_fleets = []
for instance_fleet in parsed_instance_fleets:
instance_fleet_config = {}
keys = instance_fleet.keys()
if 'Name' in keys:
instance_fleet_config['Name'] = instance_fleet['Name']
else:
instance_fleet_config['Name'] = instance_fleet['InstanceFleetType']
instance_fleet_config['InstanceFleetType'] = instance_fleet['InstanceFleetType']
if 'TargetOnDemandCapacity' in keys:
instance_fleet_config['TargetOnDemandCapacity'] = instance_fleet['TargetOnDemandCapacity']
if 'TargetSpotCapacity' in keys:
instance_fleet_config['TargetSpotCapacity'] = instance_fleet['TargetSpotCapacity']
if 'InstanceTypeConfigs' in keys:
if 'TargetSpotCapacity' in keys:
for instance_type_config in instance_fleet['InstanceTypeConfigs']:
instance_type_config_keys = instance_type_config.keys()
instance_fleet_config['InstanceTypeConfigs'] = instance_fleet['InstanceTypeConfigs']
if 'LaunchSpecifications' in keys:
instanceFleetProvisioningSpecifications = instance_fleet['LaunchSpecifications']
instance_fleet_config['LaunchSpecifications'] = {}
if 'SpotSpecification' in instanceFleetProvisioningSpecifications:
instance_fleet_config['LaunchSpecifications']['SpotSpecification'] = \
instanceFleetProvisioningSpecifications['SpotSpecification']
if 'OnDemandSpecification' in instanceFleetProvisioningSpecifications:
instance_fleet_config['LaunchSpecifications']['OnDemandSpecification'] = \
instanceFleetProvisioningSpecifications['OnDemandSpecification']
instance_fleets.append(instance_fleet_config)
return instance_fleets |
def indent_block(block, level=1):
"""
Indents the provided block of text.
Args:
block (str): The text to indent.
level (int): The number of tabs to indent with.
Returns:
str: The indented block.
"""
tab = "\t" * level
sep = "\n{:}".format(tab)
return tab + sep.join(str(block).splitlines()) |
def is_list(klass: type):
"""Determine whether klass is a List."""
return getattr(klass, "__origin__", None) == list |
def _standard_pool_name(given_pool_name):
"""Return a standard memory pool name.
The memory pool names could vary based on the garbage collector enabled.
This function returns a standard name we could refer to.
Available collectors :
https://docs.oracle.com/en/java/javase/11/gctuning/available-collectors.html
Here is an old gist listing the variations in the names:
https://gist.github.com/szegedi/1474365
"""
# mapping of standard memory pool name to all known names.
pool_name_aliases = {
"Eden Space": (
"PS Eden Space",
"Par Eden Space",
"G1 Eden Space",
),
"Survivor Space": (
"PS Survivor Space",
"Par Survivor Space",
"G1 Survivor Space",
),
"Tenured Gen": (
"PS Old Gen",
"CMS Old Gen",
"G1 Old Gen",
),
}
for standard_name, valid_names in pool_name_aliases.items():
for name in valid_names:
if name == given_pool_name:
return standard_name
# If we can't find an alternative standard name,
# just return the given memory pool name.
return given_pool_name |
def get_completion_word(details):
"""Find the completed text from some Vim completion data.
Args:
details (dict[str, str]):
Data that comes from Vim after completion finishes. For more
information, check out Vim's help documentation. `:help
v:completed_item`.
Returns:
str: The completed function.
"""
user_made_a_completion_selection = details.get('user_data', '') != ''
if not user_made_a_completion_selection:
return ''
return details['word'] |
def zero_matrix_no_numpy(matrix):
"""
First solution relying only on pure Python
Scans through the matrix once, storing in sets the indices where zeroes
have been detected (sets automatically remove duplicates).
A second loop then zeroes the rows and cols as appropriate.
Algo is O(M x N) which is the best possible since all elements have to be
touched in the general case.
"""
if matrix == []:
return []
zero_col_indices = set()
zero_row_indices = set()
N = len(matrix[0])
# We scan the matrix to locate all zeros
for i, row in enumerate(matrix):
for j, element in enumerate(row):
if element == 0:
zero_col_indices.add(j)
zero_row_indices.add(i)
for i, row in enumerate(matrix):
if i in zero_row_indices:
matrix[i] = [0] * N
else:
for j in zero_col_indices:
matrix[i][j] = 0
return matrix |
def mergeDicts(dict1, dict2):
"""
Merges values from dict2 into dict1.
If a key exists in both dictionaries, dict2 will overwrite dict1.
"""
res = {**dict1, **dict2}
return res |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.