content stringlengths 42 6.51k |
|---|
def get_radosgw_username(r_id):
"""Generate a username based on a relation id"""
gw_user = 'juju-' + r_id.replace(":", "-")
return gw_user |
def replay(i):
"""
Input: {
}
Output: {
return - return code = 0, if successful
> 0, if error
(error) - error text if return > 0
}
"""
return {'return':1, 'error':'TBD: need support in CLBlast'} |
def resolver_kind_validator(x):
"""
Property: Resolver.Kind
"""
valid_types = ["UNIT", "PIPELINE"]
if x not in valid_types:
raise ValueError("Kind must be one of: %s" % ", ".join(valid_types))
return x |
def is_iterator(obj):
"""
>>> assert is_iterator(list()) is True
>>> assert is_iterator(int) is False
"""
if isinstance(obj, (list, tuple)):
return True
try:
iter(obj)
return True
except TypeError:
return False |
def format_time(t):
"""Format seconds into a human readable form.
>>> format_time(10.4)
'10.4s'
>>> format_time(1000.4)
'16min 40.4s'
"""
m, s = divmod(t, 60)
h, m = divmod(m, 60)
if h:
return f"{h:2.0f}hr {m:2.0f}min {s:4.1f}s"
elif m:
return f"{m:2.0f}min {s:4.1f}s"
else:
return f"{s:4.1f}s" |
def is_residue(a: int, p: int):
"""
a ^ (p - 1) / 2 = x_o ^ (p - 1) / 2
therefore:
x_o ^ (p - 1) = 1 (mod p)
"""
symbol = pow(a, (p - 1) // 2, p)
if symbol == 1:
return pow(a, (p + 1) // 4, p) |
def format_universe_repo_content_type(universe_version):
""" Formats a universe repo content-type of version `universe-version`
:param universe_version: Universe content type version: "v3" or "v4"
:type universe_version: str
:return: content-type of the universe repo version `universe_version`
:rtype: str
"""
content_type = "application/" \
"vnd.dcos.universe.repo+json;" \
"charset=utf-8;version=" \
+ universe_version
return content_type |
def validate_eyr(value: str) -> bool:
"""Expiration must be between 2020 and 2030, inclusive"""
try:
return int(value) in range(2020, 2031)
except (TypeError, ValueError):
return False |
def _get_base_dataset_metadata(ds_identifier):
"""Return base metadata as dict for a given ds_identifier
"""
meta = {
"@context": {
"@vocab": "http://schema.org/",
"doap": "http://usefulinc.com/ns/doap#",
},
# increment when changes to meta data representation are done
"dcterms:conformsTo": "http://docs.datalad.org/metadata.html#v0-1",
}
if ds_identifier is not None:
meta["@id"] = ds_identifier
return meta |
def format_string(string, data):
"""Format a string for notification, based on all content data."""
return string.format(
refresh_time=data.get("refresh_time", ""),
playtime=data.get("playtime", ""),
timestamp=data.get("timestamp", ""),
artist=data.get("artist", ""),
title=data.get("title", ""),
songid=data.get("songid", ""),
album=data.get("album", ""),
asin=data.get("asin", ""),
rating=data.get("rating", ""),
coverart=data.get("coverart", ""),
release_date=data.get("release_date", "")) |
def _describe_zones_response(response):
"""
Generates a response for a describe zones request.
@param response: Response from Cloudstack.
@return: Response.
"""
return {
'template_name_or_list': 'zones.xml',
'response_type': 'DescribeAvailabilityZonesResponse',
'response': response
} |
def human_readable_time(seconds):
""" Returns human readable time
:param seconds: Amount of seconds to parse.
:type seconds: string.
"""
seconds = int(seconds)
hours = seconds / 3600
seconds = seconds % 3600
minutes = seconds / 60
seconds = seconds % 60
return "{:02.0f} hour(s) {:02.0f} minute(s) {:02.0f} second(s) ".format(hours, minutes, seconds) |
def lerp(min, max, rat):
"""
Interpolate between `min` and `max` with the 0-1 ratio `rat`.
"""
return min+(max-min)*rat |
def convert_boolean_for_praat(b):
""" Convert Python boolean for use in Praat
Praat uses "yes"/"no" or 1/0 values instead of True/False.
Convert True to "yes", False to "no"
"""
if b == True:
return "yes"
elif b == False:
return "no"
else:
raise ValueError('Input must be a Boolean') |
def find_keywords(args, key_filter=lambda x: not x.startswith("$")):
"""
This splits up strings like name=value, foo=bar into a dict. Does NOT deal
with quotes in value (e.g. key="value with space" will not work
By default, note that it takes OUT any key which starts with $ (i.e. a
single dollar sign) since for many use-cases the way Tor encodes nodes
with "$hash=name" looks like a keyword argument (but it isn't). If you
don't want this, override the "key_filter" argument to this method.
:param args: a list of strings, each with one key=value pair
:return:
a dict of key->value (both strings) of all name=value type
keywords found in args.
"""
filtered = [x for x in args if '=' in x and key_filter(x.split('=')[0])]
return dict(x.split('=', 1) for x in filtered) |
def days_to_seconds(x: float) -> float:
"""Convert time in days to seconds.
Args:
x (float): Time in days.
Returns:
float: Time in seconds.
"""
return x * 60 * 60 * 24 |
def cross(a, b) -> float:
"""Returns the cross product of a and b."""
return (float(a[0]) * b[1]) - (float(a[1]) * b[0]) |
def parse_int(value, allow_non_zero=False):
"""
Parses the given value and returns
it as an integer.
Args:
value (str): The string to be parsed.
allow_non_zero (bool): If False, all values below 1 will
be set to 1.
Returns:
int: The parsed value.
"""
if not value:
return None
try:
parsed_val = int(value)
except ValueError:
return None
if not allow_non_zero:
return 1 if parsed_val < 1 else parsed_val
return parsed_val |
def pixformat(val=None):
""" Set or get pixformat """
global _pixformat
if val is not None:
_pixformat = val
return _pixformat |
def operator_not(validator):
"""Another form of 'not' operator in 'permissions._require_operator'.
Warning: While 'permissions.operator_or' accepts multiple arguments, this operator accepts only one validator
"""
return 'not', validator |
def compile_word(word):
"""Compile a word of uppercase letters as numeric digits.
E.g., compile_word('YOU') => '(1*U+10*O+100*Y)'
Non-uppercase words unchanged: compile_word('+') => '+'"""
if word.isupper():
terms = [str(10**i) + '*' + c for i, c in enumerate(word[::-1])]
return '(' + '+'.join(terms) + ')'
else:
return word |
def scale_bbox(bbox_list, width, height):
"""
Normalize a bounding box give max_x and max_y.
:param bbox_list: list of list of coodinates in format: [xmin, ymin, xmax, ymax]
:param width: image max width.
:param height: image max height
:return: list of list of normalized coordinates.
"""
results = []
for i in bbox_list:
xmin, ymin, xmax, ymax = i
norm_cr = [xmin / width, ymin / height, xmax / width, ymax / height]
results.append(norm_cr)
return results |
def request_example_keys(endpoint, method):
"""
Returns list with keys for accessing request examples in oas dictionary
"""
return [
"paths",
endpoint,
method,
"requestBody",
"content",
"application/fhir+json",
"examples",
] |
def prepend_blanks(string, length):
"""Prepend ``length`` blank characters to each line of a ``string``
Here parameter ``string`` is a string that may consist of
several lines.
"""
def prepend_blank_line(line, length):
return " " * length + line if len(line.strip()) else line
l = [prepend_blank_line(line, length) for line in string.split("\n")]
return "\n".join(l) |
def same(x,y):
"""Are two Python objects considered the same?"""
try:
if x == y: return True
except: pass
try:
from numpy import isnan
if isnan(x) and isnan(y): return True
except: pass
## try:
## from numpy import allclose
## if allclose(x,y): return True
## except: pass
return False |
def calculate_loop_size(public_key):
"""
>>> calculate_loop_size(5764801)
8
>>> calculate_loop_size(17807724)
11
"""
subject_number = 7
value = 1
loop_size = 0
while value != public_key:
value *= subject_number
value %= 20201227
loop_size += 1
return loop_size |
def typestr(tc):
"""
typestr :: Int -> String
Return a string of the Typeclass' name to be used in reporting
"""
return ["Int","Num","Real","Ord","Enum","Fold","String","Func","Any"][tc] |
def model(x,param):
"""Modelo polinomial. `param` contiene los coeficientes.
"""
n_param = len(param)
y = 0
for i in range(n_param):
y += param[i] * x**i
return y |
def get_new_coordinates(coordinates, direction):
"""
Returns the coordinates of direction applied to the provided coordinates.
Args:
coordinates: tuple of (x, y)
direction: a direction string (like "northeast")
Returns:
tuple: tuple of (x, y) coordinates
"""
x, y = coordinates
if direction in ("north", "northwest", "northeast"):
y += 1
if direction in ("south", "southwest", "southeast"):
y -= 1
if direction in ("northwest", "west", "southwest"):
x -= 1
if direction in ("northeast", "east", "southeast"):
x += 1
return (x, y) |
def convert_to_float(number_string):
"""Convert comma-delimited real numberts in string format to a float
>>> convert_to_float("-79,1")
-79.1
"""
return(float(number_string.replace(',', '.'))) |
def get_ranks(keywords, script):
"""Return ranks of queried keyword in a given script.
Parameters
----------
keywords : str[]
Array of keywords to search in the script.
script : dict[]
JSON object containing ranks of different keywords.
Returns
-------
ranks : int[]
Array of integers in the same order as their respective keywords
"""
ranks = []
# Populate list of ranks
for keyword in keywords:
for d in script:
if d['keyword'] == keyword:
ranks.append(d['rank'])
break
# If no rank has been specified for a word, set its rank to 0
else:
ranks.append(0)
return ranks |
def longest_palindrome(s):
"""."""
n = len(s)
table = [[0 for x in range(n)] for y in range(n)]
max_length = 1
for i in range(n):
table[i][i] = True
# max_length = 2
start = 0
i = 0
while i < n - 1:
if s[i] == s[i + 1]:
table[i][i + 1] = True
start = i
max_length = 2
i = i + 1
k = 3
while k <= n:
i = 0
while i < n - k + 1:
j = i + k - 1
if table[i + 1][j - 1] and s[i] == s[j]:
table[i][j] = True
if k > max_length:
start = i
max_length = k
i = i + 1
k = k + 1
return s[start:start + max_length] |
def field_to_int(field):
"""
Return an integer representation. If a "-" was provided return zero.
"""
if field == "-":
return 0
return int(field) |
def _parseLocalVariables(line):
"""Accepts a single line in Emacs local variable declaration format and
returns a dict of all the variables {name: value}.
Raises ValueError if 'line' is in the wrong format.
See http://www.gnu.org/software/emacs/manual/html_node/File-Variables.html
"""
paren = '-*-'
start = line.find(paren) + len(paren)
end = line.rfind(paren)
if start == -1 or end == -1:
raise ValueError("%r not a valid local variable declaration" % (line,))
items = line[start:end].split(';')
localVars = {}
for item in items:
if len(item.strip()) == 0:
continue
split = item.split(':')
if len(split) != 2:
raise ValueError("%r contains invalid declaration %r"
% (line, item))
localVars[split[0].strip()] = split[1].strip()
return localVars |
def _ensure_options(given_options=None):
"""
Ensures dict contains all formatting options.
Defaults are:
with_attrs (bool): if True, generate module attribute from imports
(Default: True)
with_mods (bool): if True, generate module imports
(Default: True)
with_all (bool): if True, generate an __all__ variable
(Default: True)
relative (bool): if True, generate relative `.` imports
(Default: False)
"""
if given_options is None:
given_options = {}
default_options = {
"with_attrs": True,
"with_mods": True,
"with_all": True,
"relative": False,
"lazy_import": False,
"lazy_boilerplate": None,
"use_black": False,
}
options = default_options.copy()
for k in given_options.keys():
if k not in default_options:
raise KeyError("options got bad key={}".format(k))
options.update(given_options)
return options |
def strip_list(input_list):
"""
Strips whitespace for all individual strings in a list
Parameters:
input_list, a list of strings
Returns:
output_list, a list of strings
"""
output_list = []
for item in input_list:
output_list.append(item.strip())
return output_list |
def _linear_to_rgb(c: float) -> float:
"""Converts linear sRGB to RGB
:param c: (float) linear sRGB value
:return: (float) RGB value
"""
if c > 0.0031308:
return pow(c, 1.0 / 2.4) * 1.055 - 0.055
return abs(c * 12.92) |
def _combine_column_lists(user_entries, all_entries):
"""Combine multiple lists."""
if isinstance(user_entries, bool) and user_entries:
res = all_entries
elif isinstance(user_entries, list):
res = [e for e in user_entries if e in all_entries]
elif isinstance(user_entries, str):
res = [user_entries] if user_entries in all_entries else []
else:
res = []
res = list(res)
return res |
def StringFill(_string, _len, fill_front = False, fill_spaces = False):
"""Function to fill the string _string up to length _len
with dots. If len(_string) > _len, the string is cropped.
**kwargs: fill_front = True to fill in front of the input string.
(Preset fill_front = False)
Examples:
StringFill('test 123', 12) = 'test 123 ...'
StringFill('test 123', 12, fill_front = True) = '... test 123'
"""
tmp = len(_string)
if tmp < _len:
if fill_spaces == False:
if fill_front == True:
return (_len-tmp-1)*'.'+' '+_string
else:
return _string+' '+(_len-tmp-1)*'.'
else:
if fill_front == True:
return (_len-tmp)*' '+_string
else:
return _string+(_len-tmp)*' '
else:
return _string[:_len] |
def split_role(r):
"""
Given a string R that may be suffixed with a number, returns a
tuple (ROLE, NUM) where ROLE+NUM == R and NUM is the maximal
suffix of R consisting only of digits.
"""
i = len(r)
while i > 1 and r[i - 1].isdigit():
i -= 1
return r[:i], r[i:] |
def paramToPercent(current: int, min: int, max: int) -> int:
"""Convert a raw parameter value to a percentage given the current, minimum and maximum raw values.
@param current: The current value.
@type current: int
@param min: The minimum value.
@type current: int
@param max: The maximum value.
@type max: int
"""
return round(float(current - min) / (max - min) * 100) |
def get_cookie_name(state):
"""Generate the cookie name for the OAuth2.0 state."""
return f"oauth.{state}" |
def do_decomposition(gene_trail, selection):
"""Given a list of lists gene_trail and indexes for every item to be
selected in every list in gene_trail, returns a list representing the
corresponding decomposition.
For example, if gene_trail is [['a', 'b'], ['c'], ['d','e']] and the index
for the first list (['a', 'b']) is 0, the index for the second list (['c'])
is 0, and the index for the third list (['d', 'e']) is 1, then the
corresponding decomposition of gene_trail is ['a', 'c', 'e'].
:param gene_trail: list of lists where list items are identifiers of genes
involved in reactions of a CoMetGeNe trail
:param selection: dict storing the currently selected item for every list in
gene_trail
:return: list representing the decomposition of gene_trail given by indexes
stored in 'selection'
"""
for i in range(len(gene_trail)):
assert i in selection.keys()
for list_index in selection:
assert 0 <= selection[list_index] < len(gene_trail[list_index])
decomposition = list()
for i in range(len(gene_trail)):
decomposition.append(gene_trail[i][selection[i]])
return decomposition |
def chartoi(c):
"""
convert a single character to an integer
:param str c:
:return int:
"""
if len(c) == 1 and c.isdigit():
return int(c)
return 0 |
def reduce_docs(docs, max_budget, offset, sort_docs=False):
"""Reduces the number of `docs` (subwords) to fit maximum budget by
optionally sorting them by length, and then removing the shortest ones
until `max_budget` is exceeded. Otherwise, will go left-to-right to preserve
documents.
Args:
docs (list/array): tokenized documents.
max_budget (int): the allowed budget in words/subwords.
offset (int): additional offset for each doc.
sort_docs (bool): if set, will sort documents by length and will
attempt to remove the short ones.
Returns:
list of selected docs (preserved order).
"""
if sort_docs:
doc_lens = [len(d) for d in docs]
order_indxs = sorted(range(len(doc_lens)), key=lambda k: doc_lens[k],
reverse=True)
else:
order_indxs = range(len(docs))
curr_len = 0
indx_coll = []
for i, indx in enumerate(order_indxs):
doc = docs[indx]
if isinstance(doc, str):
raise ValueError("Documents must be tokenized.")
doc_len_w_offset = 0
# adding the separator symbol offset to all but the first doc
if i > 0:
doc_len_w_offset += offset
doc_len_w_offset += len(doc)
if doc_len_w_offset <= max_budget - curr_len:
curr_len += doc_len_w_offset
indx_coll.append(indx)
else:
break
indx_coll = sorted(indx_coll)
docs = [docs[j] for j in indx_coll]
return docs, indx_coll |
def check_zones(domain, zones):
"""
Check if the provided domain exists within the zone
"""
for zone in zones:
if domain == zone or domain.startswith(zone + "."):
return zone
return None |
def classify_list_f(a_list, *filters):
"""Classfy a list like object. Multiple filters in one loop.
- collection: list like object
- filters: the filter functions to return True/False
Return multiple filter results.
Example:
data = [1, 2, 3]
m1 = lambda x: x > 1
m2 = lambda x: x > 2
classify(data, m1, m2) -> [2, 3], [3]
"""
results = tuple([] for i in range(len(filters)))
for item in a_list:
for filter_func, result in zip(filters, results):
if filter_func(item):
result.append(item)
return results |
def is_int(value):
"""
Tests to see whether a value can be cast to an int
Args:
value: The value to be tested
Returns:
True if it can be cast, False if it can't
"""
try:
int(value)
return True
except ValueError:
return False |
def merge(x, y):
"""Given two dicts, merge them into a new dict as a shallow copy."""
z = x.copy()
z.update(y)
return z |
def str_to_other(mystr):
"""
a callable type for my argparse
See:
https://docs.python.org/2/library/argparse.html?highlight=argparse#type
"""
f1, f2, f3 = map(float, mystr.split(' '))
return [f1, f2, int(f3)] |
def isCombinationValid(combination):
"""
Checks if a combination (a tuple of 9 digits)
is a valid product equation.
>>> isCombinationValid(('3', '9', '1', '8', '6', '7', '2', '5', '4'))
True
>>> isCombinationValid(('1', '2', '3', '4', '5', '6', '7', '8', '9'))
False
"""
return (
int("".join(combination[0:2])) * int("".join(combination[2:5]))
== int("".join(combination[5:9]))
) or (
int("".join(combination[0])) * int("".join(combination[1:5]))
== int("".join(combination[5:9]))
) |
def applyFtoEachElemList2 (L, f):
"""
argument: List L and function f
apply function to each element inside of list
mutates L by replacing each element of L by f(elem)
return mutated L
"""
for index in range(len(L)):
L[index] = f(L[index])
return L |
def formatHex(n):
"""
Format 32-bit integer as hexidecimal
"""
n = n if (n >= 0) else (-n) + (1 << 31)
return "0x" + '{:08X}'.format(n) |
def canFinish(numCourses, prerequisites):
"""
:type numCourse: int
:type prerequirements: List[List[int]]
:rtype:bool
"""
'''
if not prerequisites:
return True
L = []
from collections import defaultdict
in_degrees = defaultdict(int)
graph = defaultdict(list)
# Construct the graph
# try to construct a DAG using graph
# store id in in_degrees
for u, v in prerequisites:
graph[v].append(u)
in_degrees[u] += 1
# fetch vertex with id = 0
Q = [u for u in graph if in_degrees[u] == 0]
while Q: # while Q is not empty
start = Q.pop() # remove a node from Q
L.append(start) # add n to tail of L
for v in graph[start]: # for each node v with a edge e
in_degrees[v] -= 1 # remove edge
if in_degrees[v] == 0:
Q.append(v)
# check there exist a cycle
for u in in_degrees: # if graph has edge
if in_degrees[u]:
return False
return True
'''
if not prerequisites:
return True
L = []
# use list to assign numCourses id
in_degrees = [0 for _ in range(numCourses)]
graph = [[] for _ in range(numCourses)]
# Construct the graph
# try to construct a DAG using graph
# store id in in_degrees
for u, v in prerequisites:
graph[v].append(u)
in_degrees[u] += 1
# fetch vertex with id = 0
Q = [i for i in range(len(in_degrees)) if in_degrees[i] == 0]
while Q: # while Q is not empty
start = Q.pop() # remove a node from Q
L.append(start) # add n to tail of L
for v in graph[start]: # for each node v with a edge e
in_degrees[v] -= 1 # remove edge
if in_degrees[v] == 0:
Q.append(v)
# check there exist a cycle
for u in in_degrees: # if graph has edge
if in_degrees[u]:
return False
return True |
def make_figdata(x_data, y_data, labels, dataset_name):
"""Returns a figure.data list to pass to dcc.Graph"""
return [
{
'x': x_data,
'y': y_data[i],
'name': f"{l} ({dataset_name})",
# 'mode': 'markers',
# 'marker': {'size': 10}
'mode': 'lines+markers',
'line': {'width': 2.5},
'marker': {'size': 8}
} for i, l in enumerate(labels)
] |
def action_list_to_string(action_list):
"""Util function for turning an action list into pretty string"""
action_list_string = ""
for idx, action in enumerate(action_list):
action_list_string += "{} ({})".format(
action["name"], action["action"]["class_name"]
)
if idx == len(action_list) - 1:
continue
action_list_string += " => "
return action_list_string |
def diff_between_angles(a, b):
"""Calculates the difference between two angles a and b
Args:
a (float): angle in degree
b (float): angle in degree
Returns:
float: difference between the two angles in degree.
"""
c = (b - a) % 360
if c > 180:
c -= 360
return c |
def split_path(dp):
"""Split a path in basedir path and end part for HDF5 purposes"""
idx = dp.rfind('/')
where = dp[:idx] if idx > 0 else '/'
name = dp[idx+1:]
return where, name |
def next_greater_element(number: int) -> int:
"""https://leetcode.com/problems/next-greater-element-iii/"""
digits = [int(n_char) for n_char in str(number)]
n = len(digits)
swap_index = -1
for index in range(n - 2, -1, -1):
if digits[index] < digits[index + 1]:
swap_index = index
break
if swap_index == -1:
return -1
next_greater_element_index = swap_index + 1
for index in range(next_greater_element_index + 1, n):
if digits[index] > digits[swap_index] and \
digits[index] <= digits[next_greater_element_index]:
next_greater_element_index = index
digits[swap_index], digits[next_greater_element_index] = \
digits[next_greater_element_index], digits[swap_index]
digits[swap_index + 1:] = reversed(digits[swap_index + 1:])
result = int(''.join([str(d) for d in digits]))
if result.bit_length() > 31:
return -1
return result |
def lcs(s1, s2):
"""
Longest common subsequence of two iterables. A subsequence is a
sequence that appears in the same relative order, but not necessarily contiguous.
:param s1: first iterable
:param s2: second iterable
:return: (list) the lcs
"""
matrix = [[[] for _ in range(len(s2))] for _ in range(len(s1))]
for i in range(len(s1)):
for j in range(len(s2)):
if s1[i] == s2[j]:
if i == 0 or j == 0:
matrix[i][j] = [s1[i]]
else:
matrix[i][j] = matrix[i-1][j-1] + [s1[i]]
else:
matrix[i][j] = max(matrix[i-1][j], matrix[i][j-1], key=len)
cs = matrix[-1][-1]
return cs |
def bq_convert_hour_to_index(hour, time_span, remainder):
"""Convert hour to index according to the SQL."""
return int((hour - remainder) / time_span) |
def remove_duplicates(nums) -> int:
"""
remove_duplicates
:param nums:
:return:
"""
# print(list(set(nums)))
return len(set(nums)) |
def lcs(s1: str, s2: str) -> int:
"""Return the longest common substing of two strings."""
table = [[0] * (len(s2) + 1) for _ in range(2)]
for x in s1:
for j, y in enumerate(s2, start=1):
if x == y:
table[1][j] = table[0][j - 1] + 1
elif table[1][j - 1] > table[0][j]:
table[1][j] = table[1][j - 1]
else:
table[1][j] = table[0][j]
return table[-1][-1] |
def floatConverter(num):
"""assumes num is an int, float, or string representing a number
returns a float, representing num"""
if isinstance(num, float) or isinstance(num, int) or isinstance(num, str):
return float(num)
else:
raise TypeError("not a valid input") |
def format_memory(nbytes):
"""Returns a formatted memory size string in torch profiler Event
"""
KB = 1024
MB = 1024 * KB
GB = 1024 * MB
if (abs(nbytes) >= GB):
return '{:.2f} Gb'.format(nbytes * 1.0 / GB)
elif (abs(nbytes) >= MB):
return '{:.2f} Mb'.format(nbytes * 1.0 / MB)
elif (abs(nbytes) >= KB):
return '{:.2f} Kb'.format(nbytes * 1.0 / KB)
else:
return str(nbytes) + ' b' |
def _convert_access(access: str) -> str:
"""Converts access string to a value accepted by wandb."""
access = access.upper()
assert (
access == "PROJECT" or access == "USER"
), "Queue access must be either project or user"
return access |
def electronicBasis(chain):
"""Return the basis for the electronic states of a polyene of length chain.
The basis states are tight-binding orbitals, one for each CH unit, each with
the capacity to hold two electrons. They are represented as integers
corresponding to the CH unit number."""
return tuple(range(1, chain+1)) |
def check_size(d1: int, d2: int) -> bool:
"""
Check if dataset size is the same after dataset cleaning
:param d1: Original Dataset Size
:param d2: Cleaned Dataset Size
:return: Return boolean. True
"""
return True if d1 == d2 else False |
def intlist_to_alpha(intlist):
"""
Convert a list of integers [0, 0, 1, 1, 5, ...] to a list of letters [A, A,
B, B, F, ...]. Useful for converting monomer types to compartment names
(which can then be used as atom names).
Parameters
----------
intlist : list of int
list to be converted
Notes
-----
If intlist has values >= 27, you will get the corresponding Unicode
literals.
"""
return [chr(65+i) for i in intlist] |
def find_boyer_moore(T,P):
"""Return the lowestindex of T at which substring P begins (or else -1)"""
n,m = len(T), len(P) # introduce convenient notations
if m == 0:
return 0 # trivial search for empty string
last = {} # build last dictionary
for k in range(m):
last[P[k]] = k # later occurence overwrites
# align end of pattern at index m-1 of text
i = m-1 # an index into T
k = m-1 # an index into P
while i < n:
if T[i] == P[k]: # a matching character
if k == 0:
return i # pattern begins at index i of text
else:
i -= 1 # examine previous character
k -= 1 # of both T and P
else:
j = last.get(T[i],-1) # last(T[i]) is -1 if not found
i += m - min(k, j+1) # case analysis for jump step
k = m - 1 # restart at the end of the pattern
return -1 |
def with_suffix(number, base=1000):
"""Convert number to string with SI suffix, e.g.: 14226 -> 14.2k, 5395984 -> 5.39M"""
mapping = {base**3: "G", base**2: "M", base: "k"}
for bucket, suffix in mapping.items():
if number > 0.999 * bucket:
return "{:.3g}{}".format(number / bucket, suffix)
return "{:.3g}".format(number) |
def format_message(msg):
"""Format the given message.
"""
if not any(msg.endswith(c) for c in ('.', '?', '!')) and len(msg) > 30:
msg = msg + ' ...'
return msg |
def qa(country, uv):
"""
Do qa on uv-index value:
Rule:
0 <= uv < 12 --> pass (P)
12 <= uv < 17 --> doubtful (D)
>= 17 --> error (E)
all else --> not applicable (NA)
"""
if not isinstance(uv, float):
return 'NA'
if 0 <= uv < 12:
return 'P'
elif 12 <= uv < 17:
return 'D'
elif uv >= 17:
return 'E'
else:
return 'E' |
def remove_old(handle, read_start):
""" The remove old function removes the basepairs that do not have sofclips to save memory.
:param softclip_data: A dictionary with positions and the number of "normal" bases and softclip bases.
:param read_start: An integer representing the place where the read start.
:return sofclip_data: A dictionary with positions and the number of "normal" bases and softclip bases.
"""
remove = []
new_softclip_data = {}
for position in handle:
if position < (read_start-151):
if handle[position][1] == 0:
remove.append(position)
else:
new_softclip_data.update({position: handle[position]})
remove.append(position)
else:
break
for position in remove:
handle.pop(position, None)
return new_softclip_data, handle |
def remove_tags(s):
"""
Removes tags that should be ignored when computing similarites
:param s: Sentence as a list of words
:return: Same sentence without the tags
"""
# tags = set(['<START>', '<END>', '<UNK>', 0, 1, 2, 3])
tags = set(['<START>', '<END>', '<UNK>'])
filtered_words = []
for word in s:
if word not in tags:
filtered_words.append(word)
return filtered_words |
def parse_summary(summary):
"""Parse a string from the format 'open / 41' into both its params"""
summary = summary.split("/")
summary[0] = summary[0].strip()
if "?" in summary[0]:
summary[0] = "nodata"
try:
summary[1] = int(summary[1])
except ValueError:
summary[1] = 0
return summary |
def pubkey_compressed_to_uncompressed(compressed_pubkey: bytes) -> bytes:
""" Converts compressed pubkey to uncompressed format """
assert len(compressed_pubkey) == 33
# modulo p which is defined by secp256k1's spec
p = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F
x = int.from_bytes(compressed_pubkey[1:33], byteorder='big')
y_sq = (pow(x, 3, p) + 7) % p
y = pow(y_sq, (p + 1) // 4, p)
if compressed_pubkey[0] % 2 != y % 2:
y = p - y
y_bytes = y.to_bytes(32, byteorder='big')
return b'\04' + compressed_pubkey[1:33] + y_bytes |
def run_unhovered(var):
"""
Calls the unhovered method on the variable, if it exists.
"""
if var is None:
return None
if isinstance(var, (list, tuple)):
for i in var:
run_unhovered(i)
return
f = getattr(var, "unhovered", None)
if f is not None:
f() |
def event_stream_name(high_seq: int) -> str:
"""
Construct the basename of the event stream object containing the given
highest sequence number.
"""
return f"event-stream-{high_seq}" |
def _convert_grad_position_type(grad_position):
"""Check and convert the type and size of grad position index."""
if isinstance(grad_position, tuple):
for gp in grad_position:
if not isinstance(gp, int):
raise TypeError(f"For 'F.grad', the element in 'grad_position' should be int, "
f"but got {type(gp).__name__}")
if gp < 0:
raise ValueError("The element in grad_position must be >= 0.")
elif isinstance(grad_position, int):
if grad_position < 0:
raise ValueError("grad_position must be >= 0.")
grad_position = (grad_position,)
else:
raise TypeError(f"For 'F.grad', the 'grad_position' should be int or tuple, "
f"but got {type(grad_position).__name__}")
return grad_position |
def lower(value):
"""
returns the lowercase copy of input string.
:param str value: string to make lowercase.
:rtype: str
"""
return value.lower() |
def positiveaxis(axis, ndim):
"""Positive axis
Args:
axis(num): dimension index
ndim(num): number of dimensions
Returns:
num
"""
if axis < 0:
axis += ndim
if axis < 0 or axis >= ndim:
raise IndexError("axis out of range")
return axis |
def encode_query(query, vocabulary):
"""Takes a textual query and a vocabulary (mapping from words to integers), returns the encoded query in a list.
If a word is not in the dictionary, the function returns False.
Args:
query (list): A textual query
vocabulary (dict): Mapping from all words
Returns:
[list or bool]: the encoded query in a list or False
"""
encoded = []
for token in query:
if token in vocabulary:
encoded.append(vocabulary[token])
else:
return False
return encoded |
def get_color_map_list(num_classes):
"""
Args:
num_classes (int): number of class
Returns:
color_map (list): RGB color list
"""
color_map = num_classes * [0, 0, 0]
for i in range(0, num_classes):
j = 0
lab = i
while lab:
color_map[i * 3] |= (((lab >> 0) & 1) << (7 - j))
color_map[i * 3 + 1] |= (((lab >> 1) & 1) << (7 - j))
color_map[i * 3 + 2] |= (((lab >> 2) & 1) << (7 - j))
j += 1
lab >>= 3
color_map = [color_map[i:i + 3] for i in range(0, len(color_map), 3)]
return color_map |
def undiff(usbp, usbn):
"""Convert P/N diff pair bits into J/K encoding.
>>> from cocotb_usb.usb.pp_packet import pp_packet
>>> undiff(
... #EJK_
... '1100', # p
... '1010', # n
... )
'EJK_'
>>> print(pp_packet(undiff(
... #KJKJKJKKJJKJJKKK__J - ACK handshake packet
... '0101010011011000001', # p
... '1010101100100111000', # n
... ), cycles=1))
-
K 1 Sync
J 2 Sync
K 3 Sync
J 4 Sync
K 5 Sync
J 6 Sync
K 7 Sync
K 8 Sync
-
J 1 PID (PID.ACK)
J 2 PID
K 3 PID
J 4 PID
J 5 PID
K 6 PID
K 7 PID
K 8 PID
-
_ SE0
_ SE0
J END
>>> print(pp_packet(undiff(*diff(wrap_packet(sof_packet(0))))))
----
KKKK 1 Sync
JJJJ 2 Sync
KKKK 3 Sync
JJJJ 4 Sync
KKKK 5 Sync
JJJJ 6 Sync
KKKK 7 Sync
KKKK 8 Sync
----
KKKK 1 PID (PID.SOF)
JJJJ 2 PID
JJJJ 3 PID
KKKK 4 PID
JJJJ 5 PID
JJJJ 6 PID
KKKK 7 PID
KKKK 8 PID
----
JJJJ 1 Frame #
KKKK 2 Frame #
JJJJ 3 Frame #
KKKK 4 Frame #
JJJJ 5 Frame #
KKKK 6 Frame #
JJJJ 7 Frame #
KKKK 8 Frame #
----
JJJJ 9 Frame #
KKKK 10 Frame #
JJJJ 11 Frame #
KKKK 1 CRC5
KKKK 2 CRC5
JJJJ 3 CRC5
KKKK 4 CRC5
JJJJ 5 CRC5
----
____ SE0
____ SE0
JJJJ END
"""
assert len(usbp) == len(
usbn), "Sequence different lengths!\n%s\n%s\n" % (usbp, usbn)
value = []
for i in range(0, len(usbp)):
p = usbp[i]
n = usbn[i]
value.append({
# pn
'00': '_',
'11': 'E',
'10': 'J',
'01': 'K',
}[p + n])
return "".join(value) |
def edge_overlap(low1, high1, low2, high2):
""" Returns true if two lines have >0 overlap
>>> edge_overlap(0, 1, 1, 2)
False
>>> edge_overlap(0, 2, 1, 2)
True
>>> edge_overlap(1, 2, 1, 2)
True
>>> edge_overlap(1, 2, 0, 1)
False
>>> edge_overlap(1, 2, 0, 2)
True
>>> edge_overlap(0, 1, 0, 1)
True
"""
if low1 < low2:
return low2 < high1
else:
return low1 < high2 |
def check_all_matching_tags(tag_arg_dict, target_tag_dict):
"""
Return True if all tag sets in `tag_arg_dict` is a subset of the
matching categories in `target_tag_dict`.
"""
return all(
[
tags_set.issubset(target_tag_dict.get(tag_name, set()))
for tag_name, tags_set in tag_arg_dict.items()
]
) |
def size_table_name(model_selector):
"""
Returns canonical name of injected destination desired_size table
Parameters
----------
model_selector : str
e.g. school or workplace
Returns
-------
table_name : str
"""
return "%s_destination_size" % model_selector |
def isfloat(x):
"""
>>> isfloat(12)
True
>>> isfloat(12)
True
>>> isfloat('a')
False
>>> isfloat(float('nan'))
True
>>> isfloat(float('inf'))
True
"""
try: float(x)
except: return False
return True |
def reverse_dict(d):
"""
Flip keys and values
"""
r_d = {}
for k, v in d.items():
if v not in r_d:
r_d[v] = [k]
else:
r_d[v].append(k)
return r_d |
def find(haystack, needle):
"""Return the index at which the sequence needle appears in the
sequence haystack, or -1 if it is not found, using the Boyer-
Moore-Horspool algorithm. The elements of needle and haystack must
be hashable.
>>> find([1, 1, 2], [1, 2])
1
"""
h = len(haystack)
n = len(needle)
skip = {needle[i]: n - i - 1 for i in range(n - 1)}
i = n - 1
while i < h:
for j in range(n):
if haystack[i - j] != needle[-j - 1]:
i += skip.get(haystack[i], n)
break
else:
return i - n + 1
return -1 |
def camel_case(string):
"""Returns the CamelCased form of the specified string.
"""
components = string.split('_')
return "".join(x.title() for x in components) |
def g(n):
"""Return the value of G(n), computed recursively.
>>> g(1)
1
>>> g(2)
2
>>> g(3)
3
>>> g(4)
10
>>> g(5)
22
>>> from construct_check import check
>>> check(HW_SOURCE_FILE, 'g', ['While', 'For'])
True
"""
"*** YOUR CODE HERE ***"
if n <= 3:
return n
else:
return g(n - 1) + 2 * g(n - 2) + 3 * g(n - 3) |
def quick_sort(nums: list) -> list:
""" Selects an element as pivot and partitions the given array around this pivot.
The sub-arrays are then sorted recursively.
:param nums: list of n elements to sort
:return: sorted list (in ascending order)
"""
if type(nums) is not list:
raise TypeError("quick sort only takes lists, not {}".format(str(type(nums))))
length = len(nums)
try:
if length <= 1:
return nums
else:
# Use the last element as the first pivot
pivot = nums.pop()
# Put elements greater than pivot in right list
# Put elements lesser than pivot in left list
right, left = [], []
for num in nums:
if num > pivot:
right.append(num)
else:
left.append(num)
return quick_sort(left) + [pivot] + quick_sort(right)
except TypeError:
return [] |
def is_one_of(obj, types):
"""Return true iff obj is an instance of one of the types."""
for type_ in types:
if isinstance(obj, type_):
return True
return False |
def dict_to_list(dict):
"""Transform a dictionary into a list of values."""
calc_moments_list = list()
[calc_moments_list.append(func) for func in dict.values()]
return calc_moments_list |
def bresenham(x1, y1, x2, y2):
"""
Return a list of points in a bresenham line.
Implementation hastily copied from RogueBasin.
Returns:
List[Tuple[int, int]]: A list of (x, y) points,
including both the start and end-points.
"""
points = []
issteep = abs(y2-y1) > abs(x2-x1)
if issteep:
x1, y1 = y1, x1
x2, y2 = y2, x2
rev = False
if x1 > x2:
x1, x2 = x2, x1
y1, y2 = y2, y1
rev = True
deltax = x2 - x1
deltay = abs(y2-y1)
error = int(deltax / 2)
y = y1
ystep = None
if y1 < y2:
ystep = 1
else:
ystep = -1
for x in range(x1, x2 + 1):
if issteep:
points.append((y, x))
else:
points.append((x, y))
error -= deltay
if error < 0:
y += ystep
error += deltax
# Reverse the list if the coordinates were reversed
if rev:
points.reverse()
return points |
def unpound(input: str) -> str:
"""
Removes '0x' or '#' prefix from a given string
:param input: A hexadecimal value.
:return: str
"""
return input.replace('#', '').replace('0x', '') |
def search(tokens, section):
"""Searches the given token list for the given block of information.."""
for t in tokens:
if t[0] == section:
return t[1:]
return [] |
def ne(s,t):
"""Semantically equivalent to python's !="""
return (s != t) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.