content stringlengths 42 6.51k |
|---|
def k(x,y,z):
"""
This function does stuff inside our compressionFunction
it should be (~x XOR y) v (z ^ ~x)
"""
a = (~x ^ y) | (z ^ ~x)
return a |
def format_setting_name(setting_name):
"""
Return the given setting name formatted for compatibility
for "nordvpn set" command
"""
return setting_name.replace(' ', '').replace('-', '').lower() |
def get_robot_number_and_alliance(team_num, match_data):
"""Gets the robot number (e.g. the `1` in initLineRobot1) and alliance color."""
team_key = f'frc{team_num}'
for alliance in ['red', 'blue']:
for i, key in enumerate(match_data['alliances'][alliance]['team_keys'], start=1):
if team_key == key:
return i, alliance
raise ValueError(f'Team {team_num} not found in match {match_data["match_number"]}') |
def format_puzzle(grid):
"""Formats the puzzle for printing."""
puzzle = ""
for line in grid:
puzzle += " ".join(line) + "\n"
return puzzle |
def delete_one_before_mainword(sentence, mainword, **kwargs):
"""Delete every word starting from (and including) one word before
<mainword>. Used in ambiguity detection e.g. 'there is scarring vs
atelectasis' -->mainword 'vs' --> 'there is' (delete both scarring and
atelectasis)"""
if mainword in sentence:
s = sentence.split(mainword)[0].split()
return True, (' ').join(s[0:-1])
else:
return False, sentence |
def build_object(cfg, parent, default=None, args=[], **kwargs):
"""
Build an object from a dict.
The dict must contain a key ``type``, which is a indicating the object
type. Remaining fields are treated as the arguments for constructing the
object.
Args:
cfg (any): The object, object config or object name.
parent (any): The module or a list of modules which may contain the
expected object.
default (any, optional): The default value when the object is not
found. Default: ``None``.
args (list, optional): The argument list used to build the object.
Returns:
any: The constructed object.
"""
if isinstance(cfg, str):
cfg = dict(type=cfg)
elif cfg is None:
return default
elif not isinstance(cfg, dict):
return cfg
if isinstance(parent, (list, tuple)):
for p in parent:
obj = build_object(cfg, p, args=args, **kwargs)
if obj is not None:
return obj
return default
_cfg = cfg.copy()
_cfg.update(kwargs)
obj_type = _cfg.pop('type')
if hasattr(parent, 'get'):
obj_cls = parent.get(obj_type)
else:
obj_cls = getattr(parent, obj_type, None)
return obj_cls(*args, **_cfg) if obj_cls is not None else default |
def convert_to_bits(n):
"""converts an integer `n` to bit array
ex) convert_to_bits(3) -> [1,1] """
result = []
if n == 0:
return [0]
while n > 0:
result = [(n % 2)] + result
n = n / 2
return result |
def range_check(val, lb, ub):
"""
Data range validation.
'val' should have attribute __lt__ and __gt__.
'lb', 'ub' should be of the same type as 'val'.
'lb' means lowerbound and 'ub' means upperbound.
"""
return True if hasattr(val, '__lt__') and hasattr(val, '__gt__') and \
type(val) == type(lb) and type(val) == type(ub) and \
lb <= val <= ub else False |
def exponent(attrs, inputs, proto_obj):
"""Elementwise exponent of input array."""
return 'exp', attrs, inputs |
def _substitute(template, fuzzer, benchmark):
"""Replaces {fuzzer} or {benchmark} with |fuzzer| or |benchmark| in
|template| string."""
return template.format(fuzzer=fuzzer, benchmark=benchmark) |
def list_index(xs):
"""
Return a mapping from each element of xs to its index
"""
m = {}
for (i, x) in enumerate(xs):
m[x] = i
return m |
def getopts(argv):
"""Collect command line options in a dictionary.
We cannot use sys.getopt as it is supported only in Python3.
"""
opts = {}
while argv:
if argv[0][0] == '-':
if len(argv) > 1:
opts[argv[0]] = argv[1]
else:
opts[argv[0]] = None
# Reduce the arg list
argv = argv[1:]
return opts |
def discretisation_length(N, d):
"""Returns the length of a linspace where there are N points with d intermediate (in-between) points."""
return (N - 1) * (d + 1) + 1 |
def char_delta(c: str, d: str) -> int:
""" find int difference between to characters """
if len(c) == 1 and len(d) == 1:
return ord(c) - ord(d)
else:
SyntaxError(f'the inputs need to be char not string: {c}, {d}')
return 0 |
def listify(obj):
""" Wraps all non-list or tuple objects in a list; provides a simple
way to accept flexible arguments. """
if obj is None:
return []
else:
return obj if isinstance(obj, (list, tuple, type(None))) else [obj] |
def _is_valid(queens):
"""Check current queen position is valid."""
current_row, current_col = len(queens) - 1, queens[-1]
# Check any queens can attack the current queen.
for row, col in enumerate(queens[:-1]):
col_diff = abs(current_col - col)
row_diff = abs(current_row - row)
if col_diff == 0 or col_diff == row_diff:
return False
return True |
def clean_int(
i: int,
ub: int,
lb: int = 0,
) -> int:
"""Clean an integer according to a given upper and lower bound
Parameters
----------
i : int
The integer to be cleaned
ub : int
The inclusive upper bound
lb : int, optional
The exclusive lower bound, by default 0
Returns
-------
int
The cleaned integer
"""
# Initialisations
i_temp = i
# Check if the integer is above the upper bound
if i_temp > ub:
# Set it to the upper bound
i_temp = ub
# Check if the integer is below or equal to the lower bound
elif i_temp <= lb:
# Set it to one above the lower bound
i_temp = lb + 1
return i_temp |
def radix_sort(array):
"""
Radix Sort
Complexity: O((N + B) * logb(max)
Where B is the base for representing numbers and
max is the maximum element of the input array. We
basically try to lower the complexity of counting sort.
Even though it seems good, it's good in specific cases only.
"""
n = len(array)
max_value = max(array)
step = 1
while max_value:
temp = [0] * 10
sorted_array = [0] * n
for i in range(n):
index = array[i] // step
temp[index % 10] += 1
for i in range(1, 10):
temp[i] += temp[i-1]
# By finding the partial sums and passing through the
# initial array from the end to the beginning we can know
# each time how many values exist with the same or lower digit.
# For example, if temp = [1, 1, 0, 1, 0, 1, 0, 0, 0, 0]
# then it will become [1, 2, 2, 3, 3, 4, 4, 4, 4, 4].
# If the array is [3, 11, 10, 5] then in the first pass
# (first digit), when we start from number 5 we will
# have 5 mod 10 = 5, temp[5] = 4, which means that there
# were 3 number before the number 5 with a smaller value
# for their first digit.
# So, this number will go to the 4 - 1 = 3rd position
for i in range(n-1, -1, -1):
index = array[i] // step
sorted_array[temp[index % 10] - 1] = array[i]
temp[index % 10] -= 1
for i in range(n):
array[i] = sorted_array[i]
max_value //= 10
step *= 10
return array |
def in_place_swap(a, b):
""" Interchange two numbers without an extra variable.
Based on the ideea that a^b^b = a
"""
a = a ^ b
b = b ^ a
a = a ^ b
return (a, b) |
def cvi(nir, red, green):
"""
Compute Chlorophyl Vegetation Index from red and NIR bands
CVI = \\frac { NIR }{ GREEN } - (RED + GREEN)
:param nir: Near-Infrared band
:param red: Red band
:param green: Green band
:return: CVI
"""
return (nir/green) - (red + green) |
def _gauss_first_equation(y, s, w):
"""Evaluates Gauss' first equation.
Parameters
----------
y: float
The dependent variable.
s: float
First auxiliary variable.
w: float
Second auxiliary variable.
Returns
-------
x: float
The independent variable or free-parameter.
Notes
-----
This is equation (5.6-13) from Bate's book [2].
"""
x = w / y ** 2 - s
return x |
def update_block_dropdown(block):
"""
Limit esate to sensible values.
Notes
-----
Townhouse and block should be mutually exclusive.
"""
if block:
opts = [{'label': 'No', 'value': 0}]
else:
opts = [{'label': 'Yes', 'value': 1},
{'label': 'No', 'value': 0}]
return opts |
def exclude_subsets(iter_of_sets):
""" This function takes an interable of sets and returns a new list with all
sets that are a subset of any other eliminated """
keep_sets = []
for si in iter_of_sets:
si = set(si)
any_subset = False
for sj in iter_of_sets:
sj = set(sj)
if si != sj and si.issubset(sj):
any_subset = True
break
if not any_subset:
keep_sets.append(si)
return keep_sets |
def xoxo(stringer):
"""
check whether the string x or the string o is present, if so, check the count
else, return false
"""
stringer = stringer.lower()
if stringer.find("x") != -1 and stringer.find("o") != -1:
return stringer.count("x") == stringer.count("o")
return False |
def is_plus_option(string):
"""Whether that string looks like an option
>>> is_plus_option('+/sought')
True
"""
return string[0] == '+' |
def write_sentence_list_to_file(filename, sen_l):
"""
Writes fiven list of sentences to a given file name
Removes double quotation if they are in odd number
"""
with open(filename, mode="w", encoding="utf-16") as fl:
for ln_edit1 in sen_l:
ln_edit1 = " ".join(ln_edit1.split())
if (ln_edit1.count('"') % 2) != 0:
ln_edit1 = ln_edit1.replace('"', "")
if len(ln_edit1.split()) < 4:
continue
ln_edit2 = " ".join(ln_edit1.split())
fl.write(ln_edit2 + "\n")
return None |
def location(host=None, user=None, path=None, forssh=False):
"""Construct an appropriate ssh/scp path spec based on the combination of
parameters. Supply host, user, and path.
"""
sep = "" if forssh else ":"
if host is None:
if user is None:
if path is None:
raise ValueError("must supply at least one of host, or user.")
else:
return path
else:
if path is None:
raise ValueError("user without host?")
else:
return path # ignore user in this case
else:
if user is None:
if path is None:
return "%s%s" % (host, sep)
else:
return "%s:%s" % (host, path)
else:
if path is None:
return "%s@%s%s" % (user, host, sep)
else:
return "%s@%s:%s" % (user, host, path) |
def bytes_per_pixel(pixel_type):
"""
Return the number of bytes per pixel for the given pixel type
@param pixel_type: The OMERO pixel type
@type pixel_type: String
"""
if (pixel_type == "int8" or pixel_type == "uint8"):
return 1
elif (pixel_type == "int16" or pixel_type == "uint16"):
return 2
elif (pixel_type == "int32" or
pixel_type == "uint32" or
pixel_type == "float"):
return 4
elif pixel_type == "double":
return 8
else:
raise Exception("Unknown pixel type: %s" % (pixel_type)) |
def tuple_is_smaller(t1,t2):
"""
Checks whether the tuple t1 is smaller than t2
"""
t1_forward = t1[1] > t1[0]
t2_forward = t2[1] > t2[0]
i,j,x,y = t1[0], t1[1], t2[0], t2[1]
# Edge comparison
if t1_forward and t2_forward:
if j < y or (j == y and i > x):
return True
elif j > y or (j == y and i < x):
return False
elif (not t1_forward) and (not t2_forward):
if i < x or (i == x and j < y):
return True
elif i > x or (i == x and j > y):
return False
elif t1_forward and (not t2_forward):
if j <= x:
return True
else:
return False
elif (not t1_forward) and t2_forward:
if i < y:
return True
elif i > y: # Maybe something missing here
return False
# Lexicographic order comparison
a1,b1,c1 = t1[2], t1[3], t1[4]
a2,b2,c2 = t2[2], t2[3], t2[4]
if not a1.isdigit():
a1,b1,c1 = ord(a1),ord(b1),ord(c1)
a2,b2,c2 = ord(a2),ord(b2),ord(c2)
else:
a1,b1,c1 = int(a1),int(b1),int(c1)
a2,b2,c2 = int(a2),int(b2),int(c2)
if a1 < a2:
return True
elif a1 == a2:
if b1 < b2:
return True
elif b1 == b2:
if c1 < c2:
return True
#if ord(t1[2]) < ord(t2[2]):
# return True
#elif ord(t1[2]) == ord(t2[2]):
# if ord(t1[3]) < ord(t2[3]):
# return True
# elif ord(t1[3]) == ord(t2[3]):
# if ord(t1[4]) < ord(t2[4]):
# return True
return False
#raise KeyError('Wrong key type in tuple') |
def _make_arm_parameter_values(key_values: dict) -> dict:
"""Transform a key-value dictionary into ARM template parameter data."""
result = dict()
for k, v in key_values.items():
result[k] = {"value": v}
return result |
def subprocess_open(args):
"""Execute subprocess by using Popen."""
from subprocess import Popen, PIPE
chld = Popen(args, stdout=PIPE)
data = chld.communicate()[0]
return (chld.returncode, data.rstrip().decode("utf8")) |
def get_all_pr_between_two_set_of_HOGs(graph, list_hogs1, list_hogs2):
"""
return the numbers of extant orthologous relations between two set of hogs
:param graph:
:param list_hogs1:
:param list_hogs2:
:return:
"""
pairwise_relations = 0
for hog1 in list_hogs1:
for hog2 in list_hogs2:
try:
pairwise_relations += graph[(hog1, hog2)]
except KeyError:
try:
pairwise_relations += graph[(hog2, hog1)]
except KeyError:
pass
return pairwise_relations |
def to_ordinal(n):
"""Get the suffixed number.
Returns: a string with then number and the appropriate suffix.
>>> to_ordinal(1)
'1st'
>>> to_ordinal(2)
'2nd'
>>> to_ordinal(3)
'3rd'
>>> to_ordinal(4)
'4th'
>>> to_ordinal(11)
'11th'
>>> to_ordinal(12)
'12th'
>>> to_ordinal(13)
'13th'
"""
if n < 1:
raise ValueError("n must be at least 1.")
last_digit = n % 10
if 11 <= (n % 100) <= 13:
fmt = '%dth'
elif last_digit == 1:
fmt = '%dst'
elif last_digit == 2:
fmt = '%dnd'
elif last_digit == 3:
fmt = '%drd'
else:
fmt = '%dth'
return fmt % n |
def subtract(one, two):
"""Helper function for subtracting"""
return(one - two) |
def esc_format(text):
"""Return text with formatting escaped
Markdown requires a backslash before literal underscores or asterisk, to
avoid formatting to bold or italics.
"""
for symbol in ['_', '*', '[', ']', '(', ')', '~', '`', '>', '#', '+', '-', '=', '|', '{', '}', '.', '!']:
text = str(text).replace(symbol, '\\' + symbol)
return text |
def _axis_id_to_slice(axis_id: int, tile_length: int, n_px: int) -> slice:
"""Take the axis_id from a dask block_id and create the corresponding
tile slice, taking into account edge tiles."""
if (axis_id * tile_length) + tile_length <= n_px:
return slice(axis_id * tile_length, (axis_id * tile_length) + tile_length)
else:
return slice(axis_id * tile_length, n_px) |
def reverse_string(input):
"""
Return reversed input string
Examples:
reverse_string("abc") returns "cba"
Args:
input(str): string to be reversed
Returns:
a string that is the reverse of input
"""
if len(input) == 0:
return ""
first = input[0]
next_input = input[1:]
rev = reverse_string(next_input)
return rev + first |
def cube(edge_length):
"""A cube has six square faces and twelve edges.
The function will return triangular facets rather than quadrilateral facets, so
each square face will become two triangles, giving twelve facets.
This solid is also known as:
- a square parallelepiped
- an equilateral cuboid
- a right rhombohedron
- a regular hexahedron
"""
half_edge_length = edge_length / 2
vertices = [
(half_edge_length, half_edge_length, half_edge_length),
(half_edge_length, -half_edge_length, half_edge_length),
(-half_edge_length, -half_edge_length, half_edge_length),
(-half_edge_length, half_edge_length, half_edge_length),
(half_edge_length, half_edge_length, -half_edge_length),
(half_edge_length, -half_edge_length, -half_edge_length),
(-half_edge_length, -half_edge_length, -half_edge_length),
(-half_edge_length, half_edge_length, -half_edge_length),
]
# An improvement to the faces would be to have all the triangles that form
# the sides of the cube, forming two larger triangles instead of
# parallelograms.
faces = [
(0, 1, 2),
(0, 2, 3),
(0, 1, 5),
(0, 5, 4),
(0, 4, 7),
(0, 7, 3),
(3, 2, 6),
(3, 6, 7),
(1, 6, 5),
(1, 6, 2),
(4, 5, 6),
(4, 6, 7)
]
return vertices, faces |
def add2_sub2_res(res):
"""function that takes entire output as an input"""
if isinstance(res, list):
return [r["out"] + 2 for r in res], [r["out"] - 2 for r in res]
return res["out"] + 2, res["out"] - 2 |
def purple(text):
""" Return this text formatted purple """
return '\x0306%s\x03' % text |
def match_basis(basis):
"""
Converts a string representations of basis angular momenta
to the cardinal number
"""
# Remove the supplemental functions from the string as they don't
# refer to the cardinal number
basis = basis.replace("AUG-PC", "")
basis = basis.replace("P", "")
basis = basis.replace("C", "")
basis_dict = {
"VDZ": 2.,
"VTZ": 3.,
"VQZ": 4.,
"V5Z": 5.,
"V6Z": 6.
}
return basis_dict[basis] |
def test_for_small_float(value: float, precision: int) -> bool:
"""
Returns True if 'value' is a float whose rounded str representation
has fewer significant figures than the number in 'precision'.
Return False otherwise.
"""
if not isinstance(value, (float)):
return False
if value == 0:
return False
value_as_str = str(round(abs(value), precision))
if "e" in str(value):
return True
if "." in value_as_str:
left, *_right = value_as_str.split(".")
if left != "0":
return False
if (
round(value, precision) != round(value, precision + 1)
or str(abs(round(value, precision))).replace("0", "").replace(".", "")
== str(abs(round(value, precision + 1))).replace("0", "").replace(".", "")
== ""
):
return True
else:
return False |
def elements_to_species(element_set):
"""
Get species that are placeholders for the elements, and adds H2O
"""
species = {ELEMENT_SPECIES_MAP[el] for el in element_set
if el not in ['O', 'H']}
species.add('H2O')
return species |
def compress(v):
"""Docstring."""
u = ""
for elt in v:
s = "1" if elt > 0 else "0"
s += format((abs(elt) % (1 << 7)), '#09b')[:1:-1]
s += "0" * (abs(elt) >> 7) + "1"
u += s
u += "0" * ((8 - len(u)) % 8)
return [int(u[8 * i: 8 * i + 8], 2) for i in range(len(u) // 8)] |
def DeleteSmallIntervals( intervals, min_length ):
"""combine a list of non-overlapping intervals,
and delete those that are too small.
"""
if not intervals: return []
new_intervals = []
for this_from, this_to in intervals:
if (this_to - this_from + 1) >= min_length:
new_intervals.append( (this_from, this_to ) )
return new_intervals |
def _observed_name(field, name):
"""Adjust field name to reflect `dump_to` and `load_from` attributes.
:param Field field: A marshmallow field.
:param str name: Field name
:rtype: str
"""
# use getattr in case we're running against older versions of marshmallow.
dump_to = getattr(field, 'dump_to', None)
load_from = getattr(field, 'load_from', None)
if load_from != dump_to:
return name
return dump_to or name |
def xor_hex_strings(str1, str2):
"""
Return xor of two hex strings.
An XOR of two pieces of data will be as random as the input with the most randomness.
We can thus combine two entropy sources in this way as a safeguard against one source being
compromised in some way.
For details, see http://crypto.stackexchange.com/a/17660
returns => <string> in hex format
"""
if len(str1) != len(str2):
raise Exception("tried to xor strings of unequal length")
str1_dec = int(str1, 16)
str2_dec = int(str2, 16)
xored = str1_dec ^ str2_dec
return "{:0{}x}".format(xored, len(str1)) |
def searchkw(text_list, kw_lists):
"""Search for targeted elements in the list based on the lw_lists"""
mentions_list = []
for i, x in enumerate(text_list):
if any(n in x.lower() for n in kw_lists):
mentions_list.append(i)
return mentions_list |
def option2tuple(opt):
"""Return a tuple of option, taking possible presence of level into account"""
if isinstance(opt[0], int):
tup = opt[1], opt[2:]
else:
tup = opt[0], opt[1:]
return tup |
def check_if_packs_can_be_played(packs, possible_plays):
"""
Function used to check if player can play a pack of cards in turn.
:param packs: list with packs of cards on hand
:param possible_plays: list with all possible cards to play
:return: list with possible to play packs
"""
possible_packs = []
[possible_packs.append(pack) for pack in packs for card in possible_plays if pack == card[1]]
return list(set(possible_packs)) |
def strip_string(value):
"""Remove all blank spaces from the ends of a given value."""
return value.strip() |
def get_classmap(anno_data, classmap):
"""
Find classmap from middle format annotation data
:param anno_list: [{'size':(width, height), 'objects':[{'name': '', 'bndbox':[xmin,ymin,xmax,ymax]}, ...]}, ...]
:param classmap: Existing class name and number map
:return: {'a': 0, 'b':1 ,...}
"""
for _, anno_obj in anno_data.items():
objects = anno_obj['objects']
for obj in objects:
name = obj['name']
if name not in classmap.keys():
classmap[name] = len(classmap.keys())
return classmap |
def return_agar_plates(wells=6):
"""Returns a dict of all agar plates available that can be purchased.
Parameters
----------
wells : integer
Optional, default 6 for 6-well plate
Returns
-------
dict
plates with plate identity as key and kit_id as value
Raises
------
ValueError
If wells is not a integer equaling to 1 or 6
"""
if wells == 6:
plates = {"lb_miller_50ug_ml_kan": "ki17rs7j799zc2",
"lb_miller_100ug_ml_amp": "ki17sbb845ssx9",
"lb_miller_100ug_ml_specto": "ki17sbb9r7jf98",
"lb_miller_100ug_ml_cm": "ki17urn3gg8tmj",
"lb_miller_noAB": "ki17reefwqq3sq"}
elif wells == 1:
plates = {"lb_miller_50ug_ml_kan": "ki17t8j7kkzc4g",
"lb_miller_100ug_ml_amp": "ki17t8jcebshtr",
"lb_miller_100ug_ml_specto": "ki17t8jaa96pw3",
"lb_miller_100ug_ml_cm": "ki17urn592xejq",
"lb_miller_noAB": "ki17t8jejbea4z"}
else:
raise ValueError("Wells has to be an integer, either 1 or 6")
return (plates) |
def update_strategy(strat1, strat2):
"""
Updates strategy 1 by adding key/value pairs of strategy 2.
:param strat1: Old strategy.
:param strat2: Strategy to add.
:return: A new strategy which merges strategies 1 and 2 (2 overwrites 1 in case of duplicate keys)
"""
new_strat = strat1.copy()
new_strat.update(strat2)
return new_strat |
def euler_problem_19(n=2000):
"""
You are given the following information, but you may prefer to do some research for yourself.
1 Jan 1900 was a Monday.
Thirty days has September,
April, June and November.
All the rest have thirty-one,
Saving February alone,
Which has twenty-eight, rain or shine.
And on leap years, twenty-nine.
A leap year occurs on any year evenly divisible by 4, but not on a century unless it is divisible by 400.
How many Sundays fell on the first of the month during the twentieth century (1 Jan 1901 to 31 Dec 2000)?
"""
month_to_days_common = {
1: 31,
2: 28,
3: 31,
4: 30,
5: 31,
6: 30,
7: 31,
8: 31,
9: 30,
10: 31,
11: 30,
12: 31,
}
month_to_days_leap = {
1: 31,
2: 29,
3: 31,
4: 30,
5: 31,
6: 30,
7: 31,
8: 31,
9: 30,
10: 31,
11: 30,
12: 31,
}
def count_Sunday_1sts(year, first_day):
"""
Subroutine to count the number of 1st Sundays in a year.
"""
# set up calculation
month_to_days = dict(month_to_days_common)
if year % 4 == 0:
if (year % 100 != 0) or (year % 400 == 0):
month_to_days = dict(month_to_days_leap)
val = first_day
# loop over months
count = 0
months = []
for _month in range(1, 13):
if val % 7 == 0:
count += 1
months.append((year, _month))
val += month_to_days[_month]
return count, val % 7, months[:]
# Jan 1 1900 was a Monday
first_day = 1
total_count = 0
match_months = []
for _year in range(1900, n + 1):
count, first_day, months = count_Sunday_1sts(_year, first_day)
total_count += count
match_months += months
# the problem asks for Jan 1, 1901 to Dec 31, 2000, so we exclude 1900
return total_count - count_Sunday_1sts(1900, 1)[0] |
def serialize_biomass_table_v1(analysis, type):
"""Convert the output of the biomass_loss analysis to json"""
rows = []
for year in analysis.get('biomass_loss_by_year'):
rows.append({'year': year,
'biomassLossByYear': analysis.get('biomass_loss_by_year', None).get(year, None),
'totalBiomass': analysis.get('biomass', None),
'cLossByYear': analysis.get('c_loss_by_year', None).get(year, None),
'co2LossByYear': analysis.get('co2_loss_by_year', None).get(year, None),
'treeLossByYear': analysis.get('tree_loss_by_year', None).get(year, None),
'totalAreaHa': analysis.get('area_ha', None),
})
return {
'id': None,
'type': type,
'attributes': rows
} |
def is_slice(x):
"""Tests if something is a slice"""
return isinstance(x, slice) |
def build_logname(input_filename, process_type='svm'):
"""Build the log filename based on the input filename"""
suffix = '.{}'.format(input_filename.split('.')[-1])
if isinstance(input_filename, str): # input file is a poller file -- easy case
logname = input_filename.replace(suffix, '.log')
else:
logname = '{}_process.log'.format(process_type)
return logname |
def init_actions_(service, args):
"""
This needs to return an array of actions representing the depencies between actions.
Looks at ACTION_DEPS in this module for an example of what is expected
"""
# some default logic for simple actions
return {
'test': ['install']
} |
def getPoint(arr):
"""get ponit"""
if len(arr) < 2:
return
tag = 1
help = []
while tag < len(arr):
sum = 0
sum_after = 0
for i in range(tag):
sum += arr[i]
for i in range(tag+1, len(arr)):
sum_after += arr[i]
if sum == sum_after:
help.append(arr[tag])
tag += 1
return help |
def mutiply_values(iterable, indexes):
"""Mutliplies the values of the iterable given by a list of indexes"""
indexes = set(indexes)
product = 1
for i, x in enumerate(iterable):
if i in indexes:
product *= x
indexes.remove(i)
if len(indexes) == 0:
break
return product |
def unordered_equality(seq1, seq2):
"""
Tests to see if the contents of one sequence is contained in the other
and that they are of the same length.
"""
if len(seq1) != len(seq2):
return False
# if isinstance(seq1, dict) and isinstance(seq2, dict):
# seq1 = seq1.items()
# seq2 = seq2.items()
for val in seq1:
if val not in seq2:
return False
return True |
def siso_sequential(io_lst):
"""Connects in a serial connection a list of dictionaries of the inputs and
outputs encoding single-input single-output search spaces.
Args:
io_lst (list[(dict[str,deep_architect.core.Input], dict[str,deep_architect.core.Output])]):
List of single-input single-output dictionaries encoding
Returns:
(dict[str,deep_architect.core.Input], dict[str,deep_architect.core.Output]):
Tuple with dictionaries with the inputs and outputs of the
resulting graph resulting from the sequential connection.
"""
assert len(io_lst) > 0
prev_outputs = io_lst[0][1]
for next_inputs, next_outputs in io_lst[1:]:
prev_outputs['out'].connect(next_inputs['in'])
prev_outputs = next_outputs
return io_lst[0][0], io_lst[-1][1] |
def check_palindrome(n: int) -> str:
"""Checks if n is a palindrome"""
if str(n) == str(n)[::-1]:
return 'Palindrome Number'
return 'Not Palindrome Number' |
def create_job_folder_name(job_config, app_config):
"""create standardized job folder path given application configuration"""
local_job_folder = f"{app_config['JOB_PATH']}/{job_config['jobname']}"
return(local_job_folder) |
def identity(*args):
"""Return the first argument provided to it.
Args:
*args (mixed): Arguments.
Returns:
mixed: First argument or ``None``.
Example:
>>> identity(1)
1
>>> identity(1, 2, 3)
1
>>> identity() is None
True
.. versionadded:: 1.0.0
"""
return args[0] if args else None |
def squareDistance(p1, p2):
"""Answers the square of the distance for relative comparison and to
save the time of the **sqrt**."""
tx, ty = p2[0]-p1[0], p2[1]-p1[1]
return tx*tx + ty*ty |
def valid_file(file_name):
"""
Returns True if file_name matches the condition assigned.
False otherwise.
"""
condition = (
file_name.endswith(".py")
and not(file_name.startswith("_")) or file_name == "__init__.py"
)
return condition |
def calculate_bin(memory):
"""Calculates the memory bin (EC2 Instance type) according to the amount of memory in gigabytes needed to process the job."""
if memory < 1.792:
mem_bin = 0
elif memory < 7.168:
mem_bin = 1
elif memory < 14.336:
mem_bin = 2
elif memory >= 14.336:
mem_bin = 3
else:
mem_bin = "nan"
return mem_bin |
def _ends_in_by(word):
"""
Returns True if word ends in .by, else False
Args:
word (str): Filename to check
Returns:
boolean: Whether 'word' ends with 'by' or not
"""
return word[-3:] == ".by" |
def get_keys(dictionary: dict, value):
"""
get_keys() collects all the keys that share a value
Syntax:
get_keys(dictionary, value)
Example usage:
from readyCode package import get_keys
d = {"Alice": 45, "Bob": 25, "Charlie": 45, "Doug": 15, "Ellie": 75}
keys_with_45 = get_keys(d, 45)
print(keys_with_45) # Prints ["Alice", "Charlie"]
Possible errors:
If the given iterable is not a dictionary or 2D list, it will raise an error.
"""
dictionary = dict(dictionary)
if type(dictionary) != dict:
exit("Error: not given a dictionary")
return [key for key in dictionary if dictionary[key] == value] |
def is_cmt(line,cmt):
"""Test if it is an comment line"""
if len(line)==1:
return False
else:
for i in range(len(line)):
if line[i]!=' ' and line[i]!='\t':
if len(line[i:])>len(cmt):
if line[i:i+len(cmt)]==cmt:
return True
else:
break
return False |
def removesuffix(somestring, suffix):
"""Removed a suffix from a string
Arguments
---------
somestring : str
Any string.
suffix : str
Suffix to be removed from somestring.
Returns
------
string resulting from suffix removed from somestring, if found, unchanged otherwise
"""
if somestring.endswith(suffix):
return somestring[: -1 * len(suffix)]
else:
return somestring |
def bad_fibonacci(n):
"""Return the nth Fibonacci number."""
if n <= 1:
return n
return bad_fibonacci(n - 2) + bad_fibonacci(n - 1) |
def sort_and_format_dict(l, reverse=False):
"""
{
'asks': [
{
'price': 0,
'amount': 0,
}
],
'bids': [
{
'price': 0,
'amount': 0,
}
]
}
"""
l.sort(key=lambda x: float(x['price']), reverse=reverse)
r = []
for i in l:
r.append({'price': float(i['price']), 'amount': float(i['amount'])})
return r |
def non_simple_values(obj1, obj2, obj3, obj4):
"""
>>> non_simple_values(1, 2, 3, 4)
(7, 3, 7, 3, 7, 7, 5, 5)
>>> non_simple_values(0, 0, 3, 4)
(0, 7, 4, 4, 4, 4, 4, 4)
>>> non_simple_values(0, 0, 1, -1)
(0, 0, -1, 0, -1, -1, 0, 0)
>>> non_simple_values(1, -1, 1, -1)
(0, 0, 0, 0, 0, 0, 0, 0)
>>> non_simple_values(1, 2, 1, -1)
(0, 3, 0, 3, 0, 0, 1, 1)
>>> non_simple_values(2, 1, 1, -1)
(0, 3, 1, 3, 0, 0, 1, 1)
"""
and1 = obj1 + obj2 and obj3 + obj4
or1 = obj1 + obj2 or obj3 + obj4
and_or = obj1 + obj2 and obj3 + obj4 or obj1 + obj4
or_and = obj1 + obj2 or obj3 + obj4 and obj1 + obj4
and_or_and = obj1 + obj2 and obj3 + obj4 or obj1 + obj4 and obj2 + obj4
and1_or_and = (and1 or (obj1 + obj4 and obj2 + obj4))
or_and_or = (obj1 + obj2 or obj3 + obj4) and (obj1 + obj4 or obj2 + obj4)
or1_and_or = (or1 and (obj1 + obj4 or obj2 + obj4))
return (and1, or1, and_or, or_and, and_or_and, and1_or_and, or_and_or, or1_and_or) |
def _fmt(x, pos):
"""
Used for nice formatting of powers of 10 when plotting logarithmic
"""
a, b = '{:.2e}'.format(x).split('e')
b = int(b)
if abs(float(a) - 1) < 0.01:
return r'$10^{{{}}}$'.format(b)
else:
return r'${} \times 10^{{{}}}$'.format(a, b) |
def _getMeta(data,type="header"):
"""
"""
name=data['name']
meta=data['meta']
value=""
if type=="header":
if "standard_name" in meta:value=meta['standard_name']
else:value=name
if not 'calendar' in meta and "units" in meta and meta['units']!="" :value="{},{}".format(value,meta['units'])
else:
if type in meta:value=meta[type]
else:value=None
return value |
def identity(attrs, inputs, proto_obj):
"""Returns the identity function of the the input."""
return 'identity', attrs, inputs |
def url_join(*parts):
"""
helper function to join a URL from a number of parts/fragments.
Implemented because urllib.parse.urljoin strips subpaths from
host urls if they are specified
Per https://github.com/geopython/pygeoapi/issues/695
:param parts: list of parts to join
:returns: str of resulting URL
"""
return '/'.join([p.strip().strip('/') for p in parts]) |
def or_(arg, *args):
"""Lisp style or. Evaluates expressions from left to right
and returns the value of the first truthy expression.
If all expressions evaluate to False, returns the value of the last expression.
usage
>>> or_(True, True, False)
True
>>> or_(True, False, False)
True
>>> or_(False, False, 0)
0
>>> or_(False, 0, False)
False
>>> or_(0,1,2,3,4,5)
1
>>> or_( "a"=="a", 5%2 )
True
>>> or_( "a"=="a", 5%5 )
True
>>> or_(1, [1,2,3,4,5,6,7])
1
>>> or_([], [1,2,3,4,5,6,7])
[1, 2, 3, 4, 5, 6, 7]
"""
if arg or not args:
return arg
else:
for a in args:
if a:
return a
# If none of the Arguments evaluates to true return the last one.
return args[-1] |
def solution2(nums, K):
"""sum_til record sum from begining
sum between (i, j] sum_til[j] - sum_til[i]
"""
s = 0
sum_til = []
for n in nums:
s += n
sum_til.append(s)
l = len(nums)
for i in range(l):
for j in range(i+1, l):
sum_ij = sum_til[j] if i == 0 else sum_til[j] - sum_til[i-1]
if K != 0 and sum_ij % K == 0:
return True
if K == 0 and sum_ij == 0:
return True
return False |
def latest(scores):
"""
Return the latest scores from the list
"""
return scores[-1] |
def convert (hour):
"""
converts Hours in to seconds (hours * 3600)
Args: hours(int)
return: (int value) number of seconds in hours
"""
seconds = 3600
result = hour * seconds
return result |
def str2bool(value):
"""Parse a string into a boolean value"""
return value.lower() in ("yes", "y", "true", "t", "1") |
def downcase(val: str) -> str:
"""Make all characters in a string lower case."""
return val.lower() |
def get_api_id(stack_outputs, api_logical_id):
"""Obtains an API ID from given stack outputs.
:type stack_outputs: str
:param stack_outputs: stack outputs.
:type api_logical_id: str
:param api_logical_id: logical ID of the API.
:rtype: str
:return: API ID.
"""
return stack_outputs[f'{api_logical_id}Id'] |
def comparison_marker_from_obj(obj):
"""Mark all nested objects for comparison."""
if isinstance(obj, list):
marker = []
for elem in obj:
marker.append(comparison_marker_from_obj(elem))
elif isinstance(obj, dict):
marker = {}
for k, v in obj.items():
marker[k] = comparison_marker_from_obj(v)
else:
marker = True
return marker |
def calc_f1(prec, recall):
""" Helper function to calculate the F1 Score
Parameters:
prec (int): precision
recall (int): recall
Returns:
f1 score (int)
"""
return 2*(prec*recall)/(prec+recall) if recall and prec else 0 |
def bytesHiLo(word):
"""Converts from 16-bit word to 8-bit bytes, hi & lo"""
if word > 255: # more than 1 byte
word_hi, word_lo = word >> 8, word & 0xFF # high byte and low byte
else:
word_hi, word_lo = 0, word # make sure two bytes always sent
return word_hi, word_lo |
def big_o_nn(n_base, m=1, o=1, i=1, nodes=(100, 8), t=1, method='scikit', inv=False):
"""
Calculates the expected computation effort compared to n_time
:param n_base: Calculation time for baseline n
:param algo: algorithm to calculate computation effort for
:param m: features
:param o: output neurons
:param i: iterations
:param nodes: list of node sizes (ie. [a, b, c, d] for a 4 layer network)
:param t: training examples
:param method: method for complexity calculation
:return: Calculation time extrapolated to parameters that will be used
"""
nodecomplexity = 0
for q in range(len(nodes) - 1):
nodecomplexity += nodes[q] * nodes[q + 1]
if method == 'stack':
# https://ai.stackexchange.com/questions/5728/what-is-the-time-complexity-for-training-a-neural-network-using-back-propagation
if inv:
return n_base / (t * nodecomplexity)
else:
return n_base * t * nodecomplexity
elif method == 'scikit':
# https://scikit-learn.org/stable/modules/neural_networks_supervised.html
if inv:
return n_base / (t * m * nodecomplexity * o * i)
else:
return n_base * t * nodecomplexity * o * i |
def get_option(packet, option_code):
"""
Parses for the option_code's data from ipconfig output
packet:
the packet data from "ipconfig getpacket"
option_code:
the DHCP option code to parse, for example "option_121"
Returns a list populated with each line of packet data corresponding to
the DHCP option code.
"""
option = False
option_data = []
for line in packet.splitlines():
if option:
if line:
option_data.append(line)
else:
option = False
# this has to come after the decoder for the option line
if option_code in line:
option = True
return option_data |
def lerp(x: float, in_min: float, in_max: float, out_min: float, out_max: float) -> float:
"""Linearly interpolate from in to out.
If both in values are the same, ZeroDivisionError is raised.
"""
return out_min + ((x - in_min) * (out_max - out_min)) / (in_max - in_min) |
def _absolute_path(repo_root, path):
"""Converts path relative to the repo root into an absolute file path."""
return repo_root + "/" + path |
def factorial2(n):
""" factorial """
if n != 0:
return n * factorial2(n - 1)
elif n == 1:
return 1 * factorial2(n - 1)
else:
return 1 |
def gcovOutputGen(gcovFileLineData):
"""Returns the string of the results of .gcov text file"""
import re
functionData = []
callData = []
branchData = []
outputString = ''
for line in gcovFileLineData:
if re.search('^(function)', line):
functionData.append(line)
#print(line)
elif re.search('^(call)', line):
callData.append(line)
#print(line)
elif re.search('^(branch)', line):
branchData.append(line)
#print(line)
#functions called
total = 0
noneZero = 0
temp = []
for line in functionData:
total = total + 1
temp = line.split(' ')
#print(temp[3])
if int(temp[3]) is not 0:
noneZero = noneZero + 1
if total is not 0:
percent = (noneZero / total ) * 100
outputString = outputString + 'Functions called: %3.2f' % (round(percent,2)) + '% of ' + str(total) + '\n'
#branches taken and taken at least once
count = 0
total = 0
noneZero = 0
temp = []
for line in branchData:
total = total + 1
if re.search('never executed', line):
count = count + 1
else:
temp = line.split(' ')
temp[4] = temp[4].replace('%','')
#print(temp[4])
if int(temp[4]) is not 0:
noneZero = noneZero + 1
if total is not 0:
percent = ((total - count)/total) * 100
outputString = outputString + 'Branches executed: %3.2f' % (round(percent,2)) + '% of ' + str(total) + '\n'
percent = (noneZero / total ) * 100
outputString = outputString + 'Taken at least once: %3.2f' % (round(percent,2)) + '% of ' + str(total) + '\n'
#calls taken
count = 0
total = 0
for line in callData:
total = total + 1
if re.search('never executed', line):
count = count + 1
if total is not 0:
percent = ((total - count)/total) * 100
outputString = outputString + 'Calls executed: %3.2f' % (round(percent,2)) + '% of ' + str(total) + '\n'
return outputString |
def wordify_open(p, word_chars):
"""Prepend the word start markers."""
return r"(?<![{0}]){1}".format(word_chars, p) |
def _allow_skipping(ancestors, variable, config_user):
"""Allow skipping of datasets."""
allow_skipping = all([
config_user.get('skip_nonexistent'),
not ancestors,
variable['dataset'] != variable.get('reference_dataset'),
])
return allow_skipping |
def fresnel_number(a, L, lambda_):
"""Compute the Fresnel number.
Notes
-----
if the fresnel number is << 1, paraxial assumptions hold for propagation
Parameters
----------
a : `float`
characteristic size ("radius") of an aperture
L : `float`
distance of observation
lambda_ : `float`
wavelength of light, same units as a
Returns
-------
`float`
the fresnel number for these parameters
"""
return a**2 / (L * lambda_) |
def dict_factory(colnames, rows):
"""
Returns each row as a dict.
Example::
>>> from cassandra.query import dict_factory
>>> session = cluster.connect('mykeyspace')
>>> session.row_factory = dict_factory
>>> rows = session.execute("SELECT name, age FROM users LIMIT 1")
>>> print rows[0]
{u'age': 42, u'name': u'Bob'}
.. versionchanged:: 2.0.0
moved from ``cassandra.decoder`` to ``cassandra.query``
"""
return [dict(zip(colnames, row)) for row in rows] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.