content stringlengths 42 6.51k |
|---|
def pad_in(string: str, space: int) -> str:
"""
>>> pad_in('abc', 0)
'abc'
>>> pad_in('abc', 2)
' abc'
"""
return "".join([" "] * space) + string |
def get_has_feature(sentences, features):
"""
Parameters
----------
sentences: list of strs,
The info text of a mushroom species split into sentences.
features: list of strs
Key words ["bruis", "bleed"] for attribute does-bruise-or-bleed
Return
------
list of str,
['t'] if one of feature in features is in one of the sentences and else ['f'] (dataset encoded boolean)
"""
for sentence in sentences:
sentence = sentence.lower()
for feature in features:
if feature in sentence:
return ['t']
return ['f'] |
def convert(x_s):
"""
This function converts the raw hokuyo data into meters.
:param x_s: scaled data
:return: float64 -- distance in meters
"""
scaling = 0.005 # 5 mm
offset = -100.0
x = x_s * scaling + offset
return x |
def get_year_and_month(key):
"""Returns year and month from manifest key"""
date = key.split('/')[-2]
year = date[:4]
month = date[4:6]
return year, month |
def make_car(manufacturer, type, **additions):
"""
Build a car profile.
:param manufacturer:
:param type:
:param additions:
:return car:
"""
car = dict()
car['manufacturer'] = manufacturer
car['type'] = type
for k, v in additions.items():
car[k] = v
return car |
def _penultimate_node(oid):
"""Return the penultimate node from an OID.
Args:
oid: OID
Returns:
value: Value of the penultimate node
"""
# Initialize key variables
nodes = oid.split('.')
value = int(nodes[-2])
# Return
return value |
def flat2iso(s):
"""Converts a flat timestamp, like 20070221033032 to iso time-format.
The format should be `YYYYMMDDhhmmss`
"""
ts = '%s-%s-%sT%s:%s:%sZ' % (s[:4], s[4:6], s[6:8], s[8:10], s[10:12], s[12:14])
return ts |
def main2(nums, k):
""" Store compliments in a set for lookup.
Time: O(n)
Space: O(n)
"""
prev = set()
for num in nums:
if num in prev:
return True
compliment = k - num
prev.add(compliment)
return False |
def get_float(s):
"""Return string as float or as None if it cannot be converted.
Args:
s: str, presumably decimal float or else some representation of "None"
Returns:
float or None
"""
try:
x = float(s)
except ValueError:
return None
else:
return x |
def poly(x, a):
"""
Constant function as model for the background.
"""
return [a for i in x] |
def create_station_id(loc_name, vs30, z1p0=None, z2p5=None):
""" Creates a projects station id based on if Z1.0/Z2.5 values were specified or not"""
station_id = f"{loc_name}_{str(vs30).replace('.', 'p')}"
if z1p0 is not None and z2p5 is not None:
station_id += f"_{str(z1p0).replace('.', 'p')}_{str(z2p5).replace('.', 'p')}"
return station_id |
def find_field(data_to_filter, field_name, field_value):
"""Utility function to filter blackduck objects for specific fields
Args:
data_to_filter (dict): typically the blackduck object or subselection of this
field_name (string): name of field to use in comparisons
field_value (string): value of field we seek
Returns:
object: object if found or None.
"""
return next(filter(lambda d: d.get(field_name) == field_value, data_to_filter), None) |
def cmp_version(a, b):
"""Compare two version strings (eg 0.0.1.10 > 0.0.1.9)"""
a = a.split('.')
b = b.split('.')
# Compare each individual portion of both version strings
for va, vb in zip(a, b):
ret = int(va) - int(vb)
if ret:
return ret
# Fallback to comparing length last
return len(a) - len(b) |
def getdefault(dic_with_default, key):
"""
:param dic_with_default: a dictionary with a 'default' key
:param key: a key that may be present in the dictionary or not
:returns: the value associated to the key, or to 'default'
"""
try:
return dic_with_default[key]
except KeyError:
return dic_with_default['default'] |
def asbool(value):
"""Return True if value is any of "t", "true", "y", etc (case-insensitive)."""
return str(value).strip().lower() in ("t", "true", "y", "yes", "on", "1") |
def _is_displaced(ins):
"""
returns whether an instruction has been displaced already
"""
return hasattr(ins, 'displaced') and ins.displaced |
def getSquareSegmentDistance(p, p1, p2):
"""
Square distance between point and a segment
"""
x = p1['x']
y = p1['y']
dx = p2['x'] - x
dy = p2['y'] - y
if dx != 0 or dy != 0:
t = ((p['x'] - x) * dx + (p['y'] - y) * dy) / (dx * dx + dy * dy)
if t > 1:
x = p2['x']
y = p2['y']
elif t > 0:
x += dx * t
y += dy * t
dx = p['x'] - x
dy = p['y'] - y
return dx * dx + dy * dy |
def merge_runfiles(all_runfiles):
"""Merges a list of `runfiles` objects.
Args:
all_runfiles: A list containing zero or more `runfiles` objects to
merge.
Returns:
A merged `runfiles` object, or `None` if the list was empty.
"""
result = None
for runfiles in all_runfiles:
if result == None:
result = runfiles
else:
result = result.merge(runfiles)
return result |
def allpath(path):
"""
return paths
"""
paths = path.strip("/").split("/")
for i in range(1,len(paths)):
paths[i] = paths[i-1] + "/" + paths[i]
return paths |
def interleave_list(num_list):
"""
Takes in a list of numbers and interleaves them with the second half reversed
"""
if type(num_list) != list:
raise TypeError("The argument for interleave_two_lists must be a list")
if len(num_list) <= 2:
return num_list
final_list = []
left = 0
right = len(num_list) - 1
for _ in range(0, len(num_list) // 2):
final_list.append(num_list[left])
final_list.append(num_list[right])
left += 1
right -= 1
if len(num_list) % 2 != 0:
final_list.append(num_list[len(num_list) // 2])
return final_list |
def ilshift(a, b):
"""Same as a <<= b."""
a <<= b
return a |
def flatten(l: list) -> list:
"""Returns a new, flattened, l."""
flattened = []
for i in l:
if type(i) == list: # /try:
flattened.extend(flatten(i))
else: # /except:
flattened.append(i)
return flattened |
def genomic_del2_rel_38(genomic_del2_seq_loc):
"""Create test fixture relative copy number variation"""
return {
"type": "RelativeCopyNumber",
"_id": "ga4gh:VRC.xyQ8SLzsBZmeo5M3Aoii-3iED0CeB4m5",
"subject": genomic_del2_seq_loc,
"relative_copy_class": "low-level gain"
} |
def GetLst(idx=0): # linestyle
"""
Get ordered line style
======================
"""
L = ['solid', 'dashed', 'dotted']
#L = ['solid', 'dashed', 'dash_dot', 'dotted']
return L[idx % len(L)] |
def full_swagger_name(sname: str) -> str:
"""
takes any full swagger name, either def or ref, and only returns the name part
:param sname: string containing a swagger name for some object
:return: a return with just the name, no other bits
"""
base_parts = sname.split("/")
return base_parts[-1] |
def parse_humanip(humanip_str):
"""
takes a humanip like string and return a dictionary containing wordparts
example:
humanip_str == "v1/en:muscle-abandon-abandon-access"
will return
{
'version': 1,
'language': "en",
'words': ["muscle", "abandon", "abandon", "access"]
}
"""
parsed = {'version': None, 'language': None, 'words': []}
version_language, words = humanip_str.split(":")
version, language = version_language.split("/")
word_list = words.split("-")
parsed['version'] = int(version.strip("v"))
parsed['language'] = language
parsed['words'] = word_list
return parsed |
def print_debug(name, *args, **kwargs):
"""Printing Debug
Function to display formatted output in decorator options
Args:
name: Name of Process [like "Function Source:"]
*args: Variable length argument list.
**kwargs: Arbitrary keyword arguments.
Returns:
called print function
"""
return print("DEBUG|", name, *args, **kwargs) |
def func_xy_ab_args(x, y, a=2, b=3, *args):
"""func.
Parameters
----------
x, y: float
a, b: int
args: tuple
Returns
-------
x, y: float
a, b: int
args: tuple
"""
return x, y, a, b, args, None, None, None |
def gcd(a, b):
"""Greatest common divisor
https://en.wikipedia.org/wiki/Euclidean_algorithm
"""
while a != b:
if a > b:
a = a - b
else:
b = b - a
return a |
def to_int(buf: bytes) -> int:
"""
bytes to int(little endian)
"""
return int.from_bytes(buf, byteorder="little") |
def convert_csv_to_list(string):
"""
Convert Cauma separated single string to list.
"""
return string.split(",") |
def create_synthetic_device_info(host, mock_server, plugin):
""" Creates the data returned from plugins for integration test purposes. Only does lnet data because
at present that is all we need. """
# Default is an empty dict.
result = {}
# First see if there is any explicit mocked data
try:
result = mock_server["device-plugin"][plugin]
except KeyError:
pass
# This should come from the simulator, so I am adding to the state of this code.
# It is a little inconsistent because network devices come and go as nids come and go.
# really they should be consistent. But I am down to the wire on this and this preserves
# the current testing correctly. So it is not a step backwards.
if (plugin == "linux_network") and (result == {}):
interfaces = {}
nids = {}
if host.state.startswith("lnet"):
lnet_state = host.state
else:
lnet_state = "lnet_unloaded"
mock_nids = mock_server["nids"]
interface_no = 0
if mock_nids:
for nid in mock_nids:
name = "eth%s" % interface_no
interfaces[name] = {
"mac_address": "12:34:56:78:90:%s" % interface_no,
"inet4_address": nid.nid_address,
"inet6_address": "Need An inet6 Simulated Address",
"type": nid.lnd_type,
"rx_bytes": "24400222349",
"tx_bytes": "1789870413",
"up": True,
}
nids[name] = {
"nid_address": nid.nid_address,
"lnd_type": nid.lnd_type,
"lnd_network": nid.lnd_network,
"status": "?",
"refs": "?",
"peer": "?",
"rtr": "?",
"max": "?",
"tx": "?",
"min": "?",
}
interface_no += 1
result = {"interfaces": interfaces, "lnet": {"state": lnet_state, "nids": nids}}
return {plugin: result} |
def fib(x):
"""
Assumes x an integer >= 0
Returns Fibonacci value of x
"""
assert isinstance(x, int) and x >= 0
n_1, n_2, i = 1, 1, 2
while i <= x:
n_new = n_1 + n_2
n_1, n_2 = n_2, n_new
i += 1
return n_2 |
def choose(n, i):
"""
>>> choose(4, 2)
6
"""
a = 1
for k in range(n, n-i, -1):
a = a * k
for k in range(i, 0, -1):
a = a / k
return a |
def fib(n):
"""Function to return fibonacci sequence"""
if n <= 1:
return n
else:
return fib(n-1) + fib(n-2) |
def ndx_to_iid(ndx):
""" Convert zero based index from LIST[ndx] to location index (iid)"""
suffix = str(ndx + 1)
return "L" + suffix.zfill(3) |
def verse(bottle):
"""Sing a verse"""
next_bottle = bottle - 1
s1 = "" if bottle == 1 else "s"
s2 = "" if next_bottle == 1 else "s"
num_next = "No more" if next_bottle == 0 else next_bottle
return "\n".join(
[
f"{bottle} bottle{s1} of beer on the wall,",
f"{bottle} bottle{s1} of beer,",
f"Take one down, pass it around,",
f"{num_next} bottle{s2} of beer on the wall!",
]
) |
def victory_count(PS,MS,PTW,CTW):
"""This function counts the final results of victories"""
if PS > MS:
PTW = PTW + 1
elif MS > PS:
CTW = CTW + 1
else:
pass
return(PTW,CTW) |
def sample_configuration_dist(config, root=True, num_samples_per_dist=1):
"""Expand configuration distribution specification."""
if isinstance(config, dict):
return {
k: sample_configuration_dist(
v, root=False, num_samples_per_dist=num_samples_per_dist)
for k, v in sorted(config.items())
}
elif isinstance(config, list) and root:
return [
sample_configuration_dist(
c, root=False, num_samples_per_dist=num_samples_per_dist)
for c in config
]
elif callable(config):
return [config() for _ in range(num_samples_per_dist)]
else:
return config |
def hausdorff_result_to_dict(haudorff_result):
"""
Converts the tuple returned by the Hausdorff distance functions to a dictionary
for easier use.
Args:
haudorff_result: Tuple returned from Hausdorff distance function
Returns:
Dictionary version of the tuple.
"""
return {
"max_distance": haudorff_result[0],
"x0": haudorff_result[1][0],
"x0_origin": haudorff_result[1][1],
"y0": haudorff_result[2][0],
"y0_origin": haudorff_result[2][1]
} |
def gen_workspace_tfvars_files(environment, region):
"""Generate possible Terraform workspace tfvars filenames."""
return [
# Give preference to explicit environment-region files
"%s-%s.tfvars" % (environment, region),
# Fallback to environment name only
"%s.tfvars" % environment
] |
def convert_size(size):
"""
The convert_size function converts an integer representing
bytes into a human-readable format.
:param size: The size in bytes of a file
:return: The human-readable size.
"""
sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB']
index = 0
while size > 1024:
size /= 1024.
index += 1
return '{:.2f} {}'.format(size, sizes[index]) |
def _memoize_cache_key(args, kwargs):
"""Turn args tuple and kwargs dictionary into a hashable key.
Expects that all arguments to a memoized function are either hashable
or can be uniquely identified from type(arg) and repr(arg).
"""
cache_key_list = []
# hack to get around the unhashability of lists,
# add a special case to convert them to tuples
for arg in args:
if type(arg) is list:
cache_key_list.append(tuple(arg))
else:
cache_key_list.append(arg)
for (k, v) in sorted(kwargs.items()):
if type(v) is list:
cache_key_list.append((k, tuple(v)))
else:
cache_key_list.append((k, v))
return tuple(cache_key_list) |
def get_value(vector):
"""Convert a byte-vector string into an integer"""
if len(vector) == 0:
return 0
vector = [ord(c) for c in vector]
sign = 1
if vector[0] & 0x80:
vector[0] = (vector[0] & 0x7f)
sign = -1
value = 0
for c in vector:
value *= 256
value += c
return sign * value |
def get_added_removed(new, old):
"""Return a tuple of two list.
First list contains items present in the new, but absent in the old (added).
Second list contains items present in the old, but absent in the new (removed).
"""
added = []
removed = []
for i in new:
if i not in old:
added.append(i)
for i in old:
if i not in new:
removed.append(i)
return added, removed |
def flattenJson(nested_json):
"""
Flatten json object with nested keys into a single level.
Args:
nested_json: A nested json object.
Returns:
The flattened json object if successful, None otherwise.
"""
out = {}
def flatten(x, name=''):
if type(x) is dict:
for a in x:
flatten(x[a], name + a + '/')
elif type(x) is list:
i = 0
for a in x:
flatten(a, name + str(i) + '/')
i += 1
else:
out[name[:-1]] = x
flatten(nested_json)
return out |
def parse_bool(val) -> str:
"""Parse a bool into string-ish bool - crazy; i know."""
return str(val).lower() if isinstance(val, bool) else val |
def pythonize_camelcase(origstr):
""" Turns camelCase into underscore_style """
ret = ""
for letter in origstr:
if letter.isupper():
ret += '_' + letter.lower()
else:
ret += letter
# kludge, because calc_f_f_t is silly.
ret = ret.replace("_f_f_t", "_fft")
# kludge for 3d calls
ret = ret.replace("3d", "_3d")
return ret |
def class_from_prediction(prediction):
"""
Get the class with highest probability from prediction.
:param prediction:
:return: class index
"""
max_prob = prediction[0]
if max_prob > prediction[1]:
return 0
else:
return 1 |
def _sort(unsorted):
"""Sort list."""
unsorted.sort()
return '\n'.join(unsorted) |
def _julian_day(year, month, day):
"""
Given a Anno Dominei date, computes the Julian Date in days.
Parameters
----------
year : int
month : int
day : int
Returns
-------
float
Julian Date
"""
# Formula below from
# http://scienceworld.wolfram.com/astronomy/JulianDate.html
# Also agrees with https://gist.github.com/jiffyclub/1294443
return (367*year - int(7*(year + int((month+9)/12))/4)
- int((3*(int(year + (month - 9)/7)/100)+1)/4)
+ int(275*month/9) + day + 1721028.5) |
def cvt_kdd_to_gname(kdd):
"""
Given Kdd, convert the name into gcloud compatible one
Gcloud shall have small letters and dahs instead of underscore
Parameters
------------
kdd: string
KDD name
returns: string
name suited for gcloud
"""
t = kdd
t = t.lower()
t = t. replace('_', '-')
return t |
def b(str):
""" Casts the string to bytes."""
# Poor naming but it's namely for keeping it tidy
return str.encode() |
def sub2indSH (m,n):
"""
i = sub2indSH(m,n)
Convert Spherical Harmonic (m,n) indices to array index i
Assumes that i iterates from 0 (Python style)
"""
i = n**2 + n + m
return i |
def cross(vector1, vector2):
"""Cross product of vectors vector1 and vector2."""
return [vector1[1]*vector2[2] - vector1[2]*vector2[1],
vector1[2]*vector2[0] - vector1[0]*vector2[2],
vector1[0]*vector2[1] - vector1[1]*vector2[0]] |
def replace_wiki_links(text: str, links: list) -> str:
"""
Replace all wiki links with hugo links in the given text.
"""
for link in links:
text = text.replace(link['wiki_link'], link['hugo_link'])
return text |
def next_power_of_2(number):
"""Given a number returns the following power of 2 of that number."""
return 1 if number == 0 else 2 ** (number - 1).bit_length() |
def celciusToFahrenheit(celcius):
"""assumes celcius is a number
returns a floar, the equivalent temperature in Farenheit
"""
return (celcius*9/5)+32 |
def substr_replace(name, name_maps):
"""replaces all substrings in name with those given by name_maps"""
for old, new in name_maps:
name = name.replace(old, new)
return name |
def _get_secret_from_file(file_path):
"""Fetches value of secret from a file."""
with open(file_path, "r") as file:
return file.read().strip() |
def _is_file_like(obj):
"""
Checks if an object is file-like enough to be sent to requests.
In particular, file, StringIO and cStringIO objects are file-like.
Refs http://stackoverflow.com/questions/3450857/python-determining-if-an-object-is-file-like
"""
return hasattr(obj, 'read') and hasattr(obj, 'seek') |
def pack_name(publisher_name, data_name):
"""
Construct a packed string used for naming pyromancy's compute messages.
Args:
publisher_name (str): the entity from which the message originates
examples: 'accuracy', 'nll', 'model_checkpoint', 'early_stopping'
data_name (str): the name of the data which the message originates
examples: 'train', 'test', 'val'
Returns:
the packed message name (str)
"""
return "{}|{}".format(publisher_name, data_name) |
def lengthLongestPath(input_path):
"""
:type input_path: str
:rtype: int
"""
max_length = 0
level_length = {-1: 0}
for line in input_path.split('\n'):
current_path = line.lstrip('\t')
current_level = line.count('\t')
if '.' in line:
# No need to store level_length as we are at a leaf node
current_level_length = level_length[current_level - 1] + len(current_path)
max_length = max(max_length, current_level_length)
else:
# Store the total length of the path to the current level
level_length[current_level] = level_length[current_level - 1] + len('/') + len(current_path)
return max_length |
def write_simple_templates(n_rules, body_predicates=1, order=1):
"""Generate rule template of form C < A ^ B of varying size and order"""
text_list = []
const_term = "("
for i in range(order):
const_term += chr(ord('X') + i) + ","
const_term = const_term[:-1] + ")"
write_string = "{0} #1{1} :- #2{1}".format(n_rules, const_term)
if body_predicates > 1:
for i in range(body_predicates - 1):
write_string += ", #" + str(i + 3) + const_term
text_list.append(write_string)
return text_list |
def check_binary(check_number):
"""
function that checks if the input consists of either 0 or 1.
As the binary numbers can only be 0 or 1, so we need to check this
before doing any calculations on it.
:param check_number: the number entered by the user
:return: True/False
"""
check_list = [int(i) for i in (sorted(set(list(str(check_number)))))]
print(f'\nchecking {check_number}')
for number in check_list:
if number not in [0, 1]:
# print(f'invalid binary number')
return False
return True |
def get_repo_path(template):
"""Given a git SSH path (e.g git@github.com:owner/repo.git), return the repo path
The repo path is in the form of "owner/repo"
"""
return template[:-4].split(':')[1] |
def get_diff(iter):
"""Return the maximum difference between any pair of integers in LINE"""
sorted_iter = sorted(iter)
return max(sorted_iter) - min(sorted_iter) |
def other(si, ti):
"""
Retrieves the "other" index that is not equal to the stack index or target stack index.
Parameters
----------
si : int
The stack index that would be removed from.
ti : int
The target stack index that would be added to.
Returns
-------
int
The "other" index in the list [0, 1, 2] that equates to the stack index that is unused (not stack index or target stack index).
"""
other = [0, 1, 2]
del other[other.index(ti)]
del other[other.index(si)]
return other[0] |
def rstrip2(text, skip):
""" this rstrio function is here to support older versions of Python """
for i in range(len(text)-1, -1, -1):
if not text[i] in skip:
return text[:i+1]
return text |
def validate_company(company, company_pool):
"""
check company exists in users
"""
return True if company in company_pool else False |
def cm_values_to_js(values, cm_name):
"""
Take an array of values of the form (x, (r, g, b)), and return the
corresponding JavaScript variable with the correct name.
"""
dummy = ['[{x:.3f}, [{r:.3f}, {g:.3f}, {b:.3f}]]'.format(x=value[0],
r=value[1][0],
g=value[1][1],
b=value[1][2])
for value in values]
cm_values = ', '.join(dummy)
return 'var {cm_name} = [{cm_values}];'.format(cm_name=cm_name,
cm_values=cm_values) |
def bin_search_max(func):
"""Finds the maximum value where the function returns True
Args:
func (Callable): The function to test
Returns:
int: The maximum value where the function returns True
"""
i, j = 10, 10
while func(i):
i *= 10
i //= 10
j = i
while j != 0:
if func(i):
i += j
else:
i -= j
j //= 10
return i |
def interpolate(a, x, y):
"""Interpolate between x and y. When a is 0 the value is x, when a is 1 the value is y."""
return (1 - a) * x + a * y |
def IS(l,u,y,q):
"""
calculation of the Interval Score
l: left interval limit
u: right interval limit
y: argument of IS
q: quantile level corresponding to limits
Output
IS value in y for given l,u,q
"""
if y<l:
return 2*(l-y) + q*(u-l)
elif y>u:
return 2*(y-u) + q*(u-l)
else:
return q*(u-l) |
def partition(data, left, right):
"""
:param data:
:param left:
:param right:
:return:
"""
temp = data[left]
while left < right:
while left < right and data[right] >= temp:
right -= 1
data[left] = data[right]
while left < right and data[left] <= temp:
left += 1
data[right] = data[left]
data[left] = temp
return left |
def clamp(val, min, max):
""" Clamp value between min/max values """
if val > max:
return max
if val < min:
return min
return val |
def get_weights(gt_dict):
"""Calculate weights for weighted cross entropy loss.
Args:
gt_dict: dictionary of the gt labels.
Returns:
list of weigths per class
"""
count_list = [0, 0]
for _, item in gt_dict.items():
item = list(item)
count_list[1] += item.count(1)
count_list[0] += item.count(0)
weights = [1/ count_list[i] if count_list[i]!=0 else 1 for i in range(2)]
weights_norm = [i/ sum(weights) for i in weights]
return weights_norm |
def filter_submissions(submissions, start_time, end_time = None, username = None):
"""Return all submissions created after the start_time.
Optional: Also before end_time if given.
Optional: Also by username if given."""
filtered = []
for s in submissions:
if end_time and s.created_utc >= end_time:
continue
elif username and username != s.author.name:
continue
elif s.created_utc > start_time:
filtered.append(s)
return filtered |
def get_py_param_type(context):
"""convert a param type into python accepted format.
Related to the formats accepted by the parameter under dynamic reconfigure
Args:
context (dict): context (related to an interface description)
Returns:
str: variable type in python format related to param components
Examples:
>>> context = {desc="an interface" name="misc" type="std::string"/>
>>> get_py_param_type(context)
"str_t"
"""
param_type = context['type']
if param_type not in ['std::string', 'string', 'int', 'double', 'bool']:
raise SyntaxError("Invalid type for param {}".format(param_type))
if param_type in ['std::string', 'string']:
return 'str_t'
if param_type == 'int':
return 'int_t'
if param_type == 'double':
return 'double_t'
if param_type == 'bool':
return 'bool_t' |
def as_bytes(text):
"""
Converts text to bytes, or leaves intact if already bytes or none
"""
if isinstance(text, str):
# Convert to bytes if in string form
return text.encode("utf8")
return text |
def get_translation_suggestions(input_string, spelling_suggestions, vocabulary_article):
"""Returns XML with translate suggestions"""
res = []
if len(spelling_suggestions) == 0 and len(vocabulary_article) == 0:
return res
if len(vocabulary_article['def']) != 0:
for article in vocabulary_article['def']:
for translation in article['tr']:
if 'ts' in article.keys():
subtitle = article['ts']
elif 'ts' in translation.keys():
subtitle = translation['ts']
else:
subtitle = ''
res.append({
'translation': translation['text'],
'transcription': subtitle,
})
return res |
def _to_version_number(version: str) -> int:
"""Convert version string (e.g. '2020a') to an integer of the form YYNN
(e.g. '2001'), where YY is (year - 2000) and NN is the patch number,
where 'a' is 01.
"""
year = version[0:4]
patch = version[4]
return (int(year) - 2000) * 100 + (ord(patch) - ord('a') + 1) |
def five_num_summary(items):
"""The function takes a list as input and return a dict with keys 'max', 'median', 'min', 'q1', and 'q3'
corresponding to the maximum, median, minimum, first quartile and third quartile, respectively.
Example
-------
Input: gauteng = [39660.0,36024.0, 32127.0, 39488.0, 18422.0, 23532.0, 8842.0, 37416.0, 16156.0, 18730.0, 19261.0, 25275.0]
Output: five_num_summ(gauteng) == {'max': 39660.0, 'median': 24403.5, 'min': 8842.0, 'q1': 18422.5, 'q3': 36024.5}
"""
#Importing the module
import numpy as np
items = np.array(items)
#Assigning the required data to 'num_summary'
num_summary = {'max': round(np.max(items),2), 'median': round(np.median(items),2), 'min': round(np.min(items),2), 'q1': round(np.quantile(items,0.25),2), 'q3': round(np.quantile(items,0.75),2)}
return num_summary |
def escape_byte(data):
""" Escapes (or not) a character
returns a list with the correct values """
if data not in (1, 2, 3):
return [data]
return [3, data + 3] |
def sort_tasks(tasks):
"""Sort tasks by priority"""
return sorted(tasks, key=lambda task: task[1]) |
def is_in_list(item, list_, kind):
"""Check whether an item is in a list; kind is just a string."""
if item not in list_:
raise KeyError(f"Specify {kind} from {list_}: got {item}")
return True |
def split_to_last_line_break(data):
"""This splits a byte buffer into (head, tail) where head contains the
beginning of the buffer to the last line break (inclusive) and the tail
contains all bytes after that."""
last_break_index = 1 + data.rfind(b'\n')
return data[:last_break_index], data[last_break_index:] |
def worldtidesinfo_unique_id(lat, long):
"""give a unique id for sensor"""
return "lat:{}_long:{}".format(lat, long) |
def hexsplit(string):
""" Split a hex string into 8-bit/2-hex-character groupings separated by spaces"""
return ' '.join([string[i:i+2] for i in range(0, len(string), 2)]) |
def conv(filter_value):
"""
Convert * to % got from clients for the database queries.
"""
if filter_value is None:
return '%'
return filter_value.replace('*', '%') |
def indent_lines(code: str, level: int, spaces: int = 4):
"""
indentation helper function. Add spaces in front of every line of code
:param code: string, code to be indented
:param level: indentation level
:param spaces: # of spaces per level
:return: indented string
"""
width = level * spaces
lines = code.split('\n')
return '\n'.join([line.rjust(width + len(line), ' ') for line in lines]) |
def mul(a,b):
"""Multiply two numbers
a - the first input
b - the second input
"""
multiplication = a*b
return multiplication |
def array_equal(x, y, interval=None):
"""Check if two one-dimentional integer arrays are equal.
Parameters
----------
x, y : ndarray, int
1D vectors of integers.
interval : tuple, int shape (2, ), optional
A pair of integers defining a half open interval.
Returns
-------
equality : bool
True if `x` and `y` are equal (within an interval
if specified).
"""
if interval is None:
r = range(len(x))
else:
r = range(interval[0], interval[1])
for i in r:
if x[i] != y[i]:
return False
return True |
def action_color(status):
"""
Get a action color based on the workflow status.
"""
if status == "success":
return "good"
elif status == "failure":
return "danger"
return "warning" |
def get_biggest_face(array_of_faces):
"""
:param array_of_faces: array of faces returned from detector.detectMultiScale()
:return: a 1x4 array containing the face with the biggest area (width*height)
"""
largest_area = 0
largest_face = None
for face in array_of_faces:
area = face[2] * face[3] # width * height
if area > largest_area:
largest_area = area
largest_face = face
return [largest_face] |
def get_ects_equivalent_score(score: float) -> str:
"""Return the grade in the ECTS equivalent form.
Range from A to E/F."""
if score >= 70:
return "A"
if score >= 60:
return "B"
if score >= 50:
return "C"
if score >= 40:
return "D"
if score == -1: # RPL: score is not applicable
return "N/A"
return "E/F" |
def keys_exists(element: dict, *keys) -> bool:
"""
Check if *keys (nested) exists in `element` (dict).
:param element: Dictionary to check.
:param keys: Dictionary keys to search.
:return: True if all nested keys found or False in other cases.
:raises Exception: if input element or keys are invalid.
"""
if not isinstance(element, dict):
raise AttributeError("keys_exists() expects dict as first argument.")
if len(keys) == 0:
raise AttributeError(
"keys_exists() expects at least two arguments, one given."
)
_element = element
for key in keys:
try:
_element = _element[key]
except KeyError:
return False
return True |
def overlap(region1, region2, inc=True):
"""
Returns True if range region1=[a,b] overlaps region2=[x,y]
inc -- if True, treat [a,b] and [x,y] as inclusive
"""
if inc:
return (region2[1] >= region1[0]) and (region2[0] <= region1[1])
else:
return (region2[1] > region1[0]) and (region2[0] < region1[1]) |
def ndre(nm790, nm720):
"""function returning a NDRE map.
NDRE is calculated as:
NDRE = (790nm - 720nm) / (790nm + 720nm)
which corresponds to:
NDRE = (NIR - RE) / (NIR + RE)
Parameters
----------
nm790 : numpy.ndarray
2d-numpy array of the target response at 790nm (NIR)
nm720 : numpy.ndarray
2d-numpy array of the target response at 720nm (RE)
"""
return (nm790 - nm720) / (nm790 + nm720) |
def ipStringToDict(ipString):
"""
Pass String obtioned in webform to string
Returns : Dictionary of values
"""
ipSplit = ipString.split()
#If ipSplit is only 2 words, it's a policy rule
if len(ipSplit) == 2:
ipDict = {"Chain" : ipSplit[0], "Action" : ipSplit[1]}
#Else it's a full rule
else:
tableData =''
chainData = ipSplit[0]
ifaceData =''
oufaceData =''
protData =''
source =''
sourceport=''
destination =''
port =''
stateData =''
actionData =''
for index in range(0, len(ipSplit)):
if ipSplit[index] == '-t':
tableData= ipSplit[index+1]
#elif ipSplit[index] == '-A':
# chainData= ipSplit[index+1]
elif ipSplit[index] == '-i':
ifaceData= ipSplit[index+1]
elif ipSplit[index] == '-o':
oufaceData= ipSplit[index+1]
elif ipSplit[index] == '-p':
protData= ipSplit[index+1]
elif ipSplit[index] == '-s':
source= ipSplit[index+1]
elif ipSplit[index] == '--sport':
sourceport= ipSplit[index+1]
elif ipSplit[index] == '-d':
destination= ipSplit[index+1]
elif ipSplit[index] == '--dport':
port= ipSplit[index+1]
elif ipSplit[index] == '-m':
stateData= ipSplit[index+1]
elif ipSplit[index] == '-j':
actionData= ipSplit[index+1]
ipDict = {'Table': tableData, 'Chain': chainData, 'Input': ifaceData, 'Output': oufaceData, 'Protocol': protData,
'Source': source, 'Source_Port': sourceport, 'Destination': destination,'Destination_Port': port, 'State':stateData, 'Action': actionData}
return ipDict |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.