content
stringlengths 42
6.51k
|
---|
def exists_key_in_dicts_list(dict_list, key):
"""From a list of dicts, checks if a certain key is in one of the dicts in the list.
See also https://stackoverflow.com/questions/14790980/how-can-i-check-if-key-exists-in-list-of-dicts-in-python
Parameters
----------
dict_list: list
A list of dictionaries.
key: obj
The obj to be found in dict keys
Returns
-------
Dict or None
"""
# return next((i for i,d in enumerate(dict_list) if key in d), None)
return next((d for i,d in enumerate(dict_list) if key in d), None)
|
def intcode_seven(parameter_list, code_list):
"""If first parameter is less than second parameter, stores 1 in third parameter. Else stores 0 in third parameter. Returns True"""
if parameter_list[0] < parameter_list[1]:
code_list[parameter_list[2]] = 1
else:
code_list[parameter_list[2]] = 0
return True
|
def invert_keyword(keyword):
"""Takes in a keyword e.g. [3, 1, 0, 2], which describes the mapping of
abcd to dbac, and returns the keyword that returns dbac to abcd. So if
you have a keyword that encrypts a text, the decrypting keyword woud be
its inverse and vice versa
"""
# for each index of the inv_keyword, find the position of that index in
# keyword, and have that as the value, in order to reorder the text.
# So keyword = [3, 1, 0, 2], we want [2, 1, 3, 0] to return normalcy
inv_keyword = [keyword.index(index) for index in range(len(keyword))]
return(inv_keyword)
|
def dtype_to_pandas_dtype(dtype: str) -> str:
""" Matches the given dtype to its pandas equivalent, if one exists
Args:
dtype (str): The type to attempt to match
Returns:
The pandas version of the dtype if one exists, otherwise the original
"""
if dtype == "integer":
dtype = "int"
elif dtype == "string":
dtype = "str"
elif dtype == "boolean":
dtype = "bool"
return dtype
|
def str_is_int(s):
"""Checks if a string can be converted to int."""
if not isinstance(s, str):
raise TypeError('str_is_int function only accepts strings.')
try:
int(s)
return True
except ValueError as e:
if 'invalid literal' in str(e):
return False
else:
raise e
|
def bold(text):
"""
Function to return text as bold
:param text: str to bold
:type text: str
:return: str in bold
"""
return '\x1b[1;30m'+text+'\x1b[0m' if text else '\x1b[1;30m'+'\x1b[0m'
|
def _exit_with_general_warning(exc):
"""
:param exc: exception
"""
if isinstance(exc, SystemExit):
return exc
print("WARNING - General JbossAS warning:", exc)
return 1
|
def nameSanitize(inString):
"""
Convert a string to a more file name (and web) friendly format.
Parameters
----------
inString : str
The input string to be sanitized. Typically these are combinations of metric names and metadata.
Returns
-------
str
The string after removal/replacement of non-filename friendly characters.
"""
# Replace <, > and = signs.
outString = inString.replace('>', 'gt').replace('<', 'lt').replace('=', 'eq')
# Remove single-spaces, strip '.'s and ','s
outString = outString.replace(' ', '_').replace('.', '_').replace(',', '')
# and remove / and \
outString = outString.replace('/', '_').replace('\\', '_')
# and remove parentheses
outString = outString.replace('(', '').replace(')', '')
# Remove ':' and ';"
outString = outString.replace(':', '_').replace(';', '_')
# Replace '%' and #
outString = outString.replace('%', '_').replace('#', '_')
# Remove '__'
while '__' in outString:
outString = outString.replace('__', '_')
return outString
|
def _backticks(line, in_string):
"""
Replace double quotes by backticks outside (multiline) strings.
>>> _backticks('''INSERT INTO "table" VALUES ('"string"');''', False)
('INSERT INTO `table` VALUES (\\'"string"\\');', False)
>>> _backticks('''INSERT INTO "table" VALUES ('"Heading''', False)
('INSERT INTO `table` VALUES (\\'"Heading', True)
>>> _backticks('''* "text":http://link.com''', True)
('* "text":http://link.com', True)
>>> _backticks(" ');", True)
(" ');", False)
"""
new = ''
for c in line:
if not in_string:
if c == "'":
in_string = True
elif c == '"':
new = new + '`'
continue
elif c == "'":
in_string = False
new = new + c
return new, in_string
|
def get_alphabet_from_dict(dictionary):
"""
`get_alphabet_from_dict()` gets the alphabet from the dictionary by adding each used letter.
* **dictionary** (*list*) : the input dictionary (before processing)
* **return** (*list*) : the alphabet based on the letters used in the dictionary
"""
alphabet = []
for word in dictionary:
for letter in word:
if not letter in alphabet:
alphabet.append(letter)
alphabet = list(sorted(set(alphabet)))
alphabet.insert(0, '')
return alphabet
|
def diff(first, second):
"""
compute the difference between two lists
"""
second = set(second)
return [item for item in first if item not in second]
|
def map_rows_to_cols(rows, cols):
"""
Returns a list of dictionaries.
Each dictionary is the column name to its corresponding row value.
"""
mapped_rows = []
for row in rows:
mapped_rows.append({cols[i]: row[i] for i in range(len(cols))})
return mapped_rows
|
def reorderOddEvent(nums):
"""[1,2,3,4,5,6,7]"""
def event(num):
return (num % 2) == 0
leftIndex, rightIndex = 0, len(nums) - 1
while leftIndex < rightIndex:
while leftIndex < rightIndex and not event(nums[leftIndex]):
leftIndex += 1
while leftIndex < rightIndex and event(nums[rightIndex]):
rightIndex -= 1
if leftIndex < rightIndex:
nums[leftIndex], nums[rightIndex] = nums[rightIndex], nums[leftIndex]
return nums
|
def recvall(sock, size: int):
"""Receive data of a specific size from socket.
If 'size' number of bytes are not received, None is returned.
"""
buf = b""
while size:
newbuf = sock.recv(size)
if not newbuf:
return None
buf += newbuf
size -= len(newbuf)
return buf
|
def load_secret(name, default=None):
"""Check for and load a secret value mounted by Docker in /run/secrets."""
try:
with open(f"/run/secrets/{name}") as f:
return f.read().strip()
except Exception:
return default
|
def leapyear(year):
"""Judge year is leap year or not."""
return (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0)
|
def discrete_time_approx(rate, timestep):
"""
:param rate: daily rate
:param timestep: timesteps per day
:return: rate rescaled by time step
"""
return 1. - (1. - rate)**(1. / timestep)
|
def xor(a: bytes, b: bytes) -> bytes:
"""Return a xor b.
:param a: Some bytes.
:param b: Some bytes.
:returns: a xor b
"""
assert len(a) == len(b), \
"Arguments must have same length."
a, b = bytearray(a), bytearray(b)
return bytes(map(lambda i: a[i] ^ b[i], range(len(a))))
|
def interpolation_search(to_be_searched, searching_for):
"""
Improvement over binary search when the data is uniformly distributed...
:param to_be_searched:
:param searching_for:
:return:
"""
if to_be_searched:
low = 0
high = len(to_be_searched) - 1
while low <= high and searching_for >= to_be_searched[low] and searching_for <= to_be_searched[high]:
pos = low + int((searching_for - to_be_searched[low])*(high - low) /
(to_be_searched[high] - to_be_searched[low]))
if searching_for == to_be_searched[pos]:
return pos
if searching_for < to_be_searched[pos]:
high = pos - 1
else:
low = pos + 1
return -1
|
def __firstMatch(matches, string):
""" Takes in a list of Match objects and returns the minimal start point among
them. If there aren't any successful matches it returns the length of
the searched string.
"""
starts = map(lambda m: len(string) if m is None else m.start(), matches)
return min(starts)
|
def get_item(dictionary, key):
"""
For getting an item from a dictionary in a template using a variable.
Use like:
{{ mydict|get_item:my_var }}
"""
return dictionary.get(key)
|
def get_abs_sum(lst):
""" Get absolute sum of list """
sum = 0
for x in lst:
if x < 0:
sum += (x * -1)
else:
sum += x
return sum
|
def _function_to_name(name):
"""Returns the name of a CMD function."""
return name[3:].replace('_', '-')
|
def update_bathrooms_slider(area):
"""
Update bathrooms slider to sensible values.
"""
return [1, min(int(area / 40) + 1, 5)]
|
def getMonthString(my_list):
"""Given a list of months creates the string representing the sequence"""
if not isinstance(my_list, (list, tuple)):
my_list = [my_list, ]
dic = {
1: 'JANUARY', 2: 'FEBRUARY', 3: 'MARCH',
4: 'APRIL', 5: 'MAY', 6: 'JUNE',
7: 'JULY', 8: 'AUGUST', 9: 'SEPTEMBER',
10: 'OCTOBER', 11: 'NOVEMBER', 12: 'DECEMBER'}
out = []
for i in my_list:
out.append(dic[i][0])
if len(out) == 1:
out = [dic[my_list[0]]]
return "".join(out)
|
def process_channel_names(channel_names):
"""Process to obtain the electrode name from the channel name.
Parameters
----------
channel_names : list
Channel names in the EEG.
Returns
-------
channel_names : list
Proccessed channel names, containing only the name of the electrode.
"""
channel_names = [(elem.split())[-1] for elem in channel_names]
channel_names = [(elem.replace("-", " ").split())[0] for elem in channel_names]
return channel_names
|
def safe_divide(x, y):
"""Compute x / y, but return 0 if y is zero."""
if y == 0:
return 0
else:
return x / y
|
def dataRange(data):
""" This is used to find the range of a set of data. The range is the difference between the lowest and highest valued digits in a given set of data."""
data = data
data.sort()
return data[len(data)-1] - data[0]
|
def _attr_key(attr):
"""Return an appropriate key for an attribute for sorting
Attributes have a namespace that can be either ``None`` or a string. We
can't compare the two because they're different types, so we convert
``None`` to an empty string first.
"""
return (attr[0][0] or ''), attr[0][1]
|
def min_blocks(length, block):
"""
Returns minimum number of blocks with length ``block``
necessary to cover the array with length ``length``.
"""
return (length - 1) // block + 1
|
def calc_t_int(n_group, t_frame, n_frame, n_skip):
"""Calculates the integration time.
Parameters
----------
n_group : int
Groups per integration.
t_frame : float
Frame time (in seconds).
n_frame : int
Frames per group -- always 1 except maybe brown dwarves.
n_skip : int
Skips per integration -- always 0 except maybe brown dwarves.
Returns
-------
t_int : float
Integration time (in seconds).
"""
t_int = (n_group*(n_frame + n_skip) - n_skip)*t_frame
return t_int
|
def greet(name: str):
"""
Create a simple greeting.
Parameters
----------
name: str, required
Name of person to greet.
Returns
-------
greeting: str
String with a simple greeting.
"""
# Return greeting
return f"Hello, {name}!"
|
def format_stats(stats):
"""Format statistics for printing to a table"""
result = ''
for key, value in stats.items():
result += f'{key} - {value}\n'
return result[:-1]
|
def get_div(value, start):
"""Returns the maximum divider for `value` starting from `start` value"""
div = 1
for d in range(start, 0, -1):
if (value % d) == 0:
div = d
break
return div
|
def get_name(layer_name, counters):
""" utlity for keeping track of layer names """
if not layer_name in counters:
counters[layer_name] = 0
name = layer_name + "_" + str(counters[layer_name])
counters[layer_name] += 1
return name
|
def GetTMIndex(iRes, posTM):# {{{
"""Get index of TM helix given a residue position
Return -1 if iRes is not within TM region
"""
for i in range(len(posTM)):
(b, e) = posTM[i]
if iRes >= b and iRes < e:
return i
return -1
# }}}
|
def square_root(mu, c, i0=1.0):
"""
Calculates the intensity of a given cell in the stellar surface using a
square-root limb-darkening law.
Parameters
----------
mu (``float`` or ``numpy.ndarray``):
Cosine of the angle between a line normal to the stellar surface and the
line of sight.
c (``array-like``):
Limb-darkening coefficients in the order c1, c2.
i0 (``float``, optional):
Intensity without limb-darkening. Default is 1.0.
Returns
-------
i_mu (``float`` or ``numpy.ndarray``):
Intensity with limb-darkening. The format is the same as the input
``mu``.
"""
c1, c2 = c
attenuation = 1 - c1 * (1 - mu) - c2 * (1 - mu ** 0.5)
i_mu = i0 * attenuation
return i_mu
|
def metadata_filter_as_dict(metadata_config):
"""Return the metadata filter represented as either None (no filter),
or a dictionary with at most two keys: 'additional' and 'excluded',
which contain either a list of metadata names, or the string 'all'"""
if metadata_config is None:
return {}
if metadata_config is True:
return {'additional': 'all'}
if metadata_config is False:
return {'excluded': 'all'}
if isinstance(metadata_config, dict):
assert set(metadata_config) <= set(['additional', 'excluded'])
return metadata_config
metadata_keys = metadata_config.split(',')
metadata_config = {}
for key in metadata_keys:
key = key.strip()
if key.startswith('-'):
metadata_config.setdefault('excluded', []).append(key[1:].strip())
elif key.startswith('+'):
metadata_config.setdefault('additional', []).append(key[1:].strip())
else:
metadata_config.setdefault('additional', []).append(key)
for section in metadata_config:
if 'all' in metadata_config[section]:
metadata_config[section] = 'all'
else:
metadata_config[section] = [key for key in metadata_config[section] if key]
return metadata_config
|
def _timeline_from_nodestats(nodestats, device_name):
"""Return sorted memory allocation records from list of nodestats."""
if not nodestats:
return []
lines = []
peak_mem = 0
for node in nodestats:
for mem in node.memory:
try:
records = mem.allocation_records
except: # pylint: disable=bare-except
records = []
allocator = mem.allocator_name
peak_mem = max(peak_mem, mem.allocator_bytes_in_use)
if records:
for record in records:
data = {
"time": record.alloc_micros,
"name": node.node_name,
"allocated_bytes": record.alloc_bytes,
"allocator_type": allocator,
"persist_size": node.memory_stats.persistent_memory_size
}
lines.append(data)
else:
data = {
"time": node.all_start_micros,
"name": node.node_name,
"allocated_bytes": node.memory_stats.persistent_memory_size,
"allocator_type": allocator,
"persist_size": node.memory_stats.persistent_memory_size
}
lines.append(data)
if (not node.memory) and node.memory_stats.persistent_memory_size:
data = {
"time": node.all_start_micros,
"name": node.node_name,
"allocated_bytes": node.memory_stats.persistent_memory_size,
"allocator_type": device_name,
"persist_size": node.memory_stats.persistent_memory_size,
"allocator_bytes_in_use": -1
}
lines.append(data)
return sorted(lines, key=lambda x: x["time"]), peak_mem
|
def set_users(username):
"""Returns screen names from command line or file."""
users = []
if username:
users = [u for u in username]
else:
with open('userlist.txt', 'r') as f:
users = [u.strip() for u in f.readlines()]
if not users:
raise ValueError('No user specified.')
return users
|
def pretty_size(size: int, precision: int = 2) -> str:
"""
Returns human-readable size from bytes.
Args:
size: Size in bytes.
precision: Precision for the result.
"""
if size >= 1 << 40:
return f"{size / (1 << 40):.{precision}f} TB"
if size >= 1 << 30:
return f"{size / (1 << 30):.{precision}f} GB"
if size >= 1 << 20:
return f"{size / (1 << 20):.{precision}f} MB"
if size >= 1 << 10:
return f"{size / (1 << 10):.{precision}f} KB"
return f"{size} B"
|
def clean_word(word):
"""
converts every special character into a separate token
"""
cleaned_words = []
temp = ""
for char in word:
if (ord(char)>=33 and ord(char)<=47) or (ord(char)>=58 and ord(char)<=64):
# if (ord(char)>=33 and ord(char)<=47 and ord(char)!=39) or (ord(char)>=58 and ord(char)<=64):
# separating ordinary characters from special characters, excluding single quote: 39
if temp != "":
cleaned_words.append(temp)
temp = ""
cleaned_words.append(char)
else:
temp += str(char)
if temp != "":
cleaned_words.append(temp)
return cleaned_words
|
def calc_energy_consumption(hvac_kwh_per_day, lights_kwh_per_day, misc_kwh_per_day):
"""
Energy Consumption
Notes
------
Energy consumption for different time periods
"""
farm_kwh_per_day = hvac_kwh_per_day + lights_kwh_per_day + misc_kwh_per_day
farm_kwh_per_week = farm_kwh_per_day * 7 # 7 days in a week
farm_kwh_per_month = farm_kwh_per_day * 30.417 # 365 days/12 months
farm_kwh_per_year = farm_kwh_per_day * 365
return farm_kwh_per_day, farm_kwh_per_week, farm_kwh_per_month, farm_kwh_per_year
|
def user_master_name(mdir, input_name):
""" Convert user-input filename for master into full name
Mainly used to append MasterFrame directory
Parameters
----------
mdir : str
input_name : str
Returns
-------
full_name : str
"""
islash = input_name.find('/')
if islash >= 0:
full_name = input_name
else:
full_name = mdir+'/'+input_name
# Return
return full_name
|
def joined_list(items, element):
"""Return a list with element added between each item.
Similar to str.join() except returns a list.
>>>joined_list(['a', 'b', 'c'], '@')
['a', '@', 'b', '@', 'c']
Args:
items: list
element: anything that can be an element of a list,
"""
work_items = list(items)
for x in sorted(list(range(0, len(work_items) - 1)), reverse=True):
work_items[x + 1:x + 1] = element
return work_items
|
def parse_teams(competitors):
"""Parse a competitors object from Bovada and return the home and away teams, respectively"""
if len(competitors) > 2:
raise Exception("Unexpected objects in competitors")
home_team = ""
away_team = ""
for team in competitors:
if team["home"]:
home_team = team["name"]
else:
away_team = team["name"]
if not home_team == "" or away_team == "":
return home_team.upper(), away_team.upper()
else:
raise Exception("Competitors was not properly parsed. Missing data.")
|
def create_stream_size_map(stream_indices):
"""
Creates a map from stream name to stream size from the indices table.
:param stream_indices: The stream indices table.
:return: The map.
"""
return {pair[0]: len(pair[1]) for pair in stream_indices}
|
def normalize(x, min, max):
"""
Data min-max normalization:
"""
return (x - min) / (max - min)
|
def escape_html(text):
""" For an HTML text, escapes characters that would be read as markup
Adds in a line break after '>' to make reading the text easier
"""
edited_text = str(text).replace("<", "<").replace(">", "><br>")
return edited_text
|
def lpol_sdiff(s):
"""return coefficients for seasonal difference (1-L^s)
just a trivial convenience function
Parameters
----------
s : int
number of periods in season
Returns
-------
sdiff : list, length s+1
"""
return [1] + [0] * (s - 1) + [-1]
|
def format_makehelp(target, detail):
"""
return "{target}:\t{detail}"
"""
return '{}:\t{}'.format(target, detail)
|
def merge_total_time_dict(a, b):
"""Merge two total-time dictionaries by adding the amount of collected time
in each hierarchical element.
Parameters
----------
a, b : total-time dict
A total-time dict is a dictionary with the keys being the name of the
timer and the value being a pair of a total time number and a
dictionary further splitting up the time into lower hierarchical
components.
Returns
-------
total-time dict
"""
all_keys = set(a).union(set(b))
total = dict()
for key in all_keys:
t_a, d_a = a.get(key, (0, dict()))
t_b, d_b = b.get(key, (0, dict()))
total[key] = (t_a + t_b, merge_total_time_dict(d_a, d_b))
return total
|
def middle(t):
"""
Return a new list that doesn't include the first or last elements from the original.
"""
res = t
del(res[0])
del(res[-1])
return res
|
def bolt_min_dist(d_0):
"""
Minimum bolt spacing.
:param d_0:
:return:
"""
e_1 = 1.2 * d_0
e_2 = 1.2 * d_0
e_3 = 1.5 * d_0
p_1 = 2.2 * d_0
p_2 = 2.4 * d_0
return e_1, e_2, e_3, p_1, p_2
|
def select_headers(headers, include_headers):
"""Select message header fields to be signed/verified.
>>> h = [('from','biz'),('foo','bar'),('from','baz'),('subject','boring')]
>>> i = ['from','subject','to','from']
>>> select_headers(h,i)
[('from', 'baz'), ('subject', 'boring'), ('from', 'biz')]
>>> h = [('From','biz'),('Foo','bar'),('Subject','Boring')]
>>> i = ['from','subject','to','from']
>>> select_headers(h,i)
[('From', 'biz'), ('Subject', 'Boring')]
"""
sign_headers = []
lastindex = {}
for h in include_headers:
assert h == h.lower()
i = lastindex.get(h, len(headers))
while i > 0:
i -= 1
if h == headers[i][0].lower():
sign_headers.append(headers[i])
break
lastindex[h] = i
return sign_headers
|
def quaternion_multiply(q, r):
"""
Computes quaternion multiplication
:param q: Quaternion
:param r: Quaternion
:return:
"""
q_w = q[0]
q_x = q[1]
q_y = q[2]
q_z = q[3]
r_w = r[0]
r_x = r[1]
r_y = r[2]
r_z = r[3]
return [
q_w * r_w - q_x * r_x - q_y * r_y - q_z * r_z,
q_w * r_x + q_x * r_w + q_y * r_z - q_z * r_y,
q_w * r_y + q_y * r_w + q_z * r_x - q_x * r_z,
q_w * r_z + q_z * r_w + q_x * r_y - q_y * r_x
]
|
def call_in_transaction(func, *args, **kwargs):
"""Call a function with the supplied arguments, inside a database transaction."""
return func(*args, **kwargs)
|
def schema_highlight(turn):
"""
Highlight some slot values in the utterance.
Args:
turn(dict): A dictionary of the dialogue turn.
Returns:
highlight_text(str): The dialogue utterance after highlighting.
"""
highlight_slots = ("name",)
span_info = sorted(turn["span_info"], key=lambda x: x[3])
text = turn["text"]
highlight_text = ""
prev_end = 0
for _, slot, val, start, end in span_info:
if slot not in highlight_slots or val == "dontcare":
continue
highlight_text += text[prev_end: start]
highlight_text += f"<{slot}/> {text[start: end]} </{slot}>"
prev_end = end
highlight_text += text[prev_end:]
return highlight_text
|
def is_nonempty(pot):
""" Determine if the potential has any values
"""
return any(val is not None for val in pot.values())
|
def partition_helper(a, first, last):
"""
A left_mark index are initiated at the leftmost index available (ie
not the pivot) and a right_mark at the rightmost. The left_mark is shifted
right as long as a[left_mark] < pivot and the right_mark left as long as
a[right_mark] > pivot. If left_mark < right_mark, the values at which the
marks are stopped are swapped and the process continues until they cross.
At this point, a[right_mark] and the pivot are swapped and the index of the
right_mark is returned.
"""
pivot_value = a[first]
left_mark = first + 1
right_mark = last
done = False
while not done:
while right_mark >= left_mark and a[left_mark] <= pivot_value:
left_mark += 1
while right_mark >= left_mark and a[right_mark] >= pivot_value:
right_mark -= 1
if right_mark < left_mark:
done = True
else:
a[left_mark], a[right_mark] = a[right_mark], a[left_mark]
a[first], a[right_mark] = a[right_mark], a[first]
return right_mark
|
def as_int(x, default=0):
"""Convert a thing to an integer.
Args:
x (object): Thing to convert.
default (int, optional): Default value to return in case the conversion fails.
Returns:
int: `x` as an integer.
"""
try:
return int(x)
except ValueError:
return default
|
def histogram(ratings, min_rating=None, max_rating=None):
"""
Generates a frequency count of each rating on the scale
ratings is a list of scores
Returns a list of frequencies
"""
ratings = [int(r) for r in ratings]
if min_rating is None:
min_rating = min(ratings)
if max_rating is None:
max_rating = max(ratings)
num_ratings = int(max_rating - min_rating + 1)
hist_ratings = [0 for x in range(num_ratings)]
for r in ratings:
hist_ratings[r - min_rating] += 1
return hist_ratings
|
def isAnagram(s1, s2):
"""
Checks if s1 and s2 are anagrams by counting the number of occurrences of each letter in s1 and s2.
"""
set1 = set(s1)
set2 = set(s2)
if set1 == set2:
for char in set1:
if s1.count(char) != s2.count(char):
return False
else:
return False
return True
|
def name_sort_key(name):
"""
Gets sort key for the given name, when sorting attribute, method, or such names.
Parameters
----------
name : `str`
Name of an attribute, method or class.
Returns
-------
key : `tuple` (`int`, `str`)
The generated key.
"""
if name.startswith('__'):
if name == '__new__':
prefix_count = 0
elif name == '__init__':
prefix_count = 1
elif name == '__call__':
prefix_count = 2
else:
prefix_count = 102
elif name.startswith('_'):
prefix_count = 101
else:
prefix_count = 100
return prefix_count, name
|
def extend_path(start_el, block, queue, is_lateral):
"""Extends path through block and returns true if the way is blocked"""
next_el = start_el
h = len(block)
w = len(block[0])
while next_el is not None:
current = next_el
next_el = None
for i in range(-1, 2):
add_to_height = i if is_lateral else 1
add_to_width = i if not is_lateral else 1
candidate = (current[0] + add_to_height, current[1] + add_to_width)
if candidate[0] < 0 or candidate[0] >= h or candidate[1] < 0 or candidate[1] >= w:
continue
if block[candidate[0]][candidate[1]] == '#':
if (is_lateral and candidate[1] == w - 1) or (not is_lateral and candidate[0] == h -1):
return True
elif next_el is None:
next_el = candidate
else:
queue.append(candidate)
return False
|
def get_id_of_referenced_submission(user_note):
"""Extracts the id of the submission referenced by the usernote"""
link_code_segments = user_note['l'].split(',')
if len(link_code_segments) > 1:
return link_code_segments[1]
else:
return None
|
def doc_label_name(context_type):
"""
Takes a string `context_type` and makes that a standard 'label' string.
This functions is useful for figuring out the specific label name in
metadata given the context_type.
:param context_type: A type of tokenization.
:type context_type: string
:returns: label name for `context_type` as string.
"""
return str(context_type) + '_label'
|
def convert_twos_compliment(bin_str):
""" Converts a string of binary numbers to their two's compliment integer representation """
length = len(bin_str)
if(bin_str[0] == '0'):
return int(bin_str, 2)
else:
return int(bin_str, 2) - (1 << length)
|
def sol(a, b):
"""
Follows the standard DP approach of finding common subsequence.
The common length can be >=1 so if we find a common character in both
the strings, it does the job
"""
m = len(a)
n = len(b)
dp = [[0 for _ in range(n+1)] for _ in range(m+1)]
for i in range(1, m+1):
for j in range(1, n+1):
if a[i-1] == b[j-1]:
dp[i][j] = 1 + dp[i-1][j-1]
else:
dp[i][j] = max(dp[i-1][j], dp[i][j-1])
if dp[i][j] >= 1:
return 1
return 0
|
def color_float_to_hex(r, g, b):
"""Convert RGB to hex."""
def clamp(x):
x = round(x*255)
return max(0, min(x, 255))
return "#{0:02x}{1:02x}{2:02x}".format(clamp(r), clamp(g), clamp(b))
|
def base64_decode(decvalue):
""" Base64 decode the specified value.
Example Format: SGVsbG8gV29ybGQ= """
msg = """ There was an error. Most likely this isn't a valid Base64 value
and Python choked on it """
try:
base64dec = decvalue.decode("Base64")
return(base64dec)
except:
return(msg)
|
def simplerep(obj):
"""
"""
return "{}(...)".format(obj.__class__.__name__)
|
def delete_spaces(s):
"""Deletes all the spaces of a string
Parameters:
-----------
s : str
Returns
-----------
The corresponding string
"""
s = ''.join(i for i in s if i != ' ')
return s
|
def calculate_okta(percentage):
"""
Calculate okta based on the provided percentage
:param percentage: percentage between 0 and 100
:type percentage: float
:return: an integer between 0 and 8
:rtype: int
"""
if percentage == 0:
return 0
elif 0 < percentage < 18.75:
return 1
elif 18.75 <= percentage < 31.25:
return 2
elif 31.25 <= percentage < 43.75:
return 3
elif 43.75 <= percentage < 56.25:
return 4
elif 56.25 <= percentage < 68.75:
return 5
elif 68.75 <= percentage < 81.25:
return 6
elif 81.25 <= percentage < 100:
return 7
elif percentage == 100:
return 8
else:
raise ValueError('percentage is not between 0-100')
|
def int_list_from_string(s):
"""
creates a list of integers from a string (counterpart to list_as_string(l))
:param s: string
:return:
"""
if s == "None":
return None
l = []
for element in s.split(":"):
l.append(int(element))
return l
|
def calcrange(data, log=False):
"""Return the range (min, max) of a dataset, excluding any NANs."""
xmin, xmax = None, None
for x in data:
if not log or x > 0.:
if xmin is None or x < xmin: xmin = x
if xmax is None or x > xmax: xmax = x
if xmin is None and xmax is None:
if log:
return 0.1, 1.
else:
return 0., 1.
else:
return xmin, xmax
|
def autoname(index, sizes):
"""
Given an index and list of sizes, return a
name for the layer.
>>> autoname(0, sizes=4)
'input'
>>> autoname(1, sizes=4)
'hidden1'
>>> autoname(2, sizes=4)
'hidden2'
>>> autoname(3, sizes=4)
'output'
"""
if index == 0:
n = "input"
elif index == sizes - 1:
n = "output"
elif sizes == 3:
n = "hidden"
else:
n = "hidden%d" % index
return n
|
def columns_matching_pattern(row, starts_with, does_not_match=[]):
"""
Takes in a json "row" and filters the keys to match the `starts_with`
parameter. In addition, it will remove any match that is included
in the `does_not_match` parameter.
:param dict row: A dictionary with string keys to be filtered.
:param str starts_with:
The required substring that all filtered results must start with.
:param list(str) does_not_match:
A list of key values that should be omitted from the results.
:return: A dictionary that contains only the filtered results.
:rtype: dict
"""
candidates = {k: v for k, v in row.items() if str(
k).startswith(starts_with)}
for bad_key in does_not_match:
if bad_key in candidates:
candidates.pop(bad_key)
candidates = {k[len(starts_with):].strip(): v for k,
v in candidates.items()}
return candidates
|
def AverageGrade(adjList):
"""Calculates the average grade of a graph"""
size = len(adjList)
averageGrade = 0
for i in range(size):
averageGrade += len(adjList[i])
averageGrade /= size
return averageGrade
|
def getColor(cnvtype, pathOrBen):
"""Return the shade of the item according to it's variant type."""
if cnvtype not in ["copy_number_loss","copy_number_gain"] or pathOrBen not in ["Benign", "Pathogenic"]:
return "0,0,0"
if cnvtype == "copy_number_loss":
if pathOrBen == "Pathogenic":
return "180,3,16"
else:
return "238,146,148"
if cnvtype == "copy_number_gain":
if pathOrBen == "Pathogenic":
return "17,44,138"
else:
return "122,165,211"
|
def GT(x=None, y=None):
"""
Compares two values and returns:
true when the first value is greater than the second value.
false when the first value is less than or equivalent to the second value.
See https://docs.mongodb.com/manual/reference/operator/aggregation/gt/
for more details
:param x: first value or expression
:param y: second value or expression
:return: Aggregation operator
"""
if x is None and y is None:
return {'$gt': []}
return {'$gt': [x, y]}
|
def find_one_possible_value(sorted_values, all_matching_indices):
"""Return the value that has only one element."""
for key, value in all_matching_indices.items():
if len(value) == 1:
sorted_values[key] = value[0]
return value[0]
|
def _address_set_in_column_map(address_set: tuple, column_map: list):
"""Determines if all elements of the address set are in the column map"""
for element in address_set:
if element not in column_map:
return False
return True
|
def get_user_mapping(config):
"""
Invert the definition in the config (group -> user) so can ask which group
a user belongs to
"""
user_map = {}
for group, users in config['groups'].items():
if group == 'default_group':
continue
for user in users:
if user in user_map:
msg = "User {0} already exists for group {1}".format(
user,
user_map[user],
)
raise ValueError(msg)
user_map[user] = group
return user_map
|
def limit(min_, num, max_):
"""limit a number within a specific range"""
return max(min(num,max_),min_)
|
def binner(min_size, max_size, bin_no):
"""
:param min_size lower bound of the interval to divide into bins
:param max_size upper bound of the interval to divide into bins
:param bin_no the interval will be divided into that many bins
:returns list of tuples, representing the lower and upper limits of each subinterval after dividing into bins
This function separates the input interval into bins
"""
bin_size = float(max_size - min_size) / float(bin_no)
Bins = [(min_size + bin_size * k, min_size + bin_size * (k + 1)) for k in range(0, bin_no)]
return Bins
|
def get_scenario_name(cases):
"""
This function filters the test cases from list of test cases and returns
the test cases list
:param cases: test cases
:type cases: dict
:return: test cases in dict
:rtype: dict
"""
test_cases_dict = {}
test_cases_dict_json = {}
for class_name, test_case_list in cases.items():
result = {class_name: []}
for case_name_dict in test_case_list:
key, value = list(case_name_dict.items())[0]
class_names_dict = dict(
(c_name, "") for scenario in result[class_name] for
c_name in scenario.keys())
if key not in class_names_dict:
result[class_name].append(case_name_dict)
test_cases_dict_json.update(result)
test_cases_list = list(dict((case, "") for test_case in test_case_list
for case in test_case))
test_cases_dict.update({class_name: test_cases_list})
return test_cases_dict, test_cases_dict_json
|
def to_nbsphinx(s):
"""Use the sphinx naming style for anchors of headings"""
s = s.replace(" ", "-").lower()
return "".join(filter(lambda c : c not in "()", s))
|
def is_triangular(k):
"""
k, a positive integer
returns True if k is triangular and False if not
"""
it = 1
sum = 0
while sum <= k:
if sum != k:
sum = sum + it
it += 1
else:
return True
return False
|
def validate_asn_ranges(ranges):
"""
Validate ASN ranges provided are valid and properly formatted
:param ranges: list
:return: bool
"""
errors = []
for asn_range in ranges:
if not isinstance(asn_range, list):
errors.append("Invalid range: must be a list")
elif len(asn_range) != 2:
errors.append("Invalid range: must be a list of 2 members")
elif any(map(lambda r: not isinstance(r, int), asn_range)):
errors.append("Invalid range: Expected integer values")
elif asn_range[1] <= asn_range[0]:
errors.append("Invalid range: 2nd element must be bigger than 1st")
elif asn_range[0] < 1 or asn_range[1] > 2 ** 32 - 1:
errors.append("Invalid range: must be a valid range between 1"
" and 4294967295")
return errors
|
def fit_func(freqs, intercept, slope):
"""A fit function to use for fitting IRASA separated 1/f power spectra components."""
return slope * freqs + intercept
|
def normalize_arr(arr):
"""
Normalizes a normal python list.
Probably works with numpy arrays too.
"""
total = sum(arr)
if total == 0:
print("Arr is empty/All numbers are zero, returning [1], This is a warning")
return [1]
return [i / total for i in arr]
|
def clock_sec(value):
"""
2 bytes: seconds: 0 to 59
"""
return {'seconds': value}
|
def rm_backslash(params):
""" A '-' at the beginning of a line is a special charter in YAML,
used backslash to escape, need to remove the added backslash for local run.
"""
return {k.strip('\\'): v for k, v in params.items()}
|
def dialog_username_extractor(buttons):
""" Extract username of a follow button from a dialog box """
if not isinstance(buttons, list):
buttons = [buttons]
person_list = []
for person in buttons:
if person and hasattr(person, 'text') and person.text:
try:
person_list.append(person.find_element_by_xpath("../../../*")
.find_elements_by_tag_name("a")[1].text)
except IndexError:
pass # Element list is too short to have a [1] element
return person_list
|
def getattr_recursive(variable, attribute):
"""
Get attributes recursively.
"""
if '.' in attribute:
top, remaining = attribute.split('.', 1)
return getattr_recursive(getattr(variable, top), remaining)
else:
return getattr(variable, attribute)
|
def _is_visible(idx_row, idx_col, lengths) -> bool:
"""
Index -> {(idx_row, idx_col): bool}).
"""
return (idx_col, idx_row) in lengths
|
def inclusive_range(start, end, stride=1):
""" Returns a range that includes the start and end. """
temp_range = list(range(start, end, stride))
if(end not in temp_range):
temp_range.append(end)
return temp_range
|
def parse_cigar(cigarlist, ope):
""" for a specific operation (mismach, match, insertion, deletion... see above)
return occurences and index in the alignment """
tlength = 0
coordinate = []
# count matches, indels and mismatches
oplist = (0, 1, 2, 7, 8)
for operation, length in cigarlist:
if operation == ope:
coordinate.append([length, tlength])
if operation in oplist:
tlength += length
return coordinate
|
def _prepname(str):
"""custom string formatting function for creating a legible label from a parm name
takes an incoming label, and sets it to title case unless the 'word' is all caps"""
parts = ()
for part in str.split(" "):
if not part.isupper():
parts += (part.capitalize(),)
else:
parts += (part,)
return " ".join(parts)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.