content stringlengths 42 6.51k |
|---|
def create_crumb(title, url=None):
"""
Helper function
"""
crumb = """<span class="breadcrumb-arrow">""" \
""">""" \
"""</span>"""
if url:
crumb = "%s<a href='%s'>%s</a>" % (crumb, url, title)
else:
crumb = "%s %s" % (crumb, title)
return crumb |
def fixed_implies_implicant(fixed,implicant):
"""Returns True if and only if the (possibly partial) state "fixed" implies
the implicant.
Parameters
----------
fixed : partial state dictionary
State (or partial state) representing fixed variable states.
implicant : partial state dictionary
State (or partial state) representing the target implicant.
Returns
-------
bool
True if and only if the implicant is in the logical domain of influence
of the fixed (partial) state.
"""
rval = True
for k,v in implicant.items():
if not k in fixed:
rval = False
break
elif fixed[k] != v:
rval = False
break
return rval |
def recursion_power(number: int, exp: int, result: int = 1) -> int:
"""
Perpangkatan dengan metode rekursif
rumus matematika: number^exp
>>> recursion_power(2, 5)
32
>>> recursion_power(100, 0)
1
>>> recursion_power(0, 100)
0
>>> recursion_power(1, 100)
1
"""
if exp < 1:
return result
else:
return recursion_power(number, exp - 1, result * number) |
def vlan_range_to_list(vlans):
"""Converts single VLAN or range of VLANs into a list
Example:
Input (vlans): 2-4,8,10,12-14 OR 3, OR 2,5,10
Returns: [2,3,4,8,10,12,13,14] OR [3] or [2,5,10]
Args:
vlans (str): User input parameter of a VLAN or range of VLANs
Returns:
list: ordered list of all VLAN(s) in range
"""
final = []
list_of_ranges = []
if ',' in vlans:
list_of_ranges = vlans.split(',')
else:
list_of_ranges.append(vlans)
for each in list_of_ranges:
# check to see if it's a single VLAN (not a range)
if '-' not in each:
final.append(each)
else:
low = int(each.split('-')[0])
high = int(each.split('-')[1])
for num in range(low, high+1):
vlan = str(num)
final.append(vlan)
return final |
def bool_to_str(value):
"""Return 'true' for True, 'false' for False, original value otherwise."""
if value is True:
return "true"
if value is False:
return "false"
return value |
def image_space_to_region(x, y, x1, y1, x2, y2):
""" Relative coords to Region (screen) space """
w = (x2 - x1)
h = (y2 - y1)
sc = w
return x1 + (x + 0.5) * sc, (y1 + y2) * 0.5 + y * sc |
def addNodeFront(node, head, tail) :
""" Given a node and the head pointer of a linked list, adds the node before the linked list head and returns the head of the list """
if head is None :
head = node
tail = node
return (head, tail)
head.prev = node
node.next = head
head = node
return (head, tail) |
def get_max_profit1(stock_prices):
"""
- Time: O(n^2)
- Space: O(1)
* n is len(stock_prices)
"""
length = len(stock_prices)
assert length > 1, 'Getting a profit requires at least 2 prices'
profit = stock_prices[1] - stock_prices[0]
length = len(stock_prices)
for i in range(length):
for j in range(i + 1, length):
if stock_prices[j] - stock_prices[i] > profit:
profit = stock_prices[j] - stock_prices[i]
return profit |
def third_part(txt):
"""Third logical part for password."""
m, d, y = txt.split('/')
return f'{y.zfill(4)}{m.zfill(2)}{d.zfill(2)}' |
def cubicinout(x):
"""Return the value at x of the 'cubic in out' easing function between 0 and 1."""
if x < 0.5:
return 4 * x**3
else:
return 1/2 * ((2*x - 2)**3 + 2) |
def flatten(json_response):
"""
flattens the json response received from graphQL, and returns the list of topics
:param json_response: response of the format mentioned in graph_query
:return: list of topics
"""
topics = []
if json_response.get("data", None) is not None:
# print(json_response["data"])
language_nodes = json_response["data"]["repository"]["languages"]["nodes"]
for node in language_nodes:
node["name"] = node["name"][0].capitalize() + node["name"][1:]
topics.append(node["name"])
if(len(topics) > 4):
break
topic_nodes = json_response["data"]["repository"]["repositoryTopics"]["nodes"]
for node in topic_nodes:
topics.append(node["topic"]["name"].capitalize())
if(len(topics) > 15):
break
print(len(topics))
return topics |
def build_query_id_to_partition(query_ids, sizes):
"""Partition a given list of query IDs.
:param query_ids: an input array of query IDs.
:param sizes: partion sizes
:return: a dictionary that maps each query ID to its respective partition ID
"""
assert sum(sizes) == len(query_ids)
query_id_to_partition = dict()
start = 0
for part_id in range(len(sizes)):
end = start + sizes[part_id]
for k in range(start, end):
query_id_to_partition[query_ids[k]] = part_id
start = end
return query_id_to_partition |
def removekey(d, key):
"""remove selected key from dict and return new dict"""
r = dict(d)
del r[key]
return r |
def majority(*args):
"""
Evaluate majority function on arbitrary number of inputs.
:param args: tuple of Boolean inputs
:return: [bool] value of majority function
"""
return sum(args) > len(args)/2 |
def nth_fibonacci_bruteforce(n: int) -> int:
"""
>>> nth_fibonacci_bruteforce(100)
354224848179261915075
>>> nth_fibonacci_bruteforce(-100)
-100
"""
if n <= 1:
return n
fib0 = 0
fib1 = 1
for i in range(2, n + 1):
fib0, fib1 = fib1, fib0 + fib1
return fib1 |
def substrings(a, b, n):
"""Return substrings of length n in both a and b"""
def substring_parse(string, n):
length = len(string)
substrings = set()
for i in range(length - n + 1):
substrings.add(string[i:i+n])
return substrings
# parsing a into substrings
a = substring_parse(a, n)
# parsing b into substrings
b = substring_parse(b, n)
common_lines = a & b
return list(common_lines) |
def findCameraInArchive(camArchives, cameraID):
"""Find the entries in the camera archive directories for the given camera
Args:
camArchives (list): Result of getHpwrenCameraArchives() above
cameraID (str): ID of camera to fetch images from
Returns:
List of archive dirs that matching camera
"""
matchingCams = list(filter(lambda x: cameraID == x['id'], camArchives))
# logging.warning('Found %d match(es): %s', len(matchingCams), matchingCams)
if matchingCams:
return matchingCams[0]['dirs']
else:
return [] |
def url_origin(url: str) -> str:
"""
Return the protocol & domain-name (without path)
"""
parts = url.split('/')
return '/'.join(parts[0:3]) |
def parse_host_and_port(raw):
"""Returns a tuple comprising hostname and port number from raw text"""
host_and_port = raw.split(':')
if len(host_and_port) == 2:
return host_and_port
else:
return raw, None |
def getcommontype(action):
"""Get common type from action."""
return action if action == 'stock' else 'product' |
def _get_resource_tag(
resource_type,
tag,
runtime,
chip,
resource_id=None,
):
"""
Get resource tag by resource type.
IMPORTANT:
resource_id is optional to enable calling this method before the training resource has been created
resource_tag will be incomplete (missing resource_id appended to the end) when resource_id is NOT supplied
:param resource_type: Type of resource (job, function, model, stream) - currently not used but here to enable generic method
:param tag: User defined tag for the resource
:param runtime: Runtime used to serve the resource Valid values: python, tfserving, tflight
:param chip: Type of hardware chip used to server the resource
:param resource_id: (optional) Id that uniquely identifies the trained resource
:return: resource tag
"""
resource_tag = tag + runtime + chip
if resource_id:
resource_tag += resource_id
return resource_tag |
def digits_in_base(number, base):
"""
Convert a number to a list of the digits it would have if written
in base @base.
For example:
- (16, 2) -> [1, 6] as 1*10 + 6 = 16
- (44, 4) -> [2, 3, 0] as 2*4*4 + 3*4 + 0 = 44
"""
if number == 0:
return [ 0 ]
digits = []
while number != 0:
digit = int(number % base)
number = int(number / base)
digits.append(digit)
digits.reverse()
return digits |
def climate_validation(climate):
""" Decide if the climate input is valid.
Parameters:
(str): A user's input to the climate input.
Return:
(str): A single valid string, such as "cold", "cool" or " Moderate" and so on.
"""
while climate != "1" and climate != "2" and climate != "3" and climate != "4" and climate != "5" :
print("\nI'm sorry, but " + climate + " is not a valid choice. Please try again.")
climate = input("\nWhat climate do you prefer?"
+ "\n 1) Cold"
+ "\n 2) Cool"
+ "\n 3) Moderate"
+ "\n 4) Warm"
+ "\n 5) Hot"
+ "\n> ")
return climate |
def binary(num, length=8):
"""
Format an integer to binary without the leading '0b'
"""
return format(num, '0{}b'.format(length)) |
def key_value_parser(path,keys,separator=' '):
"""
Key value parser for URL paths
Uses a dictionary of keyname: callback to setup allowed parameters
The callback will be executed to transform given value
Examples:
>>> list(sorted(key_value_parser('/invalidkey1/randomvalue/key1/0/key3/5/key1/False/key2/key3/value2/', {'key1': bool,'key2': str,'key3': int}).items()))
[('key1', True), ('key2', 'key3'), ('key3', 5)]
>>> list(sorted(key_value_parser('/invalidkey1/randomvalue/key1/1/key3/5/key1/0/key2/key3/value2/', {'key1': bool,'key2': str,'key3': int}).items()))
[('key1', True), ('key2', 'key3'), ('key3', 5)]
"""
items=path.split('/')
keylist=keys.keys()
data={}
skipnext=False
for i in range(len(items)):
if skipnext:
# Skip next item because it is a value
skipnext=False
else:
# Get current item
item=items[i]
if item in keylist:
# Next item is the value
if i < len(items)-1:
try:
if keys[item] == bool:
try:
value=bool(int(items[i+1]))
except:
value=False
else:
value=keys[item](items[i+1])
data[item]=value
# Set flag to skip next item
skipnext=True
except:
pass
return data |
def cut_file_type(file_name):
"""
:param file_name:
:return:
"""
file_name_parts = file_name.split(".")
return file_name.replace("." + file_name_parts[len(file_name_parts)-1], "") |
def numrev(n):
"""Reversing a Number."""
if type(n) == int:
a = n
rev = 0
while a > 0:
rev = rev * 10
rev = rev + a % 10
a = a // 10
return rev
else:
raise Exception('Only positive integers allowed.') |
def add_required_cargo_fields(toml_3p):
"""Add required fields for a Cargo.toml to be parsed by `cargo tree`."""
toml_3p["package"] = {
"name": "chromium",
"version": "1.0.0",
}
return toml_3p |
def _s2cmi(m, nidx):
"""
Sparse to contiguous mapping inserter.
>>> m1={3:0, 4:1, 7:2}
>>> _s2cmi(m1, 5); m1
1
{3: 0, 4: 1, 5: 2, 7: 3}
>>> _s2cmi(m1, 0); m1
0
{0: 0, 3: 1, 4: 2, 5: 3, 7: 4}
>>> _s2cmi(m1, 8); m1
4
{0: 0, 3: 1, 4: 2, 5: 3, 7: 4, 8: 5}
"""
nv = -1
for i, v in m.items():
if i >= nidx:
m[i] += 1
elif v > nv:
nv = v
m[nidx] = nv + 1
return nv + 1 |
def smooth_nulls(matrix):
"""This function takes a matrix as an input. For any values that meet
a condition, it averages the value at the same index in both the preceding
and the following rows and assigns the result as its value"""
for i, year in enumerate(matrix):
for j, day in enumerate(year):
if day is False:
if i == 0:
matrix[i][j] = matrix[i + 1][j]
elif i + 1 == len(matrix):
matrix[i][j] = matrix[i - 1][j]
else:
year_before = matrix[i - 1][j]
year_after = matrix[i + 1][j]
matrix[i][j] = (year_before + year_after) / 2
return matrix |
def bbox_vflip(bbox, rows, cols):
"""Flip a bounding box vertically around the x-axis."""
x_min, y_min, x_max, y_max = bbox
return [x_min, 1 - y_max, x_max, 1 - y_min] |
def apses_to_ae(apo, per, radius = None):
""" Convert apoapsis and periapsis altitudes (expressed in altitudes or absolute values, e.g. 300x800km) to semi-major axis (a)
and eccentricity (e). If radius is specified, the apo and per are altitudes, if not specified, apo and per are absolute
values """
# sanity checks
if apo < per:
apo, per = per, apo
# If radius is specified, the apo and per are expressed as altitudes (distance to surface, not to Earth center)
if radius:
apo += radius
per += radius
if (apo == per):
return apo, 0 # circular orbit, zero eccentricity
e = (apo - per) / (per + apo)
a = apo / (1+e)
return a,e |
def uneditableInput(
placeholder="",
span=2,
inlineHelpText=False,
blockHelpText=False):
"""
*Generate a uneditableInput - TBS style*
**Key Arguments:**
- ``placeholder`` -- the placeholder text
- ``span`` -- column span
- ``inlineHelpText`` -- inline and block level support for help text that appears around form controls
- ``blockHelpText`` -- a longer block of help text that breaks onto a new line and may extend beyond one line
**Return:**
- ``uneditableInput`` -- an uneditable input - the user can see but not interact
"""
if span:
span = "span%(span)s" % locals()
else:
span = ""
if inlineHelpText:
inlineHelpText = """<span class="help-inline">%(inlineHelpText)s</span>""" % locals(
)
else:
inlineHelpText = ""
if blockHelpText:
blockHelpText = """<span class="help-block">%(blockHelpText)s</span>""" % locals(
)
else:
blockHelpText = ""
uneditableInput = """
<span class="%(span)s uneditable-input">
%(placeholder)s
</span>%(inlineHelpText)s%(blockHelpText)s""" % locals()
return uneditableInput |
def normalize_bid(iccu_bid):
"""
u'IT\\ICCU\\AGR\\0000002' => 'AGR0000002'
"""
return "".join(iccu_bid.split("\\")[-2:]) |
def get_partition_key(partition_type, partition_num=None):
"""Generates a unique key for a partition using its attributes"""
key = 'partition'
if partition_type in ['cv', 'test']:
return '_'.join([key, partition_type])
elif partition_type == 'train':
assert partition_num is not None
return '_'.join([key, partition_type, str(partition_num)])
else:
raise Exception('Invalid partition type {}'.format(partition_type)) |
def identifier_keys(items):
"""Convert dictionary keys to identifiers
replace spaces with underscores
lowercase the string
remove initial digits
For convenience of use with NameSpace (above)
>>> assert identifier_keys({'A fred': 1})['a_fred'] == 1
"""
def identify(x):
return x.lower().replace(" ", "_").lstrip("0123456789")
return {identify(k): v for k, v in items.items()} |
def _shift_num_right_by(num: int, digits: int) -> int:
"""Shift a number to the right by discarding some digits
We actually use string conversion here since division can provide
wrong results due to precision errors for very big numbers. e.g.:
6150000000000000000000000000000000000000000000000 // 1e27
6.149999999999999e+21 <--- wrong
"""
return int(str(num)[:-digits]) |
def get_cell_description(cell_input):
"""Gets cell description
Cell description is the first line of a cell, in one of this formats:
* single line docstring
* single line comment
* function definition
* %magick
"""
try:
first_line = cell_input.split("\n")[0]
if first_line.startswith(('"', '#', 'def', '%')):
return first_line.replace('"','').replace("#",'').replace('def ', '').replace("_", " ").strip()
except:
pass
return "" |
def diffs(l):
"""
'Simple' (i.e. not pairs) differences of a list l.
"""
d = [l[i]-l[i-1] for i in range(1,len(l))]
d = list(dict.fromkeys(d))
d = sorted(d)
return d |
def sumBase(n: int, k: int) :
"""
Given an integer n (in base 10) and a base k, return the sum of the digits of n after converting n from base 10 to base k.
After converting, each digit should be interpreted as a base 10 number, and the sum should be returned in base 10.
TC : O(N)
SC : O(1)
n : int (integer base 10)
k : int (base to be converted to)
return value : int
"""
summation=0
while n >= k :
summation = summation + n%k
n=n//k
print(n)
return (summation + n) |
def hsv2rgb(h, s, v):
"""http://en.wikipedia.org/wiki/HSL_and_HSV
h (hue) in [0, 360[
s (saturation) in [0, 1]
v (value) in [0, 1]
return rgb in range [0, 1]
"""
if v == 0:
return 0, 0, 0
if s == 0:
return v, v, v
i, f = divmod(h / 60., 1)
p = v * (1 - s)
q = v * (1 - s * f)
t = v * (1 - s * (1 - f))
if i == 0:
return v, t, p
elif i == 1:
return q, v, p
elif i == 2:
return p, v, t
elif i == 3:
return p, q, v
elif i == 4:
return t, p, v
elif i == 5:
return v, p, q
else:
raise RuntimeError('h must be in [0, 360]') |
def _maybe_to_dense(obj):
"""
try to convert to dense
"""
if hasattr(obj, 'to_dense'):
return obj.to_dense()
return obj |
def is_negation(bigram_first_word):
"""Gets the fist word of a bigram and checks if this words is a negation or contraction word"""
NEGATION_WORDS = ['no','not']
NEGATION_CONTRACTIONS = ["isn't","aren't","wasn't","weren't","haven't",
"hasn't","hadn't","won't","wouldn't","don't",
"doesn't","didn't","can't","couldn't","shouldn't"
"mightn't","mustn't","ain't","mayn't","oughtn't",
"shan't"]
return (bigram_first_word in NEGATION_WORDS) or (bigram_first_word in NEGATION_CONTRACTIONS) |
def common_suffix(*seqs):
"""Return the subsequence that is a common ending of sequences in ``seqs``.
>>> from sympy.utilities.iterables import common_suffix
>>> common_suffix(list(range(3)))
[0, 1, 2]
>>> common_suffix(list(range(3)), list(range(4)))
[]
>>> common_suffix([1, 2, 3], [9, 2, 3])
[2, 3]
>>> common_suffix([1, 2, 3], [9, 7, 3])
[3]
"""
if not all(seqs):
return []
elif len(seqs) == 1:
return seqs[0]
i = 0
for i in range(-1, -min(len(s) for s in seqs) - 1, -1):
if not all(seqs[j][i] == seqs[0][i] for j in range(len(seqs))):
break
else:
i -= 1
if i == -1:
return []
else:
return seqs[0][i + 1:] |
def check_flag(params, string, delete):
"""
Check if a parameter (string) was beeen declared in the line of commands (params) and return the associated value.
If delete is true the related string will be deleted
If string is not present, return None
Input:
params = list of parameters from original command line
string = string to be searched
delete = Boolean variable to check if the selected string must be deleted after copied in value variable
Output:
value = parameter associated to the selected string
"""
i = 0
value = None
size = len(string)
for line in params:
tmp = line.find(string)
if tmp != -1:
start = tmp + size
sel_string = line[start:]
if delete:
params.pop(i)
value = sel_string
i += 1
return value |
def codecs_error_ascii_to_hex(exception):
"""On unicode decode error (bytes -> unicode error), tries to replace
invalid unknown bytes by their hex notation."""
if isinstance(exception, UnicodeDecodeError):
obj = exception.object
start = exception.start
end = exception.end
invalid_part = obj[start:end]
result = []
for character in invalid_part:
# Python 2 strings
if isinstance(character, str):
result.append(u"\\x{}".format(character.encode("hex")))
# Python 3 int
elif isinstance(character, int):
result.append(u"\\{}".format(hex(character)[1:]))
else:
raise exception
result = ("".join(result), end)
return result
raise exception |
def get_label_features(features, parents=None):
"""
Recursively get a list of all features that are ClassLabels
:param features:
:param parents:
:return: pairs of tuples as above and the list of class names
"""
if parents is None:
parents = []
label_features = []
for name, feat in features.items():
if isinstance(feat, dict):
if "names" in feat:
label_features += [(tuple(parents + [name]), feat["names"])]
elif "feature" in feat:
if "names" in feat:
label_features += [
(tuple(parents + [name]), feat["feature"]["names"])
]
elif isinstance(feat["feature"], dict):
label_features += get_label_features(
feat["feature"], parents + [name]
)
else:
for k, v in feat.items():
if isinstance(v, dict):
label_features += get_label_features(v, parents + [name, k])
elif name == "names":
label_features += [(tuple(parents), feat)]
return label_features |
def rect2poly(ll, ur):
"""
Convert rectangle defined by lower left/upper right
to a closed polygon representation.
"""
x0, y0 = ll
x1, y1 = ur
return [
[x0, y0],
[x0, y1],
[x1, y1],
[x1, y0],
[x0, y0]
] |
def check_if_duplicates(aList_in):
"""[Check if given list contains any duplicates]
Returns:
[type]: [description]
"""
iFlag_unique = 1
for elem in aList_in:
if aList_in.count(elem) > 1:
iFlag_unique = 0
break
else:
pass
return iFlag_unique |
def intersection_over_union(boxA, boxB):
"""
IOU (Intersection over Union) = Area of overlap / Area of union
@param boxA=[x0, y0, x1, y1] (x1 > x0 && y1 > y0) two pointer are diagonal
"""
boxA = [int(x) for x in boxA]
boxB = [int(x) for x in boxB]
xA = max(boxA[0], boxB[0])
yA = max(boxA[1], boxB[1])
xB = min(boxA[2], boxB[2])
yB = min(boxA[3], boxB[3])
interArea = max(0, xB - xA + 1) * max(0, yB - yA + 1)
boxAArea = (boxA[2] - boxA[0] + 1) * (boxA[3] - boxA[1] + 1)
boxBArea = (boxB[2] - boxB[0] + 1) * (boxB[3] - boxB[1] + 1)
iou = interArea / float(boxAArea + boxBArea - interArea)
return iou |
def generateNumberTriangleLines(numberTriangle):
"""
Generate the lines that when printed will give the number triangle
appearance.
Params:
numberTriangle - 2D list representing elements of a number triangle
Returns:
numberTriangleLines - List of strings to print the number triangle in
order.
"""
numberTriangleLines = []
for lineIndex in range(len(numberTriangle)):
currentLine = ""
for index, elem in enumerate(numberTriangle[lineIndex]):
currentLine += str(elem)
if index < len(numberTriangle[lineIndex]) - 1:
currentLine += " "
numberTriangleLines.append(currentLine)
return numberTriangleLines |
def SplitAttr(attr):
"""Takes a fully-scoped attributed and returns a tuple of the
(scope, attr). If there is no scope it returns (None, attr).
"""
s = ''
a = ''
if attr:
if attr.find('/') >= 0:
tokens = attr.split('/')
else:
tokens = attr.rsplit('.', 1)
if len(tokens) == 1:
a = attr
else:
if tokens[1]:
s = tokens[0]
a = tokens[1]
else:
s = tokens[0]
return (s, a) |
def snake_to_pascal(value: str) -> str:
"""method_name -> MethodName"""
return ''.join(map(lambda x: x[0].upper() + x[1:], value.replace('.', '_').split('_'))) |
def a2b(a):
"""test -> 01110100011001010111001101110100"""
return ''.join([format(ord(c), '08b') for c in a]) |
def calc_jaccard_index(multiset_a, multiset_b):
"""Calculate jaccard's coefficient for two multisets mutliset_a
and multiset_b.
Jaccard index of two set is equal to:
(no. of elements in intersection of two multisets)
_____________________________________________
(no. of elements in union of two multisets)
Note: intersection and union of two multisets is similar to union-all and
intersect-all operations in SQL.
Args:
multiset_a: list(int). First set.
multiset_b: list(int). Second set.
Returns:
float. Jaccard index of two sets.
"""
multiset_a = sorted(multiset_a[:])
multiset_b = sorted(multiset_b[:])
small_set = (
multiset_a[:] if len(multiset_a) < len(multiset_b) else multiset_b[:])
union_set = (
multiset_b[:] if len(multiset_a) < len(multiset_b) else multiset_a[:])
index = 0
extra_elements = []
for elem in small_set:
while index < len(union_set) and elem > union_set[index]:
index += 1
if index >= len(union_set) or elem < union_set[index]:
extra_elements.append(elem)
elif elem == union_set[index]:
index += 1
union_set.extend(extra_elements)
if union_set == []:
return 0
index = 0
intersection_set = []
for elem in multiset_a:
while index < len(multiset_b) and elem > multiset_b[index]:
index += 1
if index < len(multiset_b) and elem == multiset_b[index]:
index += 1
intersection_set.append(elem)
coeff = float(len(intersection_set)) / len(union_set)
return coeff |
def case_insensitive_dict_get(d, key, default=None):
"""
Searches a dict for the first key matching case insensitively. If there is
an exact match by case for the key, that match is given preference.
Args:
d: dict to search
key: key name to retrieve case-insensitively
Returns: value or default
"""
if not key:
return default
if key in d:
return d[key]
if isinstance(key, str):
key_lower = key.lower()
for k in d:
if k.lower() == key_lower:
return d[k]
return default |
def stringify_rgb(rgb):
"""Used to convert rgb to string for saving in db"""
rgb_value = f"{rgb[0]}, {rgb[1]}, {rgb[2]}, {rgb[3]}"
return rgb_value |
def isPowerOfFour(num):
"""
:type num: int
:rtype: bool
"""
return num > 0 and (num&(num-1)) == 0 and (num & 0x55555555) != 0 |
def ipv4_range_type(string):
""" Validates an IPv4 address or address range. """
import re
ip_format = r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}'
if not re.match("^{}$".format(ip_format), string):
if not re.match("^{}-{}$".format(ip_format, ip_format), string):
raise ValueError
return string |
def __progress_class(replicating_locks, total_locks):
"""
Returns the progress class (10%, 20%, ...) of currently replicating locks.
:param replicating_locks: Currently replicating locks.
:param total_locks: Total locks.
"""
try:
return int(float(total_locks - replicating_locks) / float(total_locks) * 10) * 10
except Exception:
return 0 |
def _lrp_meanPcrEff(tarGroup, vecTarget, pcrEff, vecSkipSample, vecNoPlateau, vecShortLogLin):
"""A function which calculates the mean efficiency of the selected target group excluding bad ones.
Args:
tarGroup: The target number
vecTarget: The vector with the targets numbers
pcrEff: The array with the PCR efficiencies
vecSkipSample: Skip the sample
vecNoPlateau: True if there is no plateau
vecShortLogLin: True indicates a short log lin phase
Returns:
An array with [meanPcrEff, pcrEffVar].
"""
cnt = 0
sumEff = 0.0
sumEff2 = 0.0
for j in range(0, len(pcrEff)):
if tarGroup is None or tarGroup == vecTarget[j]:
if (not (vecSkipSample[j] or vecNoPlateau[j] or vecShortLogLin[j])) and pcrEff[j] > 1.0:
cnt += 1
sumEff += pcrEff[j]
sumEff2 += pcrEff[j] * pcrEff[j]
if cnt > 1:
meanPcrEff = sumEff / cnt
pcrEffVar = (sumEff2 - (sumEff * sumEff) / cnt) / (cnt - 1)
else:
meanPcrEff = 1.0
pcrEffVar = 100
return [meanPcrEff, pcrEffVar] |
def get_round_digits(pair):
"""Get the number of digits for the round function."""
numberofdigits = 4
if pair:
base = pair.split("_")[0]
if base in ("BTC", "BNB", "ETH"):
numberofdigits = 8
return numberofdigits |
def metric_fn(labels, predictions):
""" Defines extra evaluation metrics to canned and custom estimators.
By default, this returns an empty dictionary
Args:
labels: A Tensor of the same shape as predictions
predictions: A Tensor of arbitrary shape
Returns:
dictionary of string:metric
"""
metrics = {}
return metrics |
def islist(string):
"""
Checks if a string can be converted into a list.
Parameters
----------
value : str
Returns
-------
bool:
True/False if the string can/can not be converted into a list.
"""
return (list(string)[0] == "[") and (list(string)[-1] == "]") |
def is_active_bot(user_info):
"""
Returns true if the provided user info describes an active bot (i.e. not deleted)
"""
if not user_info['ok']:
return False
user = user_info['user']
return user.get('is_bot', False) and not user['deleted'] |
def encode3(s):
"""
convert string => bytes
for compatibility python 2/3
"""
if type(s)==str:
return s.encode('UTF-8')
return s |
def json_analysis(data):
"""
This fuction creates json navigator, where user can choose
what object or data he/she wants to see, by using recursion
"""
if isinstance(data, dict):
print("This object is dictionary")
print(data.keys())
users_input = str(input("Please choose what key do you want to see: "))
for key in data:
if users_input == key:
key_data = data[key]
return json_analysis(key_data)
elif isinstance(data, list):
print("This object is list")
print("This list has ",len(data),"elements")
users_input = int(input("Please choose what number of list do you want to see: "))
for els in data:
if els == data[users_input]:
list_data = data[users_input]
return json_analysis(list_data)
elif isinstance(data, str):
print(data)
elif isinstance(data, int):
print(data) |
def reorder(datalist, indexlist):
"""reorder(datalist, indexlist)
Returns a new list that is ordered according to the indexes in the
indexlist.
e.g.
reorder(["a", "b", "c"], [2, 0, 1]) -> ["c", "a", "b"]
"""
return [datalist[idx] for idx in indexlist] |
def capitalize(s):
"""Return a new string like s, but with the first letter capitalized."""
return (s[0].upper() + s[1:]) if s else s |
def mean(iterable):
"""
mean(iter: iterable)
mean of a list with numbers
args:
iterable: list => eg: 0, [1,2,3,4,5]
return:
number => eg: 3
"""
ss, i = 0, 0
for e in iterable:
i += 1
ss += e
return ss / i |
def merge_sort(array):
"""Merge sort data structure function."""
if len(array) > 1:
if len(array) % 2 == 0:
half = int(len(array) / 2)
else:
half = int(len(array) / 2 + .5)
left_half = array[:half]
right_half = array[half:]
merge_sort(left_half)
merge_sort(right_half)
main_count = 0
left_count = 0
right_count = 0
pass
while left_count < len(left_half) and right_count < len(right_half):
if left_half[left_count] < right_half[right_count]:
array[main_count] = left_half[left_count]
main_count += 1
left_count += 1
else:
array[main_count] = right_half[right_count]
main_count += 1
right_count += 1
while left_count < len(left_half):
array[main_count] = left_half[left_count]
main_count += 1
left_count += 1
while right_count < len(right_half):
array[main_count] = right_half[right_count]
main_count += 1
right_count += 1
else:
if len(array) == 0:
return array
if not isinstance(array[0], int):
raise TypeError('Must be an integer, please try again.')
return array |
def snake_split(s):
"""
Split a string into words list using snake_case rules.
"""
s = s.strip().replace(" ", "")
return s.split("_") |
def get_free_item_obj(free_items, sku):
"""Fetch free item obj
:param free_items: List
:param sku: String
:rtype: Dictionary
"""
for item in free_items:
if item["item"] == sku:
return item |
def win_check(board, mark):
"""Check if player with respective marker wins"""
if board[1] == mark:
if (board[2] == mark and board[3] == mark
or board[4] == mark and board[7] == mark
or board[5] == mark and board[9] == mark):
return True
if board[5] == mark:
if (board[2] == mark and board[8] == mark
or board[3] == mark and board[7] == mark
or board[4] == mark and board[6] == mark):
return True
if board[9] == mark:
if (board[3] == mark and board[6] == mark
or board[7] == mark and board[8] == mark):
return True
return False |
def iround(x):
"""Round floating point number and cast to int."""
return int(round(x)) |
def is_abba(abba_str):
"""Returns true if 4 character string consists of a pair of two different characters followed
by the reverse of that pair"""
if len(abba_str) != 4:
raise Exception
return abba_str[0] == abba_str[3] and abba_str[1] == abba_str[2] and abba_str[0] != abba_str[1] |
def bresenham_line(x0, y0, x1, y1):
"""
Return all pixels between (x0, y0) and (x1, y1) as a list.
:param x0: Self explanatory.
:param y0: Self explanatory.
:param x1: Self explanatory.
:param y1: Self explanatory.
:return: List of pixel coordinate tuples.
"""
steep = abs(y1 - y0) > abs(x1 - x0)
if steep:
x0, y0 = y0, x0
x1, y1 = y1, x1
switched = False
if x0 > x1:
switched = True
x0, x1 = x1, x0
y0, y1 = y1, y0
if y0 < y1:
y_step = 1
else:
y_step = -1
delta_x = x1 - x0
delta_y = abs(y1 - y0)
error = - delta_x / 2
y = y0
line = []
for x in range(x0, x1 + 1):
if steep:
line.append((y, x))
else:
line.append((x, y))
error = error + delta_y
if error > 0:
y = y + y_step
error = error - delta_x
if switched:
line.reverse()
return line |
def is_connected_seed(seed:int):
"""Returns True if the given seed would generate a connected graph, False otherwise."""
# We reserve those seed divisible by 3 to the NOT solvable instances
return (seed % 3) != 0 |
def build_dict(transitions, labels, to_filter=[]):
"""Build a python dictionary from the data in the GAP record produced
by kbmag to describe a finite-state automaton.
Parameters
-----------
transitions : list
list of tuples of length `n`, where `n` is the number of
possible labels. If the `i`th entry of tuple `j` is `k`, then there is
an edge from vertex `j` to vertex `k` with label `i`. Note that this
implies that every vertex has outdegree `len(labels)`.
labels : list
ordered list of edge labels appearing in transitions.
to_filter : list
vertices to discard when building the automaton
(i.e. the "failure states" of the automaton).
Returns
------
dict
Dictionary describing the finite-state automaton, in the format
expected by the `geometry_tools.automata.fsa.FSA` class.
"""
v_dict = {}
for i, neighbors in enumerate(transitions):
n_dict = {}
for label, vertex in zip(labels, neighbors):
if vertex not in to_filter:
n_dict[label] = vertex
v_dict[i+1] = n_dict
return v_dict |
def get_group_detail(groups):
"""
Iterate over group details from the response and retrieve details of groups.
:param groups: list of group details from response
:return: list of detailed element of groups
:rtype: list
"""
return [{
'ID': group.get('id', ''),
'Name': group.get('name', '')
} for group in groups] |
def orderPath (nodesDict, start, stop, path):
"""
Internal function used by shortestWay to
put into order nodes from the routing table.
Return the shortest path from start to stop
"""
if start == stop:
return path + [start]
return orderPath (nodesDict, start, nodesDict[stop][0], path + [stop]) |
def _from_fan_speed(fan_speed: int) -> int:
"""Convert the Tradfri API fan speed to a percentage value."""
nearest_10: int = round(fan_speed / 10) * 10 # Round to nearest multiple of 10
return round(nearest_10 / 50 * 100) |
def cut_name(matrix: list) -> list:
"""
Clear matrix
:param matrix: matrix to clear
:return: cleared matrix
"""
new_matrix = []
for line in matrix:
new_matrix.append(line[1:])
return new_matrix |
def ix(museum_ix, mvsas_ix, day_ix, p_len, d_len):
"""Return the index of the variable list represented by the composite indexes"""
return day_ix + (d_len)*(mvsas_ix + (p_len)*(museum_ix)) |
def bool_from_env_string(string: str) -> bool:
"""Convert a string recieved from an environment variable into a
bool.
'true', 'TRUE', 'TrUe', 1, '1' = True
Everything else is False.
:param string: The string to convert to a bool.
"""
if str(string).lower() == 'false' or str(string) == '':
return False
if str(string).lower() == 'true':
return True
try:
int_value = int(string)
if int_value == 1:
return True
else:
return False
except:
return False |
def removenone(d):
"""
Return d with null values removed from all k,v pairs in d and sub objects (list and dict only).
When invoked by external (non-recursive) callers, `d` should be a dict object, or else behavior is undefined.
"""
if isinstance(d, dict):
# Recursively call removenone on values in case value is itself a dict
d = {k:removenone(v) for (k,v) in d.items()}
# Filter out k,v tuples where v is None
return dict(filter(lambda t: t[1] != None, d.items()))
elif isinstance(d, list):
# Recursively call removenone on values in case any is a dict
d = [removenone(v) for v in d]
# Filter out array values which are None
return list(filter(lambda e: e!=None, d))
else:
# Do not iterate into d
return d |
def listInts(input_list):
"""
This function takes a list of ints and/or floats and converts all values to
type int
:param list input_list: list of ints and/or floats
:return list int_list: list of only ints
"""
for i in range(len(input_list)):
try:
input_list[i] = int(input_list[i])
except (TypeError, ValueError):
print("\nValues in input list must be types int or float\n")
# raise TypeError
int_list = input_list
return int_list |
def factorial_n(num):
""" (int) -> float
Computes num!
Returns the factorial of <num>
"""
# Check for valid input
if isinstance(num, int) and num >= 0:
# Base Case - terminates recursion
if num == 0:
return 1
# Breakdown
else:
return num * factorial_n(num - 1) # n*(n - 1)!
else:
return 'Expected Positive integer' |
def dms_to_degrees(v):
"""Convert degree/minute/second to decimal degrees."""
d = float(v[0][0]) / float(v[0][1])
m = float(v[1][0]) / float(v[1][1])
s = float(v[2][0]) / float(v[2][1])
return d + (m / 60.0) + (s / 3600.0) |
def calc_polynomial(x, a, b, c):
"""
y = ax^2 + bx + c
:param x:
:param a:
:param b:
:param c:
:return:
"""
return a * x ** 2 + b * x + c |
def transitive_closure(roots, successors) -> set:
""" Transitive closure is a simple unordered graph exploration. """
black = set()
grey = set(roots)
while grey:
k = grey.pop()
if k not in black:
black.add(k)
them = successors(k)
if them is not None: grey.update(them)
return black |
def lower(s):
"""lower(s) -> string
Return a copy of the string s converted to lowercase.
"""
return s.lower() |
def J_p2(Ep, norm=1.0, alpha=2.0):
"""
Defines the particle distribution of the protons as a power law
Parameters
----------
- Ep = E_proton (GeV)
- alpha = slope
- norm = the normalization (at 1 GeV) in units of cm^-3 GeV-1
Outputs
--------
- The particle distribution times energy in units of cm^-3
"""
return Ep*norm*(Ep/1.0)**(-alpha) |
def destructure(answers: dict, *keys: str) -> list:
"""[summary]
Args:
answers (dict)
Returns:
list: an ordered list of values corresponding to the provided keys
"""
return [answers[key] if key in answers else None for key in keys] |
def fun_lr(lr, total_iters, warmup_total_iters, warmup_lr_start, iters):
"""Cosine learning rate with warm up."""
factor = pow((1 - 1.0 * iters / total_iters), 0.9)
if warmup_total_iters > 0 and iters < warmup_total_iters:
factor = 1.0 * iters / warmup_total_iters
return lr*factor |
def createnozzlelist(nozzles, activen, spacing, firstnozzle=1):
"""
create an evenly spaced list with ones and zeros
"""
list = [0] * nozzles
for x in range(activen):
list[x * (spacing + 1) + firstnozzle] = 1
return list |
def simple_conditionals(conditional_A, conditional_B, conditional_C, conditional_D):
"""
Simplified, more readable test function
"""
return (conditional_A) and (conditional_B) and (conditional_C) and (conditional_D) |
def package_get_details(manifest, package, v_str):
"""Return the manifest details for a given version of a package.
This is just a dictionary access - however, we abstract it away
behind this filter.
"""
try:
return manifest['packages'][package][v_str]
except KeyError:
return None |
def get_len(obj):
"""
A utility function for getting the length of an object.
Args:
obj: An object, optionally iterable.
Returns:
The length of that object if it is a list or tuple, otherwise 1.
"""
if not isinstance(obj, (list, tuple)):
return 1
else:
return len(obj) |
def is_block_number(provided):
"""
Check if the value is a proper Ethereum block number.
:param provided: The value to check.
:return: True iff the value is of correct type.
"""
return type(provided) == int |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.