content stringlengths 42 6.51k |
|---|
def inversion_slow(arr):
"""
Counting the number of inversion by O(N*N).
"""
cnt = 0
for i in range(0, len(arr) - 1):
for j in range(i + 1, len(arr)):
if arr[i] > arr[j]:
cnt += 1
return cnt |
def _id_to_box(id_, dim):
"""Convert id to box ID"""
row = id_ // (dim ** 3)
col = (id_ % (dim ** 2)) // dim
return row * dim + col |
def get_size(origin_size = None, crop_size = None, resize_size = None):
""" Get the resulting image size after cropping and resizing """
if resize_size is not None:
image_size = resize_size
elif crop_size is not None:
image_size = crop_size
elif origin_size:
image_size = origin_size
else:
raise ValueError('One of the argument should be not None')
return image_size |
def doubles(digits):
""" Return number of adjacent doubles. """
count = 0
for i in range(5):
if digits[i] == digits[i+1]:
count += 1
return count |
def most_common(lst):
"""Returns the most common element in a list
Args:
lst (list): list with any datatype
Returns:
an element of lst (any): the most common element
if commonests tie, randomly selected
Raises:
ValueError: if lst is None or empty list
"""
if not lst:
raise ValueError("input must be non-empty list")
return max(set(lst), key=lst.count) |
def __id(self):
"""Return identifier of the dictionary."""
return getattr(self, "_id", None) |
def get_goods_linked_to_destination_as_list(goods, country_id):
"""
Instead of iterating over each goods list of countries without the ability to break loops in django templating.
This function will make a match for which goods are being exported to the country supplied,
and return the list of goods
:param goods: list of goods on the application
:param country_id: id of country we are interested in
:return: list of goods that go to destination
"""
item_number = 1
list_of_goods = []
for good in goods:
for country in good["countries"]:
if country["id"] == country_id:
list_of_goods.append(f"{item_number}. {good['description']}")
item_number += 1
break
else:
break
return list_of_goods |
def equals(data, expected):
""" equals(data, expected) -> True if data and expected list are equals. """
if len(data) != len(expected):
return False
for index, item in enumerate(data):
if expected[index] != item:
return False
return True |
def check_result_add(Var: list):
"""
This check goes through Var list (1,a)(2,a)(3,b) ...
and test if 1>=2>=3>=4
and a>=b>=c>=
It means it fails if it not grows
:param Var: result from add operation
:return: True if need RaiseException, false - eveything ok
"""
prevNum = 1
prevAlpha = "a"
for (number, alpha) in Var:
if number == prevNum or number == prevNum + 1:
pass
else:
return True
prevNum = number
if alpha != prevAlpha or alpha != chr(ord(prevAlpha) + 1):
pass
else:
return True
prevAlpha = alpha
return False |
def meta_value(file_name, meta_file, meta_table_key, key):
"""Get metadata value specifed in metadata file.
Args:
file_name: File in pipeline.
meta_file: Metadata file to query. Has keys of top-level metadata
such as "mesh_meta", "anim_meta", etc.
meta_table_key: Key of the metadata table inside meta_file.
Has key 'name' of partial file names.
key: Key to query.
Returns:
Value associate with the specified key if found, None otherwise.
"""
if meta_file is not None:
meta_table = meta_file.get(meta_table_key)
if meta_table is not None:
for entry in meta_table:
if entry['name'] in file_name and key in entry:
return entry[key]
return None |
def swap_places_colon(ingredient):
"""Split string `ingredient` by colon and swap the first and second tokens."""
components = ingredient.split(':')
if len(components) <= 1:
return ingredient
else:
return '{} {}'.format(
swap_places_colon(':'.join(components[1:])), components[0]) |
def all_not_none(*args):
"""
Returns a boolean indicating if all arguments are not None.
"""
return all(arg is not None for arg in args) |
def tick(price, tick_size=0.05):
"""
Rounds a given price to the requested tick
"""
return round(price / tick_size) * tick_size |
def get_label(s):
"""
>>> get_label('>Rosalind_4120')
'Rosalind_4120'
"""
return s[1:] |
def avg(first_num, second_num):
"""computes the average of two numbers"""
return (first_num + second_num) / 2.0 |
def merge_and_sort(first_half, second_half):
"""
This will merge two sorted subarrays.
The subarrays are sorted from lowest to highest.
This must handle when both merged elements are equal!! ***
"""
j = 0 # this is a counter assigned to first_half
k = 0 # this is a counter assigned to second_half
merged = [] # this is the output, append to this progressively during the merge
while j < len(first_half) and k < len(second_half):
#print("first_half", "second_half")
print(first_half, second_half)
if first_half[j] < second_half[k]:
merged.append(first_half[j])
j+=1
else:
merged.append(second_half[k]) # handled the equal case in this else
k+=1
# Handle merging any remainders after one array is exhausted in the while statement.
if j < len(first_half):
merged.extend(first_half[j:len(first_half)])
if k < len(second_half):
merged.extend(second_half[k:len(second_half)])
return merged |
def reversed_domain(s):
"""
>>> reversed_domain("aaa.bbb.ccc")
'ccc.bbb.aaa'
"""
return ".".join(reversed(s.split("."))) |
def pseudoGPU(gpuRank,rank):
"""This is a temporary function to assign gpu's based on rank."""
if rank < 2:
return gpuRank
elif rank < 4:
return list() #gpuRank
elif rank < 6:
return list()
elif rank < 8:
return list() |
def pl_nap(time, nap_min):
"""power law nap time"""
if(time<nap_min):
return nap_min
a = 2.
b = 0.5
nap_max = 3600 #1 hour
return (a*time**b)%nap_max |
def get_unique_list(input_list):
"""Remove duplicates in list and retain order
Parameters
----------
input_list : list
any list of objects
Returns
-------
list
input_list without duplicates
"""
rtn_list_unique = []
for value in input_list:
if value not in rtn_list_unique:
rtn_list_unique.append(value)
return rtn_list_unique |
def _parse_violations(pep8_output):
""" Parse the pep8 output and count the number of violations. """
return len(pep8_output.splitlines()) |
def product(iterable):
"""
Returns the product of the elements of an iterable
"""
res = 1
for i in iterable:
res *= i
return res |
def sticky_option(ctx, param, value):
"""parses sticky cli option"""
if value:
return 'SOURCE_IP'
return None |
def month_converter(month):
"""
brendan gave this to me - give it a 3 char month, returns integer
"""
months = ['JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC']
return months.index(month) + 1 |
def pivot_index(A, i0):
"""Finds a line of index >= i with the highest coefficient at column i in absolute value"""
i_max = i0
for i in range(i0 + 1, len(A)):
if abs(A[i]) > abs(A[i_max]):
i_max = i
return i_max |
def seperate_messsage_person(message_with_person):
"""
Seperates the person from the message and returns both
"""
# Split by the first colon
split_colon = message_with_person.split(":")
# Get the person out of it and avoid the first whitespace
person = split_colon.pop(0)[1:]
# Stitch the message together again
message = " ".join(split_colon)
return person, message |
def str_encode(dt, encoding="utf-8"):
"""
check dt type, then encoding
"""
if isinstance(dt, str):
return dt.encode(encoding) if encoding else dt
elif isinstance(dt, bytes):
return dt
else:
raise TypeError("argument must be str or bytes, NOT {!r}".format(dt)) |
def onOffFromBool(b):
"""Return 'ON' if `b` is `True` and 'OFF' if `b` is `False`
Parameters
----------
b : boolean
The value to evaluate
Return
------
'ON' for `True`, 'OFF' for `False`
"""
#print(b)
r = "ON" if b else "OFF"
return r |
def to_numeric(lit):
"""Return value of a numeric literal string. If the string can not be
converted then the original string is returned.
:param lit:
:return:
"""
# Handle '0'
if lit == '0':
return 0
# Hex/Binary
litneg = lit[1:] if lit[0] == '-' else lit
if litneg[0] == '0':
if litneg[1] in 'xX':
return int(lit, 16)
elif litneg[1] in 'bB':
return int(lit, 2)
else:
try:
return int(lit, 8)
except ValueError:
pass
# Int/Float/Complex
try:
return int(lit)
except ValueError:
pass
try:
return float(lit)
except ValueError:
pass
try:
return complex(lit)
except ValueError:
pass
# return original str
return lit |
def is_marked_match(marked_string_list, begin, length):
"""The function returns true if the match consists in
the marked list, else false.
@marked_string_list - list with marked indexes
@begin - start index of match
@length - length of match
"""
if begin in marked_string_list or \
(begin + length - 1) in marked_string_list:
return True
else:
return False |
def get_variant_prices_from_lines(lines):
"""Get's price of each individual item within the lines."""
return [
line.variant.get_price()
for line in lines
for item in range(line.quantity)] |
def harvest(varlist, advance):
"""Return set of best variables from list of best
varlist is a list each element of which is a comma-separated
list of variable names
advance is how many winners to advance - at least the number
of combinations"""
# may return more or fewer variables than specified
win = set()
for vlist in varlist:
win.update(vlist.replace(",", " ").split())
if len(win) >= advance:
break
return win |
def set_bit(bitboard, bit):
"""
sets bit at position bit of bitboard to 1
"""
return bitboard | (1 << bit) |
def count_texts(text):
"""Return a tuple containing num of words, characters and lines."""
return len(text.split()), len(text), len(text.splitlines()) |
def play(board, turn):
"""
Plays next moviment based on the received current state(board) of the game.
This function must returns the integer related to the position.
So, if you want to play on p3, you must return 3, and so on.
You are only allowed to play on positions which are currently None.
The turn parameter will be always between 1 and 9, and it is
related to the current turn. So, if three positions are occupied,
the received turn parameter will be 4.
If this function returns an invalid value, then this player loses the match.
Example of how this function will be called
>>> play({'p1': 'x', 'p2': None, 'p3': None, 'p4': None, 'p5': 'o', 'p6': None, 'p7': None, 'p8': None, 'p9': 'x'}, 4)
2
"""
if board['p1'] is None:
return 1
elif board['p2'] is None:
return 2
elif board['p3'] is None:
return 3
elif board['p4'] is None:
return 4
elif board['p5'] is None:
return 5
elif board['p6'] is None:
return 6
elif board['p7'] is None:
return 7
elif board['p8'] is None:
return 8
elif board['p9'] is None:
return 9 |
def add_postfix_to_keys(d: dict, postfix: str) -> dict: # pylint:disable=invalid-name
"""Update keys of a dictionary from "key" to "key_postfix"""
d_ = {} # pylint:disable=invalid-name
postfix = str(postfix)
for key, value in d.items():
d_[key + '_' + postfix] = value
return d_ |
def final(iterator):
"""Returns the final element of an iterator."""
ret = None
for x in iterator:
ret = x
return ret |
def tolist(x):
"""Convert a python tuple or singleton object to a list if not already a list """
if isinstance(x, list):
return x
elif isinstance(x, tuple):
return list(x)
elif isinstance(x, set):
return list(x)
else:
return [x] |
def split_sbts_nodes_comms(dataset):
"""
Returns processed database
:param dataset: list of sentence pairs
:return: list of paralel data e.g.
(['first source sentence', 'second', ...], ['first target sentence', 'second', ...])
"""
sbts = []
nodes = []
comms = []
edges = []
for sbt, node, edge, comm in dataset:
sbts.append(sbt)
nodes.append(node)
comms.append(comm)
edges.append(edge)
return sbts, nodes, edges, comms |
def _remove_namespace(subject: str) -> str:
"""If a namespace is present in the subject string, remove it."""
return subject.rsplit('}').pop() |
def separate_time(undivided_time, is_seconds = False):
""" Given the time in hours or seconds, returns the time in common divisions,
i.e. days, hours, minutes, seconds
"""
if is_seconds is True:
_undivided_time = undivided_time
else:
_undivided_time = undivided_time * 3600
days, r1 = divmod(_undivided_time, 86400) # 86400 s = 24 hr * 60 (min/hr) * 60 (s/min)
hours, r2 = divmod(r1, 3600) # 3600 s = 60 min * 60 (s/min)
minutes, seconds = divmod(r2, 60)
return int(days), int(hours), int(minutes), seconds |
def IsInt(value: str) -> bool:
"""Check if a string can be safely casted to an int.
Args:
value (str): The string to check.
Returns:
bool: True if the string can be casted to an int.
"""
try:
_ = int(value)
except ValueError:
return False
return True |
def tupleEqualNoOrder(t1: tuple, t2: tuple) -> bool:
"""Check if two two-element tuples have the same elements."""
assert len(t1) == 2
assert len(t2) == 2
if(t1[0] == t2[0]):
return t1[1] == t2[1]
else:
return t1[0] == t2[1] and t1[1] == t2[0] |
def get_method(name, attrs, bases, exclude=None):
""" Gets a method of a class by name.
:param name: Name of method to get.
:type name: str
:param attrs: Dictionary of class attributes.
:type attrs: dict
:param bases: Bases for the class to use for lookup.
:type bases: list
:param exclude: Iterable of bases to exclude from search.
:type exclude: list
:return: The class method or None
"""
if exclude is None:
exclude = []
# If the method is present return it directly.
if name in attrs:
return attrs[name]
# Try to find the method one by one
for b in bases:
sub_method = get_method(name, b.__dict__, b.__bases__, exclude=exclude)
if sub_method is not None:
if b in exclude:
return None
else:
return sub_method
# else return None
return None |
def get_range( samp ):
""" Creates range object from input
Parameters:
* samp (list, array, tuple): array object with three elements [start, stop, step]
Returns:
* range: (start, stop, step) object
Notes:
* stop position is increased by addition with the step to allow for
complete iteration over the range
"""
return range( samp[0], samp[1]+samp[2], samp[2] ) |
def loop_binary_search(data, target, low_index, high_index):
""" Binary Search Iterativa """
while(low_index < high_index):
mid_index = (low_index + high_index) // 2
if target == data[mid_index]:
return True
elif target < data[mid_index]:
high_index = (mid_index - 1)
else:
low_index = (mid_index + 1)
return False |
def get_model_vars(models, model_dir):
"""Method for getting model_vars if a Mallet object does not exist.
Parameters:
- models (list): A list of model numbers
- model_dir (str): Path to the directory containing the models
Returns:
- model_vars (dict): A dict containing the model numbers and the names of their output_state files
"""
model_vars = {}
for topic_num in models:
topic_num = str(topic_num)
subdir = model_dir + '/topics' + topic_num
model_vars[topic_num] = {'model_state': 'topic-state' +topic_num + '.gz'}
return model_vars |
def splice_signatures(*sigs):
"""Creates a new signature by splicing together any number of signatures.
The splicing effectively flattens the top level input signatures. For
instance, it would perform the following mapping:
- `*sigs: sd1, (sd2, sd3, sd4), (), sd5`
- return: `(sd1, sd2, sd3, sd4, sd5)`
Args:
*sigs: Any number of signatures. A signature is either a `ShapeDtype`
instance or a tuple of `ShapeDtype` instances.
Returns:
A single `ShapeDtype` instance if the spliced signature has one element,
else a tuple of `ShapeDtype` instances.
"""
result_sigs = []
for sig in sigs:
if isinstance(sig, (list, tuple)):
result_sigs.extend(sig)
else:
result_sigs.append(sig)
return result_sigs[0] if len(result_sigs) == 1 else tuple(result_sigs) |
def remove_duplicates(seq):
"""
Removes duplicates from a list.
As seen in:
http://stackoverflow.com/a/480227
"""
seen = set()
seen_add = seen.add
return [x for x in seq if x not in seen and not seen_add(x)] |
def rgb565(r, g=0, b=0):
"""Convert red, green and blue values (0-255) into a 16-bit 565 encoding."""
try:
r, g, b = r # see if the first var is a tuple/list
except TypeError:
pass
return (r & 0xf8) << 8 | (g & 0xfc) << 3 | b >> 3 |
def column_value(item, args):
"""Return the value stored in a column.
YAML usage:
outputs:
outcol:
function: identity
arguments: [col(KEYCOL)]
value: column_value
value_arguments: [col(VALUECOL)]
"""
return item[args[0]] |
def within(value, min_value, max_value):
"""
Deterimine whether or not a values is within the
limits provided.
"""
return (value >= min_value and value < max_value) |
def create_popup_id_query_selector(iteration):
"""
:param iteration:
:return:
"""
return '#' + 'popup' + iteration |
def merge_two_dicts(into, merge_me):
"""Given two dicts, merge them into a new dict as a shallow copy."""
new_dict = into.copy()
new_dict.update(merge_me)
return new_dict |
def is_right_censored(lc, frange):
""" Returns true if the light curve is cutoff on the right. """
return len(lc['t0'])-1 in frange |
def filter_type(findings, allowlist):
"""
Filter list of findings to return only those with a type in the allowlist.
**Parameters**
``findings``
List of dictionary objects (JSON) for findings
``allowlist``
List of strings matching severity categories to allow through filter
"""
filtered_values = []
allowlist = [type.lower() for type in allowlist]
for finding in findings:
if finding["finding_type"].lower() in allowlist:
filtered_values.append(finding)
return filtered_values |
def to_bool(value):
"""A slight modification of bool(). This function converts string literals
'True' and 'False' to boolean values accordingly.
Parameters
----------
value
The value to be converted to boolean.
Raises
------
ValueError
If literal value is not convertible to boolean value.
Returns
-------
bool
The boolean value acquired after conversion.
"""
if isinstance(value, str):
if value == "True":
return True
elif value == "False":
return False
else:
raise ValueError(f"Invalid literal for to_bool(): '{value}'")
else:
return bool(value) |
def _normalize_pkg_style(style):
"""
Internally, zip and fastzip internally behave similar to how an
`inplace` python binary behaves in OSS Buck.
"""
if not style:
return None
# Support some aliases that are used internally, otherwise return the style
# directly if it is unrecognized
if style in ("zip", "fastzip"):
return "inplace"
if style in ("xar",):
return "standalone"
return style |
def _process(proc_data):
"""
Final processing to conform to the schema.
Parameters:
proc_data: (List of Dictionaries) raw structured data to process
Returns:
List of Dictionaries. Each Dictionary represents a row in the csv
file.
"""
# No further processing
return proc_data |
def str2float(item):
"""Convert string type to float type
"""
if item == 'NR':
return None
elif item:
try:
return float(item)
except ValueError:
return None
else:
return None |
def d(d):
"""Decode the given bytes instance using UTF-8."""
return d.decode('UTF-8') |
def _unsplit_name(name):
"""
Convert "this_name" into "This Name".
"""
return " ".join(s.capitalize() for s in name.split('_')) |
def sliding_sum(report):
"""Meh
>>> sliding_sum([199, 200, 208, 210, 200, 207, 240, 269, 260, 263])
[607, 618, 618, 617, 647, 716, 769, 792]
"""
return [sum(report[n : n + 3]) for n in range(len(report) - 2)] |
def line2dict (feat_names, feat_vals, ignore_blank):
""" Create dictionary from the input line."""
result = dict()
if len(feat_names) != len(feat_vals):
raise ValueError("Feature vector length does not match: expected=%s got=%s" % (len(feat_names),len(feat_vals)))
for i in range(len(feat_names)):
if ignore_blank and feat_vals[i] == "":
continue
result[feat_names[i]] = feat_vals[i]
return result |
def colnum_string(n):
""" colnum_string: get column letter
Args: n (int) index of column to get letter for
Returns: str letter(s) of column
"""
string = ""
while n > 0:
n, remainder = divmod(n - 1, 26)
string = chr(65 + remainder) + string
return string |
def filter_action_servers(topics):
""" Returns a list of action servers """
action_servers = []
possible_action_server = ''
possibility = [0, 0, 0, 0, 0]
action_topics = ['cancel', 'feedback', 'goal', 'result', 'status']
for topic in sorted(topics):
split = topic.split('/')
if(len(split) >= 3):
topic = split.pop()
namespace = '/'.join(split)
if(possible_action_server != namespace):
possible_action_server = namespace
possibility = [0, 0, 0, 0, 0]
if possible_action_server == namespace and topic in action_topics:
possibility[action_topics.index(topic)] = 1
if all(p == 1 for p in possibility):
action_servers.append(possible_action_server)
return action_servers |
def smooth_color_func(niter, func):
"""Version of :func:`smooth_color` that accepts a function.
Can be used to pre-calculate a color list outside of a loop.
Parameters
----------
niter : int
number of iterations
func : callable
Examples
--------
>>> from pwtools import mpl
>>> mpl.smooth_color_func(3, lambda z: (z,0,1-z))
[(0.0, 0, 1.0), (0.5, 0, 0.5), (1.0, 0, 0.0)]
>>> for ii,color in enumerate(mpl.smooth_color_func(10, lambda z: (z,0,1-z))):
... plot(rand(20)+ii, color=color)
"""
col = []
fniter = float(niter) - 1
for ii in range(niter):
z = float(ii) / fniter
col.append(func(z))
return col |
def add_sub_token(sub_tokens, idx, tok_to_orig_index, all_query_tokens):
"""add sub tokens"""
for sub_token in sub_tokens:
tok_to_orig_index.append(idx)
all_query_tokens.append(sub_token)
return tok_to_orig_index, all_query_tokens |
def dustSurfaceDensitySingle(R, Rin, Sig0, p):
"""
Calculates the dust surface density (Sigma d) from single power law.
"""
return Sig0 * pow(R / Rin, -p) |
def fixedGradient(q, k, dx, U1):
""" Neumann boundary condition
Assume that the resulted gradient at BC is fixed.
Please see any numerical analysis text book for details.
Return: float
"""
Ug = q / k * 2 * dx + U1
return Ug |
def exact_solution(t, x):
"""
Exact solition Solution.
Parameters
----------
t
x
mode
"""
return 1 / (1 + x**2) |
def mul2D(v1,v2):
"""Elementwise multiplication of vector v1 with v2"""
return (v1[0] * v2[0], v1[1] * v2[1]) |
def get_texts_by_category(texts, categories, choose_category):
"""
:param texts:
:param category:
:return:
"""
text_chosen = []
for i in range(len(texts)):
if categories[i] == choose_category:
text_chosen += [texts[i]]
return text_chosen |
def escape(string, escape_chars, escape_with="\\"):
"""
Escapes all chars given inside the given string.
:param string: The string where to escape characters.
:param escape_chars: The string or Iterable that contains the characters
to escape. Each char inside this string will be
escaped in the order given. Duplicate chars are
allowed.
:param escape_with: The string that should be used as escape sequence.
:return: The escaped string.
"""
for chr in escape_chars:
string = string.replace(chr, escape_with + chr)
return string |
def length_str(msec: float) -> str:
"""
Convert a number of milliseconds into a human-readable representation of
the length of a track.
"""
seconds = (msec or 0)/1000
remainder_seconds = seconds % 60
minutes = (seconds - remainder_seconds) / 60
if minutes >= 60:
remainder_minutes = minutes % 60
hours = (minutes - remainder_minutes) / 60
return '%i:%02d:%02d' % (hours, remainder_minutes, remainder_seconds)
else:
return '%i:%02d' % (minutes, remainder_seconds) |
def indicator(function_array_to_be_indicated, its_domain, barrier):
"""the indicator influences the function argument, not value. So here it iterates through x-domain and cuts any
values of function with an argument less than H"""
indicated = []
for index in range(len(its_domain)):
if its_domain[index] > barrier:
indicated.append(function_array_to_be_indicated[index])
else:
indicated.append(0)
return indicated |
def ColonizeMac(mac):
""" Given a MAC address, normalize its colons.
Example: ABCDEF123456 -> AB:CD:EF:12:34:56
"""
mac_no_colons = ''.join(mac.strip().split(':'))
groups = (mac_no_colons[x:x+2] for x in range(0, len(mac_no_colons), 2))
return ':'.join(groups) |
def normalize_program_type(program_type):
""" Function that normalizes a program type string for use in a cache key. """
return str(program_type).lower() |
def find_stem(arr):
"""
Find longest common substring in array of strings.
From https://www.geeksforgeeks.org/longest-common-substring-array-strings/
"""
# Determine size of the array
n = len(arr)
# Take first word from array
# as reference
s = arr[0]
ll = len(s)
res = ""
for i in range(ll):
for j in range(i + 1, ll + 1):
# generating all possible substrings of our ref string arr[0] i.e s
stem = s[i:j]
k = 1
for k in range(1, n):
# Check if the generated stem is common to to all words
if stem not in arr[k]:
break
# If current substring is present in all strings and its length is
# greater than current result
if k + 1 == n and len(res) < len(stem):
res = stem
return res |
def _find_ancestors(individual, index):
"""
Find the ancestors of the node at the given index.
:param individual: The individual to find the nodes in.
:param index: The index of the node to find the ancestors of.
:return: A list of indices that represent the ancestors.
"""
visited = 0
ancestors = []
for j in reversed(range(index)):
arity = individual[j].arity
if arity > visited:
ancestors.append(j)
visited = 0
else:
visited = (visited - arity) + 1
return ancestors |
def format_indentation(string):
"""
Replace indentation (4 spaces) with '\t'
Args:
string: A string.
Returns:
string: A string.
"""
return string.replace(" ", " ") |
def page_not_found(e):
"""Return a custom 404 error."""
return '<h1>Sorry, nothing at this URL.<h1>', 404 |
def intZASuffix( ZA_ii ) :
"""ZA_ii can be an integer (e.g., 92235) or a string of the from "zaZZZAAA_suffix"
(e.g., "za095242m"). Returns the tuple integer ZA and _suffix from ZA_i. For
examples, ZA_i = 92235 would return ( 92235, "" ) and ZA_i = "za095242m" would
return ( 95242, "m" )."""
try :
ZA_i = int( ZA_ii )
except :
ZA_i = ZA_ii
if ( type( ZA_i ) == type( 1 ) ) : return ( ZA_i, "" )
ZA = None
Suffix = ""
if ( ( type( ZA_i ) == type( "" ) ) or ( type( ZA_i ) == type( u"" ) ) ) :
if( ZA_i[:2] == "za" ) and ( len( ZA_i ) > 7 ) :
ZA = int( ZA_i[2:8] )
if ( len( ZA_i ) > 8 ) and ( ZA_i[8] != "/" ) : Suffix = ZA_i[8:]
elif ( type( ZA_i ) == type( 1 ) ) :
ZA = int( ZA_i )
if( ZA is None ) : raise Exception( "\nError in intZA: invalid ZA = %s" % repr(ZA_i) )
return ( ZA, Suffix ) |
def remove_the_last_person(queue):
"""Remove the person in the last index from the queue and return their name.
:param queue: list - names in the queue.
:return: str - name that has been removed from the end of the queue.
"""
return queue.pop() |
def get_light_events(events):
"""
:param events:
:return:
"""
# Filter to keep only lights on and lights off events
light_events = list(filter(lambda e: "light" in e[-1].lower(), events))
# Make sure events are sorted by init time
light_events = sorted(light_events, key=lambda x: x[0])
# Standardize to (onset, duration, "LIGHTS ON/OFF (STOP/START)") tuples
# Also subtract offset seconds (if array was shifted in time due to trimming, e.g. with start/stop PSG events)
light_events = [(e[0], e[1], "LIGHTS ON (STOP)" if "on" in e[-1].lower() else "LIGHTS OFF (START)")
for e in light_events]
return light_events |
def is_cube(n):
"""Returns if a number is a cube"""
return round(n ** (1/3)) ** 3 == n |
def computeSignalValueInFrame(startbit, ln, fmt, value):
"""
compute the signal value in the frame
"""
import pprint
frame = 0
if fmt == 1: # Intel
# using "sawtooth bit counting policy" here
pos = ((7 - (startbit % 8)) + 8*(int(startbit/8)))
while ln > 0:
# How many bits can we stuff in current byte?
# (Should be 8 for anything but the first loop)
availbitsInByte = 1 + (pos % 8)
# extract relevant bits from value
valueInByte = value & ((1<<availbitsInByte)-1)
# stuff relevant bits into frame at the "corresponding inverted bit"
posInFrame = ((7 - (pos % 8)) + 8*(int(pos/8)))
frame |= valueInByte << posInFrame
# move to the next byte
pos += 0xf
# discard used bytes
value = value >> availbitsInByte
# reduce length by how many bits we consumed
ln -= availbitsInByte
else: # Motorola
# Work this out in "sequential bit counting policy"
# Compute the LSB position in "sequential"
lsbpos = ((7 - (startbit % 8)) + 8*(int(startbit/8)))
# deduce the MSB position
msbpos = 1 + lsbpos - ln
# "reverse" the value
cvalue = int(format(value, 'b')[::-1],2)
# shift the value to the proper position in the frame
frame = cvalue << msbpos
# Return frame, to be accumulated by caller
return frame |
def interval_trigger_dict(ts_epoch):
"""An interval trigger as a dictionary."""
return {
'weeks': 1,
'days': 1,
'hours': 1,
'minutes': 1,
'seconds': 1,
'start_date': ts_epoch,
'end_date': ts_epoch,
'timezone': 'utc',
'jitter': 1,
} |
def _preview_eval(value):
""" Evaluate with mid and end"""
mid = 0
end = 0
return eval(value,{"__builtins__":None},{"mid":mid,"end":end}) |
def controlPoints(cmd, data):
"""
Checks if there are control points in the path data
Returns the indices of all values in the path data which are control points
"""
cmd = cmd.lower()
if cmd in ['c', 's', 'q']:
indices = range(len(data))
if cmd == 'c': # c: (x1 y1 x2 y2 x y)+
return [index for index in indices if (index % 6) < 4]
elif cmd in ['s', 'q']: # s: (x2 y2 x y)+ q: (x1 y1 x y)+
return [index for index in indices if (index % 4) < 2]
return [] |
def is_dementia(code):
"""
ICD9
294.10, 294.11 , 294.20, 294.21
290.- (all codes and variants in 290.- tree)
ICD10
F01.- All codes and their variants in this trees
F02.- All codes and their variants in this trees
F03.- All codes and their variants in this trees
:param code: code string to test
:return: true or false
"""
assert isinstance(code, str)
code_set = ('294.10', '294.11', '294.20', '294.21', '2941', '29411', '2942', '29421')
code_set += ('290',)
code_set += ('F01', 'F02', 'F03')
return code.startswith(code_set) |
def insertionSort(array):
"""
input: array of integers
return : sorted array
"""
for i in range(1, len(array)):
target = array[i]
hole = i
while hole > 0 and array[hole - 1] > target:
array[hole] = array[hole - 1]
hole = hole - 1
array[hole] = target
return array |
def vector(p0, p1):
"""Return the vector of the points
p0 = (xo,yo), p1 = (x1,y1)"""
a = p1[0] - p0[0]
b = p1[1] - p0[1]
return (a, b) |
def get_phys_by_index(vnic, vnics, nics):
"""
Uses information stored in the OCI VNIC metadata to find the physical
interface that a VNIC is associated with.
Parameters
----------
vnic : dict
The virtual interface card name.
vnics : dict
The list of virtual interface cards.
nics : dict
The list of available network interface cards.
Returns
-------
str
The interface name if found, None otherwise.
"""
candidates = {}
for v in vnics:
if vnic['nicIndex'] == v['nicIndex']:
candidates[v['macAddr'].lower()] = True
for n, d in nics.items():
if d['physical'] and d['mac'] in candidates and not d.get('physfn'):
return n
return None |
def numonlynoblank(tovalidate):
"""Returns T or F depending on whether the input is a single character in 0-9, or ."""
return tovalidate.isdecimal() | (tovalidate == '.') |
def xor(a: bool, b: bool) -> bool:
"""Boolean XOR operator.
This implements the XOR boolean operator and has the following truth table:
===== ===== =======
a b a XOR b
===== ===== =======
True True False
True False True
False True True
False False False
===== ===== =======
:param a:
First boolean value.
:param b:
Second boolean value.
:return:
The result of `a` XOR `b` from the truth table above.
"""
return (a and not b) or (not a and b) |
def replace(data, match, repl):
"""Replace variable with replacement text"""
if isinstance(data, dict):
return {k: replace(v, match, repl) for k, v in data.items()}
elif isinstance(data, list):
return [replace(i, match, repl) for i in data]
else:
return data.replace(match, repl) |
def merge_dicts(*dict_args):
"""
Given any number of dicts, shallow copy and merge into a new dict,
precedence goes to key value pairs in latter dicts.
https://stackoverflow.com/questions/38987/how-to-merge-two-dictionaries-in-a-single-expression
"""
result = {}
for dictionary in dict_args:
result.update(dictionary)
return result |
def find_combos_internal_cache(adapters, position, cache):
"""Part 2 - recursion, using dynamic programming (cache/memoization) - wrote this afterwards"""
# successful combo - we made it to the end!
if position == len(adapters) - 1:
return 1, cache
# if the value is in the cache, grab it
elif position in cache:
return cache[position], cache
# if it's not in the cache, do the work
else:
answer = 0
for new_position in range(position + 1, len(adapters)):
if adapters[new_position] - adapters[position] <= 3:
this_answer, cache = find_combos_internal_cache(adapters, new_position, cache)
answer += this_answer
cache[position] = answer
return answer, cache |
def joule_to_kwh(joule):
"""
Convert joule to kilo Watt/hour
How to Use:
Give arguments for joule parameter
*USE KEYWORD ARGUMENTS FOR EASY USE, OTHERWISE
IT'LL BE HARD TO UNDERSTAND AND USE.'
Parameters:
joule (int):energy in Joule
Returns:
int: the value of energy in kilo Watt/hour
"""
kwh = joule / (3.6 ** 10 ** -19)
return kwh |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.