content
stringlengths 42
6.51k
|
---|
def subset_or_none(dict1: dict, dict2: dict) -> dict:
"""
If the keys of dict2 are a subset of the keys of dict1,
return a copy of dict1 updated with the values of dict2,
otherwise return an empty dict of the same type as dict1
"""
new_dict = dict1.copy()
new_dict.update(dict2)
if new_dict.keys() == dict1.keys():
return dict1.__class__(new_dict)
return dict1.__class__()
|
def get_bracket_depth(idx, left_bracket_indices, right_bracket_indices):
"""
Get the bracket depth of index idx.
Args:
idx (int): the index.
left_bracket_indices (list[int]): the left bracket index list.
right_bracket_indices (list[int]): the right bracket index list.
Returns:
An integer which is the bracket depth.
Raises:
ValueError if idx is not inside any bracket.
"""
depth = -1
for i, left_idx in enumerate(left_bracket_indices):
if idx >= left_idx and idx <= right_bracket_indices[i]:
depth += 1
if depth < 0:
raise ValueError("cannot find bracket depth")
return depth
|
def get_random_string(size=32):
"""Creates a random (hex) string which contains 'size' characters."""
return ''.join("{0:02x}".format(b) for b in open('/dev/urandom', 'rb').read(int(size/2)))
|
def generate_otp(label, user, key):
"""Generates a otpauth:// URI"""
return "otpauth://totp/%s:%s?secret=%s&issuer=%s" % (label,user,key,label)
|
def remove_empty(d):
"""
Helper function that removes all keys from a dictionary (d), that have an
empty value.
"""
for key in d.keys():
if not d[key]:
del d[key]
return d
|
def ensure_list(var):
"""Converts to a list, safely"""
if isinstance(var, str):
return [var]
return var
|
def _parse_directories(dir_list):
"""Helper function for parsing and cleaning a list of directories for analysis.
:param list[str] dir_list: A list of directories to parse.
:rtype: list[str]
:return: The cleaned up list of directories.
"""
return [line for line in dir_list if line is not None]
|
def _solution_to_selection(collector, solution_index, flat_vars, flat_vars_inverse, n_courses):
"""
Given a solution found by the solver, extract the list of indices of selected options.
Specifically, if selection[i]=j, the j-th option of the i-th course was selected,
selection[i]=None if the course was not selected.
"""
selection = [None] * n_courses
for j in range(len(flat_vars)):
if collector.PerformedValue(solution_index, flat_vars[j]):
course_index, opt_index = flat_vars_inverse[j]
if (selection[course_index] is not None) and (selection[course_index] != opt_index):
raise RuntimeError("Multiple options were chosen for "
"course {} ".format(course_index))
selection[course_index] = opt_index
return selection
|
def _global_to_local_key_slice(global_key, globalshape,
local_to_global_dict, axis=0):
""" Helper method to process slice keys """
if global_key == slice(None):
return global_key
if local_to_global_dict is None:
return global_key
global_start, global_stop, global_step = \
global_key.indices(globalshape[axis])
global_min, global_max = local_to_global_dict[axis]
#Condition slice start/stop
global_start = global_start if global_start is not None else 0
global_stop = \
global_stop if global_stop is not None else globalshape[axis]
#Bias start/stop by local min/max
local_start = global_start - global_min
local_stop = global_stop - global_min
local_key = slice(local_start, local_stop, global_step)
return local_key
|
def recursive_update(to_update, update):
"""
Recursively updates nested directories.
Args:
to_update (dict or collections.Mapping):
dict to update.
update (dict or collections.Mapping):
dict containing new values.
Returns:
dict: to_update
"""
if update:
for key, value in update.items():
if isinstance(value, dict):
value = recursive_update(to_update.get(key, {}), value)
to_update[key] = value
return to_update
|
def is_summable(num1, num2):
"""
If two numbers can be summed in a needed way.
Examples
-----
9000 80 -> True (9080)
20 30 -> False (20 30)
1 2 -> False (1 2)
2 1 -> False (2 1)
20 1 -> True (21)
-----
"""
if num1 == 10 or num2 == 0:
return False
place = len(str(num2))
str1 = str(num1)
if len(str1) > place and str1[-place] == "0":
return True
return False
|
def _FormatBytes(byts):
"""Pretty-print a number of bytes."""
if byts > 2**20.0:
byts /= 2**20.0
return '%.2fm' % byts
if byts > 2**10.0:
byts /= 2**10.0
return '%.2fk' % byts
return str(byts)
|
def without_fixed_prefix(form, prefix_length):
""" Return a new form with ``prefix_length`` chars removed from left """
word, tag, normal_form, score, methods_stack = form
return (word[prefix_length:], tag, normal_form[prefix_length:],
score, methods_stack)
|
def probably_reconstruction(file) -> bool:
"""Decide if a path may be a reconstruction file."""
return file.endswith("json") and "reconstruction" in file
|
def viz_b(body):
"""Create HTML b for graphviz"""
return '<B>{}</B>'.format(body)
|
def get_mouse_pos(mouse_pos, rows, width):
"""
Return the cell that has been clicked on with the mouse.
params:
mouse_pos (int, int): position of the cursor
rows (int): number of rows in the grid
width (int): width of the scren
return:
row, col (int, int): coordinates of clicked cell
"""
cell_width = width // rows
y, x = mouse_pos # get the x, y coordinates of the mouse
row = y // cell_width
col = x // cell_width
return row, col
|
def filter_colons(part):
"""Funtion to filter out timestamps (e.g. 08:30) and websites (e.g. http://site.com)"""
new_parts = []
split_part = part.split(':')
for idx in range(0, len(split_part)):
if idx == 0:
new_parts.append(split_part[idx])
elif split_part[idx][0].isalpha():
new_parts.append(split_part[idx])
else:
new_parts[-1] += ':' + split_part[idx] # not actually a new part, just add to last one
return new_parts
|
def get_date_shortcode(date_str):
"""
Get shortcode for the standard date strings, to use in submodel names
"""
if date_str == "std_contest":
return "SC"
elif date_str == "std_contest_daily":
return "SCD"
elif date_str == "std_future":
return "SF"
elif date_str == "std_test":
return "ST"
elif date_str == "std_val":
return "SV"
elif date_str == "std_contest_eval":
return "SCE"
elif date_str == "std_contest_eval_daily":
return "SCED"
elif date_str == "std_paper":
return "SP"
else:
return date_str
|
def age_similarity_scorer(age_1, age_2):
"""Compares two ages, returns 0 if they match, returns penalty of -1 otherwise.
Conservative assumptions:
1) If age cannot be cleanly cast to int, consider comparators to be a match
2) If ages are within 2 years, consider comparators to be a match
"""
try:
age_1 = int(age_1)
except:
return 0
try:
age_2 = int(age_2)
except:
return 0
# client requested age tolerance of 2 years:
if abs(age_1 - age_2) <= 2:
return 0
else:
return -1
|
def easy_iseven(x):
"""Takes a number and returns True if it's even, otherwise False"""
return x % 2 == 0
|
def _flatten(indices) -> tuple:
"""Return a flat tuple of integers to represent the indices.
Slice objects are not hashable, so we convert them.
"""
result = []
for x in indices:
if isinstance(x, slice):
result.extend([x.start, x.stop, x.step])
else:
result.append(x)
return tuple(result)
|
def int_to_bytes(integer_value: int) -> list:
"""
Converts a single integer number to an list with the length 2 with highest
byte first.
The returned list contains values in the range [0-255]
:param integer: the integer to convert
:return: the list with the high byte first
"""
if not (isinstance(integer_value, int) and 0 <= integer_value <= 65535):
raise ValueError(f'integer_value to be packed must be unsigned short: [0-65535]! value was {integer_value}')
return [(integer_value >> 8) & 0xFF, integer_value & 0xFF]
|
def find_sigfigs(text):
"""Parse through a snippet of text that states what the values are in."""
text = text.lower()
if text.find('million') != -1:
text = 'million'
return text
elif text.find('thousand') != -1:
text = 'thousand'
return text
elif text.find('billion') != -1:
text = 'billion'
return text
else:
text = 'unknown'
return text
|
def permutations(l):
"""
Return all the permutations of the list l.
Obivously this should only be used for extremely small lists (like less
than 9 members).
Paramters:
l - list to find permutations of
Return value:
list of lists, each list a permutation of l.
"""
if len(l) > 0:
return [ [x] + perms for x in l
for perms in permutations([ e for e in l if e != x]) ]
else:
return [[]]
|
def test_string_content(string):
"""Detects if string is integer, float or string.
Parameters
----------
string : string
An input string to be tested.
Returns
-------
string
A string with value 'int' if input is an integer,
'float' if the input is a float and 'string' if it
is just a regular string.
"""
try:
float(string)
return 'int' if ((string.count('.') == 0) and \
('e' not in string) and \
('E' not in string)) else 'float'
except ValueError:
return 'string'
|
def bubbleSort_decr1(array):
"""
It repeatedly swaps adjacent elements that are out of order
it has O(n2) time complexity
larger numbers are sorted first
"""
for i in range(len(array)):
for j in range(len(array)-1,i,-1):
if array[j-1] < array[j]:
array[j], array[j-1] = array[j-1], array[j]
return array
|
def title(name, code):
"""
Build a new valid title route for the rickroll
> http://rr.noordstar.me/ef8b2bb9
> http://rr.noordstar.me/the-title-that-emphasizes-your-point-well-ef8b2bb9
These are interpreted the same way.
"""
url = ""
for char in name:
char = char.lower()
if char in ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']:
url += char
elif char in [' ', '-', '/']:
url += '-'
else:
continue
if len(url) >= 41:
break
url += '-' + code
return url
|
def filter_empty_layer_containers(layer_list):
"""Filter out nested layers from containers."""
existing = set()
to_visit = layer_list[::-1]
filtered = []
while to_visit:
obj = to_visit.pop()
obj_id = id(obj)
if obj_id in existing:
continue
existing.add(obj_id)
if hasattr(obj, '_layers'):
filtered.append(obj)
to_visit.extend(obj.layers[::-1])
return filtered
|
def find_duckling_conflict_queries(duckling_outputs):
"""
Finds queries where duckling predicts multiple entities for the SAME span
:param duckling_outputs: PARSED duckling responses, dicts from dimension to a dict mapping tuple spans to values
:return:
"""
conflict_responses = {}
for i, response in enumerate(duckling_outputs):
response_values = list(response.values())
response_spans = []
for rv in response_values:
spans = list(rv.keys())
response_spans.extend(spans)
if len(response_spans) != len(set(response_spans)):
conflict_responses[i] = response
return conflict_responses
|
def running_mean(mylist, N):
"""
return the list with a running mean acroos the array, with a given kernel size
@param mylist array,list over which to average
@param value length of the averaging kernel
"""
cumsum, moving_aves = [0], []
for i, x in enumerate(mylist, 1):
cumsum.append(cumsum[i-1] + x)
if i >= N:
moving_ave = (cumsum[i] - cumsum[i-N])/N
# can do stuff with moving_ave here
moving_aves.append(moving_ave)
return moving_aves
|
def MapLines(f, s):
"""Apply a function across each line in a flat string.
Args:
f: A string transform function for a line.
s: A string consisting of potentially multiple lines.
Returns:
A flat string with f applied to each line.
"""
return '\n'.join(f(line) for line in s.split('\n'))
|
def get_lang_probability(lang_prob):
"""
Takes a string with the format lang:probability and returns
a tuple (lang, probability)
Args:
lang_prob: str
"""
lang, probability = lang_prob.split(":")
try:
probability = float(probability)
except Exception as e:
print("Cound not convert probability to float")
print(e)
return (lang, probability)
|
def ij_to_list_index(i, j, n):
"""
Assuming you have a symetric nxn matrix M and take the entries of the upper triangular including the
diagonal and then ravel it to transform it into a list. This function will transform a matrix location
given row i and column j into the proper list index.
:param i: row index of the matrix M
:param j: column index of matrix M
:param n: total number of rows / colums of n
:return: The correct index of the lost
"""
assert j >= i, "We only consider the upper triangular part..."
index = 0
for k in range(i):
index += n - k - 1
return index + j
|
def format_data_ascii(data):
"""Try to make an ASCII representation of the bytes.
Non printable characters are replaced by '?' except null character which
is replaced by '.'.
"""
msg_str = ''
for byte in data:
char = chr(byte)
if char == '\0':
msg_str = msg_str + '.'
elif ord(char) < 32 or ord(char) > 126:
msg_str = msg_str + '?'
else:
msg_str = msg_str + char
return msg_str
|
def bool2yn(b):
"""Helper function, returns \"yes\" if *b* is True, \"no\" if *b* is False."""
return ["no", "yes"][b]
|
def moveDWValues(tokens: list) -> list:
"""
Takes sanitised, tokenised URCL code.
Returns URCL code with all DW values moved to the end.
"""
DWValues = []
index = 0
while index < len(tokens):
line = tokens[index]
if line[0] == "DW":
DWValues.append(line)
tokens.pop(index)
elif line[0].startswith("."):
if index < len(tokens) - 1:
if tokens[index + 1][0] == "DW":
DWValues.append(line)
tokens.pop(index)
else:
index += 1
else:
index += 1
else:
index += 1
tokens += DWValues
return tokens
|
def url_join(*parts: str) -> str:
""" Join the different url parts with forward slashes. """
return "/".join([part.strip("/") for part in parts]) + ("/" if parts and parts[-1].endswith("/") else "")
|
def map_box(sbox, dbox, v):
"""
sbox is (lat1, lat2, long1, long2),
dbox is (x1, x2, y1, y2),
v is (lat, long).
result is (x, y)
"""
xscale = abs(dbox[1]-dbox[0])/abs(sbox[3]-sbox[2])
yscale = abs(dbox[3]-dbox[2])/abs(sbox[1]-sbox[0])
x = (v[1]-sbox[2]+dbox[0])*xscale
y = (v[0]-sbox[0]+dbox[2])*yscale
return x,y
|
def options_from_form(spawner, formdata):
"""Extract the passed form data into the self.user_options variable."""
options = {}
if formdata.get('is_custom_image', ["off"])[0] == "on":
options["image"] = formdata.get('custom_image', [None])[0]
else:
options["image"] = formdata.get('defined_image', [None])[0]
options["cpu_limit"] = formdata.get('cpu_limit', [None])[0]
options["mem_limit"] = formdata.get('mem_limit', [None])[0]
options["is_mount_volume"] = formdata.get('is_mount_volume', ["off"])[0]
options["days_to_live"] = formdata.get('days_to_live', [None])[0]
env = {}
env_lines = formdata.get('env', [''])
for line in env_lines[0].splitlines():
if line:
key, value = line.split('=', 1)
env[key.strip()] = value.strip()
options['env'] = env
options['shm_size'] = formdata.get('shm_size', [None])[0]
options['gpus'] = formdata.get('gpus', [None])[0]
return options
|
def make_region(chromosome, begin, end):
""" Create region string from coordinates.
takes 2 (1 for human 1-9) digit chromosome,
begin and end positions (1 indexed)"""
region = "chr" + str(chromosome) + ":" + str(begin) + "-" + str(end)
return region
|
def cve_is_about_system(cpe_type):
"""
Determines whether CVE is about system.
:param cpe_type: One of {'a', 'o', 'h'} = application, operating system,
hardware
:return: true if CVE is about system.
"""
return ('o' in cpe_type or 'h' in cpe_type) and 'a' not in cpe_type
|
def round_float_math(number: float) -> int:
"""
Unified rounding in all python versions.
Parameters:
----------
number : float
Input number.
Returns:
-------
int
Output rounded number.
"""
if abs(round(number) - number) == 0.5:
return int(2.0 * round(0.5 * number))
else:
return int(round(number))
|
def get_sample_t(ref_t, idx, num_samples, sr):
"""
Calculates Unix time for individual sample point (within a record).
The sample point time is calculated by subtracting a multiple of
1/sr from the reference time corresponding to the final sample point
in the record, where sr is the sample rate.
:param ref_t: The Unix time to use as a basis for the calculation.
:type ref_t: float
:param idx: The zero-based index of the sample point within the record.
:type idx: int
:param num_samples: The number of sample points within the record.
:type num_samples: int
:param sr: The sample rate (per second) of the record.
:type sr: float
:return: An estimated Unix time corresponding to the sample point.
:rtype: float
"""
return ref_t - ((1/sr)*(num_samples - 1 - idx))
|
def standardise_signal_pattern(signal_pattern: str) -> str:
"""
Sorts the letters in the given signal pattern alphabetically
"""
return "".join(sorted(signal_pattern))
|
def process_procedure(procedure):
"""
Cleans and sets new style division for calculations procedures. Used by
both the :view:`qa.perform.Upload` &
:view:`qa.perform.CompositeCalculation` views.
"""
return "\n".join([procedure, "\n"]).replace('\r', '\n')
|
def divup(x: int, y: int) -> int:
"""Divide x by y and round the result upwards."""
return (x + y - 1) // y
|
def can_semnops(f):
"""
checks if function has any semnops that
can be replaced
"""
if hasattr(f, 'displaced_bytes'):
return True
return False
|
def get_linked_to_dff_skills(dff_shared_state, current_turn, prev_active_skill):
"""Collect the skill names to turn on (actually this should be the only skill because active skill is the only)
which were linked to from one dff-skill to another one.
Returns:
list of skill names to turn on
"""
to_skills = []
for to_skill in dff_shared_state.get("cross_links", {}).keys():
cross_links = dff_shared_state.get("cross_links", {})[to_skill]
if (
cross_links.get(str(current_turn - 1), {}).get("from_service", "") == prev_active_skill
or cross_links.get(str(current_turn - 2), {}).get("from_service", "") == prev_active_skill
):
to_skills.append(to_skill)
return to_skills
|
def getdtype(real, logical):
"""
Converts a (real, logical) pair into one of the three types:
'real', 'complex' and 'binary'
"""
return "binary" if logical else ("real" if real else "complex")
|
def create_C1(data_set):
"""
Create frequent candidate 1-itemset C1 by scaning data set.
Args:
data_set: A list of transactions. Each transaction contains several items.
Returns:
C1: A set which contains all frequent candidate 1-itemsets
"""
C1 = set()
for t in data_set:
for item in t:
item_set = frozenset([item])
C1.add(item_set)
return C1
|
def nullable_string_tuple_to_string_array(nullable_string_tuple):
"""
Converts a nullable string tuple to an array representing it.
Parameters
----------
nullable_string_tuple : `None` or `tuple` of `str`
The value to convert.
Returns
-------
array : `list` of `str`
"""
if nullable_string_tuple is None:
array = []
else:
array = list(nullable_string_tuple)
return array
|
def Interpolate(a, b, p):
"""\
Interpolate between values a and b at float position p (0-1)
"""
return a + (b - a) * p
|
def gray_code(n: int):
"""Problem 48: Gray Code.
Parameters
----------
n : int
The number of
Returns
-------
"""
gray_code_list = ['0', '1']
if n == 1:
return gray_code_list
for i in range(0, n - 1):
# Prefix list elements with '0'
gray_code_left = ['0' + x for x in gray_code_list]
gray_code_list.reverse()
# After reversing prefix list elements with '1'
gray_code_right = ['1' + x for x in gray_code_list]
# Join lists
gray_code_left.extend(gray_code_right)
gray_code_list = gray_code_left
return gray_code_list
|
def add_leading_zeros(input_string: str, out_len: int) -> str:
"""This function adds leading zeros to the input string. The output string will have length == out_len
Args:
input_string (str): the input string
out_len (int): length of output string with leading zeros
Returns:
out_string (str): the initial string but wiht leading zeros up to out_len characters
"""
out_string = input_string.zfill(out_len)
return out_string
|
def lowercase(text):
"""Converts all text to lowercase"""
return text.lower()
|
def get_gene_palette(num_cls=182): #Ref: CCNet
""" Returns the color map for visualizing the segmentation mask.
Args:
num_cls: Number of classes
Returns:
The color map
"""
n = num_cls
palette = [0] * (n * 3)
for j in range(0, n):
lab = j
palette[j * 3 + 0] = 0
palette[j * 3 + 1] = 0
palette[j * 3 + 2] = 0
i = 0
while lab:
palette[j * 3 + 0] |= (((lab >> 0) & 1) << (7 - i))
palette[j * 3 + 1] |= (((lab >> 1) & 1) << (7 - i))
palette[j * 3 + 2] |= (((lab >> 2) & 1) << (7 - i))
i += 1
lab >>= 3
return palette
|
def _update_link(link):
"""The database contains links in the format
'http://leafe.com/download/<fname>'. I want this to be more explicit by
specifying the link as '/download_file/<fname>', so this function does
that. When I convert the site to use exclusively this newer code, I can
update the database, making this function moot.
"""
return link.replace("/download/", "/download_file/")
|
def calc_check_digit(number):
"""Calculate the check digit."""
# Old NIT
if number[10:13] <= '100':
weights = (14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2)
total = sum(int(n) * w for n, w in zip(number, weights))
return str((total % 11) % 10)
# New NIT
weights = (2, 7, 6, 5, 4, 3, 2, 7, 6, 5, 4, 3, 2)
total = sum(int(n) * w for n, w in zip(number, weights))
return str((-total % 11) % 10)
|
def check_game_status(board):
"""Return game status by current board status.
Args:
board (list): Current board state
Returns:
int:
-1: game in progress
0: draw game,
1 or 2 for finished game(winner mark code).
"""
for t in [1, 2]:
for j in range(0, 9, 3):
if [t] * 3 == [board[i] for i in range(j, j+3)]:
return t
for j in range(0, 3):
if board[j] == t and board[j+3] == t and board[j+6] == t:
return t
if board[0] == t and board[4] == t and board[8] == t:
return t
if board[2] == t and board[4] == t and board[6] == t:
return t
for i in range(9):
if board[i] == 0:
# still playing
return -1
# draw game
return 0
|
def IsResultFailure(result_data): # pragma: no cover
"""Returns true if result_data indicates a failure."""
while isinstance(result_data, list):
result_data = result_data[0]
if not result_data:
return False
# 0 means SUCCESS and 1 means WARNINGS.
return result_data not in (0, 1, '0', '1')
|
def get_file_content_type(extension):
"""
:param string extension: file extension
:returns string: mime type based on file extension
"""
try:
mime_types = {
'docx': 'application/vnd.openxmlformats-officedocument'
'.wordprocessingml.document',
'xls': 'application/vnd.ms-excel',
'xlsx': 'application/vnd.openxmlformats-officedocument'
'.spreadsheetml.sheet',
'pdf': 'application/pdf',
'csv': 'text/csv',
}
except KeyError:
return NotImplementedError
return mime_types[extension]
|
def evenFibSum(limit):
"""Sum even Fib numbers below 'limit'"""
sum = 0
a,b = 1,2
while b < limit:
if b % 2 == 0:
sum += b
a,b = b,a+b
return sum
|
def find_id(list, type):
"""Find id of given type in pubmed islist"""
matches = [x for x in list if x['idtype'] == type]
if matches:
return matches[0]["value"]
else:
raise KeyError("Id of type '" + type + "' not found in idlist.")
|
def metric(grams):
""" Converts grams to kilograms if grams are greater than 1,000. """
grams = int(grams)
if grams >= 1000:
kilograms = 0
kilograms = grams / 1000.0
# If there is no remainder, convert the float to an integer
# so that the '.0' is removed.
if not (grams % 1000):
kilograms = int(kilograms)
return u'%s %s' % (str(kilograms), 'kg')
else:
return u'%s %s' % (str(grams), 'g')
|
def helper(n, big):
"""
:param n: int, an integer number
:param big: the current largest digit
:return: int, the final largest digit
"""
n = abs(n)
if n == 0:
return big
else:
# check the last digit of a number
if big < int(n % 10):
big = int(n % 10)
# check the rest of the digits
return helper(n/10, big)
|
def _truncate_bitmap(what):
"""Determine the index of greatest byte that isn't all zeros, and
return the bitmap that contains all the bytes less than that index.
"""
for i in range(len(what) - 1, -1, -1):
if what[i] != 0:
return what[0: i + 1]
return what[0:1]
|
def AmbiguousCst(cst_lst):
"""
Returns properly formated string for declaring ambiguous constraints,
it takes a list of Rosetta-formated constraints string.
"""
header = 'AmbiguousConstraint\n'
for cst in cst_lst:
header += cst
header += 'END_AMBIGUOUS\n'
return header
|
def check_in_field(pos, field_config):
"""
Return flag to indicate whether the object is in the field
"""
k1 = field_config['borderline'][0]
k2 = field_config['borderline'][1]
b = field_config['borderline'][2]
flag = k1 * pos[0] + k2 * pos[1] + b > 0
return flag
|
def expand_comma(value):
"""
Adds a space after each comma, to allow word-wrapping of
long comma-separated lists."""
return value.replace(",", ", ")
|
def has_file_allowed_extension(filename, extensions):
"""Checks if a file is an allowed extension.
Args:
filename (string): path to a file
extensions (iterable of strings): extensions to consider (lowercase)
Returns:
bool: True if the filename ends with one of given extensions
"""
filename_lower = filename.lower()
return any(filename_lower.endswith(ext) for ext in extensions)
|
def appstruct_to_inputs(request, appstruct):
"""
Transforms appstruct to wps inputs.
"""
# LOGGER.debug("appstruct=%s", appstruct)
inputs = []
for key, values in list(appstruct.items()):
if key in ['_async_check', 'csrf_token']:
continue
if not isinstance(values, list):
values = [values]
for value in values:
# LOGGER.debug("key=%s, value=%s, type=%s", key, value, type(value))
inputs.append((str(key).strip(), str(value).strip()))
# LOGGER.debug("inputs form appstruct=%s", inputs)
return inputs
|
def asplit(string:str, number=2) -> list:
"""
Splits a string ever n characters -> default is 2
"""
return [string[i:i+number] for i in range(0, len(string), number)]
|
def load_txs(file):
"""
Load tsv format TXS annotation
Args:
file (str): TXS file
Returns:
list: TXS list
"""
if not file:
return list()
with open(file, "r") as f:
txs_text = f.readlines()
txs_data = list(map(lambda x: x.rstrip("\n").split("\t"), txs_text))
txs_list = list(map(lambda x: (x[0], int(x[1]), x[2]), txs_data))
return txs_list
|
def pluralize(value: int, noun: str) -> str:
"""Pluralize a noun."""
nouns = {"success": "successes", "die": "dice"}
pluralized = f"{value} {noun}"
if value != 1:
if noun in nouns:
pluralized = f"{value} {nouns[noun]}"
else:
pluralized += "s"
return pluralized
|
def add_content_in_dict(sample_dict, key, list_of_values):
"""Append multiple values to a key in the given dictionary"""
if key not in sample_dict:
sample_dict[key] = ""
sample_dict[key]=(list_of_values) # because it initializes, it replaces the first key value pair
return sample_dict
|
def _error_connection_handler(sock, client_addr, header):
"""
utility handler that does nothing more than provide a rejection header
@param sock: socket connection
@type sock: socket.socket
@param client_addr: client address
@type client_addr: str
@param header: request header
@type header: dict
"""
return {'error': "unhandled connection"}
|
def to_bits(cs):
"""Split a string into a list of numeric and non-numeric substrings."""
if not cs:
return []
out = []
tmp = ""
is_number = True
first = True
for c in cs:
if c in ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]:
if is_number:
tmp += c
else:
if not first:
out.append(tmp)
tmp = c
is_number = True
else:
if is_number:
if not first:
out.append(tmp)
tmp = c
is_number = False
else:
tmp += c
first = False
if not first:
out.append(tmp)
return out
|
def get_gcd(a, b):
""" The GCD (greatest common divisor) is the highest number that evenly divides both width and height. """
return a if b == 0 else get_gcd(b, a % b)
|
def pad_or_truncate(to_pad, length):
"""
Truncate or pad (with zeros) a GT text field
:param to_pad: text to pad
:type to_pad: either string or bytes
:param length: grow or shrink input to this length ("Procrustean bed")
:type length: int
:return: processed text field
:rtype:
"""
if isinstance(to_pad, str):
to_pad = to_pad.encode('latin-1')
return to_pad.ljust(length, b'\0')[0:length]
|
def mb_bl_ind(tr1, tr2):
"""Returns the baseline index for given track indices.
By convention, tr1 < tr2. Otherwise, a warning is printed,
and same baseline returned.
"""
if tr1 == tr2:
print("ERROR: no baseline between same tracks")
return None
if tr1 > tr2:
print("WARNING: tr1 exepcted < than tr2")
mx = max(tr1, tr2)
bl = mx*(mx-1)/2 + min(tr1, tr2)
return bl.astype(int)
|
def get_lock_status_flags(lock_status_value):
"""
Decode a lock status value provided as a hex string (like '0880'),
returning an array of strings representing the parsed bits into
textual described flags.
"""
flags = []
try:
status_value = bytearray.fromhex(lock_status_value)
if not status_value:
return ['NO-INPUT-ERROR']
except:
return ['BAD-INPUT-ERROR']
# check first status byte
if len(status_value) >= 1:
if status_value[0] == 0xff:
flags.append('unknown-status')
else:
if (status_value[0] & 0x01):
# matches 0b00000001
flags.append('closed')
else:
flags.append('open')
if status_value[0] & 0x08:
# matches 0b00001000
flags.append('child-safety')
if status_value[0] & 0x10:
# matches 0b00010000 (available for eRL2-2019+)
flags.append('secured-plugin')
if status_value[0] & 0x80:
# matches 0b10000000 (available for eRL2-2019+)
flags.append('unsecured-plugin')
# check second status byte (available for eRL2-2019+)
if len(status_value) >= 2:
if status_value[1] == 0xff:
flags.append('unknown-extended')
else:
if status_value[1] & 0x01:
# matches 0b00000001
flags.append('smart-plugin')
if status_value[1] & 0x80:
# matches 0b10000000
flags.append('button-pressed')
else:
flags.append('missing-status-value')
return flags
|
def max_pairwise_product(numbers):
"""
max_pairwise_product gets the two biggest numbers and returns the product of them
TimeComplexity: O(n)
"""
biggest = -9999999999999
second_bigest = -9999999999999
for ele in numbers:
if ele > biggest:
biggest, second_bigest = ele, biggest
elif ele > second_bigest:
second_bigest = ele
return biggest * second_bigest
|
def transitionsCount(trans):
"""Statistic function. Returs the count of the atuomaton transtions.
The calculation is done only from the a given transition dictionary.
The forward and backward transtion dictionary might coresponded, for
better results.
Args:
trans (dict): Transition dictionary.
Returns:
int: Count of a transtion from transition dictionary.
"""
count = 0
for fromS in trans:
for letter in trans[fromS]:
count += len(trans[fromS][letter])
return count
|
def get_test_node(request_or_item):
"""
Return the test node, typically a _pytest.Function.
Provided arg may be the node already, or the pytest request
:param request_or_item:
:return:
"""
try:
return request_or_item.node
except AttributeError:
return request_or_item
|
def valid_sequence(seq):
"""
Checks if the given sequences if valid.
"""
for chr in seq:
if not (chr == 'A' or chr == 'C' or chr == 'G' or chr == 'T'):
return False
return True
|
def first_letter_lower(input_string):
"""
Returns a new string with the first letter as lowercase
:param input_string: str
:return: str
"""
return input_string[:1].lower() + input_string[1:]
|
def lists_of_series_are_equal(list_of_series_1,list_of_series_2):
"""Equality test for list of series"""
return all([(s1==s2).all() for s1,s2 in zip(list_of_series_1,list_of_series_2)])
|
def passport_is_valid_1(passport):
""" Determines whether a passport is valid or not only checking the presence of the fields.
:param passport: passport
:return: boolean
"""
return all(field in passport.keys() for field in ['byr', 'iyr', 'eyr', 'hgt', 'hcl', 'ecl', 'pid'])
|
def sifchain_fees(sifchain_fees_int):
"""returns a string suitable for passing to sifnoded"""
return f"{sifchain_fees_int}rowan"
|
def deep_access(x, keylist):
"""Access an arbitrary nested part of dictionary x using keylist."""
val = x
for key in keylist:
val = val.get(key, 0)
return val
|
def bound(x, m, M=None):
"""
:param x: scalar
Either have m as scalar, so bound(x,m,M) which returns m <= x <= M *OR*
have m as length 2 vector, bound(x,m, <IGNORED>) returns m[0] <= x <= m[1].
"""
if M is None:
M = m[1]
m = m[0]
# bound x between min (m) and Max (M)
return min(max(x, m), M)
|
def reverseListOrder(query):
"""Reverse the order in a list."""
list_query = list(query)
list_query.reverse()
return list_query
|
def get_binary_class(value, thresh=4.0):
"""
Map a continuous value to a binary classification by thresholding.
"""
return int(value > thresh)
|
def _is_valid_ip_address(ipaddr):
"""
<Purpose>
Determines if ipaddr is a valid IP address.
0.X and 224-255.X addresses are not allowed.
Additionally, 192.168.0.0 is not allowed.
<Arguments>
ipaddr: String to check for validity. (It will check that this is a string).
<Returns>
True if a valid IP, False otherwise.
"""
# Argument must be of the string type
if not type(ipaddr) == str:
return False
if ipaddr == '192.168.0.0':
return False
# A valid IP should have 4 segments, explode on the period
octets = ipaddr.split(".")
# Check that we have 4 parts
if len(octets) != 4:
return False
# Check that each segment is a number between 0 and 255 inclusively.
for octet in octets:
# Attempt to convert to an integer
try:
ipnumber = int(octet)
except ValueError:
# There was an error converting to an integer, not an IP
return False
# IP addresses octets must be between 0 and 255
if not (ipnumber >= 0 and ipnumber <= 255):
return False
# should not have a ValueError (I already checked)
firstipnumber = int(octets[0])
# IP addresses with the first octet 0 refer to all local IPs. These are
# not allowed
if firstipnumber == 0:
return False
# IP addresses with the first octet >=224 are either Multicast or reserved.
# These are not allowed
if firstipnumber >= 224:
return False
# At this point, assume the IP is valid
return True
|
def project_onto_basis(x, y, z, xx, xy, xz, yx, yy, yz, zx, zy, zz):
"""Project vector onto different basis.
Parameters
----------
x : float or array-like
X component of vector
y : float or array-like
Y component of vector
z : float or array-like
Z component of vector
xx, yx, zx : float or array-like
X component of the x, y, z unit vector of new basis in original basis
xy, yy, zy : float or array-like
Y component of the x, y, z unit vector of new basis in original basis
xz, yz, zz : float or array-like
Z component of the x, y, z unit vector of new basis in original basis
Returns
-------
x, y, z
Vector projected onto new basis
"""
out_x = x * xx + y * xy + z * xz
out_y = x * yx + y * yy + z * yz
out_z = x * zx + y * zy + z * zz
return out_x, out_y, out_z
|
def print_totals(hist_dict, filename):
"""
Parameters
----------
hist_dict : Dictionary
Histogram dictionary containing number of repeats with certain length.
filename : String
Output file name.
Returns
-------
total : Int
Total number of repeats found.
"""
keys = list(hist_dict.keys()) # list of repeat lengths
keys.sort()
file = open(filename, 'w')
file.write('rep_num total\n')
total = 0 # count repeats
for rep_num in keys:
repeats = hist_dict[rep_num]
line = '{:7} {}\n'.format(rep_num, repeats)
file.write(line)
total += repeats
# print total number of repeats
file.write('\nTotal: {}'.format(total))
file.close()
return total
|
def double_number(number):
"""Multiply given number by 2
:param number:
:return:
"""
print("Inside double_number()")
return number * 2
|
def update_activity(p_dict, slug):
"""Updates activity by slug"""
updated_param = {
"name": p_dict["name"] if "name" in p_dict else "Testing Infra",
"slug": p_dict["slug"] if "slug" in p_dict else slug,
"uuid": "3cf78d25-411c-4d1f-80c8-a09e5e12cae3",
"created_at": "2014-04-16",
"updated_at": "2014-04-17",
"deleted_at": None,
"revision": 2
}
return updated_param
|
def f1d7p(f, h):
"""
A highly accurate seven-point finite difference stencil
for computing derivatives of a function.
"""
fm3, fm2, fm1, f1, f2, f3 = [f(i*h) for i in [-3, -2, -1, 1, 2, 3]]
fp = (f3-9*f2+45*f1-45*fm1+9*fm2-fm3)/(60*h)
return fp
|
def verify_unit_interval(value):
"""Throw an exception if the value is not on the unit interval [0,1].
"""
if not (value >= 0 and value <= 1):
raise ValueError("expected value on the interval [0, 1].")
return value
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.