content
stringlengths 42
6.51k
|
---|
def format_size(num, suffix="B"):
"""
Credit: Fred Cirera, http://stackoverflow.com/a/1094933
"""
for unit in ["", "Ki", "Mi", "Gi", "Ti", "Pi", "Ei", "Zi"]:
if abs(num) < 1024.0:
return "%3.1f%s%s" % (num, unit, suffix)
num /= 1024.0
|
def min_max_indexes(seq):
"""
Uses enumerate, max, and min to return the indices of the values
in a list with the maximum and minimum value:
"""
minimum = min(enumerate(seq), key=lambda s: s[1])
maximum = max(enumerate(seq), key=lambda s: s[1])
return minimum[0], maximum[0]
|
def AddSysPath(new_path):
""" AddSysPath(new_path): adds a directory to Python's sys.path
Does not add the directory if it does not exist or if it's already on
sys.path. Returns 1 if OK, -1 if new_path does not exist, 0 if it was
already on sys.path.
"""
import sys, os
# Avoid adding nonexistent paths
if not os.path.exists(new_path): return -1
# Standardize the path. Windows is case-insensitive, so lowercase
# for definiteness if we are on Windows.
new_path = os.path.abspath(new_path)
if sys.platform == 'win32':
new_path = new_path.lower()
# Check against all currently available paths
for x in sys.path:
x = os.path.abspath(x)
if sys.platform == 'win32':
x = x.lower()
if new_path in (x, x + os.sep):
return 0
sys.path.append(new_path)
# if you want the new_path to take precedence over existing
# directories already in sys.path, instead of appending, use:
# sys.path.insert(0, new_path)
return 1
|
def sdss_url(ra: float, dec: float):
"""
Construct URL for public Sloan Digital Sky Survey (SDSS) cutout.
from SkyPortal
"""
return (
f"http://skyserver.sdss.org/dr12/SkyserverWS/ImgCutout/getjpeg"
f"?ra={ra}&dec={dec}&scale=0.3&width=200&height=200"
f"&opt=G&query=&Grid=on"
)
|
def is_array(value):
"""Check if value is an array."""
return isinstance(value, list)
|
def _lax_friedrichs_flux(d_f, d_u, n_x, c):
"""Computes the Lax-Friedrichs flux."""
return 0.5 * n_x * d_f + 0.5 * c * d_u
|
def parse_arg_list_int(list_int):
"""Parse an argument as a list of integers."""
try:
params = [int(param) for param in list_int.split(",")]
except:
raise AttributeError()
return params
|
def make_population(population_size, solution_generator, *args, **kwargs):
"""Make a population with the supplied generator."""
return [
solution_generator(*args, **kwargs) for _ in range(population_size)
]
|
def compute_border_indices(log2_T, J, i0, i1):
"""
Computes border indices at all scales which correspond to the original
signal boundaries after padding.
At the finest resolution,
original_signal = padded_signal[..., i0:i1].
This function finds the integers i0, i1 for all temporal subsamplings
by 2**J, being conservative on the indices.
Maximal subsampling is by `2**log2_T` if `average=True`, else by
`2**max(log2_T, J)`. We compute indices up to latter to be sure.
Parameters
----------
log2_T : int
Maximal subsampling by low-pass filtering is `2**log2_T`.
J : int / tuple[int]
Maximal subsampling by band-pass filtering is `2**J`.
i0 : int
start index of the original signal at the finest resolution
i1 : int
end index (excluded) of the original signal at the finest resolution
Returns
-------
ind_start, ind_end: dictionaries with keys in [0, ..., log2_T] such that the
original signal is in padded_signal[ind_start[j]:ind_end[j]]
after subsampling by 2**j
References
----------
This is a modification of
https://github.com/kymatio/kymatio/blob/master/kymatio/scattering1d/utils.py
Kymatio, (C) 2018-present. The Kymatio developers.
"""
if isinstance(J, tuple):
J = max(J)
ind_start = {0: i0}
ind_end = {0: i1}
for j in range(1, max(log2_T, J) + 1):
ind_start[j] = (ind_start[j - 1] // 2) + (ind_start[j - 1] % 2)
ind_end[j] = (ind_end[j - 1] // 2) + (ind_end[j - 1] % 2)
return ind_start, ind_end
|
def open_file(input_file):
"""Check if the file format entered is supported"""
try:
teste = open(input_file, "r")
teste.close()
return True
except FileNotFoundError:
print('"%s"' % input_file, "not found. Type again: ")
return False
|
def underscore_targets(targets):
""" Takes in a list of targets and prefixes them with an underscore if they do not have one.
"""
result = []
for target in targets:
t = target
if target[0] != '_':
t = '_' + t
result.append(t)
return result
|
def get_spanner_instance_config(project_id, config):
""" Generate the instance config URL """
return "projects/{}/instanceConfigs/{}".format(project_id, config)
|
def get_resource_by_path(path, resources):
"""gets the resource that matches given path
Args:
path (str): path to find
resources (list(str)): list of resources
Returns:
dict: resource that matches given path, None otherwise
"""
return next(
(x for x in resources if x['path'] == path),
None)
|
def generate_latex_label(label_id):
"""Generates a LaTeX label with the given ID"""
return "\\label{%s}" % label_id
|
def get_tags(sections):
"""
Credit: https://www.kaggle.com/davidmezzetti/cord-19-analysis-with-sentence-embeddings
Searches input sections for matching keywords. If found, returns the keyword tag.
Args:
sections: list of text sections
Returns:
tags
"""
keywords = ["2019-ncov", "2019 novel coronavirus", "coronavirus 2019", "coronavirus disease 19", "covid-19",
"covid 19", "ncov-2019",
"sars-cov-2", "wuhan coronavirus", "wuhan pneumonia", "wuhan virus"]
tags = None
for text in sections:
if any(x in text.lower() for x in keywords):
tags = "COVID-19"
return tags
|
def generate_xmas_tree1(rows=10):
"""Generate a xmas tree of stars (*) for given rows (default 10).
Each row has row_number*2-1 stars, simple example: for rows=3 the
output would be like this (ignore docstring's indentation):
*
***
*****"""
width = rows * 2
output = []
for i in range(1, width + 1, 2):
row = "*" * i
output.append(row.center(width, " "))
return "\n".join(output)
|
def red(s):
"""
Return the given string (``s``) surrounded by the ANSI escape codes to
print it in red.
:param s: string to console-color red
:type s: str
:returns: s surrounded by ANSI color escapes for red text
:rtype: str
"""
return "\033[0;31m" + s + "\033[0m"
|
def hasNumbers(inputString):
"""
Tests to see if the ticker has numbers.
Param: inputString (any string) like "TSLA" or "INTC"
"""
return any(char.isdigit() for char in inputString)
|
def prepare_log(message, code=""):
"""
It gives a different look to your logs so that you can easily identify them.
:param message: message you want to log
:param code: error code if you want to log error (optional)
:return:
styled log message
"""
if code:
message = f"|~| {message}, error_code: {code} |~|"
else:
message = f"|~| {message} |~|"
return message
|
def split_at_linelen(line, length):
"""Split a line at specific length for code blocks or
other formatted RST sections.
"""
# Get number of splits we should have in line
i = int(len(line)/length)
p = 0
while i > 0:
p = p+length
# If position in string is not a space
# walk backwards until we hit a space
while line[p] != ' ':
p -= 1
# Split the line
line = line[:p] + '\n' + line[p+1:]
i -= 1
return line
|
def encode(number, base):
"""Encode given number in base 10 to digits in given base.
number: int -- integer representation of number (in base 10)
base: int -- base to convert to
return: str -- string representation of number (in given base)"""
# Handle up to base 36 [0-9a-z]
assert 2 <= base <= 36, 'base is out of range: {}'.format(base)
# Handle unsigned numbers only for now
assert number >= 0, 'number is negative: {}'.format(number)
dividend = number
divisor = base
quotient = 1
# in ascii table lower case 'a' is at the number 97
# so adding 10 + 87 = 97 => 'a', 11 + 87 = 98 => 'b' and so on
hex_letter_offset = 87
result = ''
while quotient != 0:
# check if dividend(number) is less than divisor(base)
# if true no need to devide. then divedend = remainder
if dividend < divisor:
remainder = dividend
quotient = 0
else:
remainder = dividend % divisor
# updating the dividend until it is less than devisor
dividend = (dividend - remainder) // divisor
if remainder > 9:
remainder = chr(remainder + hex_letter_offset)
result += str(remainder)
return result[::-1]
|
def get_as_subtext_field(field, field_title=None) -> str:
"""Get a certain variable as part of the subtext, along with a title for that variable."""
s = ""
if field:
s = f"{field} | "
else:
return ""
if field_title:
s = f"{field_title}: " + s
return s
|
def Zip(*data, **kwargs):
"""Recursive unzipping of data structure
Example: Zip(*[(('a',2), 1), (('b',3), 2), (('c',3), 3), (('d',2), 4)])
==> [[['a', 'b', 'c', 'd'], [2, 3, 3, 2]], [1, 2, 3, 4]]
Each subtree in the original data must be in the form of a tuple.
In the **kwargs, you can set the function that is applied to each fully unzipped subtree.
"""
import collections
function = kwargs["function"] if "function" in kwargs else None
if len(data) == 1:
return data[0]
data = [list(element) for element in zip(*data)]
for i, element in enumerate(data):
if isinstance(element[0], tuple):
data[i] = Zip(*element, **kwargs)
elif isinstance(element, list):
if function is not None:
data[i] = function(element)
return data
|
def pres_text(trial):
"""
input: current presentation trial # (int)
output: presentation instruction text (string) for given presentation trial
"""
pres1 = ' Now we will begin the main experiment! ' \
'Again you will see cue icons, followed by a series of image pairs and letters (and a fixation cross).' \
'\n\n Remember to: ' \
'\n\n Keep your eyes staring at the cross' \
'\n Shift your attention to the SAME cued side and part for EACH pair' \
'\n Immeditaely press 1 ("x") or 3 ("o") when you see the letter ' \
'\n\n Do you have questions? Ask them now! ' \
'\n Otherwise, position your hand over the 1 and 3 buttons, clear your mind, and press any key to begin. '
pres2 = ' Feel free to take a moment to rest, if you like! ' \
' When you\'re ready, we will do another round with a cue, followed by image pairs and letters.' \
' \n\n Remember to: ' \
'\n Keep your eyes staring at the cross' \
'\n Shift your attention to the SAME cued side and part for EACH pair' \
'\n Immeditaely press 1 ("x") or 3 ("o") when you see the letter ' \
'\n\n Press any key to begin. '
instructions = [pres1, pres2]
if trial >= 1:
num = 1
else:
num = 0
return(instructions[num])
|
def list_to_dict(object_list, key_attribute='id'):
"""Converts an object list to a dict
:param object_list: list of objects to be put into a dict
:type object_list: list
:param key_attribute: object attribute used as index by dict
:type key_attribute: str
:return: dict containing the objects in the list
:rtype: dict
"""
return dict((getattr(o, key_attribute), o) for o in object_list)
|
def check_uniqueness_in_columns(board: list):
"""
Check buildings of unique height in each column.
Return True if buildings in all columns column have unique height, False otherwise.
>>> check_uniqueness_in_columns(['***21**', '412453*', '423145*', '*543215',\
'*35214*', '*41532*', '*2*1***'])
True
>>> check_uniqueness_in_columns(['***21**', '412453*', '4231452', '*543215',\
'*352142', '*41532*', '*2*1***'])
True
>>> check_uniqueness_in_columns(['***21**', '412453*', '423145*', '*543215',\
'*35214*', '*41534*', '*2*1***'])
False
>>> check_uniqueness_in_columns(['***21**', '432453*', '423145*', '*543215',\
'*35214*', '*41532*', '*2*1***'])
False
"""
for col_idx in range(1, len(board[0]) - 1):
heights = set()
for row_idx in range(1, len(board) - 1):
if board[row_idx][col_idx] == '*':
continue
if board[row_idx][col_idx] in heights:
return False
heights.add(board[row_idx][col_idx])
return True
|
def make_name(url: str):
"""
Auxiliary function to retrieve CIF name from an URL
Parameters
----------
url : An URL for a CIF in COD.
Returns
-------
A CIFname string from an URL from COD
"""
return url.split("/")[-1].split(".")[0] + ".cif"
|
def validate_image_choices(dep_var, x_dim, bs, splits, num_epochs, num_channels):
"""
Checks to see if user choices are consistent with expectations
Returns failure message if it fails, None otherwise.
"""
splits = [float(num) for num in splits]
if sum(splits) != 1:
return 'Splits must add up to 1 (Currently adding up to ' + str(sum(splits)) + ')'
if num_channels not in [1, 3]:
return 'Number of channels in image (' + str(num_channels) + ' found) should be 1 or 3'
return None
|
def get_all_keys(items):
"""Get all keys in a list of dictionary.
Parameters
----------
items : list
List of dictionaries.
Returns
-------
list
List containing all keys in the dictionary.
"""
ret = []
if not hasattr(items, "__iter__"):
return ret
if isinstance(items, str):
return ret
for i, item in enumerate(items):
if isinstance(item, list):
ret.append(get_all_keys(item))
elif isinstance(item, dict):
[ret.append(it) for it in item.keys() if it not in ret]
return ret
|
def cube_shade(x, y, z, n):
"""Return the color diference between the sides of the cube."""
return [
1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, # top
0.3, 0.3, 0.3, 0.3, 0.3, 0.3, 0.3, 0.3, 0.3, 0.3, 0.3, 0.3, # bottom
0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, # left
0.8, 0.8, 0.8, 0.8, 0.8, 0.8, 0.8, 0.8, 0.8, 0.8, 0.8, 0.8, # right
0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, # front
0.8, 0.8, 0.8, 0.8, 0.8, 0.8, 0.8, 0.8, 0.8, 0.8, 0.8, 0.8, # back
]
|
def get_mirror_vertex_index(symmetry_table, vertex_index):
"""
Function that uses symmetry table to return symmetrical vertex index of the given 1; -1 if failed
:param vertex_index: int
:return: int
"""
mirror_index = -1
if not symmetry_table:
return mirror_index
for i in range(len(symmetry_table)):
if vertex_index == symmetry_table[i]:
if i % 2 == 0:
mirror_index = symmetry_table[i + 1]
else:
mirror_index = symmetry_table[i - 1]
break
return mirror_index
|
def circulation_default_extension_max_count(loan):
"""Return a default extensions max count."""
return float("inf")
|
def partition(array, start, end):
""" sets up markers for pivot point, left marker
and right marker then iteratively swap into place
as the markers converge"""
# initialize variables
piv = array[start]
left = start+1
right = end
done = False # create switch
while not done:
# iterate pointer through without swap if item is
# less than pivot point
while (left <= right) and (array[left] <= piv):
left += 1
# iterate pointer through without swap if item is
# greater than pivot point
while (array[right] >= piv) and (right >= left):
right -= 1
if right < left:
done = True # switch to break loop
# otherwise, swap items
else:
temp = array[left]
array[left] = array[right]
array[right] = temp
temp = array[start]
array[start] = array[right]
array[right] = temp
return right
|
def count_offspring(cycle: int, days: int) -> int:
"""Counts how many offspring will be spawn over a given period"""
if cycle >= days:
return 1
if cycle == 0:
return count_offspring(8, days - 1) + count_offspring(6, days - 1)
return count_offspring(cycle - 1, days - 1)
|
def destination_index(circle):
"""
>>> destination_index([3, 2, 5, 4, 6, 7])
(2, 1)
>>> destination_index([2, 5, 4, 6, 7, 3])
(7, 4)
>>> destination_index([5, 8, 9, 1, 3, 2])
(3, 4)
"""
val_next = circle[0] - 1
while val_next not in circle:
val_next -= 1
if val_next < 0:
val_next = max(circle)
return val_next, circle.index(val_next)
|
def addprint(x: int, y: int):
"""Print and "added" representation of `x` and `y`."""
expr = x + y
return "base addprint(x=%r, y=%r): %r" % (x, y, expr)
|
def latexify_n2col(x, nplaces=None, **kwargs):
"""Render a number into LaTeX in a 2-column format, where the columns split
immediately to the left of the decimal point. This gives nice alignment of
numbers in a table.
"""
if nplaces is not None:
t = '%.*f' % (nplaces, x)
else:
t = '%f' % x
if '.' not in t:
return '$%s$ &' % t
left, right = t.split('.')
return '$%s$ & $.%s$' % (left, right)
|
def create_login_role(username, password):
"""Helper method to construct SQL: create role."""
# "create role if not exists" is not valid syntax
return f"DROP ROLE IF EXISTS {username}; CREATE ROLE {username} WITH CREATEROLE LOGIN PASSWORD '{password}';"
|
def identifyByCurrent(abfIDs, slopesDrug, slopesBaseline,threshold):
"""
Identify a responder by asking whether the change of current is BIGGER than a given threshold.
"""
responders=[]
nonResponders=[]
for i in range(len(abfIDs)):
deltaCurrent = round(slopesDrug[i]-slopesBaseline[i],3) # pA / min
if deltaCurrent > threshold:
nonResponders.append(abfIDs[i])
else:
responders.append(abfIDs[i])
return responders, nonResponders
|
def to_time_unit_string(seconds, friendlier=True):
"""Converts seconds to a (friendlier) time unit string, as 1h, 10m etc.)"""
seconds_str = str(seconds).replace('.0', '')
if seconds_str == '60':
seconds_str = '1m'
elif seconds_str == '600':
seconds_str = '10m'
elif seconds_str == '3600':
seconds_str = '1h'
else:
seconds_str = seconds_str+'s'
return seconds_str
|
def find_missing_number(array: list):
"""return the missing number in the continuous integer sequence"""
array.sort()
missing = 0
for index, number in enumerate(array):
if index != number:
missing = index
print(f'Missing from the continuous sequence: {index}')
break
return missing
|
def parse_boolean(s):
"""Takes a string and returns the equivalent as a boolean value."""
s = s.strip().lower()
if s in ("yes", "true", "on", "1"):
return True
elif s in ("no", "false", "off", "0", "none"):
return False
else:
raise ValueError("Invalid boolean value %r" % s)
|
def grid_dist(pos1, pos2):
"""
Get the grid distance between two different grid locations
:param pos1: first position (tuple)
:param pos2: second position (tuple)
:return: The `manhattan` distance between those two positions
"""
x1, y1 = pos1
x2, y2 = pos2
dy = y2 - y1
dx = x2 - x1
# If different sign, take the max of difference in position
if dy * dx < 0:
return max([abs(dy), abs(dx)])
# Same sign or zero just take sum
else:
return abs(dy + dx)
|
def export_stop_mask_pft(pve_wm, pve_gm, pve_csf):
"""
full path to a nifti file containing the
tractography stop mask
"""
return {"stop_file": [pve_wm, pve_gm, pve_csf]}
|
def gCallback(dataset, geneid, colors):
"""Callback to set initial value of green slider from dict.
Positional arguments:
dataset -- Currently selected dataset.
geneid -- Not needed, only to register input.
colors -- Dictionary containing the color values.
"""
colorsDict = colors
try:
colorVal = colorsDict[dataset][4:-1].split(',')[1]
return int(colorVal)
except KeyError:
return 0
|
def false_discovery_rate(cm):
"""
false discovery rate (FDR)
FDR = FP / (FP + TP) = 1 - PPV
"""
return cm[0][1] / float(cm[0][1] + cm[1][1])
|
def ordered(obj):
"""Helper function for dict comparison.
Recursively orders a json-like dict or list of dicts.
Args:
obj: either a list or a dict
Returns:
either a sorted list of elements or sorted list of tuples
"""
if isinstance(obj, dict):
return sorted((k, ordered(v)) for k, v in obj.items())
if isinstance(obj, list):
return sorted(ordered(x) for x in obj)
else:
return obj
|
def scale_ticks_params(tick_scale='linear'):
""" Helper function for learning cureve plots.
Args:
tick_scale : available values are [linear, log2, log10]
"""
if tick_scale == 'linear':
base = None
label_scale = 'Linear Scale'
else:
if tick_scale == 'log2':
base = 2
label_scale = 'Log2 Scale'
elif tick_scale == 'log10':
base = 10
label_scale = 'Log10 Scale'
else:
raise ValueError('The specified tick scale is not supported.')
return base, label_scale
|
def inject_into_param(ptype, max_tests, inst_idxs, inst_params, prev_inj_insts, cur_inst_idx, common_params):
"""
Decide if the implicitly given parameter should be injected into.
:param ptype: "GET" or "POST"
:param max_tests: maximum times a parameter should be injected into
:param inst_idxs: list of indices where the parameter is used in
:param inst_params: info about parameters of the current instance
:param prev_inj_insts: list of parameters of previous injections of the parameter
:param cur_inst_idx: index of the current instance
:param common_params: the list of common parameters
:return: True if the parameter should be injected into, otherwise False
"""
# inject into parameter if no other potential instances left
inj_count = len(prev_inj_insts)
rem_inst_count = len([idx for idx in inst_idxs if idx >= cur_inst_idx])
if rem_inst_count <= max_tests - inj_count:
if not any(prev_inst_params == inst_params for prev_inst_params in prev_inj_insts):
return True
elif inj_count >= max_tests:
return False
# inject into parameter if at least one common parameter has a different value than before
check_ptypes = ("GET", ) if ptype == "GET" else ("GET", "POST")
for ptype_check in check_ptypes:
cur_common_params = [key for key in common_params[ptype_check] if key in inst_params[ptype_check]]
for prev_inst_params in prev_inj_insts:
# check if this instance has a common parameter that is not in any previous instance
if any(common_key not in prev_inst_params[ptype_check] for common_key in cur_common_params):
return True
# check if this instance has common parameter with value different from previous instances
if any(inst_params[ptype_check][common_key] != prev_inst_params[ptype_check][common_key]
for common_key in cur_common_params):
return True
return False
|
def replace_by_list(my_string, list_strs, new_value):
"""
Applies a character override to a string based on a list of strings
"""
for s in list_strs:
my_string = my_string.replace(s, new_value)
return my_string
|
def dependencyParseAndPutOffsets(parseResult):
"""
Args:
parseResult:
Returns:
(rel, left{charStartOffset, charEndOffset, wordNumber}, right{charStartOffset, charEndOffset, wordNumber})
dependency parse of the sentence where each item is of the form
"""
dParse = parseResult['sentences'][0]['basic-dependencies']
tokens = parseResult['sentences'][0]['tokens']
result = []
for item in dParse:
rel = item['dep']
leftIndex = item['governor']
rightIndex = item['dependent']
if 'governorGloss' not in item:
if leftIndex == 0:
item['governorGloss'] = 'ROOT'
else:
item['governorGloss'] = tokens[leftIndex- 1]['word']
if 'dependentGloss' not in item:
if rightIndex == 0:
item['dependentGloss'] = 'ROOT'
else:
item['dependentGloss'] = tokens[rightIndex - 1]['word']
# left and right order is important
left = item['governorGloss']
right = item['dependentGloss']
leftIndex -= 1
rightIndex -= 1
left += '{' + str(tokens[leftIndex]['characterOffsetBegin']) + ' ' + str(
tokens[leftIndex]['characterOffsetEnd']) + ' ' + str(leftIndex + 1) + '}'
right += '{' + str(tokens[rightIndex]['characterOffsetBegin']) + ' ' + str(
tokens[rightIndex]['characterOffsetEnd']) + ' ' + str(rightIndex + 1) + '}'
result.append([rel, left, right])
return result
|
def remove_empty_from_dict(original):
"""get a new dict which removes keys with empty value
:param dict original: original dict, should not be None
:return: a new dict which removes keys with empty values
"""
return dict((k, v) for k, v in original.items()
if v is not None and v != '' and v != [] and v != {})
|
def find_max_difference(array_1, array_2):
"""Find the maximum absolute difference between array_1[j] and array_2[j]."""
return max([abs(array_1[j] - array_2[j]) for j in range(len(array_1))])
|
def is_proper_position(dimension, position):
"""
Check whether the given position is a proper position for any board
with the given dimension.
- The given position must be a tuple of length 2 whose elements are both
natural numbers.
- The first element identifies the column. It may not exceed the given
dimension.
- The second element identifies the row. It may not exceed the given
dimension incremented with 1 (taking into account the overflow position)
ASSUMPTIONS
- None
"""
if not isinstance(position, tuple) or len(position) != 2:
return False
if position[0] <= 0 or position[1] <= 0: # Negative integer
return False
if position[0] > dimension or position[1] > dimension + 1: # Greater than dimension
return False
return True
|
def map_module(mod):
"""Map module names as needed"""
if mod == "lambda":
return "awslambda"
return mod
|
def _text_color(route_color: str):
"""Calculate if route_text_color should be white or black"""
# This isn't perfect, but works for what we're doing
red, green, blue = int(route_color[:2], base=16), int(route_color[2:4], base=16), int(route_color[4:6], base=16)
yiq = 0.299 * red + 0.587 * green + 0.114 * blue
if yiq > 128: return "000000"
else: return "FFFFFF"
|
def translate_dna_to_peptide(dna_str):
""" Translate a DNA sequence encoding a peptide to amino-acid sequence via RNA.
If 'N' is included in input dna, 'X' will be outputted since 'N' represents
uncertainty. Also will output a flag indicating if has stop codon.
Parameters
----------
dna_str: str or List(str). dna string to be translated.
Returns
-------
aa_str: translated peptide
has_stop_codon: Indicator for showing if the input dna contains stop codon
"""
codontable = {
'ATA': 'I', 'ATC': 'I', 'ATT': 'I', 'ATG': 'M',
'ACA': 'T', 'ACC': 'T', 'ACG': 'T', 'ACT': 'T',
'AAC': 'N', 'AAT': 'N', 'AAA': 'K', 'AAG': 'K',
'AGC': 'S', 'AGT': 'S', 'AGA': 'R', 'AGG': 'R',
'CTA': 'L', 'CTC': 'L', 'CTG': 'L', 'CTT': 'L',
'CCA': 'P', 'CCC': 'P', 'CCG': 'P', 'CCT': 'P',
'CAC': 'H', 'CAT': 'H', 'CAA': 'Q', 'CAG': 'Q',
'CGA': 'R', 'CGC': 'R', 'CGG': 'R', 'CGT': 'R',
'GTA': 'V', 'GTC': 'V', 'GTG': 'V', 'GTT': 'V',
'GCA': 'A', 'GCC': 'A', 'GCG': 'A', 'GCT': 'A',
'GAC': 'D', 'GAT': 'D', 'GAA': 'E', 'GAG': 'E',
'GGA': 'G', 'GGC': 'G', 'GGG': 'G', 'GGT': 'G',
'TCA': 'S', 'TCC': 'S', 'TCG': 'S', 'TCT': 'S',
'TTC': 'F', 'TTT': 'F', 'TTA': 'L', 'TTG': 'L',
'TAC': 'Y', 'TAT': 'Y', 'TAA': '_', 'TAG': '_',
'TGC': 'C', 'TGT': 'C', 'TGA': '_', 'TGG': 'W'
}
dna_str = dna_str.upper()
has_stop_codon = False
aa_str = []
for idx in range(0, len(dna_str), 3):
codon = dna_str[idx:idx + 3]
if len(codon) < 3:
break
if 'N' in codon:
aa_str.append('X')
else:
if codontable[codon] == '_':
has_stop_codon = True
return ''.join(aa_str), has_stop_codon
else:
aa_str.append(codontable[codon])
return ''.join(aa_str), has_stop_codon
|
def annealing_epsilon(episode: int, min_e: float, max_e: float, target_episode: int) -> float:
"""Return an linearly annealed epsilon
Epsilon will decrease over time until it reaches `target_episode`
(epsilon)
|
max_e ---|\
| \
| \
| \
min_e ---|____\_______________(episode)
|
target_episode
slope = (min_e - max_e) / (target_episode)
intercept = max_e
e = slope * episode + intercept
Args:
episode (int): Current episode
min_e (float): Minimum epsilon
max_e (float): Maximum epsilon
target_episode (int): epsilon becomes the `min_e` at `target_episode`
Returns:
float: epsilon between `min_e` and `max_e`
"""
slope = (min_e - max_e) / (target_episode)
intercept = max_e
return max(min_e, slope * episode + intercept)
|
def is_triangular(k):
"""
k, a positive integer
returns True if k is triangular and False if not
"""
triangular_number = 0
for i in range(1, k+1):
triangular_number = triangular_number + i
if triangular_number == k:
return True
elif triangular_number > k:
return False
else:
continue
|
def jinja2_split(env, s, ch):
"""Splits string 's' with character 'ch' as delimiter into a list of parts.
"""
return s.split(ch)
|
def isPowerOfTwo_ver2(n: int) -> bool:
"""
:type n: int
:rtype: bool - returns true if n is power of 2, false otherwise
"""
return n > 0 and bin(n).count("1") == 1
|
def find_message(text):
"""Find a secret message"""
return ''.join(a for a in text if ord(a) in range (65, 91))
|
def get_boolean(value) -> bool:
"""Convert a value to a boolean.
Args:
value: String value to convert.
Return:
bool: True if string.lower() in ["yes", "true"]. False otherwise.
"""
bool_val = False
try:
if value.lower() in ["yes", "true"]:
bool_val = True
except AttributeError:
error = "Could not convert '%s' to bool, must be a string" % (value)
raise AttributeError(error)
return bool_val
|
def maybe_download(train_data, test_data, train2_data=""):
"""Maybe downloads training data and returns train and test file names."""
if train_data:
train_file_name = train_data
else:
train_file_name = "training_data.csv"
if test_data:
test_file_name = test_data
else:
#test_file_name = "./data/test-1.csv"
test_file_name = "testing_data.csv"
if train2_data:
train2_file_name = train2_data
else:
train2_file_name = "training_data_augmented.csv"
#test_file_name = "./data/train-1.csv"
return train_file_name, test_file_name, train2_file_name
|
def read_image(filename):
"""Read in the file from path and return the opaque binary data
:rtype: str
"""
with open(filename) as handle:
return handle.read()
|
def deleteDuplicateLabels(tokens: list) -> list:
"""
Takes sanitised, tokenised URCL code.
Returns URCL code with all duplicated labels removed.
"""
index = 0
while index < len(tokens) - 1:
line = tokens[index]
line2 = tokens[index + 1]
if line[0].startswith(".") and line2[0].startswith("."):
label = line[0]
label2 = line2[0]
for index3 in range(len(tokens)):
line3 = tokens[index3]
while line3.count(label2) != 0:
tokens[index3][line3.index(label2)] = label
tokens.pop(index + 1)
else:
index += 1
return tokens
|
def row_to_index(row):
"""
Returns the 0-based index of given row name.
Parameters
----------
row : int or unicode
Row name.
Returns
-------
int
0-based row index.
Examples
--------
>>> row_to_index('1')
0
"""
row = int(row)
assert row > 0, 'Row must be greater than 0!'
return row - 1
|
def binary_search(lst, val):
"""This function will bring in a list and a value. Returns index of value or -1 if value not found."""
status = False
for n in range(len(lst)):
if lst[n] == val:
status = True
return n
if status is False:
return -1
|
def getlimit(code, aname):
"""
:param code:
:param aname:
:return:
"""
if code[:-1] == '15900' or code == '511880' or code == '511990' or code == '131810' or code == '204001':
return 1000000
else:
if aname == 'a1':
return 0 # 10000#0 means except money fund, no other trades are allowed
elif aname == 'a2':
return 10000
|
def get_hour(day_str):
"""
UTILITY FUNCTION
just returns the hour from the date string. USED in ((apply)) method to create a
column of hours.
"""
return day_str[11:13]
|
def isfloat(value):
"""
Check input for float conversion.
:param value: input value
:type value:str
:return: True if input_value is a number and False otherwise
"""
try:
float(value)
return True
except ValueError:
return False
|
def dict_to_one(dp_dict):
"""Input a dictionary, return a dictionary that all items are set to one.
Used for disable dropout, dropconnect layer and so on.
Parameters
----------
dp_dict : dictionary
The dictionary contains key and number, e.g. keeping probabilities.
"""
return {x: 1 for x in dp_dict}
|
def print_matrix(matrix):
"""
:param matrix:print_matrix
:return:None
"""
if not matrix:
return None
start = 0
row = len(matrix)
col = len(matrix[0])
while row > start * 2 and col > start * 2:
# one round
col_end = col - start - 1
row_end = row - start - 1
for j in range(start, col_end+1):
print(matrix[start][j])
if row_end > start:
for i in range(start+1, row_end+1):
print(matrix[i][col_end])
if col_end > start and row_end > start:
for j in range(col_end-1, start-1, -1):
print(matrix[row_end][j])
if col_end > start and row_end - 1 > start:
for i in range(row_end-1,start,-1):
print(matrix[i][start])
start += 1
return
|
def _get_module_name(module):
"""returns a module's name"""
# multiprocessing imports the __main__ module into a new module called
# __parents_main__ and then renames it. We need the modulename to
# always be the same as the one in the parent process.
if module.__name__ == "__parents_main__":
return "__main__"
return module.__name__
|
def compute_applicable_changes(previous_applicable_steps, applicable_steps):
"""
Computes and returns the new applicable steps and the no longer
applicable steps from previous and current list of applicable steps
"""
new_applicable_steps = []
no_longer_applicable_steps = []
# new applicable steps
for step in applicable_steps:
if step not in previous_applicable_steps:
new_applicable_steps.append(step)
# no longer applicable steps
for step in previous_applicable_steps:
if step not in applicable_steps:
no_longer_applicable_steps.append(step)
# Debug #
# print("\nCompute new applicable")
# print("applicable_steps:")
# for step in applicable_steps:
# print(" {}".format(step.action))
# print("previous_applicable_steps:")
# for step in previous_applicable_steps:
# print(" {}".format(step.action))
# print("new applicable steps :")
# for new_app_step in new_applicable_steps:
# print(" {}".format(new_app_step.action))
# print("no longer applicable steps :")
# for no_long_app_steps in no_longer_applicable_steps:
# print(" {}".format(no_long_app_steps.action))
return new_applicable_steps, no_longer_applicable_steps
|
def parse_nat_msg(msg):
""" Parse a syslog message from the nat program into a python
dictionary.
:param msg: nat msg from syslog
:return: a dictionary of nat related key value pairs
"""
dnat_in = ''
out = ''
mac = ''
src = -1
dest = -1
len_ = -1
tos = -1
proc = -1
ttl = -1
id_ = -1
proto = ''
spt = -1
dpt = -1
window = -1
res = ''
urgp = -1
words = msg.split(' ')
for w in words:
if w.startswith('DNAT_IN='):
dnat_in = w.split('=')[1]
elif w.startswith('OUT='):
out = w.split('=')[1]
elif w.startswith('MAC='):
mac = w.split('=')[1]
elif w.startswith('SRC='):
src = w.split('=')[1]
elif w.startswith('DST='):
dest = w.split('=')[1]
elif w.startswith('LEN='):
len_ = w.split('=')[1]
elif w.startswith('TOS='):
tos = w.split('=')[1]
elif w.startswith('PREC='):
proc = w.split('=')[1]
elif w.startswith('TTL='):
ttl = w.split('=')[1]
elif w.startswith('ID='):
id_ = w.split('=')[1]
elif w.startswith('PROTO='):
proto = w.split('=')[1]
elif w.startswith('SPT='):
spt = w.split('=')[1]
elif w.startswith('DPT='):
dpt = w.split('=')[1]
elif w.startswith('WINDOW='):
window = w.split('=')[1]
elif w.startswith('RES='):
res = w.split('=')[1]
elif w.startswith('URGP='):
urgp = w.split('=')[1]
d = dict()
d['dnat_in'] = dnat_in
d['out'] = out
d['mac_address'] = mac
d['src_ip'] = src
d['dest_ip'] = dest
d['len'] = len_
d['tos'] = tos
d['proc'] = proc
d['ttl'] = ttl
d['id'] = id_
d['proto'] = proto
d['spt'] = spt
d['dpt'] = dpt
d['window'] = window
d['res'] = res
d['urgp'] = urgp
return d
|
def hex_to_rgb(col_hex):
"""Convert a hex colour to an RGB tuple"""
col_hex = col_hex.lstrip("#")
return bytearray.fromhex(col_hex)
|
def merge(left_array, right_array):
"""Merge two sorted lists into one sorted list
Note:
this function is a helper method for merge sort.
It doesn't work correctly with unsorted input params.
Implemented as a public function because of usage in
multiprocess modification of a merge sort.
Args:
left_array: sorted list
right_array: sorted list
Returns:
sorted list which consists of all elements passed as parameters
"""
i, j = 0, 0
result = []
while True:
if i >= len(left_array):
result.extend(right_array[j:])
break
if j >= len(right_array):
result.extend(left_array[i:])
break
if left_array[i] <= right_array[j]:
result.append(left_array[i])
i += 1
else:
result.append(right_array[j])
j += 1
return result
|
def make_list_slug(name):
"""Return the slug for use in url for given list name."""
slug = name.lower()
# These characters are just stripped in the url
for char in '!@#$%^*()[]{}/=?+\\|':
slug = slug.replace(char, '')
# These characters get replaced
slug = slug.replace('&', 'and')
slug = slug.replace(' ', '-')
return slug
|
def read_gtf(feature_filename, sources, types):
"""
Parse feature_filename and return:
1) a dictionary of features keyed by IDs and 2) a dictionary mapping features to IDs.
:param feature_filename:
:param sources:
:param types:
:return:
"""
types = set(types)
features, feature_to_id = {}, {}
for line_num, line in enumerate(feature_filename):
if line[0] != '#':
split_line = line.strip().split('\t')
assert len(split_line) >= 7, 'Column error on line {}: {}'.format(
line_num, split_line)
feature_type = split_line[2]
if feature_type in types:
fields = dict([
field_value_pair.strip().split(' ')
for field_value_pair in split_line[8].split(';')
if len(field_value_pair) > 0
])
if fields['gene_source'].strip('"') in sources:
chrom = split_line[0]
start = int(split_line[3])
end = int(split_line[4])
if split_line[6] == '+':
strand = 1
elif split_line[6] == '-':
strand = -1
else:
strand = 0
gene_name = fields['gene_name'].strip('"')
ensembl_id = fields['gene_id'].strip('"')
# Make sure not duplicated ensembl IDs
assert ensembl_id not in features
features[ensembl_id] = {
'contig': chrom,
'start': start,
'end': end,
'strand': strand,
'gene_name': gene_name,
'ensembl_id': ensembl_id
}
if gene_name not in feature_to_id:
feature_to_id[gene_name] = ensembl_id
return features, feature_to_id
|
def where_to_go(point1, point2, separator):
"""
Takes in two integers, point1 and point2, and a string separator.
Returns all the integers between point1 and point2 with the
string separator separating each integer.
Parameters:
point1: Starting point/integer.
point2: Ending point/integer.
separator: String to separate each integer with.
Returns:
String containing all integers between and including
point1 and point2 separated by separator string.
>>> where_to_go(17, 17, 'left')
'17'
>>> where_to_go(1, 8, ',')
'1,2,3,4,5,6,7,8'
>>> where_to_go(8, 1, '->')
'8->7->6->5->4->3->2->1'
# Add AT LEAST 3 doctests below, DO NOT delete this line
>>> where_to_go(1, 5, '')
'12345'
>>> where_to_go(1, 5, 'nft')
'1nft2nft3nft4nft5'
>>> where_to_go(-5, 0, ' ')
'-5 -4 -3 -2 -1 0'
>>> where_to_go(-5, 0, '!')
'-5!-4!-3!-2!-1!0'
"""
if point1 < point2:
return str(point1) + separator + \
where_to_go(point1 + 1, point2, separator)
elif point2 < point1:
return str(point1) + separator + \
where_to_go(point1 - 1, point2, separator)
elif point2 == point1:
return str(point1)
|
def truncate_down_to_maxlen(split_sentence, maxlen):
""" function used to truncate a sentence down to maxlen words """
# truncate it
truncated_split_sentence = split_sentence[:maxlen]
# return the rejoined sentence
return " ".join(truncated_split_sentence)
|
def make_baseurl(scheme, host, port=None):
"""Creates URL using given parameters.
Args
-----
scheme (str): http or https
host (str): hostname
port (int, optional): Port number as integer
Returns
-------
Formatted URL to use with http apis.
"""
base_url = None
if port is None:
base_url = "{}://{}".format(scheme, host)
else:
base_url = "{}://{}:{}".format(scheme, host, port)
return base_url
|
def normalizeAngle(angle):
"""
:param angle: (float)
:return: (float) the angle in [-pi, pi]
"""
# while angle > np.pi:
# angle -= 2 * np.pi
# while angle < -np.pi:
# angle += 2 * np.pi
# return angle
return angle
|
def problem_1_3(left: str, right: str) -> bool:
"""
Given two strings, write a method to decide if one is a permutation of the other.
So, I could iterate through a range of indicies and construct a single hashmap to store the counts of a character.
We can add from one str and remove from the other. This would result in all values should equal = 0
>>> problem_1_3("abc", "cba")
True
>>> problem_1_3("a", "b")
False
>>> problem_1_3("aabbcc", "ccbbaa")
True
The below solution using a defaultdict should return with speed of O(n)
"""
if len(left) != len(right):
return False
from collections import defaultdict
_d = defaultdict(int)
for i in range(len(left)):
_d[left[i]] += 1
_d[right[i]] -= 1
for v in _d.values():
if v != 0:
return False
return True
|
def get_subclass_dict(cls):
"""Get a dictionary with the subclasses of class 'cls'.
This method returns a dictionary with all the classes that inherit from
class cls.
Note that this method only works for new style classes
:param cls: class to which we want to find all subclasses
:type cls: class object
:return: dictionary whose keys are the names of the subclasses and values
are the subclass objects.
:rtype: dict
"""
subclass_dict = {}
for subclass in cls.__subclasses__():
subclass_dict[subclass.__name__] = subclass
subclass_dict.update(get_subclass_dict(subclass))
return subclass_dict
|
def _get_perm_phase(order, phase):
"""Get the phase of the given permutation of points."""
n_points = len(order)
return phase ** sum(
1 for i in range(n_points) for j in range(i + 1, n_points)
if order[i] > order[j]
)
|
def _ParseHeader(header):
"""Parses a str header into a (key, value) pair."""
key, _, value = header.partition(':')
return key.strip(), value.strip()
|
def getCountsAndAverages(IDandRatingsTuple):
""" Calculate average rating
Args:
IDandRatingsTuple: a single tuple of (MovieID, (Rating1, Rating2, Rating3, ...))
Returns:
tuple: a tuple of (MovieID, (number of ratings, averageRating))
"""
rateCnt = len(IDandRatingsTuple[1])
return (IDandRatingsTuple[0], (rateCnt, float(sum(IDandRatingsTuple[1]))/rateCnt))
|
def consume_token(s, token, l_trunc=0, r_trunc=0, strip_leading=True):
"""
:param s: String to scan
:param token: Substring to target
:param l_trunc: Truncate chars from left; Positive integer
:param r_trunc: Truncate chars from right; Positive integer
:param strip_leading: Remove leading whitespace
:return: Modified input string
"""
s_len = len(s)
token_len = len(token)
result = s[l_trunc + s.find(token) + token_len:s_len - r_trunc]
if strip_leading:
result = result.strip()
return result
|
def angleToInt(angle):
"""
Converts an angle to an integer the servo understands
"""
return int(angle/300.0*1023)
|
def titleToURL(wikiTitles:list):
"""
Observations:
Function converts wikipadia titles to urls
From observation, wikipedia urls are just https://en.wikipedia.org/wiki/ followed by title
having their spaces replaced with "_"
i.e. a wiki page with the title "Computer science" (without the quotes), has the url
https://en.wikipedia.org/wiki/Computer_science
Input:
wikiTitles : list,
list of valid wikipedia titles
Called By: extractWikiData
"""
urls = []
for title in wikiTitles:
urls.append("https://en.wikipedia.org/wiki/"+"_".join(title.split(" ")))
return urls
|
def y_gradient(y, constraint_set):
"""
Computes y gradient
"""
constraint_keys = constraint_set['constraints']
gradient = 0
for key in constraint_keys:
current_constraint = constraint_set[key]
a_matrix = current_constraint['A']
bound_loss = current_constraint['bound_loss']
for i, _ in enumerate(a_matrix):
constraint = a_matrix[i]
gradient += 2*constraint * bound_loss[i]
return gradient
|
def strsize(b):
"""Return human representation of bytes b. A negative number of bytes
raises a value error."""
if b < 0:
raise ValueError("Invalid negative byte number")
if b < 1024:
return "%dB" % b
if b < 1024 * 10:
return "%dKB" % (b // 1024)
if b < 1024 * 1024:
return "%.2fKB" % (float(b) / 1024)
if b < 1024 * 1024 * 10:
return "%.2fMB" % (float(b) / (1024 * 1024))
if b < 1024 * 1024 * 1024:
return "%.1fMB" % (float(b) / (1024 * 1024))
if b < 1024 * 1024 * 1024 * 10:
return "%.2fGB" % (float(b) / (1024 * 1024 * 1024))
return "%.1fGB" % (float(b) / (1024 * 1024 * 1024))
|
def kvp_string_to_rec(string):
"""Take an input string 'a=b,c=d,e=f' and return the record
{'a':'b','c':'d','e':'f'}"""
rec = {}
for kvp in string.split(','):
arr = kvp.split('=')
if len(arr) > 2:
raise Exception("Cannot convert %s to KVP" % string)
rec[arr[0]] = arr[1]
return rec
|
def validate_scale_increment(value, _):
"""Validate the `scale_increment` input."""
if value is not None and not 0 < value < 1:
return 'scale increment needs to be between 0 and 1.'
|
def get_instance_data(sample_annotation_data: list):
"""Gets a dictionary mapping every instance token -> data about it
Args:
sample_annotation_data (list): a list of dictionaries with
sample annotation information
Returns:
dict: a dictionary mapping instance_tokens to dicts about them
"""
# Map from instance_token -> dict
instance_data = {}
for annotation in sample_annotation_data:
instance_token = annotation["instance_token"]
if instance_token in instance_data:
# If the instance token already exists in the instance_data
timestamp = annotation["timestamp"]
if timestamp < instance_data[instance_token]["first_annotation_timestamp"]:
instance_data[instance_token]["first_annotation_token"] = annotation[
"token"
]
instance_data[instance_token]["first_annotation_timestamp"] = timestamp
elif timestamp > instance_data[instance_token]["last_annotation_timestamp"]:
instance_data[instance_token]["last_annotation_token"] = annotation[
"token"
]
instance_data[instance_token]["last_annotation_timestamp"] = timestamp
# Update the count
instance_data[instance_token]["nbr_annotations"] += 1
else:
# If we need to add the instance for the first time
instance_data[instance_token] = {
"token": instance_token,
"category_token": annotation["category_token"],
"nbr_annotations": 1,
"first_annotation_token": annotation["token"],
"first_annotation_timestamp": annotation["timestamp"],
"last_annotation_token": annotation["token"],
"last_annotation_timestamp": annotation["timestamp"],
}
# Remove timestamps
for instance_dict in instance_data.values():
del instance_dict["first_annotation_timestamp"]
del instance_dict["last_annotation_timestamp"]
return instance_data
|
def sort_012(input_list):
"""
Given an input array consisting on only 0, 1, and 2, sort the array in a single traversal.
Args:
input_list(list): List to be sorted
"""
z,o = 0,0
t = len(input_list) - 1
while o <= t:
if input_list[o] == 0:
input_list[o], input_list[z] = input_list[z], input_list[o]
z += 1
o += 1
elif input_list[o] == 1:
o += 1
elif input_list[o] == 2:
input_list[o], input_list[t] = input_list[t], input_list[o]
t -= 1
return input_list
|
def jaccard(seq1, seq2):
"""
Computes the distance between two sequences using the formula below:
D(X, Y) = 1 - |X intersection Y| / |X union Y|
:type seq1: a list of of strings
:param seq1: a sequence
:type seq2: a list of of strings
:param seq2: a sequence
:return dist: the distance
"""
dist = 1 - len(set(seq1).intersection(set(seq2))) / len(set(seq1).union(set(seq2)))
return dist
|
def line_line_intersection(x1, y1, x2, y2, x3, y3, x4, y4, infinite=False):
""" Determines the intersection point of two lines, or two finite line segments if infinite=False.
When the lines do not intersect, returns an empty list.
"""
# Based on: P. Bourke, http://local.wasp.uwa.edu.au/~pbourke/geometry/lineline2d/
ua = (x4-x3)*(y1-y3) - (y4-y3)*(x1-x3)
ub = (x2-x1)*(y1-y3) - (y2-y1)*(x1-x3)
d = (y4-y3)*(x2-x1) - (x4-x3)*(y2-y1)
if d == 0:
if ua == ub == 0:
# The lines are coincident
return []
else:
# The lines are parallel.
return []
ua /= float(d)
ub /= float(d)
if not infinite and not (0<=ua<=1 and 0<=ub<=1):
# Intersection point is not within both line segments.
return None, None
return [(x1+ua*(x2-x1), y1+ua*(y2-y1))]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.