content stringlengths 42 6.51k |
|---|
def get_subscriber_ids(subscribers):
"""This function pulls the subscriber IDs out of dictionaries and into a single list.
:param subscribers: A list of dictionaries containing subscriber information from which to extract the IDs
:type subscribers: list
:returns: A list of IDs for the supplied subscribers
"""
subscriber_ids = []
for subscriber in subscribers:
subscriber_ids.append(subscriber['id'])
return subscriber_ids |
def ensure_str(s, encoding='utf-8', errors='strict'):
"""Coerce *s* to `str`.
For Python 3:
- `str` -> `str`
- `bytes or bytearray` -> decoded to `str`
"""
if not isinstance(s, (str, bytes, bytearray)):
raise TypeError("not expecting type '%s'" % type(s))
if isinstance(s, (bytes, bytearray)):
s = s.decode(encoding, errors)
return s |
def to_deg(value, loc):
"""convert decimal coordinates into degrees, munutes and seconds tuple
Keyword arguments: value is float gps-value, loc is direction list ["S", "N"] or ["W", "E"]
return: tuple like (25, 13, 48.343 ,'N')
"""
if value < 0:
loc_value = loc[0]
elif value > 0:
loc_value = loc[1]
else:
loc_value = ""
abs_value = abs(value)
deg = int(abs_value)
t1 = (abs_value-deg)*60
min = int(t1)
sec = round((t1 - min)* 60, 5)
return (deg, min, sec, loc_value) |
def safe_version(*args, **kwargs):
"""
Package resources is a very slow load
"""
import pkg_resources
return pkg_resources.safe_version(*args, **kwargs) |
def addslashes(s, escaped_chars=None):
"""Add slashes for given characters. Default is for ``\`` and ``'``.
:param s: string
:param escaped_chars: list of characters to prefix with a slash ``\``
:return: string with slashed characters
:rtype: str
:Example:
>>> addslashes("'")
"\\'"
"""
if escaped_chars is None:
escaped_chars = ["\\", "'", ]
# l = ["\\", '"', "'", "\0", ]
for i in escaped_chars:
if i in s:
s = s.replace(i, '\\' + i)
return s |
def get_token_time(token_index, sentence, duration):
"""
Linearly interpolate to guess the time a token was utterred
"""
sentence_len = max(len(sentence), 1)
return token_index / sentence_len * duration |
def get_half_star(value):
"""one of those things that's weirdly hard with templates"""
return f"{value}.5" |
def _is_in_cycle(monomer, cl_prototypes, visited, root):
"""Recursively checks for cycles in conservation law dependencies via
Depth First Search
Arguments:
monomer: current location in cl dependency graph
cl_prototypes: dict that contains dependency and target indexes for
every monomer @type dict
visited: history of visited monomers with conservation laws
root: monomer at which the cycle search was started
Returns:
Raises:
"""
if monomer == root:
return True # we found a cycle and root is part of it
if monomer in visited:
return False # we found a cycle but root is not part of it
visited.append(monomer)
prototype = cl_prototypes[monomer]
if prototype['target_index'] not in prototype['dependency_idx']:
return False
return any(
_is_in_cycle(
connecting_monomer,
cl_prototypes,
visited,
root
)
for connecting_monomer in prototype['dependency_idx'][
prototype['target_index']
]
) |
def field(s, n, d):
"""
Engage does not put empty fields into the JSON from API calls.
That means we need to be careful when try to get fields from a
dict parsed from JSON provided by Engage.
This function checks to see if a field ('n') is in a dict ('s').
If the answer is yes, then the value is returned. If no, then
'd' is returned. """
if n in s:
return s[n]
else:
return d |
def convert_bin_magnitude(val, orders):
"""Convert a number to another binary order of magnitude.
Args:
val (int, float): Value to convert.
orders (int): Orders of magnitude, such as 3 to convert a value in
bytes to gibibytes (GiB), or -2 to convert a value in
tebibytes (TiB) to mebibytes (MiB).
Returns:
"""
return val / 1024 ** orders |
def indexOfMaxValue (theList):
"""Finds the maximum value of theList.
:param theList: The list in which to find the maximum
:type theList: list
:return: The maximum value and its indexes w/in the list
:rtype: tuple
"""
max_value = theList[0]
max_index = []
for i in range(len(theList)):
if theList[i] == max_value:
max_index.append(i)
elif theList[i] > max_value:
max_index.clear()
max_value = theList[i]
max_index.append(i)
return max_value, max_index |
def list_non_None(lst):
""" return [i for i,s in enumerate(cex_list) if not s == None]"""
L = []
for i in range(len(lst)):
if not lst[i] == None:
L = L + [i]
return L |
def _unique_ids(pairs_list, used_ids):
"""Return pairs_list that does not contain previously used ids"""
pairs_list_f = [x for x in pairs_list
if ((used_ids[x[0][0]] == 0) and
(used_ids[x[1][0]] == 0))]
return pairs_list_f |
def quick_sort(seq):
"""Quicksort method."""
if isinstance(seq, list):
if len(seq) <= 1:
return seq
piv, seq = seq[0], seq[1:]
low, high = [x for x in seq if x <= piv], [x for x in seq if x > piv]
return quick_sort(low) + [piv] + quick_sort(high)
else:
raise TypeError('Input type must be a list.') |
def jaccard(A: set, B: set) -> float:
"""Jaccard Similarity Coefficient or Intersection over Union
Parameters:
-----------
A, B : set
Sets of unique shingles
Return:
-------
metric : float
The Jaccard Similarity Coefficient
"""
u = float(len(A.intersection(B)))
return u / (len(A) + len(B) - u) |
def sort(d):
"""sort dictionary by keys"""
if isinstance(d, dict):
return {k: d[k] for k in sorted(d)}
return d |
def list_difference(l1, l2):
"""list substraction compatible with Python2"""
# return l1 - l2
return list(set(l1) - set(l2)) |
def _resolve_resource_path(resource):
"""Returns sfc resource path."""
if resource == 'port_pair':
return "/sfc/port_pairs"
elif resource == 'port_pair_group':
return "/sfc/port_pair_groups"
elif resource == 'port_chain':
return "/sfc/port_chains"
elif resource == 'flow_classifier':
return "/sfc/flow_classifiers" |
def rpartition(seq, n):
"""
Partition sequence in groups of n starting from the end of sequence.
"""
seq = list(seq)
out = []
while seq:
new = []
for _ in range(n):
if not seq:
break
new.append(seq.pop())
out.append(new[::-1])
return out[::-1] |
def IsArray(obj):
"""Determine if an object is an array"""
return isinstance(obj, (list, tuple)) |
def count_set_bits(bitmap):
"""
Counts the number of bits set to 1 in bitmap
"""
bmp = bitmap
count = 0
n = 1
while bmp > 0:
if bmp & 1:
count += 1
bmp = bmp >> 1
n = n + 1
return count |
def find(k, seq):
"""
Search for item in a list.
Returns: Boolean
"""
# for item in seq:
# if k == item:
# return True
if k in seq:
return True
else:
return False |
def get_crop_size(crop_w, crop_h, image_w, image_h):
"""
Determines the correct scale size for the image
when img w == crop w and img h > crop h
Use these dimensions
when img h == crop h and img w > crop w
Use these dimensions
"""
scale1 = float(crop_w) / float(image_w)
scale2 = float(crop_h) / float(image_h)
scale1_w = crop_w # int(round(img_w * scale1))
scale1_h = int(round(image_h * scale1))
scale2_w = int(round(image_w * scale2))
scale2_h = crop_h # int(round(img_h * scale2))
if scale1_h > crop_h: # scale1_w == crop_w
# crop on vertical
return (scale1_w, scale1_h)
else: # scale2_h == crop_h and scale2_w > crop_w
#crop on horizontal
return (scale2_w, scale2_h) |
def convertAbsCoco2relCoco(x, y, w, h, img_w, img_h):
"""
INPUT: coco absolute parameters, image width, image height (in pixels)
OUTPUT: coco relative parameters
"""
x_rel = x/img_w
y_rel = y/img_h
w_rel = w/img_w
h_rel = h/img_h
return (x_rel, y_rel, w_rel, h_rel) |
def new_solution(A, refs):
"""
check if A is already in the reference solutions
"""
for B in refs:
match = True
for a, b in zip(A, B):
a.sort()
b.sort()
if a != b:
match = False
break
if match:
return False
return True |
def invert_bloblist(bloblist):
""" Returns a dictionary on the form md5sum -> [blobinfo,
blobinfo, ...] """
result = {}
for bi in bloblist:
if bi['md5sum'] not in result:
result[bi['md5sum']] = []
result[bi['md5sum']].append(bi)
return result |
def shout_echo(word1, echo=1):
"""Concatenate echo copies of word1 and three
exclamation marks at the end of the string."""
# Initialize empty strings: echo_word, shout_words
echo_word=''
shout_words=''
# Add exception handling with try-except
try:
# Concatenate echo copies of word1 using *: echo_word
echo_word = word1*echo
# Concatenate '!!!' to echo_word: shout_words
shout_words = echo_word+'!!!'
except:
# Print error message
print("word1 must be a string and echo must be an integer.")
# Return shout_words
return shout_words |
def get_req_pkg_name(r):
"""Return the package name part of a python package requirement.
For example
"funcsigs;python<'3.5'" will return "funcsigs"
"pytest>=3" will return "pytest"
"""
return r.replace('<', '=').replace('>', '=').replace(';', '=').split("=")[0] |
def get_seq_diff(seq_tuple):
"""Returns the difference between two TCP sequence numbers."""
(seq_min, seq_max) = seq_tuple
if None in (seq_min, seq_max) or 0 in (seq_min, seq_max):
return None
# Seq wrap-around
diff = seq_max - seq_min
if diff < 0:
diff += 2 ** 32
return diff |
def _get_pkg_and_version(pkg_str):
"""Uses Python style package==0.1 version specifications.
"""
parts = pkg_str.split("==")
if len(parts) == 1:
return parts[0], None
else:
assert len(parts) == 2
return parts |
def topological_sort(graph):
"""
Repeatedly go through all of the nodes in the graph, moving each of
the nodes that has all its edges resolved, onto a sequence that
forms our sorted graph. A node has all of its edges resolved and
can be moved once all the nodes its edges point to, have been moved
from the unsorted graph onto the sorted one.
Parameters
----------
graph : dict
Dictionary that has graph structure.
Raises
------
RuntimeError
If graph has cycles.
Returns
-------
list
List of nodes sorted in topological order.
"""
sorted_nodes = []
graph_unsorted = graph.copy()
while graph_unsorted:
acyclic = False
for node, edges in list(graph_unsorted.items()):
if all(edge not in graph_unsorted for edge in edges):
acyclic = True
del graph_unsorted[node]
sorted_nodes.append(node)
if not acyclic:
raise RuntimeError("A cyclic dependency occurred")
return sorted_nodes |
def call_plugins(plugins, method, *arg, **kw):
"""Call all method on plugins in list, that define it, with provided
arguments. The first response that is not None is returned.
"""
for plug in plugins:
func = getattr(plug, method, None)
if func is None:
continue
#LOG.debug("call plugin %s: %s", plug.name, method)
result = func(*arg, **kw)
if result is not None:
return result
return None |
def find_common_elements(list_1, list_2):
"""
Simple method to find the intersection of two lists.
Args:
list_1 and list_2: The two lists
Returns:
intersection: The common elements of the two lists
"""
return [i for i in list_1 if i in list_2] |
def asIntOrNone(val):
"""Converts floats, integers and string representations of integers
(in any base) to integers. Truncates floats.
If val is "NaN" (case irrelevant) returns None.
Raises ValueError or TypeError for all other values
"""
if hasattr(val, "lower"):
# string-like object; check for NaN and force base to 0
if val.lower() in ("nan", "?"):
return None
return int(val, 0)
else:
# not a string; convert as a number (base cannot be specified)
return int(val) |
def uniq_count(data):
"""
Count number of unique elements in the data.
Args:
data (list): values.
Returns the number of unique elements in the data.
"""
uniq_atom_list = list(set(data))
return len(uniq_atom_list) |
def ValueErrorOnFalse(ok, *args):
"""Returns None / arg / (args,...) if ok."""
if not isinstance(ok, bool):
raise TypeError('Use ValueErrorOnFalse only on bool return value')
if not ok:
raise ValueError('CLIF wrapped call returned False')
# Plain return args will turn 1 into (1,) and None into () which is unwanted.
if args:
return args if len(args) > 1 else args[0]
return None |
def sum_up_diagonals(matrix):
"""Given a matrix [square list of lists], return sum of diagonals.
Sum of TL-to-BR diagonal along with BL-to-TR diagonal:
>>> m1 = [
... [1, 2],
... [30, 40],
... ]
>>> sum_up_diagonals(m1)
73
>>> m2 = [
... [1, 2, 3],
... [4, 5, 6],
... [7, 8, 9],
... ]
>>> sum_up_diagonals(m2)
25
"""
# # m4 = [[1, 2, 3, 4, 5, 6], 1, 6 0, 5
# # [4, 5, 6, 7, 8, 6], 5, 8 1, 4
# # [7, 8, 9, 0, 1, 6], 9, 0 2, 3
# # [6, 7, 8, 9, 0, 6], 8, 9 3, 2
# # [5, 6, 7, 8, 9, 6], 6, 9 4, 1
# # [4, 5, 6, 7, 8, 9]] 4, 9 5, 0
# # ny = 6 my = 3
# # nx = 6 mx = 3
# # m4 = [[1, 2, 3, 4, 5], 1, 5 0, 4
# # [4, 5, 6, 7, 8], 5, 7 1, 3
# # [7, 8, 9, 0, 1], 9 2, 2
# # [6, 7, 8, 9, 0], 7, 9 1, 3
# # [5, 6, 7, 8, 9]] 5, 9 0, 4
# # ny = 5 my = 2
# # nx = 5 mx = 2
# # m4 = [[1, 2, 3, 4], 1, 4 0, 3
# # [4, 5, 6, 7], 5, 6 1, 2
# # [7, 8, 9, 0], 8, 9 2, 1
# # [6, 7, 8, 9]] 6, 9 3, 0
# # ny = 4 my = 2
# # nx = 4 mx = 2
# # m3 = [[1, 2, 3], 1, 3 0, 2
# # [4, 5, 6], 5 1, 1
# # [7, 8, 9]] 7, 9 3, 0
# # ny = 3 my = 1
# # nx = 3 mx = 1
# # m2 = [[1, 2], 1, 2 0, 1
# # [4, 5]] 4, 5 1, 0
# # ny = 2 my = 1
# # nx = 2 mx = 1
ny = len(matrix)
sum = 0
for iy, m in enumerate(matrix): # rows 0, 1
ix = ny - iy -1
m[ix] + m[iy]
if (iy == ix):
sum = sum + m[ix]
else:
sum = sum + m[ix] + m[iy]
return sum |
def traditional_constants_isf_equation(tdd):
""" Traditional ISF equation with constants from ACE consensus """
a = 1700
return a / tdd |
def last_non_empty_cell(cells):
"""Returns the index + 1 for the last non-empty cell
"""
idx = len(cells)
for cell in cells[::-1]:
if cell.source:
return idx
idx -= 1
return idx |
def stringToLengthAndCombo(combo_string):
"""Creates a tuple of (attribute, value) tuples from a given string.
Args:
combo_string: string representation of (attribute, value) tuples.
Returns:
combo_tuple: tuple of (attribute, value) tuples.
"""
length = len(combo_string.split(';'))
combo_list = []
for col_vals in combo_string.split(';'):
parts = col_vals.split(':')
if len(parts) == 2:
combo_list.append((parts[0], parts[1]))
combo_tuple = tuple(combo_list)
return length, combo_tuple |
def optimal_tuning_ratio(mass_ratio):
"""
Returns optimal tuning ratio (TMD freq / Mode freq) per eqn (7) in
Warburton & Ayorinde (1980)
"""
return 1 / (1 + mass_ratio) |
def is_power_of_two(x):
"""
Returns true if x is a power of two, false otherwise.
"""
from math import log
if x <= 0:
return False
log2 = int(log(x, 2))
return x == 2 ** log2 |
def median(l):
"""
Compute the median of a list.
"""
length = len(l)
if length % 2 == 1:
return l[(length + 1) // 2 - 1]
else:
a = l[(length // 2) - 1]
b = l[length // 2]
return (float(a + b)) / 2 |
def check_numeric_type_instance(value) -> bool:
"""Method checks if value is int or float
Parameters
----------
value : Expected Numeric type
Returns
-------
: bool
True - value is numeric, False - value is other than the number
"""
if isinstance(value, str):
return False
else:
try:
_ = int(value)
except Exception as _e:
return False
return True |
def is_ray_thru_point(ray_start, ray_end, pos) -> bool:
"""Helper function: returns true iff x,y coordinates of pos is colinear with (start,end) and lies between them
"""
if pos == ray_end or pos == ray_start:
return False
x1, y1 = ray_start
x2, y2 = ray_end
xp, yp = pos
# Colinearity test: using ray_start as the reference, check that slopes are equal. In other words,
# (y2-y1)/(x2-x1)=(yp-y1)/(xp-x1). Avoiding divide-by-zero, this is:
colinear = (y2 - y1) * (xp - x1) == (yp - y1) * (x2 - x1)
if not colinear:
return False
# Dot product test: dot of (pos-start) x (end-start) must lie between 0 and the norm of (end-start)
dot = (x2 - x1) * (xp - x1) + (y2 - y1) * (yp - y1)
norm = (x2 - x1) ** 2 + (y2 - y1) ** 2
return 0 < dot < norm |
def get_lessons_of_a_teacher(username, all_lessons):
"""
Get the lessons that a teacher has.
"""
users_lessons = dict()
# Filter all the lessons of one user
for lesson in all_lessons:
#logging.error(lesson)
#logging.error(all_lessons[lesson])
for one_class in all_lessons[lesson]:
if 'instructor' in one_class:
if username == one_class['instructor']:
if lesson not in users_lessons.keys():
users_lessons[lesson] = list()
users_lessons[lesson].append(one_class)
return users_lessons |
def _BoolsToInts(arg_list):
"""Convert any True values to 1s and Falses to 0s.
Google's copy of MySQLdb has bool-to-int conversion disabled,
and yet it seems to be needed otherwise they are converted
to strings and always interpreted as 0 (which is FALSE).
Args:
arg_list: (nested) list of SQL statment argument values, which may
include some boolean values.
Returns:
The same list, but with True replaced by 1 and False replaced by 0.
"""
result = []
for arg in arg_list:
if isinstance(arg, (list, tuple)):
result.append(_BoolsToInts(arg))
elif arg is True:
result.append(1)
elif arg is False:
result.append(0)
else:
result.append(arg)
return result |
def format_size(bytes):
"""
Format a file size in a human-readable way.
:param bytes: Number of bytes
:type bytes: int
:return: string
"""
if bytes > 1000000:
return '%.1fMB' % (bytes / 1000000.0)
if bytes > 10 * 1000:
return '%ikB' % (bytes / 1000)
if bytes > 1000:
return '%.1fkB' % (bytes / 1000.0)
return '%ibytes' % bytes |
def sort_alternatives(scores, alternatives, reverse):
""" sorts alternatives by score """
sorted_scores, sorted_alternatives = (list(t) for t in zip(*sorted(zip(scores, alternatives), reverse=reverse)))
return sorted_scores, sorted_alternatives |
def will_be_vertical_line(no_rows, rows):
"""
>>> will_be_vertical_line(10, [0, 9])
True
>>> will_be_vertical_line(10, [2, 9])
False
"""
return no_rows - 1 in rows and 0 in rows |
def iou_score(fn: float, fp: float, tp: float) -> float:
"""
Calculate intersection over union.
:param fn: False negative count.
:param fp: False positive count.
:param tp: True positive count.
:return: IoU score.
"""
return 0.0 if fp + tp + fn == 0 else tp / (fp + tp + fn) |
def extract_tuple(mapping, keys):
"""
Extract a tuple from a mapping by requesting a sequence of keys.
Missing keys will result in `None` values in the resulting tuple.
"""
return tuple([mapping.get(key) for key in keys]) |
def utils_kwargs_str(**kwargs):
"""format a list of kwargs for use with utils.py"""
return ' '.join(['--kwarg={}={}'.format(k, v) for k, v in kwargs.items()]) |
def oneliner(text):
""" remove \n in text.
"""
return text.replace(u'\n', ' ') |
def toint(v):
"""Check and convert a value to an integer"""
return int(v) if not v in '.AG' else v |
def calc_f1_score(n_tp: int, n_fp: int, n_fn: int) -> float:
"""Calculate F1 score."""
if (n_tp + n_fp) == 0 or (n_tp + n_fn) == 0:
return 0
precision = n_tp / (n_tp + n_fp)
recall = n_tp / (n_tp + n_fn)
if precision > 0 or recall > 0:
f1 = (2 * precision * recall) / (precision + recall)
else:
f1 = 0
return f1 |
def quicksort(array: list) -> list:
"""
Quicksort Algorithm, implemented with the Explanation on: https://en.wikipedia.org/wiki/Quicksort
:param array: The array, that should be sorted using the QuickSort Algorithm
:return: The sorted array
"""
elements = len(array)
if elements < 2:
return array
current_position = 0
for i in range(1, elements):
if array[i] <= array[0]:
current_position += 1
temp = array[i]
array[i] = array[current_position]
array[current_position] = temp
temp = array[0]
array[0] = array[current_position]
array[current_position] = temp
left = quicksort(array[0:current_position])
right = quicksort(array[current_position + 1:elements])
array = left + [array[current_position]] + right
return array |
def human_to_bed_chrom_start_stop(start, stop):
"""
Returns a tuple containing chromosome coords in BED convention.
:param start: first bp coordinate of subsequence (chromosome starts with 1 not 0).
:param stop: last bp coordinate of subsequence (chromosome starts with 1 not 0).
:return: bed_coords = (bed_start, bed_stop)
"""
bed_start = start-1
bed_stop = stop
bed_coords = (bed_start, bed_stop)
return bed_coords |
def max_val(t):
""" t, tuple or list
Each element of t is either an int, a tuple, or a list
No tuple or list is empty
Returns the maximum int in t or (recursively) in an element of t """
maxVal = False
def helper(obj):
nonlocal maxVal
for el in obj:
if isinstance(el, int):
if maxVal == False or maxVal < el:
maxVal = el
else:
helper(el)
helper(t)
return maxVal |
def count_interests(rows):
"""counts how many rows have non-None interests"""
return len([row for row in rows if row["interest"] is not None]) |
def capitalize(s):
"""
Capitalize the first char of a string, without
affecting the rest of the string.
This differs from `str.capitalize` since the latter
also lowercases the rest of the string.
"""
if not s:
return s
return "".join([s[0].upper(), s[1:]]) |
def get_key(obj, key, default=None):
"""
Utility method to grab nested key
"""
try:
result = obj[key.split('.')[0]]
for k in key.split('.')[1:]:
result = result[k]
except Exception as e:
result = default
return result |
def tolist(arg):
""" convert argument to list """
if isinstance(arg, list):
return arg
if isinstance(arg, tuple):
return list(arg)
if isinstance(arg, str):
return [arg]
raise TypeError("require string, tuple or list") |
def dict_clean_empty(d):
"""Returns dict with all empty elements removed, value 0 retained"""
if not isinstance(d, (dict, list)):
return d
if isinstance(d, list):
return [v for v in (dict_clean_empty(v) for v in d) if v]
return {k: v for k, v in ((k, dict_clean_empty(v)) for k, v in d.items()) if v or v == 0} |
def create_codes_and_names_of_A_matrix(db):
"""
Create a dictionary a tuple (activity name, reference product,
unit, location) as key, and its code as value.
:return: a dictionary to map indices to activities
:rtype: dict
"""
return {
(
i["name"],
i["reference product"],
i["unit"],
i["location"],
): i["code"]
for i in db
} |
def midpoint(p1, p2):
"""Get midpoint coordinate between two points
Args:
p1 (tuple): Point 1
p2 (tuple): Point 2
Returns:
tuple: Midpoint coordinate
"""
return [int((p1[0] + p2[0])/2), int((p1[1] + p2[1])/2)] |
def line_point_extraction(ln_name, mkr_trc_locs):
"""
:param ln_name:
:param mkr_trc_locs:
:return:
"""
ln_pt_ls = []
for i in range(len(mkr_trc_locs)):
if mkr_trc_locs[i][0]==ln_name:
ln_pt_ls.append(i)
line_pts = None
line_pts = [mkr_trc_locs[i] for i in ln_pt_ls]
# Assumes that data is in the desired order
#option to sort if needed:
#sorted_line_pts = sorted(line_pts, key=lambda x: x[2])
return line_pts |
def bahai_date(major, cycle, year, month, day):
"""Return a Bahai date data structure."""
return [major, cycle, year, month, day] |
def mean(array):
"""Take mean of array like."""
return sum(array) / len(array) |
def linear_search_iterative(array, item):
"""O(n) beacuse we are iterating through each item"""
# loop over all array values until item is found
for index, value in enumerate(array):
if item == value:
return index # found
return None |
def decode_file_size(high: int, low: int) -> int:
"""File size can be encoded as 64 bits or 32 bits values.
If upper 32 bits are set, it's a 64 bits integer value.
Otherwise it's a 32 bits value. 0xFFFFFFFF means zero.
"""
if high != 0xFFFFFFFF:
return (high << 32) | (low & 0xFFFFFFFF)
elif low != 0xFFFFFFFF:
return low
else:
return 0 |
def safe_str(obj, repr_line_break=False):
""" This is because non-ascii values can break normal str function """
try:
if repr_line_break:
return str(obj).replace('\n', '\\n')
else:
return str(obj)
except Exception as e:
return obj.encode('utf-8') |
def gcd(a: int, b: int) -> int:
"""
Eucledian Algorithm to calculate gcd of two integers
"""
while b:
a, b = b, a % b
return a |
def add_wtp_to_MSOA_data(consumer_data, population_data):
"""
Take the WTP lookup table for all ages. Add to the population data based on age.
"""
d1 = {d['age']:d for d in consumer_data}
population_data = [dict(d, **d1.get(d['age'], {})) for d in population_data]
return population_data |
def format_pair(kv_tuple):
# type: (tuple) -> str
"""Generate key/value pair
Returns:
str -- 'key=val'
"""
return '{}={}'.format(*kv_tuple) |
def Mc_eta_m1_m2(m1, m2):
"""
Computes the symmetric mass-ratio (eta)
and chirp mass (Mc) from the component masses
input: m1, m2
output: Mc, eta
"""
Mc = (m1*m2)**(3./5.)/(m1+m2)**(1./5.)
eta = m1*m2/(m1+m2)**2
return Mc, eta |
def cubic_map(pop, rate):
"""
Define the equation for the cubic map.
Arguments
---------
pop: float
current population value at time t
rate: float
growth rate parameter values
Returns
-------
float
scalar result of cubic map at time t+1
"""
return rate * pop ** 3 + pop * (1 - rate) |
def add_line(output, buffer, line_height):
"""Add a new line to the output array.
:param output: The output array the line shall be appended to
:param buffer: An array of space we add at the beginning of each line
:param line_height: The user defined line height
:returns: The output array with new line
"""
if not output:
line_height = 0
for _ in range(line_height):
output.append("")
output.extend(buffer)
return output |
def split_class_def(iter_):
"""Splits into class or def lines."""
iter_ = iter_.strip()
if iter_.startswith("def"):
iter_ = iter_[3:]
# elif iter_.startswith("class"):
# x = iter_[6:-2]
return iter_ |
def _name_to_desc(name):
"""Convert a name (e.g.: 'NoteOn') to a description (e.g.: 'Note On')."""
if len(name) < 1:
return ''
desc = list()
desc.append(name[0])
for index in range(1, len(name)):
if name[index].isupper():
desc.append(' ')
desc.append(name[index])
return ''.join(desc) |
def imgstr(imgloc):
"""html img tag"""
istr = ('<div style="display: block; text-align: left;">'
'<a href="{0}"><img src="{0}" border="0" height="200"></a></div>')
return istr.format(imgloc) |
def get_list_index(str_list, selection):
"""
Gets the index of the string in a list of strings. This is case
case insensitive and returns the index of the default string.
It removes any EOL in the strings.
Parameters:
str_list(list of (:term:`String`))
selection (:term:`String`):
default(:term:`String`):
Returns:
index of selected entry
Exception:
ValueError if the selection cannot be found in the list
"""
l1 = [li.replace('\n', '').lower() for li in str_list]
# l2 = [hi.lower() for hi in l1]
# ValueError if match fails
col_index = l1.index(selection.lower())
return col_index |
def all_smaller(nums1: set, nums2: set) -> bool:
"""Return whether every number in nums1 is less than every number in num2.
You may ASSUME that:
- nums1 is non-empty
- nums2 is non-empty
- nums1 and nums2 contain only integers and/or floats
>>> all_smaller({2}, {3})
True
>>> all_smaller({3}, {2})
False
>>> all_smaller({2, 3}, {2, 3})
False
>>> all_smaller({1, 2, 3}, {4, 5, 6})
True
>>> all_smaller({-100, -101}, {-1, 0})
True
>>> all_smaller({0.11}, {0.1})
False
>>> all_smaller({-0.01}, {-0.009})
True
Hint: use the min and max functions.
"""
assert len(nums1) != 0
assert len(nums2) != 0
return max(nums1) < min(nums2) |
def calculateBalloonSize(robotHeight, balloonHeight):
"""
Dynamically Calculating the balloon size, bsed on the known robot size
Parameters
---------
robotHeight: float
relative height of the robot in the picture
balloonHeight: float
relative height of the balloon in the picture
Returns
-------
float
estimated absolute ballon size in mm
"""
print('Calculated BALLOON SIZE: ', balloonHeight/robotHeight*66)
return balloonHeight/robotHeight*66 |
def get_unique_parents(entity_list):
"""Translate a list of entities to a list of their (unique) parents."""
unique_parents = {entity.get_parent() for entity in entity_list}
return list(unique_parents) |
def _cycle_row(C, X):
"""Compute vector v s.t. <v,alpha> is
the number of subsystems in `X`"""
return [1 if C[i] in X else 0 for i in range(len(C))] |
def dict_exchange(dicts: dict) -> dict:
"""
>>> dict_exchange({'a': 'b', 'c': 'd'})
{'b': 'a', 'd': 'c'}
"""
key = dicts.keys()
valve = dicts.values()
return dict(zip(valve, key)) |
def _enforce_unicode(value):
"""
This function enforces the strings passed to be unicode, so we won't
need to guess what's the encoding of the binary strings passed in.
If someone needs to pass the binary string, use BytesIO and wrap it with
`FileBodyProducer`.
"""
if isinstance(value, str):
return value
elif isinstance(value, bytes):
# we got a byte string, and we have no idea what's the encoding of it
# we can only assume that it's something cool
try:
return value.decode("utf-8")
except UnicodeDecodeError:
raise ValueError(
"Supplied raw bytes that are not ascii/utf-8."
" When supplying raw string make sure it's ascii or utf-8"
", or work with unicode if you are not sure")
else:
raise ValueError(
"Unsupported field type: %s" % (value.__class__.__name__,)) |
def get_identifiers(available_identifiers_map, requested_values):
"""
Get the device id from service tag
or Get the group id from Group names
or get the id from baseline names
"""
id_list = []
for key, val in available_identifiers_map.items():
if val in requested_values:
id_list.append(key)
return id_list |
def truncate_time(time_string):
""" HH:MM:SS -> HH:MM """
return ':'.join(time_string.split(':')[:2]) |
def mean(seq):
"""Returns the arithmetic mean of the sequence *seq* =
:math:`\{x_1,\ldots,x_n\}` as :math:`A = \\frac{1}{n} \sum_{i=1}^n x_i`.
"""
return sum(seq) / len(seq) |
def encode6(Property_Area):
"""
This function encodes a loan status to either 1 or 0.
"""
if Property_Area == 'Urban':
return 1
elif Property_Area == 'Rural':
return 0
else:
return 2 |
def mock_downloads(url, body, **kwargs):
"""Mocks the ubs _downloads route"""
response = {
"found": [],
"not_found": [],
"error": []
}
not_found_hashes = ["31132832bc0f3ce4a15601dc190c98b9a40a9aba1d87dae59b217610175bdfde"]
for hash in body["sha256"]:
if hash not in not_found_hashes:
response["found"].append({"sha256": hash, "url": "AWS_DOWNLOAD_URL"})
return response |
def array_stats(values_array):
"""
Computes the sum of all the elements in the array, the sum of the square of
each element and the number of elements of the array.
Parameters
----------
values_array : array like of numerical values.
Represents the set of values to compute the operation.
Returns
-------
float.
The sum of all the elements in the array.
float
The sum of the square value of each element in the array.
int.
The number of elements in the array.
"""
sum_ = 0
sum_sq = 0
n = 0
for item in values_array:
sum_ += item
sum_sq += item * item
n += 1
return sum_, sum_sq, n |
def bfs(graph, source):
"""
get connected component containing some source
"""
to_explore = {source}
visited = set()
while len(to_explore) > 0:
v = to_explore.pop()
if v not in visited:
to_explore.update(graph[v])
visited.add(v)
return visited |
def word_to_index(vocab):
"""
Encoding words by indexing.
Parameters
----------
vocab: list.
Returns
-------
word_to_idx dictionary.
"""
word_to_idx = {}
for word in vocab:
word_to_idx[word] = len(word_to_idx)
return word_to_idx |
def chunk_tasks(n_tasks, n_batches, arr=None, args=None, start_idx=0):
"""Split the tasks into some number of batches to sent out to MPI workers.
Parameters
----------
n_tasks : int
The total number of tasks to divide.
n_batches : int
The number of batches to split the tasks into. Often, you may want to do
``n_batches=pool.size`` for equal sharing amongst MPI workers.
arr : iterable (optional)
Instead of returning indices that specify the batches, you can also
directly split an array into batches.
args : iterable (optional)
Other arguments to add to each task.
start_idx : int (optional)
What index in the tasks to start from?
"""
if args is None:
args = []
args = list(args)
tasks = []
if n_batches > 0 and n_tasks > n_batches:
# chunk by the number of batches, often the pool size
base_chunk_size = n_tasks // n_batches
rmdr = n_tasks % n_batches
i1 = start_idx
for i in range(n_batches):
i2 = i1 + base_chunk_size
if i < rmdr:
i2 += 1
if arr is None: # store indices
tasks.append([(i1, i2), i1] + args)
else: # store sliced array
tasks.append([arr[i1:i2], i1] + args)
i1 = i2
else:
if arr is None: # store indices
tasks.append([(start_idx, n_tasks+start_idx), start_idx] + args)
else: # store sliced array
tasks.append([arr[start_idx:n_tasks+start_idx], start_idx] + args)
return tasks |
def clean_ip(ip):
"""
Cleans the ip address up, useful for removing leading zeros, e.g.::
192.168.010.001 -> 192.168.10.1
:type ip: string
:param ip: An IP address.
:rtype: string
:return: The cleaned up IP.
"""
return '.'.join(str(int(i)) for i in ip.split('.')) |
def remove_special_characters(string:str) -> str:
""" removing special characters from string """
assert isinstance(string,str), "cannot remove special characters from non-string datatype"
string_with_valid_characters = ""
for character in string:
if character.isalnum() or character == ' ':
string_with_valid_characters += character
return string_with_valid_characters |
def find_nums(a):
"""Find the missing numbers in a given list.
input = integers, consecutive, positivea and negative with gaps
output = integers, that fill in gaps of input
"""
res = []
comp = list(range(a[0], a[-1]))
for num in comp:
if num not in a:
res.append(num)
return res |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.