content
stringlengths 42
6.51k
|
|---|
def get_shard_basename(shard: int) -> str:
"""Get the basename for a streaming dataset shard.
Args:
shard (int): Shard index.
Returns:
str: Basename of file.
"""
return f'{shard:06}.mds'
|
def get_timeout_error_regex(rpc_backend_name):
"""
Given an RPC backend name, returns a partial string indicating the error we
should receive when an RPC has timed out. Useful for use with
assertRaisesRegex() to ensure we have the right errors during timeout.
"""
if rpc_backend_name in ["PROCESS_GROUP", "FAULTY_PROCESS_GROUP", "TENSORPIPE"]:
return "RPC ran for more than"
else:
return "(Timed out)|(Task expired)"
|
def corrected_proj_param(big_H, lil_h, R):
"""
Eq. 4.11
Calculates the corrected projection parameter for a cloud target
Parameters
------------
big_H : int
Satellite's height above the Earth's surface, in km
lil_h : int
Cloud's altitude above the Earth's surface, in km
R : int
Earth's radius, in km
Returns
------------
P_h : float
Corrected projection parameter
"""
P_h = (R + big_H) / (R + lil_h)
return P_h
|
def validate_input(lang):
"""
function to validate the input by user
"""
if lang.lower() not in ('en', 'fr', 'hi', 'es'):
return False
else:
return True
|
def associate(first_list, second_list, offset, max_difference):
"""
Associate two dictionaries of (stamp,data). As the time stamps never match exactly, we aim
to find the closest match for every input tuple.
Input:
first_list -- first dictionary of (stamp,data) tuples
second_list -- second dictionary of (stamp,data) tuples
offset -- time offset between both dictionaries (e.g., to model the delay between the sensors)
max_difference -- search radius for candidate generation
Output:
matches -- list of matched tuples ((stamp1,data1),(stamp2,data2))
"""
first_keys = list(first_list.keys()) # copy both keys lists, so we can remove from them later
second_keys = list(second_list.keys())
potential_matches = [(abs(a - (b + offset)), a, b)
for a in first_keys
for b in second_keys
if abs(a - (b + offset)) < max_difference]
potential_matches.sort()
matches = []
for diff, a, b in potential_matches:
if a in first_keys and b in second_keys:
first_keys.remove(a)
second_keys.remove(b)
matches.append((a, b))
matches.sort()
return matches
|
def __strip_string(value):
"""Simple helper - strip string, don't change numbers"""
if not type(value) == str:
pass
else:
value = value.replace(' ','').replace(',','').strip()
return value
|
def bit_get(val, idx):
"""Gets the bit value.
Args:
val: Input value, int or numpy int array.
idx: Which bit of the input val.
Returns:
The "idx"-th bit of input val.
"""
return (val >> idx) & 1
|
def replicate(l):
"""
Replicates if there is only one element.
"""
if(len(l) == 1):
l.append(l[0])
return l
|
def bounding_box_half_values(bbox_min, bbox_max):
"""
Returns the values half way between max and min XYZ given tuples
:param bbox_min: tuple, contains the minimum X,Y,Z values of the mesh bounding box
:param bbox_max: tuple, contains the maximum X,Y,Z values of the mesh bounding box
:return: tuple(int, int, int)
"""
min_x, min_y, min_z = bbox_min
max_x, max_y, max_z = bbox_max
half_x = (min_x + max_x) * 0.5
half_y = (min_y + max_y) * 0.5
half_z = (min_z + max_z) * 0.5
return half_x, half_y, half_z
|
def first(iterable):
"""Returns the first item of ``iterable``.
"""
try:
return next(iter(iterable))
except StopIteration:
return None
|
def get_windows_version(windows_version: str = 'win7') -> str:
"""
valid windows versions : 'nt40', 'vista', 'win10', 'win2k', 'win2k3', 'win2k8', 'win31', 'win7', 'win8', 'win81', 'win95', 'win98', 'winxp'
>>> import unittest
>>> assert get_windows_version() == 'win7'
>>> assert get_windows_version('nt40') == 'nt40'
>>> unittest.TestCase().assertRaises(RuntimeError, get_windows_version, windows_version='invalid')
"""
valid_windows_versions = ['nt40', 'vista', 'win10', 'win2k', 'win2k3', 'win2k8', 'win31', 'win7', 'win8', 'win81', 'win95', 'win98', 'winxp']
if not windows_version:
windows_version = 'win7'
windows_version = windows_version.lower().strip()
if windows_version not in valid_windows_versions:
raise RuntimeError('Invalid windows_version: "{windows_version}"'.format(windows_version=windows_version))
return windows_version
|
def in_box(boxes, x, y):
"""Finds out whether a pixel is inside one of the boxes listed"""
for box in boxes:
x1, y1, x2, y2 = box
if x>=x1 and x<=x2 and y>=y1 and y<=y2:
return True
return False
|
def verify_positive(value):
"""Throws exception if value is not positive"""
if not value > 0:
raise ValueError("expected positive integer")
return value
|
def create_hue_success_response(entity_number, attr, value):
"""Create a success response for an attribute set on a light."""
success_key = f"/lights/{entity_number}/state/{attr}"
return {"success": {success_key: value}}
|
def _minor(x, i, j):
"""The minor matrix of x
:param i: the column to eliminate
:param j: the row to eliminate
:returns: x without column i and row j
"""
return [[x[n][m] for m in range(len(x[0])) if m != j]
for n in range(len(x)) if n != i]
|
def multiply_2(factor):
"""
Example without using annotations. Better example of how to use assert.
:param factor:
:return: results: int
"""
assert type(factor) is int or type(factor) is float, "MAMMA MIA!"
# Above example shows that we need that type of variable factor has to either int or float.
# Otherwise will print out an extra annotation.
results = factor * factor * factor
return results
|
def ordinal(number: int) -> str:
"""
>>> ordinal(5)
'5th'
>>> ordinal(151)
'151st'
"""
if number < 20:
if number == 1:
pripona = 'st'
elif number == 2:
pripona = 'nd'
elif number == 3:
pripona = 'rd'
else:
pripona = 'th'
else: #determining pripona pre > 20
desiatky = str(number)
desiatky = desiatky[-2]
jednotky = str(number)
jednotky = jednotky[-1]
if desiatky == "1":
pripona = "th"
else:
if jednotky == "1":
pripona = 'st'
elif jednotky == "2":
pripona = 'nd'
elif jednotky == "3":
pripona = 'rd'
else:
pripona = 'th'
return str(number)+pripona
|
def conn_string_with_embedded_password(conn_string_password):
"""
A mock connection string with the `conn_string_password` fixture embedded.
"""
return f"redshift+psycopg2://no_user:{conn_string_password}@111.11.1.1:1111/foo"
|
def get_pseudo_id_code_number(pseudo_ids):
"""
:param self:
:param pseudo_ids:
:return: pseudo_id prefix
pseudo_id number
"""
if len(pseudo_ids) == 0:
return None, 0
elif pseudo_ids[-1] and '-' in pseudo_ids[-1]:
prefix, znumber_str = pseudo_ids[-1].split('-')
return prefix, int(znumber_str)
else:
return None, -1
|
def _reGlue(words):
"""Helper function to turn a list of words into a string"""
ret = ""
for i in range(len(words)):
ret += words[i] + " "
ret = ret.strip()
return ret
|
def longest(s1, s2):
"""This function takes two strings and gives you a string of the unique letters from each string."""
x = s1 + s2
y = (''.join(set(x)))
z = sorted(y)
return ''.join(z)
|
def ezip(*args):
"""
Eager version of the builtin zip function.
This provides the same functionality as python2 zip.
Note this is inefficient and should only be used when prototyping and
debugging.
"""
return list(zip(*args))
|
def int_to_bin_string(x, bits_for_element):
"""
Convert an integer to a binary string and put initial padding
to make it long bits_for_element
x: integer
bit_for_element: bit length of machine words
Returns:
string
"""
encoded_text = "{0:b}".format(x)
len_bin = len(encoded_text)
if len_bin < bits_for_element: #aggiungo gli 0 iniziali che perdo trasformando in int
encoded_text = "0"*(bits_for_element-len_bin)+encoded_text
return encoded_text
|
def reverse_ordering(ordering_tuple):
"""
Given an order_by tuple such as `('-created', 'uuid')` reverse the
ordering and return a new tuple, eg. `('created', '-uuid')`.
"""
def invert(x):
return x[1:] if (x.startswith('-')) else '-' + x
return tuple([invert(item) for item in ordering_tuple])
|
def get_class_name_value(obj):
"""
Returns object class name from LLDB value.
It returns type name without asterisk or ampersand.
:param lldb.SBValue obj: LLDB value object.
:return: Object class name from LLDB value.
:rtype: str | None
"""
if obj is None:
return None
t = obj.GetType()
""":type: lldb.SBType"""
if t is None:
return None
if t.IsPointerType():
t = t.GetPointeeType()
if t.IsReferenceType():
t = t.GetDereferencedType()
return None if t is None else t.GetName()
|
def compare_multiset_states(s1, s2):
"""compare for equality two instances of multiset partition states
This is useful for comparing different versions of the algorithm
to verify correctness."""
# Comparison is physical, the only use of semantics is to ignore
# trash off the top of the stack.
f1, lpart1, pstack1 = s1
f2, lpart2, pstack2 = s2
if (lpart1 == lpart2) and (f1[0:lpart1+1] == f2[0:lpart2+1]):
if pstack1[0:f1[lpart1+1]] == pstack2[0:f2[lpart2+1]]:
return True
return False
|
def lr_decay(N, step, learning_rate):
"""
learning rate decay
Args:
learning_rate: base learning rate
step: current iteration number
N: total number of iterations over which learning rate is decayed
"""
min_lr = 0.00001
res = learning_rate * ((N - step) / N) ** 2
return max(res, min_lr)
|
def find_matching_peering(from_cluster, to_cluster, desired_provider):
"""
Ensures there is a matching peering with the desired provider type
going from the destination (to) cluster back to this one (from)
"""
peering_info = to_cluster['peering']
peer_connections = peering_info['connections']
for peer_connection in peer_connections:
if not peer_connection['provider'] == desired_provider:
continue
if not peer_connection['cluster']:
continue
if from_cluster['name'] == peer_connection['cluster']['name']:
return peer_connection
return None
|
def rectangles_circum(n: int):
"""Return `n` fixed circumference rectangles, w + h = n"""
output = list()
for i in range(1, n + 1):
output.append((i, n - i + 1))
output.sort(key=lambda x: x[1], reverse=True)
return output
|
def check_criteria(header):
"""Check file if we want the file
Parameters
----------
header : fits header object
from astropy.io.fits.open function
Returns
-------
Bool
True or False
"""
image_list = ['sky', 'object']
try:
if header['IMAGETYP'] in image_list:
return True, 'sci'
except:
return False, ''
object_list = ['twilight']
try:
if header['OBJECT'] in object_list:
return True, 'twi'
except:
return False, ''
object_list = ['zero']
try:
if header['IMAGETYP'] in object_list:
return True, 'zro'
except:
return False, ''
return False, ''
|
def scale_to_range(value, min_value, max_value):
""" Convert 0-1 value to value between min_value and max_value (inclusive) """
scaled_value = min_value + int(value * (max_value - min_value + 1))
return scaled_value if scaled_value <= max_value else max_value
|
def convert_kelvin_to_rankine(temp):
"""Convert the temperature from Kelvin to Rankine scale.
:param float temp: The temperature in degrees Kelvin.
:returns: The temperature in degrees Rankine.
:rtype: float
"""
return (temp * 9) / 5
|
def make_key_constant(key):
"""
Convert a key into an C enum value constant label.
"""
return 'k' + str(key)
|
def decimal_to_hex(number):
"""
Calculates the hex of the given decimal number.
:param number: decimal number in string or integer format
:return string of the equivalent hex number
"""
if isinstance(number, str):
number = int(number)
hexadec = []
hex_equivalents = {10: 'A', 11: 'B', 12: 'C', 13: 'D', 14: 'E', 15: 'F'}
while number >= 1:
remainder = number % 16
if remainder < 10:
hexadec.append(remainder)
elif remainder >= 10:
hexadec.append(hex_equivalents[remainder])
number = number // 16
return ''.join(map(str, hexadec[::-1]))
|
def box(text1, text2=''):
"""Create an HTML box of text"""
raw_html = '<div align=left style="padding:8px;font-size:28px;margin-top:5px;margin-bottom:5px">' + text1 + '<span style="color:red">' + text2 + '</div>'
return raw_html
|
def is_str(object):
"""RETURN : True/False """
return isinstance(object, str)
|
def hard_decision(y):
"""
Hard decision of a log-likelihood.
"""
if y >= 0:
return 0
else:
return 1
|
def get_success_builds(builds):
"""Get number of success builds."""
return [b for b in builds if b["result"] == "SUCCESS"]
|
def is_string(s):
"""
Portable function to answer whether a variable is a string.
Parameters
----------
s : object
An object that is potentially a string
Returns
-------
isstring : bool
A boolean decision on whether ``s`` is a string or not
"""
return isinstance(s, str)
|
def get_AQI_level(value):
"""calculate AQI
:param value:
:return: string
"""
if 50 >= value >= 0:
return "Good"
elif 100 >= value >= 51:
return "Moderate"
elif 150 >= value >= 101:
return "Unhealthy for Sensitive Groups"
elif 200 >= value >= 151:
return "Unhealthy"
elif 300 >= value >= 201:
return "Very Unhealthy"
elif 500 >= value >= 301:
return "Hazardous"
elif value > 500:
return "Extremely High Level"
else:
return None
|
def _create_axis(axis_type, variation="Linear", title=None):
"""
Creates a 2d or 3d axis.
:params axis_type: 2d or 3d axis
:params variation: axis type (log, line, linear, etc)
:parmas title: axis title
:returns: plotly axis dictionnary
"""
if axis_type not in ["3d", "2d"]:
return None
default_style = {
"background": "rgb(230, 230, 230)",
"gridcolor": "rgb(255, 255, 255)",
"zerolinecolor": "rgb(255, 255, 255)",
}
if axis_type == "3d":
return {
"showbackground": True,
"backgroundcolor": default_style["background"],
"gridcolor": default_style["gridcolor"],
"title": title,
"type": variation,
"zerolinecolor": default_style["zerolinecolor"],
}
if axis_type == "2d":
return {
"xgap": 10,
"ygap": 10,
"backgroundcolor": default_style["background"],
"gridcolor": default_style["gridcolor"],
"title": title,
"zerolinecolor": default_style["zerolinecolor"],
"color": "#444",
}
|
def baseNumbers(seq):
"""
Counts the number of each base in the string. Currently only accepts g,c,a,t bases.
Input
seq = string of valid DNA bases
Output
storage = dict with lowercase base letters as keys and count of each in seq as values.
"""
# Expects a string
# Returns a dict with the counts for each base
seq = seq.lower()
storage = {'g':0,'c':0,'a':0,'t':0}
for eachBase in seq:
storage[eachBase] += 1
return(storage)
|
def isBalanced(s):
"""
Checks if a string has balanced parentheses. This method can be easily extended to
include braces, curly brackets etc by adding the opening/closing equivalents
in the obvious places.
"""
expr = ''.join([x for x in s if x in '()'])
if len(expr)%2!=0:
return False
opening=set('(')
match=set([ ('(',')') ])
stack=[]
for char in expr:
if char in opening:
stack.append(char)
else:
if len(stack)==0:
return False
lastOpen=stack.pop()
# This part only becomes relevant if other entities (like braces) are allowed
# if (lastOpen, char) not in match:
# return False
return len(stack)==0
|
def distance_paris(lat1, lng1, lat2, lng2):
"""
Distance euclidienne approchant la distance de Haversine
(uniquement pour Paris).
@param lat1 lattitude
@param lng1 longitude
@param lat2 lattitude
@param lng2 longitude
@return distance
"""
return ((lat1 - lat2) ** 2 + (lng1 - lng2) ** 2) ** 0.5 * 90
|
def exception_class(name):
"""declare exception class"""
return "class {0}(UserError):\n pass".format(name)
|
def avg_dicts(dict1, dict2):
"""
merge two dictionaries and avg their values
:param dict1:
:param dict2:
:return:
"""
from collections import Counter
sums = Counter()
counters = Counter()
for itemset in [dict1, dict2]:
sums.update(itemset)
counters.update(itemset.keys())
return {x: float(sums[x])/counters[x] for x in sums.keys()}
|
def bin_retweet_count(retweets: float) -> str:
"""Fcn to bin retweet counts via if-else statements, rather than cut()
function, to compare performance of computation in Class 5.
Arguments:
- retweets: number of retweets in millions
Returns:
- categorical variable grouping retweets into one of four buckets
"""
if retweets < 10:
retweet_cat_group = "<10"
elif (retweets >= 10) & (retweets < 50):
retweet_cat_group = "10-50"
elif (retweets >= 50) & (retweets < 150):
retweet_cat_group = "50-150"
else:
retweet_cat_group = "150+"
return retweet_cat_group
|
def cut(value, arg):
"""Removes all values of arg from the given string"""
if arg:
return value.replace(arg, '')
else:
return "#"
|
def try_parse_float(possible_float):
"""Try to parse a float."""
try:
return float(possible_float)
except (TypeError, ValueError):
return 0.0
|
def ConvertLotType(aLotType,aIncludePossible):
"""
Returns a list of strings to query LotType on
Keyword arguments:
aLotType -- integer value representing Lot Type -- 0 = both, 1 = Vacant Lot, 2 = Vacant Building
aIncludePossible -- boolean value, if true will include possible vacant lot or possible vacant building in query strings
"""
# initialize empty list
query_strings = []
if aLotType == 0 or aLotType == 1:
query_strings.append("Vacant Lot")
if aIncludePossible:
query_strings.append("Possible Vacant Lot")
if aLotType == 0 or aLotType == 2:
query_strings.append("Vacant Building")
if aIncludePossible:
query_strings.append("Possible Vacant Building")
return query_strings
|
def title_case(value):
"""Return the specified string in title case."""
return " ".join(word[0].upper() + word[1:] for word in value.split())
|
def split_polygon(polygon):
"""Split polygon array to string.
:param polygon: list of array describing polygon area e.g.
'[[28.01513671875,-25.77516058680343],[28.855590820312504,-25.567220388070023],
[29.168701171875004,-26.34265280938059]]
:type polygon: list
:returns: A string of polygon e.g. 50.7 7.1 50.7 7.12 50.71 7.11
:rtype: str
"""
if len(polygon) < 3:
raise ValueError(
'At least 3 lat/lon float value pairs must be provided')
polygon_string = ''
for poly in polygon:
polygon_string += ' '.join(map(str, poly))
polygon_string += ' '
return polygon_string.strip()
|
def best_ss_to_expand_greedy(new_set, supersets, ruleWeights, max_mask):
""" Returns index of the best superset to expand, given the rule
weights and the maximum allowed mask size. -1 if none possible.
"""
bestSuperset = None
bestCost = float('inf')
new_set = set(new_set)
for superset in supersets:
# if this merge would exceed the current mask size limit, skip it
if len(new_set.union(superset)) > max_mask:
continue
# the rule increase is the sum of all rules that involve each part added to the superset
cost = sum(ruleWeights[part] for part in new_set.difference(superset))
if cost < bestCost:
bestCost = cost
bestSuperset = superset
# if no merge is possible, return -1
if bestSuperset == None:
return -1
return supersets.index(bestSuperset)
|
def GMLstring2points(pointstring):
"""Converts the list of points in string (GML) to a list."""
listPoints = []
#-- List of coordinates
coords = pointstring.split()
#-- Store the coordinate tuple
assert(len(coords) % 3 == 0)
for i in range(0, len(coords), 3):
listPoints.append([coords[i], coords[i+1], coords[i+2]])
return listPoints
|
def is_empty (l):
"""
Returns true if the list is empty, false else.
:param l: The list
:type l: dict
:rtype: boolean
"""
return l == { "head" : None, "tail" : None }
|
def prob17(limit=1000):
"""
If the numbers 1 to 5 are written out in words: one, two, three, four,
five, then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total.
If all the numbers from 1 to 1000 (one thousand) inclusive were written out
in words, how many letters would be used?
NOTE: Do not count spaces or hyphens. For example, 342 (three hundred and
forty-two) contains 23 letters and 115 (one hundred and fifteen) contains
20 letters. The use of "and" when writing out numbers is in compliance with
British usage.
"""
digits = {1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five',
6: 'six', 7: 'seven', 8: 'eight', 9: 'nine'}
exceptions = {10: 'ten', 11: 'eleven', 12: 'twelve', 14: 'fourteen'}
bases = {2: 'twen', 3: 'thir', 4: 'for', 5: 'fif',
6: 'six', 7: 'seven', 8: 'eigh', 9: 'nine'}
powers = {1: 'teen', 10: 'ty', 100: 'hundred', 1000: 'thousand'}
count = 0
for num in range(1, limit + 1):
right = str(num)[-2:]
#print right
if int(right) == 0:
pass
elif int(right) in exceptions:
count += len(exceptions[int(right)])
elif 10 < int(right) < 20:
count += len(bases[int(right[1])]) + len(powers[1])
else:
if right[-1] != '0':
count += len(digits[int(right[-1])])
if len(right) == 2 and right[0] != '0':
count += len(bases[int(right[0])]) + len(powers[10])
if len(str(num)) > 2:
left = str(num)[:-2]
#print left
if right != '00':
count += 3
if left[-1] != '0':
count += len(digits[int(left[-1])]) + len(powers[100])
if len(left) == 2 and left[0] != '0':
count += len(digits[int(left[0])]) + len(powers[1000])
return count
|
def gray_code_sequence_string(bit_count: int) -> list:
"""
Will output the n-bit grey sequence as a
string of bits
>>> gray_code_sequence_string(2)
['00', '01', '11', '10']
>>> gray_code_sequence_string(1)
['0', '1']
"""
# The approach is a recursive one
# Base case achieved when either n = 0 or n=1
if bit_count == 0:
return ["0"]
if bit_count == 1:
return ["0", "1"]
seq_len = 1 << bit_count # defines the length of the sequence
# 1<< n is equivalent to 2^n
# recursive answer will generate answer for n-1 bits
smaller_sequence = gray_code_sequence_string(bit_count - 1)
sequence = []
# append 0 to first half of the smaller sequence generated
for i in range(seq_len // 2):
generated_no = "0" + smaller_sequence[i]
sequence.append(generated_no)
# append 1 to second half ... start from the end of the list
for i in reversed(range(seq_len // 2)):
generated_no = "1" + smaller_sequence[i]
sequence.append(generated_no)
return sequence
|
def get_distance(sigma_phi_1, sigma_phi_2, mean_phi_1, mean_phi_2, phi_1, phi_2):
"""
Returns the "distance" that an object has relative to a specific region in terms of phi_1 and phi_2 considering the standar deviation.
Arguments:
sigma_phi_1 {float} - Standard deviation in phi_1 axis.
sigma_phi_2 {float} - Standard deviation in phi_2 axis.
mean_phi_1 {float} - Mean or center of the region in phi_1 axis.
mean_phi_2 {float} - Mean or center of the region in phi_2 axis.
phi_1 {float} - Center of the object in phi_1 axis.
phi_2 {float} - Center of the object in phi_2 axis.
Returns:
Float -- Distance between the center of the object and the center of the region.
"""
return ( ( phi_1 - mean_phi_1 ) / sigma_phi_1 )**2 + ( ( phi_2 - mean_phi_2 ) / sigma_phi_2 )**2
# return ( phi_1 - mean_phi_1 )**2 + ( phi_2 - mean_phi_2 )**2
|
def arr_startswith(input_str, match_arr):
"""
Test if string starts with any member of array.
Arguments:
input_str (str): String to check against.
match_arr (list): List of items to check for.
Returns:
True if input_str starts with amy member of match_arr
"""
for item in match_arr:
if input_str.startswith(item):
return True
return False
|
def validate_new_patient(in_data): # test
"""Validates input to add_new_patient for correct fields
Args:
in_data: dictionary received from POST request
Returns:
boolean: if in_data contains the correct fields
"""
expected_keys = {"patient_id", "attending_email", "patient_age"}
for key in in_data.keys():
if key not in expected_keys:
return False
return True
|
def compare_dataIds(dataIds_1, dataIds_2):
"""Compare two list of dataids.
Return a list of dataIds present in 'raw' or 'eimage' (1) but not in 'calexp' (2).
"""
print("INFO %i input dataIds found" % len(dataIds_1))
print("INFO %i calexp dataIds found" % len(dataIds_2))
dataIds_1 = [{k: v for k, v in d.items() if k != 'snap'} for d in dataIds_1]
return [dataid for dataid in dataIds_1 if dataid not in dataIds_2]
|
def is_int(string):
"""
Check if string is an integer
:param string:
:return: True or false
"""
try:
int(string)
return True
except ValueError:
return False
|
def compute_hash(test):
"""
Computes a unique hash for a test
"""
result = ""
for val in test:
result += val
return result
|
def get_key_value(obj, key):
"""Get value for a nested key using period separated accessor
:param dict obj: Dict or json-like object
:param str key: Key, can be in the form of 'key.nestedkey'
"""
keys = key.split(".")
if len(keys) == 1:
return obj.get(keys[0])
else:
return get_key_value(obj.get(keys[0]), ".".join(keys[1:]))
|
def autocomplete_query(term, orgtype="all"):
"""
Look up an organisation using the first part of the name
"""
doc = {
"suggest": {
"suggest-1": {
"prefix": term,
"completion": {"field": "complete_names", "fuzzy": {"fuzziness": 1}},
}
}
}
# if not orgtype or orgtype == 'all':
# orgtype = [o.slug for o in OrganisationType.objects.all()]
# elif orgtype:
# orgtype = orgtype.split("+")
# doc["suggest"]["suggest-1"]["completion"]["contexts"] = {
# "organisationType": orgtype
# }
return doc
|
def to_decimal(num, base, alphabet='0123456789abcdefghijklmnopqrstuvwxyz'):
"""Converts a number from some base to decimal.
alphabet: 'digits' that the base system uses"""
using = str(num)[::-1]
res = 0
for i in range(len(using)):
res += alphabet.find(using[i])*base**i
return res
|
def flatten(lst):
"""Flatten a 2D array."""
return [item for sublist in lst for item in sublist]
|
def _dump_multilinestring(obj, fmt):
"""
Dump a GeoJSON-like MultiLineString object to WKT.
Input parameters and return value are the MULTILINESTRING equivalent to
:func:`_dump_point`.
"""
coords = obj['coordinates']
mlls = 'MULTILINESTRING (%s)'
linestrs = ('(%s)' % ', '.join(' '.join(fmt % c for c in pt)
for pt in linestr) for linestr in coords)
mlls %= ', '.join(ls for ls in linestrs)
return mlls
|
def get_html_result(params):
"""
Get the result html string of the macro
"""
html_str = """<div> Model succesfully deployed to API designer </div>
<div>Model folder : %s</div>
<div>API service : %s</div>
<div>Endpoint : %s</div>
<a href="https://www.w3schools.com">See Service in API designer</a>
""" % (params.get('model_folder_id'), params.get('service_id'), params.get('endpoint_id'))
return html_str
|
def longest_increasing_subsequence_optimized2(sequence):
"""
Optimized dynamic programming algorithm for
counting the length of the longest increasing subsequence
using segment tree data structure to achieve better complexity
type sequence: list[int]
rtype: int
"""
length = len(sequence)
tree = [0] * (length<<2)
sorted_seq = sorted((x, -i) for i, x in enumerate(sequence))
def update(pos, left, right, target, vertex):
if left == right:
tree[pos] = vertex
return
mid = (left+right)>>1
if target <= mid:
vertex(pos<<1, left, mid, target, vertex)
else:
vertex((pos<<1)|1, mid+1, right, target, vertex)
tree[pos] = max(tree[pos<<1], tree[(pos<<1)|1])
def get_max(pos, left, right, start, end):
if left > end or right < start:
return 0
if left >= start and right <= end:
return tree[pos]
mid = (left+right)>>1
return max(get_max(pos<<1, left, mid, start, end),
get_max((pos<<1)|1, mid+1, right, start, end))
ans = 0
for tup in sorted_seq:
i = -tup[1]
cur = get_max(1, 0, length-1, 0, i-1)+1
ans = max(ans, cur)
update(1, 0, length-1, i, cur)
return ans
|
def remove_non_printable_chars(s):
"""
removes
'ZERO WIDTH SPACE' (U+200B)
'ZERO WIDTH NO-BREAK SPACE' (U+FEFF)
"""
return s.replace(u'\ufeff', '').replace(u'\u200f', '')
|
def file_to_string(filename):
""" file contents into a string """
data = ""
try:
with open(filename, 'r') as myfile:
data = myfile.read()
except IOError:
pass
return data
|
def wilight_to_hass_hue(value):
"""Convert wilight hue 1..255 to hass 0..360 scale."""
return min(360, round((value * 360) / 255, 3))
|
def is_special_name(word):
""" The name is specific if starts and ends with '__' """
return word.startswith('__') and word.endswith('__')
|
def single_element(s, or_else=...):
"""Get the element out of a set of cardinality 1"""
if len(s) == 0:
if or_else is not ...:
return or_else
raise ValueError("Set is empty.")
if len(s) > 1:
set_string = " " + "\n ".join(map(repr, s))
raise ValueError("Set contains more than one element."
f"Cannot select successor unambiguously from: \n"
f"{set_string}")
for q in s:
return q
|
def visit_data_missing(idx,row):
"""
Generate a report indicating which Visit Dates are missing.
"""
error = dict()
if row.get('exclude') != 1:
if row.get('visit_ignore___yes') != 1:
if type(row.get('visit_date')) != str:
error = dict(subject_site_id = idx[0],
event_name = idx[1],
error = 'ERROR: Visit date missing.'
)
return error
|
def join_s3_uri(bucket, key):
"""
Join AWS S3 URI from bucket and key.
:type bucket: str
:type key: str
:rtype: str
"""
return "s3://{}/{}".format(bucket, key)
|
def leap_year(year, calendar='standard'):
"""Determine if year is a leap year
Args:
year (numeric)
"""
leap = False
if ((calendar in ['standard', 'gregorian',
'proleptic_gregorian', 'julian']) and
(year % 4 == 0)):
leap = True
if ((calendar == 'proleptic_gregorian') and
(year % 100 == 0) and
(year % 400 != 0)):
leap = False
elif ((calendar in ['standard', 'gregorian']) and
(year % 100 == 0) and (year % 400 != 0) and
(year < 1583)):
leap = False
return leap
|
def _get_y_offset(value, location, side, is_vertical, is_flipped_y):
"""Return an offset along the y axis.
Parameters
----------
value : float
location : {'first', 'last', 'inner', 'outer'}
side : {'first', 'last'}
is_vertical : bool
is_flipped_y : bool
Returns
-------
float
"""
if is_vertical:
if not is_flipped_y:
value = -value
else:
if is_flipped_y:
if (location == "first"
or (side == "first" and location == "outer")
or (side == "last" and location == "inner")):
value = -value
else:
if (location == "last"
or (side == "first" and location == "inner")
or (side == "last" and location == "outer")):
value = -value
return value
|
def has_filtering_tag(task):
"""
Indicates if an Asana task has the opt-out tag
"""
for tag in task["tags"]:
if tag["name"] == "roadmap_ignore":
return False
return True
|
def irb_decay_to_gate_infidelity(irb_decay, rb_decay, dim):
"""
Eq. 4 of [IRB], which provides an estimate of the infidelity of the interleaved gate,
given both the observed interleaved and standard decay parameters.
:param irb_decay: Observed decay parameter in irb experiment with desired gate interleaved between Cliffords
:param rb_decay: Observed decay parameter in standard rb experiment.
:param dim: Dimension of the Hilbert space, 2**num_qubits
:return: Estimated gate infidelity (1 - fidelity) of the interleaved gate.
"""
return ((dim - 1) / dim) * (1 - irb_decay / rb_decay)
|
def format_time(time_us):
"""Defines how to format time in torch profiler Event.
"""
US_IN_SECOND = 1000.0 * 1000.0
US_IN_MS = 1000.0
if time_us >= US_IN_SECOND:
return '{:.3f}s'.format(time_us / US_IN_SECOND)
if time_us >= US_IN_MS:
return '{:.3f}ms'.format(time_us / US_IN_MS)
return '{:.3f}us'.format(time_us)
|
def info_to_context(info):
"""
Convert a CMGroup's ``info`` into a context for HTML templating.
Use some sensible defaults for ordering items.
"""
top_keys = ['notes', 'method_doc', 'sql']
more_keys = [key for key in info.keys() if key not in top_keys]
ordered_keys = top_keys + sorted(more_keys)
ret = []
for item in ordered_keys:
if item in info and info[item]: # Value is not blank
ret.append({'key': item, 'value': info[item]})
return ret
|
def _how(how):
"""Helper function to return the correct resampler
Args:
how:
"""
if how.lower() == "average":
return "mean"
elif how.lower() == "linear":
return "interpolate"
elif how.lower() == "no":
return "max"
else:
return "max"
|
def rotate(scale, n):
""" Left-rotate a scale by n positions. """
return scale[n:] + scale[:n]
|
def nearby_cells(number_of_rows, number_of_columns, index: tuple):
""""
Receives the size of the diagram and an index and returns the cells that are close to it.
"""
row_index = index[0]
column_index = index[1]
is_upper_vertical_edge = row_index == 0
is_lower_vertical_edge = row_index == number_of_rows - 1
is_left_horizontal_edge = column_index == 0
is_right_horizontal_edge = column_index == number_of_columns -1
below = [(row_index+1, column_index)]
above = [(row_index-1, column_index)]
right = [(row_index, column_index + 1)]
left = [(row_index, column_index -1)]
above_left = [(row_index-1, column_index-1)]
above_right = [(row_index-1, column_index+1)]
below_left = [(row_index+1, column_index-1)]
below_right = [(row_index+1, column_index+1)]
if number_of_rows == 1:
if is_left_horizontal_edge:
answer = right
elif is_right_horizontal_edge:
answer = left
else:
answer = left + right
elif number_of_columns == 1:
if is_upper_vertical_edge:
answer = below
elif is_lower_vertical_edge:
answer = above
else:
answer = above + below
else:
if is_upper_vertical_edge and is_left_horizontal_edge:
answer = below + right + below_right
elif is_upper_vertical_edge and is_right_horizontal_edge:
answer = below + left + below_left
elif is_lower_vertical_edge and is_left_horizontal_edge:
answer = above + right + above_right
elif is_lower_vertical_edge and is_right_horizontal_edge:
answer = above + left + above_left
elif is_upper_vertical_edge:
answer = below + right + below_right + left + below_left
elif is_lower_vertical_edge:
answer = above + right + left + above_left + above_right
elif is_left_horizontal_edge:
answer = above + below + right + above_right + below_right
elif is_right_horizontal_edge:
answer = above + below + left + above_left + below_left
else:
answer = above + above_right + above_left + below_left + below_right + below + left + right
return answer
|
def number_to_name(number):
"""
Converts an integer called number to a string.
Otherwise, it sends an error message letting you know that
an invalid choice was made.
"""
if number == 0:
return "rock"
elif number == 1:
return "Spock"
elif number == 2:
return "paper"
elif number == 3:
return "lizard"
elif number == 4:
return "scissors"
else:
return "Not a valid choice"
|
def bash(cmd):
"""
Run a bash-specific command
:param cmd: the command to run
:return: 0 if successful
:raises
CalledProcessError: raised when command has a non-zero result
Note: On Windows, bash and the gcloud SDK binaries (e.g. bq, gsutil) must be in PATH
"""
import subprocess
import platform
bash_cmd = '/bin/bash'
if platform.system().lower().startswith('windows'):
# extensions are not inferred
cmd = cmd.replace('bq ', 'bq.cmd ').replace('gsutil ', 'gsutil.cmd ')
bash_cmd = 'bash'
return subprocess.check_call([bash_cmd, '-c', cmd], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
def strpos(string, search_val, offset = 0):
"""
Returns the position of `search_val` in `string`, or False if it doesn't exist. If `offset` is defined, will start looking if `search_val` exists after the `offset`.
"""
try:
return string[offset:].index(search_val) + offset
except ValueError:
return False
|
def ek_R56Q(cell):
"""
Returns the R56Q reversal potential (in mV) for the given integer index
``cell``.
"""
reversal_potentials = {
1: -96.0,
2: -95.0,
3: -90.5,
4: -94.5,
5: -94.5,
6: -101.0
}
return reversal_potentials[cell]
|
def create_delete_marker_msg(id):
""" Creates a delete marker message.
Marker with the given id will be delete, -1 deletes all markers
Args:
id (int): Identifier of the marker
Returns:
dict: JSON message to be emitted as socketio event
"""
return {'id': id}
|
def choice(value, choices):
"""OpenEmbedded 'choice' type
Acts as a multiple choice for the user. To use this, set the variable
type flag to 'choice', and set the 'choices' flag to a space separated
list of valid values."""
if not isinstance(value, str):
raise TypeError("choice accepts a string, not '%s'" % type(value))
value = value.lower()
choices = choices.lower()
if value not in choices.split():
raise ValueError("Invalid choice '%s'. Valid choices: %s" %
(value, choices))
return value
|
def button_string(channel, function):
"""Returns the string representation of an Extended Mode button."""
return 'CH{:s}_{:s}'.format(channel, function)
|
def is_circular_pattern(digit: int):
"""
Circular primes:
2, 3, 5, 7, 13, 17, 37, 79,
113, 197, 199, 337, 1193, 3779,
11939, 19937, 193939, 199933
:param digit:
:return:
"""
pattern = '1379'
if len(str(digit)) > 1:
for d in str(digit):
if d not in pattern:
return False
return True
|
def avg_relative_error(ground_truth, predictions):
"""calculate the relative error between ground truth and predictions
Args:
ground_truth (dict): the ground truth, with keys and values
predictions (dict): the predictions, with keys and values
Returns:
float: the average relative error
"""
# if len(ground_truth) != len(predictions):
# print("Length mismatch!")
# print("Length of ground_truth is " + str(len(ground_truth)))
# print("Length of predictions is " + str(len(predictions)))
# print("System aborts!")
# sys.exit(1)
relative_errors = []
# ground_truth.pop('9.0', None)
# ground_truth.pop('NULL', None)
# print(ground_truth)
# print(predictions)
for key_gt, value_gt in ground_truth.items():
if (ground_truth[key_gt] != 0):
re = abs(float(ground_truth[key_gt]) -
float(predictions[key_gt])) / float(ground_truth[key_gt])
# print(key_gt + str(re))
relative_errors.append(re)
else:
print(
"Zero is found in ground_truth, so removed to calculate relative error.")
# print(sum(relative_errors))
# print((relative_errors))
# print(len(relative_errors))
return sum(relative_errors) / len(relative_errors)
|
def user_from_face_id(face_id: str) -> str:
"""Returns the name from a face ID."""
return face_id.split("_")[0].capitalize()
|
def get_container_links(name):
"""retrieve the links relevant to the container to get various input arguments, etc."""
api_links = {
"args": "/api/container/args/%s" % (name),
"selflink": "/api/container/%s" % (name),
"labels": "/api/container/labels/%s" % (name),
}
actions = {"view": "/container/%s" % (name), "run": "/container/run/%s" % (name)}
response = {"api": api_links, "actions": actions}
return response
|
def sad_merge_segments(segments):
"""For SAD, segments given a single speaker label (SPEECH) and overlapping segments are merged."""
prev_beg, prev_end = 0.0, 0.0
smoothed_segments = []
for seg in segments:
beg, end = seg[0], seg[2]
if beg > prev_beg and end < prev_end:
continue
elif end > prev_end:
if beg > prev_end:
smooth = [prev_beg, (prev_end - prev_beg), prev_end, "speech"]
smoothed_segments.append(smooth)
prev_beg = beg
prev_end = end
else:
prev_end = end
smooth = [prev_beg, (prev_end - prev_beg), prev_end, "speech"]
smoothed_segments.append(smooth)
return smoothed_segments
|
def splitList(listToSplit, num_sublists=1):
"""
Function that splits a list into a given number of sublists
Reference: https://stackoverflow.com/questions/752308/split-list-into-smaller-lists-split-in-half
"""
length = len(listToSplit)
return [
listToSplit[i * length // num_sublists : (i + 1) * length // num_sublists]
for i in range(num_sublists)
]
|
def convert_name(name):
""" Convert a python distribution name into a rez-safe package name."""
return name.replace('-', '_')
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.