content stringlengths 42 6.51k |
|---|
def map_structure(operation, *param_groups):
""" Expects a pair of list of lists of identical structure representing
two sets of parameter states. This will apply the desired operation to
each element in the two groups
:param param_groups_1: The first parameter group
:param param_groups_2: The second parameter group
:return: A list of lists which is the result of the operation applied to
each pair of elements in the inputs
"""
param_groups_return = []
for groups in zip(*param_groups):
group_grads = []
for ps in zip(*groups):
group_grads.append(operation(*ps))
param_groups_return.append(group_grads)
return param_groups_return |
def get_match(match, index, default=''):
"""
Returns a value from match list for a given index. In the list is out of
bounds `default` is returned.
"""
if index >= len(match):
return default
else:
return match[index] |
def reformat_params(params):
"""Transform from pygmm input to spreadsheet input."""
if "mechanism" in params:
# Replace mechanism with flags
mech = params.pop("mechanism")
if mech == "SS":
params["flag_u"] = 0
params["flag_rv"] = 0
params["flag_nm"] = 0
elif mech == "NS":
params["flag_u"] = 0
params["flag_rv"] = 0
params["flag_nm"] = 1
elif mech == "RS":
params["flag_u"] = 0
params["flag_rv"] = 1
params["flag_nm"] = 0
elif mech == "U":
params["flag_u"] = 1
params["flag_rv"] = 0
params["flag_nm"] = 0
try:
on_hanging_wall = params.pop("on_hanging_wall")
params["flag_hw"] = 1 if on_hanging_wall else 0
except KeyError:
pass
try:
params["flag_meas"] = params.pop("vs_source")
except KeyError:
pass
try:
params["region"] = params["region"].replace("_", " ").title()
except KeyError:
pass
# Replace None with 999
for key in ["depth_tor", "depth_hyp", "depth_1_0", "depth_2_5", "width", "dist_y0"]:
if key in params and params[key] is None:
params[key] = 999
if "dist_rup" not in params and "dist_jb" in params:
params["dist_rup"] = params["dist_jb"]
try:
# No supported to changing the DPP
params.pop("dpp_centered")
except KeyError:
pass
return params |
def drude(ep, eb, gamma, e):
"""dielectric function according to Drude theory"""
eps = 1 - (ep ** 2 - eb * e * 1j) / (e ** 2 + 2 * e * gamma * 1j) # Mod drude term
return eps |
def clean_names(names):
"""Removes whitespace from channel names, useful sometimes when comparing
lists of channels.
Parameters
----------
names : list
List of channel names
Returns
-------
list
Returns list of channel names without any whitespace.
"""
return [name.replace(' ', '') for name in names] |
def shell_sort(arr):
"""Shell Sort
Complexity: O(n^2)
:param arr: The input array, unsorted.
:return arr: The sorted array
"""
n = len(arr)
# Initialize size of the gap
gap = n // 2
while gap > 0:
y_index = gap
while y_index < len(arr):
y = arr[y_index]
x_index = y_index - gap
while x_index >= 0 and y < arr[x_index]:
arr[x_index + gap] = arr[x_index]
x_index = x_index - gap
arr[x_index + gap] = y
y_index = y_index + 1
gap = gap//2
return arr |
def knapval_rep(capacity, items):
"""
Returns the maximum value achievable in 'capacity'
weight using 'items' when repeated items are allowed
"""
options = list(
item.value + knapval_rep(capacity-item.weight, items) for item in items if item.weight <= capacity)
if len(options):
return max(options)
else:
return 0 |
def capitalize_name(name):
"""
:param name: a string containing a name
:return: the string where the first letter of every token is capitalized
"""
tokens = name.split(" ")
tokens_capitalized = [token[0].upper()+token[1:].lower() for token in tokens]
return " ".join(tokens_capitalized) |
def format_collapse(ttype, dims):
"""
Given a type and a tuple of dimensions, return a struct of
[[[ttype, dims[-1]], dims[-2]], ...]
>>> format_collapse(int, (1, 2, 3))
[[[<class 'int'>, 3], 2], 1]
"""
if len(dims) == 1:
return [ttype, dims[0]]
else:
return format_collapse([ttype, dims[-1]], dims[:-1]) |
def decode_string(v, encoding="utf-8"):
""" Returns the given value as a Unicode string (if possible).
"""
if isinstance(encoding, str):
encoding = ((encoding,),) + (("windows-1252",), ("utf-8", "ignore"))
if isinstance(v, bytes):
for e in encoding:
try:
return v.decode(*e)
except:
pass
return v
return str(v) |
def _guess_type_from_network(network):
"""
Return a best guess of the type of network (road, hiking, bus, bicycle)
from the network tag itself.
"""
if network in ['iwn', 'nwn', 'rwn', 'lwn']:
return 'hiking'
elif network in ['icn', 'ncn', 'rcn', 'lcn']:
return 'bicycle'
else:
# hack for now - how can we tell bus routes from road routes?
# it seems all bus routes are relations, where we have a route type
# given, so this should default to roads.
return 'road' |
def read_vx(pointdata):
"""Read a variable-length index."""
if pointdata[0] != 255:
index = pointdata[0] * 256 + pointdata[1]
size = 2
else:
index = pointdata[1] * 65536 + pointdata[2] * 256 + pointdata[3]
size = 4
return index, size |
def get_volume():
"""
Example of amixer output :
Simple mixer control 'Master',0
Capabilities: pvolume pswitch pswitch-joined
Playback channels: Front Left - Front Right
Limits: Playback 0 - 65536
Mono:
Front Left: Playback 40634 [62%] [on]
Front Right: Playback 40634 [62%] [on]
"""
return 0
# m = alsaaudio.Mixer(get_mixer_name())
# return int(m.getvolume()[0]) |
def get_hosts_ram_usage_ceilo(ceilo, hosts_ram_total):
"""Get ram usage for each host from ceilometer
:param ceilo: A Ceilometer client.
:type ceilo: *
:param hosts_ram_total: A dictionary of (host, total_ram)
:type hosts_ram_total: dict(str: *)
:return: A dictionary of (host, ram_usage)
:rtype: dict(str: *)
"""
hosts_ram_usage = dict() #dict of (host, ram_usage)
for host in hosts_ram_total:
#actually hostname_nodename
host_res_id = "_".join([host, host])
#sample of ram usage in percentage
host_mem_usage = ceilo.samples.list(meter_name='host.memory.usage',
limit=1,
q=[{'field':'resource_id',
'op':'eq',
'value':host_res_id}])
if host_mem_usage:
host_mem_usage = host_mem_usage[0].counter_volume
host_mem_total = hosts_ram_total[host]
hosts_ram_usage[host] = (int)((host_mem_usage/100)*host_mem_total)
return hosts_ram_usage |
def iterable(obj):
"""Return true if the argument is iterable"""
try:
iter(obj)
except TypeError:
return False
return True |
def center_y(cell_lower_left_y, cell_height, y0, word_height):
""" This function centers text along the y-axis
:param cell_lower_left_y: Lower left y-coordinate
:param cell_height: Height of cell in which text appears
:param y0: Lower bound of text (sometimes can be lower than cell_lower_left-y (i.e. letter y))
:param word_height: Height of plotted word
:return: Centered y-position
"""
return cell_lower_left_y + ((cell_height / 2.0) - y0) - (word_height / 2.0) |
def bstr_to_set(b):
"""
Convert a byte string to a set of the length-1 bytes obejcts within it.
"""
return set(bytes([c]) for c in b) |
def calc_p_ratio(hps, nhps, total_hps, total_nhps):
"""
Returns a ratio between the proportion hps/nhps to the proportion nhps/hps. The larger proportion will be the
numerator and the lower proportion will be the denominator (and thus the p-ratio>=1).
This corrects for the total_hps/total_nhps imbalance in the data set.
:param hps: number of hps
:param nhps: number of nhps
:param total_hps: total number of hps in the dataset
:param total_nhps: total number of nhps in the dataset
:return: ratio x/y where x=hps/nhps, y=nhps/hps if x > y, else y/x
"""
hps_proportion = (hps+1) / (total_hps+1) # add-one smoothing
nhps_proportion = (nhps+1) / (total_nhps+1) # add-one smoothing
p_ratio = round(max(hps_proportion, nhps_proportion)/min(hps_proportion, nhps_proportion), 2)
return p_ratio |
def segno(x):
"""
Input: x, a number
Return: 1.0 if x>0,
-1.0 if x<0,
0.0 if x==0
"""
if x > 0.0: return 1.0
elif x < 0.0: return -1.0
elif x == 0.0: return 0.0 |
def clean_arguments(args: dict) -> dict:
"""Cleans up a dictionary from keys containing value `None`.
:param args: A dictionary of argument/value pairs generated with ArgumentParser
:return: A dictionary with argument/value pairs without `None` values
:rtype: dict
"""
rv = {}
for (key, val) in args.items():
if isinstance(val, dict):
val = clean_arguments(val) or None
if val is not None:
rv[key] = val
return rv |
def is_error_yandex_response(data: dict) -> bool:
"""
:returns: Yandex response contains error or not.
"""
return ("error" in data) |
def convert_edition_to_shortform(edition):
"""Convert edition to shortform Enterprise or Community or N/E"""
if edition.lower() in ['enterprise', 'true', 'ee'] or 'enterprise' in edition.lower():
return "Enterprise"
if edition.lower() in ['community', 'false', 'ce'] or 'community' in edition.lower():
return "Community"
return "N/E" |
def betterFib(n):
"""
Better implementation of nth Fibonacci number generator
Time complexity - O(n)
Space complexity - O(n)
:param n: The nth term
:return: The nth fibonnaci number
"""
fib = [None] * n
#print fib
if n == 0:
return 0
elif n == 1:
return 1
elif fib[n-1] is not None:
return fib[n-1]
else :
fib[n-1] = betterFib(n-1) + betterFib(n-2)
return fib[n-1] |
def irange(start, end):
"""Inclusive range from start to end (vs. Python insanity.)
irange(1,5) -> 1, 2, 3, 4, 5"""
return range( start, end + 1 ) |
def extract_cfda(field, type):
""" Helper function representing the cfda psql functions """
extracted_values = []
if field:
entries = [entry.strip() for entry in field.split(';')]
if type == 'numbers':
extracted_values = [entry[:entry.index(' ')] for entry in entries]
else:
extracted_values = [entry[entry.index(' ')+1:] for entry in entries]
return ', '.join(extracted_values) |
def strip_article_title_word(word:str):
"""
Used when tokenizing the titles of articles
in order to index them for search
"""
return word.strip('":;?!<>\'').lower() |
def successResponse(response):
"""
Format the given object as a positive response.
"""
response = str(response)
return '+OK %s\r\n' % (response,) |
def component_src_subdir(category, type):
"""name of the subdir of component source to be generated
"""
return '%s_%s' % (category, type) |
def line(k, x):
""" line function """
return k[0]*x + k[1] |
def find_intersection(*args):
"""Find intersecting list of values between an arbitrary number of arguments.
:return: Returns list[] containing intersecting values.
"""
# Original case:
# unique_codes = list(country_codes['ped'].intersection(country_codes['gtd'].intersection(country_codes['mfi'])))
# No args, no intersection.
if args is None:
return None
# If there are args, incrementally find the intersection among all of them.
if len(args) > 0:
set_values = set(args[0])
for i in range(len(args)):
set_values = set_values.intersection(set(args[i]))
return list(set_values)
# If not returned, return nothing.
return None |
def _to_hass_temperature(temperature):
"""Convert percentage to Home Assistant color temperature units."""
return int(temperature * 346) + 154 |
def _shorten_name(name):
"""Format asset name to ensure they match the backend requirements."""
if len(name) < 100:
return name
return name[:75] + '...' + name[:20] |
def camelize(src: str) -> str:
"""Convert snake_case to camelCase."""
components = src.split("_")
return components[0] + "".join(x.title() for x in components[1:]) |
def _make_filename_from_pytest_nodeid(nodeid):
"""Transforms pytest nodeid to safe file name"""
return (nodeid.lower()
.replace('/', '_')
.replace(':', '_')
.replace('.', '_')) |
def subset_of_dict(dict, chosen_keys):
"""make a new dict from key-values of chosen keys in a list"""
return {key: value for key, value in dict.items() if key in chosen_keys} |
def build_query_from_table(name):
""" Create a query given the table name
Args:
name: Table name
Returns:
query string
"""
return "SELECT * FROM {0}".format(name) |
def _GenerateQueryParameters(parameters):
"""Generates query parameters using parameters.
Reference: https://goo.gl/SyALkb.
Currently this function only supports parameters of a single value. To support
struct or array parameters, please refer to the link above.
Args:
parameters ([tuples]): A list of parameter tuples in the format:
[(name, type, value)]
"""
if not parameters:
return None
query_params = []
for name, p_type, value in parameters:
query_params.append({
'name': name,
'parameterType': {
'type': p_type
},
'parameterValue': {
'value': value
}
})
return query_params |
def is_inconsistent(results_dict, iterations):
"""Return whether or not a single test is inconsistent."""
return len(results_dict) > 1 or sum(results_dict.values()) != iterations |
def _decode_int(data):
"""
decode integer from bytearray
return int, remaining data
"""
data = data[1:]
end = data.index(b'e')
return int(data[:end],10), data[end+1:] |
def xmltag_split2(tag, namespaces, colon=False):
"""Return XML namespace prefix of element"""
try:
nsuri = tag.split('}')[0].split('{')[1]
nsprefix = [key for key, value in namespaces.items()
if value == nsuri]
value = nsprefix[0]
if colon:
return '%s:' % nsprefix[0]
else:
return nsprefix[0]
except:
return '' |
def _get_spm_arch(swift_cpu):
"""Maps the Bazel architeture value to a suitable SPM architecture value.
Args:
bzl_arch: A `string` representing the Bazel architecture value.
Returns:
A `string` representing the SPM architecture value.
"""
# No mapping at this time.
return swift_cpu |
def crc8P1(byteData):
"""
Generate 8 bit CRC of supplied string + 1
eg as used in REVO PI30 protocol
"""
CRC = 0
for b in byteData:
CRC = CRC + b
CRC += 1
CRC &= 0xFF
return CRC |
def remove_whitespace (string):
"""
Useless function how remove all whitespaces of string
@type string: numpy str
@param string: The string with whitespaces
@rtype: str
@return: Return the saem string but whitout whitespaces
"""
if (type(string) is not str):
raise TypeError('Type of string must be \'str\' and not ' + str(type(string)))
return string.replace(' ', '') |
def usage(prtflag):
"""
Do something with the usage message.
If the prtflag parameter is non-zero, we'll print and exit.
If it is zero, we'll just return the string.
"""
#
# Set up our usage string.
#
outstr = """zeek-grep [options]
where [options] are:
-filter - define a filter for search log files
-and - AND filter results instead of OR'ing them
-meta - display metadata lines from log files
-h - don't display log filenames (NYI)
-verbose - give verbose output
-Version - show version and exit
-help - show usage message
-man - show man page
"""
#
# Just return the output if we aren't to print the usage string.
#
if(prtflag == 0):
return(outstr)
#
# Print the usage string and exit.
#
print("usage: " + outstr.rstrip())
exit(0) |
def protobuf_get_constant_type(proto_type) :
"""About protobuf write types see :
https://developers.google.com/protocol-buffers/docs/encoding#structure
+--------------------------------------+
+ Type + Meaning + Used For +
+--------------------------------------+
+ + + int32, int64, uint32+
+ 0 + Varint + uint64,sint32,sint64+
+ + + boolean, enum +
+--------------------------------------+
+ + + +
+ 1 + 64-bit + fixed64, sfixed64, +
+ + + double +
+--------------------------------------+
+ 2 + string + string +
+--------------------------------------+
+ 5 + 32-bit + float +
+--------------------------------------+
"""
if 'uInt32' == proto_type or \
'sInt32' == proto_type or \
'int32' == proto_type :
return 0
elif 'double' == proto_type :
return 1
elif 'string' == proto_type :
return 2
elif 'float' == proto_type :
return 5
return 2 |
def write_arbitrary_beam_section(inps, ts, branch_paths, nsm, outp_id, core=None):
"""writes the PBRSECT/PBMSECT card"""
end = ''
for key, dicts in [('INP', inps), ('T', ts), ('BRP', branch_paths), ('CORE', core)]:
if dicts is None:
continue
# dicts = {int index : int/float value}
for index, value1 in sorted(dicts.items()):
if index == 0:
if isinstance(value1, list):
for value1i in value1:
end += ' %s=%s,\n' % (key, value1i)
else:
end += ' %s=%s,\n' % (key, value1)
else:
if isinstance(value1, list):
if len(value1) == 2:
assert len(value1) == 2, value1
thicknessi = value1[0]
points = value1[1]
end += ' %s(%s)=[%s, PT=(%s,%s)],\n' % (
key, index, thicknessi, points[0], points[1])
else:
assert len(value1) == 1, value1
end += ' %s=%s,\n' % (key, value1[0])
else:
end += ' %s(%s)=%s,\n' % (key, index, value1)
for key, value in [('NSM', nsm), ('outp', outp_id),]:
if value:
end += ' %s=%s,\n' % (key, value)
if end:
end = end[:-2] + '\n'
return end |
def complement(y, n):
"""Complement of y in [0,...,n-1]. E.g. y = (0,2), n=4, return [1,3]."""
return sorted(list(set(range(n)) - set(y))) |
def get_music(song):
"""Artists who intoned the text"""
artists = [contributor['contributor_name'] for contributor in song['contributors']]
artists = [a for a in artists if a is not None]
if len(artists) == 0 and song['song_description']:
return song['song_description']
elif len(artists) > 2:
return " & ".join([", ".join(artists[:-1]), artists[-1]])
else:
return ' & '.join(artists) |
def bitmask(str):
"""
bitmask from character string
"""
res = []
for ci in range(0, len(str)):
c = str[ci]
for i in range(0, 8):
res.append(((ord(c) << i) & 0x80) >> 7)
return res |
def zfp_rate_opts(rate):
"""Create compression options for ZFP in fixed-rate mode
The float rate parameter is the number of compressed bits per value.
"""
zfp_mode_rate = 1
from struct import pack, unpack
rate = pack('<d', rate) # Pack as IEEE 754 double
high = unpack('<I', rate[0:4])[0] # Unpack high bits as unsigned int
low = unpack('<I', rate[4:8])[0] # Unpack low bits as unsigned int
return zfp_mode_rate, 0, high, low, 0, 0 |
def anisotropy_from_intensity(Ipar, Iper):
"""
Calculate anisotropy from crossed intensities values.
"""
return (Ipar - Iper)/(Ipar + 2*Iper) |
def _get_positional_body(*args, **kwargs):
"""Verify args and kwargs are valid, and then return the positional body, if users passed it in."""
if len(args) > 1:
raise TypeError("There can only be one positional argument, which is the POST body of this request.")
if args and "options" in kwargs:
raise TypeError(
"You have already supplied the request body as a positional parameter, "
"you can not supply it as a keyword argument as well."
)
return args[0] if args else None |
def fib_iter(number):
"""Funkce vypocita number-te finonacciho cislo pomoci linearniho
iterativniho algoritmu.
0. fibonacciho cislo je 0, 1. je 1
"""
if number == 0:
return 0
lower = 0
higher = 1
for i in range(number - 1):
lower, higher = higher, lower + higher
return higher |
def fsplit(pred, objs):
"""Split a list into two classes according to the predicate."""
t = []
f = []
for obj in objs:
if pred(obj):
t.append(obj)
else:
f.append(obj)
return (t, f) |
def compute_anchored_length(qry_aln_beg, qry_aln_end, ref_aln_beg, ref_aln_end,
aln_len, qry_len, ref_len):
"""
Compute the maximal length of the alignable region anchored by the best hit
"""
if qry_aln_beg < qry_aln_end:
qab = qry_aln_beg
qae = qry_aln_end
else:
qab = qry_aln_end
qae = qry_aln_beg
if ref_aln_beg < ref_aln_end:
rab = ref_aln_beg
rae = ref_aln_end
else:
rab = ref_aln_end
rae = ref_aln_beg
left_ohang = min(qab, rab)-1
right_ohang = min(qry_len-qae, ref_len-rae)
return left_ohang + aln_len + right_ohang |
def transform_data(data_array):
"""Trasnform a matrix with String elements to one with integers."""
transformed_data = []
n = len(data_array)
for row in range(0, n):
temp = []
for elem in range(0, n):
temp.append(int(data_array[row][elem]))
transformed_data.append(temp)
return transformed_data |
def NcbiNameLookup(names):
"""Returns dict mapping taxon id -> NCBI scientific name."""
result = {}
for name in names:
if name.NameClass == "scientific name":
result[name.TaxonId] = name
return result |
def overlap(start1, end1, start2, end2):
"""Does the range (start1, end1) overlap with (start2, end2)?"""
return not (end1 < start2 or end2 < start1) |
def display_list_by_prefix(names_list, starting_spaces=0):
"""Creates a help string for names_list grouped by prefix."""
cur_prefix, result_lines = None, []
space = " " * starting_spaces
for name in sorted(names_list):
split = name.split("_", 1)
prefix = split[0]
if cur_prefix != prefix:
result_lines.append(space + prefix + ":")
cur_prefix = prefix
result_lines.append(space + " * " + name)
return "\n".join(result_lines) |
def multiply_matrix_by_real(a, real):
"""
Return result of real*a
:param a: a 2 dimensional array
:param real: a real
:return: a 2 dimensional array
"""
return [[j*real for j in i] for i in a] |
def obj_id(obj):
"""Return the last four digits of id(obj), for dumps & traces."""
return str(id(obj))[-4:] |
def convert(x):
"""
function takes x which is an array in the form
x = [(station, distance), ......] // note station is an object
and returns an array in the form of
[(station.name, station.town, distance ), ......]
"""
res_arr = []
for tuple in x:
res_arr.append((tuple[0].name, tuple[0].town, tuple[1]))
return res_arr |
def one_of_k_encoding_unk(x, allowable_set):
"""Maps inputs not in the allowable set to the last element."""
if x not in allowable_set:
x = allowable_set[-1]
return list(map(lambda s: x == s, allowable_set)) |
def bboxFromString(bboxStr):
""" Get bbox dictionary from comma separated string of the form
'-76.769782 39.273610 -76.717498 39.326008'
@param bboxStr String representing bounding box in WGS84 coordinates
@return Dict representing bounding box with keys: minX, minY, maxX, maxY, and srs
"""
bbox = bboxStr.split()
bbox = dict({'minX': float(bbox[0]), 'minY': float(bbox[1]), 'maxX': float(bbox[2]), 'maxY': float(bbox[3]), 'srs': 'EPSG:4326'})
return bbox |
def _AddLabels(existing_labels, labels_to_add):
"""Adds labels in labels_to_add to existing_labels."""
updated_labels = existing_labels + labels_to_add
return list(set(updated_labels)) |
def which(program):
"""Returns full path to `program` if found in $PATH or else None
if the executable is not found.
SRC: http://stackoverflow.com/a/377028/983310
"""
import os
def is_exe(fpath):
return os.path.isfile(fpath) and os.access(fpath, os.X_OK)
fpath, fname = os.path.split(program)
if fpath:
if is_exe(program):
return program
else:
for path in os.environ["PATH"].split(os.pathsep):
path = path.strip('"')
exe_file = os.path.join(path, program)
if is_exe(exe_file):
return exe_file
return None |
def get_magic_number(divisor, word_size):
"""
Given word size W >= 1 and divisor d, where 1 <= d < 2**W,
finds the least integer m and integer p such that
floor(mn // 2**p) == floor(n // d) for 0 <= n < 2**W
with 0 <= m < 2**(W+1) and p >= W.
Implements the algorithm described by Hacker's Delight [2E], specifically,
section 10-9 Unsigned Division by Divisors >= 1.
Parameters
----------
divisor : int
The divisor d in the problem statement.
word_size : int
The word size W in the problem statement. The number of bits.
Returns
-------
M : hex
The magic number.
p : int
The exponent p.
algorithm_type : See common.h
"""
d, W = divisor, word_size
nc = (2**W // d) * d - 1 # Eqn (24a)
for p in range(2 * W + 1): # Eqn (29)
if 2 ** p > nc * (d - 1 - (2 ** p - 1) % d): # Eqn (27)
m = (2 ** p + d - 1 - (2 ** p - 1) % d) // d # Eqn (26)
# Unsigned case, the magic number M is given by:
# m if 0 <= m < 2**W
# m - 2**W if 2**W <= m < 2**(W+1)
if 0 <= m < 2**W:
return d, W, m, p, "AlgorithmType::OVERFLOW_SMALL"
elif 2**W <= m < 2**(W+1):
return d, W, m - 2**W, p, "AlgorithmType::OVERFLOW_LARGE"
else:
raise RuntimeError("Invalid case. Not enough bits?") |
def solve(arr: list) -> int:
""" This function returns the difference between the count of even numbers and the count of odd numbers. """
even = []
odd = []
for item in arr:
if str(item).isdigit():
if item % 2 == 0:
even.append(item)
else:
odd.append(item)
return len(even) - len(odd) |
def _pylontech_quirk(dvcc, bms, charge_voltage, charge_current, feedback_allowed):
""" Quirk for Pylontech. Make a bit of room at the top. Pylontech says that
at 51.8V the battery is 95% full, and that balancing starts at 90%.
53.2V is normally considered 100% full, and 54V raises an alarm. By
running the battery at 52.4V it will be 99%-100% full, balancing should
be active, and we should avoid high voltage alarms.
Identify 24-V batteries by the lower charge voltage, and do the same
thing with an 8-to-15 cell ratio, +-3.48V per cell.
"""
# Use 3.48V per cell plus a little, 52.4V for 48V batteries.
# Use 3.46V per cell plus a little, 27.8V for 24V batteries testing shows that's 100% SOC.
# That leaves 1.6V margin for 48V batteries and 1.0V for 24V.
# See https://github.com/victronenergy/venus/issues/536
if charge_voltage > 30:
# 48V battery (15 cells)
return (min(charge_voltage, 52.4), charge_current, feedback_allowed)
else:
# 24V battery (8 cells). 24V batteries send CCL=0 when they are full,
# whereas the 48V batteries reduce CCL by 50% when the battery is full.
# Do the same for 24V batteries. The normal limit is C/2, so put the
# limit to C/4. Note that this is just a nicety, the important part is
# to clip the charge voltage to 27.8 volts. That fixes the sawtooth
# issue.
capacity = bms.capacity or 55
return (min(charge_voltage, 27.8), max(charge_current, round(capacity/4.0)), feedback_allowed) |
def fib_loop(num):
"""
Finds the N-th fibonacci number using ordinary for-loop.
:param int num: The N-th fibonacci number (index).
:return: Computed number.
"""
if num < 2:
return num
first, second = 0, 1
for i in range(2, num + 1):
first, second = second, first + second
return second |
def matrix_inverse(matrix):
"""Docstring"""
dimension = len(matrix)
con = 0.0
for k in range(dimension):
con = matrix[k][k]
matrix[k][k] = 1
for j in range(dimension):
matrix[k][j] = matrix[k][j]/con
for i in range(dimension):
if i != k:
con = matrix[i][k]
matrix[i][k] = 0.0
for j in range(dimension):
matrix[i][j] -= matrix[k][j]*con
return matrix |
def diff(rankx, ranky):
""" Return the difference of valuations rankx and ranky.
Trivial, but included for consistency with other modules.
"""
return float(ranky - rankx) |
def _apply_decreasing_rate(value: float, rate: float) -> float:
"""
Apply a decreasing rate to a value
:param value: current value
:param rate: per second
:return: updated value
"""
return value - (60 * rate) |
def _check_frequency(frequency):
"""Check given frequency is valid."""
if frequency is None:
frequency = 'monthly'
if frequency not in ('daily', 'monthly'):
raise ValueError("Unsupported frequency '%r'" % frequency)
return frequency |
def can_merge(a, b):
"""
Test if two cubes may be merged into a single cube (their bounding box)
:param a: cube a, tuple of tuple ((min coords), (max coords))
:param b: cube b, tuple of tuple ((min coords), (max coords))
:return: bool, if cubes can be merged
"""
c = 0 # Count the number of continued dimensions
for i, j, k, l in zip(a[0], a[1], b[0], b[1]):
x = i == k and j == l # If this dimension matches exactly
y = i == l or j == k # If one cube continues the other
z = y and (c == 0) # If we are the first dimension to be continued
if not x and not z:
return False
if y: # Increment the continued dimension count
c += 1
return True |
def make_full_path(path, name):
""" Combine path and name to make full path"""
if path == "/":
full_path = "/" + name
else:
assert not path.endswith('/'), "non-root path ends with '/' (%s)" % path
full_path = path + "/" + name
# remove any duplicate slashes, should be unnecessary
# full_path = re.sub(r'//+',r'/', full_path)
return full_path |
def sum_rec_goingup_idx(x, i, j):
"""
"""
if i < j:
return x[i] + sum_rec_goingup_idx(x, i + 1, j)
if i == j:
return x[i]
return 0 |
def get_regexp_pattern(regexp):
"""
Helper that returns regexp pattern from given value.
:param regexp: regular expression to stringify
:type regexp: _sre.SRE_Pattern or str
:returns: string representation of given regexp pattern
:rtype: str
"""
try:
return regexp.pattern
except AttributeError:
return str(regexp) |
def odd_desc(count):
"""
Replace ___ with a single call to range to return a list of descending odd numbers ending with 1
For e.g if count = 2, return a list of 2 odds [3,1]. See the test below if it is not clear
"""
return list(reversed(range(1,count*2,2))) |
def highlight_text(text):
"""Returns text with html highlights.
Parameters
----------
text: String
The text to be highlighted.
Returns
-------
ht: String
The text with html highlight information.
"""
return f"""<code style="background:yellow; color:black; padding-top: 5px; padding-bottom: 5px">
{text}
</code>""".strip() |
def sub_dir_by_split(d):
""" build out the split portion of the results directory structure.
:param dict d: A dictionary holding BIDS terms for path-building
"""
return "_".join([
'-'.join(['parby', d['parby'], ]),
'-'.join(['splby', d['splby'], ]),
'-'.join(['batch', d['batch'], ]),
]) |
def convert_to_unicode(text):
"""Converts `text` to Unicode (if it's not already)."""
if isinstance(text, str):
return text
elif isinstance(text, bytes):
return text.decode('utf-8', 'ignore')
else:
raise ValueError('Unsupported string type: %s' % (type(text))) |
def factorial(n):
""" Returns the factorial of n.
"""
f = 1
while (n > 0):
f = f * n
n = n - 1
return f |
def _preprocess_and_filter_original_dataset(data):
"""Filters out badly visible or uninteresting signs."""
label_order = ("EMPTY", "50_SIGN", "70_SIGN", "80_SIGN")
filtered_data = []
for image, signs in data:
if not signs:
filtered_data.append((image, label_order.index("EMPTY")))
else:
# take the most visible of the interesting signs
signs = [s for s in signs
if s.name in label_order and s.visibility == "VISIBLE"]
if signs:
filtered_data.append((image, label_order.index(signs[0].name)))
return filtered_data |
def sqrt(n: int) -> int:
"""Gets the integer square root of an integer rounded toward zero."""
return int(n ** 0.5) |
def kwattr(d, name, default=None):
"""Return attribute, converted to lowercase."""
v = d.get(name, default)
if v != default and v is not None:
v = v.strip().lower()
v = v or default
return v |
def _getImport(libs, val):
"""
Dynamically imports a library into memory for referencing during configuration file parsing.
Args:
libs (list): The list of libraries already imported.
val (str): The name of the new library to import.
Returns:
(str): The name of the newly imported library. If library is already imported then returns None.
"""
if val is not None and isinstance(val,str) and val.strip() != "":
if "." in val:
parts = val.split(".")
parts.pop()
ret = ".".join(parts)
if ret in libs:
return None
libs.append(ret)
return ret
return None |
def nested_map(fn, x, iter_type=list):
"""
A python analogue to BPL "apply_to_nested"
https://github.com/brendenlake/BPL/blob/master/stroke_util/apply_to_nested.m
"""
if isinstance(x, iter_type):
return [nested_map(fn, elt) for elt in x]
else:
return fn(x) |
def count_sixes(results):
"""
Count the number of sixes in a list of integers.
"""
return sum(1 for roll in results if roll == 6) |
def sol(arr, n, k):
"""
Store the position of the element in a hash and keep updating it
as we go forward. If the element already exists in the hash check
the distance between them and return True if it is <= k
"""
h = {}
for i in range(n):
if arr[i] in h:
pos = h[arr[i]]
if pos+k >= i:
return True
h[arr[i]] = i
return False |
def distance_xy(p1, p2):
"""Calculates 2D distance between p1 and p2. p1 and p2 are vectors of
length >= 2."""
return ((p1[0]-p2[0])**2 + (p1[1]-p2[1])**2)**0.5 |
def crop_axis(points, axis_number):
"""keeps only the axis_number most important axis"""
return [point[:axis_number] for point in points] |
def make_ping(userid):
"""Turn a user ID into a ping"""
return f"<@{userid}>" |
def __wavelength_to_rgb(wavelength, gamma=0.8):
"""Not intended for use by users, See noah.org: http://www.noah.org/wiki/Wavelength_to_RGB_in_Python .
Parameters
----------
wavelength : `float` or `int`
wavelength of light
gamma : `float`, optional
output gamma
Returns
-------
`tuple`
R, G, B values
"""
wavelength = float(wavelength)
if wavelength >= 380 and wavelength <= 440:
attenuation = 0.3 + 0.7 * (wavelength - 380) / (440 - 380)
R = ((-(wavelength - 440) / (440 - 380)) * attenuation) ** gamma
G = 0.0
B = (1.0 * attenuation) ** gamma
elif wavelength >= 440 and wavelength <= 490:
R = 0.0
G = ((wavelength - 440) / (490 - 440)) ** gamma
B = 1.0
elif wavelength >= 490 and wavelength <= 510:
R = 0.0
G = 1.0
B = (-(wavelength - 510) / (510 - 490)) ** gamma
elif wavelength >= 510 and wavelength <= 580:
R = ((wavelength - 510) / (580 - 510)) ** gamma
G = 1.0
B = 0.0
elif wavelength >= 580 and wavelength <= 645:
R = 1.0
G = (-(wavelength - 645) / (645 - 580)) ** gamma
B = 0.0
elif wavelength >= 645 and wavelength <= 750:
attenuation = 0.3 + 0.7 * (750 - wavelength) / (750 - 645)
R = (1.0 * attenuation) ** gamma
G = 0.0
B = 0.0
else:
R = 0.0
G = 0.0
B = 0.0
return (R, G, B) |
def append_str_to(append_to: str, *args, sep=", ", **kwargs):
"""Concatenate to a string.
Args:
append_to(str): The string to append to.
args(list): list of string characters to concatenate.
sep(str): Seperator to use between concatenated strings.
kwargs(dict): Mapping of variables with intended string values.
Returns:
str, joined strings seperated
"""
append_to = append_to or ""
result_list = [append_to] + list(args) + list(kwargs.values())
return f"{sep}".join(filter(len, result_list)) |
def is_degrading(metric_value, best_metric_value, metric):
"""Return true if metric value is degrading."""
if metric not in ['spr', 'rmse', 'pearson', 'both']:
raise Exception('Unsupported metric: {}'.format(metric))
if metric == 'both':
spr = metric_value[0]
rmse = metric_value[1]
best_spr = best_metric_value[0]
best_rmse = best_metric_value[1]
return spr < best_spr or rmse > best_rmse
if metric in ['spr', 'pearson']:
return metric_value < best_metric_value
return metric_value > best_metric_value |
def _get_tag_value(x, i=0):
""" Get the nearest to 'i' position xml tag name.
x -- xml string
i -- position to start searching tag from
return -- (tag, value) pair.
e.g
<d>
<e>value4</e>
</d>
result is ('d', '<e>value4</e>')
"""
x = x.strip()
value = ''
tag = ''
# skip <? > tag
if x[i:].startswith('<?'):
i += 2
while i < len(x) and x[i] != '<':
i += 1
# check for empty tag like '</tag>'
if x[i:].startswith('</'):
i += 2
in_attr = False
while i < len(x) and x[i] != '>':
if x[i] == ' ':
in_attr = True
if not in_attr:
tag += x[i]
i += 1
return tag.strip(), '', x[i + 1:],
# not an xml, treat like a value
if not x[i:].startswith('<'):
return '', x[i:], ''
i += 1 # <
# read first open tag
in_attr = False
while i < len(x) and x[i] != '>':
# get rid of attributes
if x[i] == ' ':
in_attr = True
if not in_attr:
tag += x[i]
i += 1
i += 1 # >
# replace self-closing <tag/> by <tag>None</tag>
empty_elmt = '<' + tag + ' />'
closed_elmt = '<' + tag + '>None</' + tag + '>'
if x.startswith(empty_elmt):
x = x.replace(empty_elmt, closed_elmt)
while i < len(x):
value += x[i]
if x[i] == '>' and value.endswith('</' + tag + '>'):
# Note: will not work with xml like <a> <a></a> </a>
close_tag_len = len(tag) + 2 # />
value = value[:-close_tag_len]
break
i += 1
return tag.strip(), value[:-1], x[i + 1:] |
def validate_subnet_input(subnetCount, host_bits):
"""
Validates Subnet count input
:param subnetCount: Subnet count from user input
:param host_bits: Number of host bits of from the network object
:return: 'valid' if subnetCount is valid, Invalid reason otherwise
"""
if subnetCount.isnumeric() and int(subnetCount) > 0:
bits_required = (int(subnetCount) - 1).bit_length()
if bits_required < host_bits - 1:
return 'valid'
elif bits_required >= host_bits:
return "'Subnets to be created value' is too high"
else:
return "There will not be any usable host in each subnet with given 'Subnets to be created value'"
else:
return 'Subnets to be created value should be Positive Numeric value' |
def indented_entry_to_str(entries, indent=0, sep=' '):
"""Pretty formatting."""
# Get the longest keys' width
width = max([len(t[0]) for t in entries])
output = []
for name, entry in entries:
if indent > 0:
output.append(f'{"":{indent}}{name:{width}}{sep}{entry}')
else:
output.append(f'{name:{width}}{sep}{entry}')
return '\n'.join(output) |
def intsqrt(x):
"""
Return the largest integer whose square is less than or equal to x.
"""
if x == 0:
return 0
# invariant: l^2 <= x and x < r^2
l = 1
r = x
while r-l > 1:
m = l + (r-l)//2
s = m*m
if s <= x:
l = m
else:
r = m
return l |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.