content stringlengths 42 6.51k |
|---|
def trim_description(desc: str, n_words: int) -> str:
"""Return the first `n_words` words of description `desc`/"""
return " ".join(str(desc).split(" ")[0:n_words]) |
def same_spot_check(moves):
"""validate that two cars are not going to the same spot"""
movesaccepted = True
for move in moves:
if move['movestatus']=='rejected':
continue
for other_move in moves:
if (other_move['movestatus']=='rejected') or (
other_move['itemid'] == move['itemid']):
continue
if (move['new_x']==other_move['new_x']) and (
move['new_y']==other_move['new_y']):
#two moves to the same spot
move['movestatus']='rejected'
other_move['movestatus']='rejected'
movesaccepted = False
return movesaccepted |
def obj_to_dict(obj):
"""Converts XML object to an easy to use dict."""
if obj is None:
return None
res = {}
res['type'] = obj.tag
res['id'] = int(obj.get('id'))
res['version'] = int(obj.get('version'))
res['deleted'] = obj.get('visible') == 'false'
if obj.tag == 'node' and 'lon' in obj.keys() and 'lat' in obj.keys():
res['coords'] = (obj.get('lon'), obj.get('lat'))
res['tags'] = {tag.get('k'): tag.get('v') for tag in obj.iterchildren('tag')}
if obj.tag == 'way':
res['refs'] = [x.get('ref') for x in obj.iterchildren('nd')]
elif obj.tag == 'relation':
res['refs'] = [(x.get('type'), x.get('ref'), x.get('role')) for x in obj.iterchildren('member')]
return res |
def hue(p):
"""
Returns the saturation of a pixel.
Gray pixels have saturation 0.
:param p: A tuple of (R,G,B) values
:return: A saturation value between 0 and 360
"""
min_c = min(p)
max_c = max(p)
d = float(max_c - min_c)
if d == 0:
return 0
if max_c == p[0]:
h = (p[1] - p[2]) / d
elif max_c == p[1]:
h = 2 + (p[2] - p[0]) / d
else:
h = 4 + (p[0] - p[1]) / d
h *= 60
if h < 0:
h += 360
return h |
def _destupidize_dict(mylist):
"""The opposite of _stupidize_dict()"""
output = {}
for item in mylist:
output[item['key']] = item['value']
return output |
def cost_function(pos_neg, off_on):
"""
Cost function for a sequence of control messages, lower is better.
:param pos_neg: count of forward<->reverse transitions, cost=10
:param off_on: count of off->on transitions, cost=5
:return: cost
"""
return 10 * pos_neg + 5 * off_on |
def values(dictionaries, key):
"""
Go through the list of dictionaries and add all values of a certain key
to a list.
"""
value_list = []
for item in dictionaries:
if isinstance(item, dict) and key in item:
if item[key] not in value_list:
value_list.append(item[key])
return value_list |
def quote(s):
"""
Quotes a string if it needs it
"""
if " " in s:
return "\"" + s + "\""
else:
return s |
def url_path_join(*pieces):
"""Join components into a relative url.
Use to prevent double slash when joining subpath. This will leave the
initial and final / in place.
Code based on Jupyter notebook `url_path_join`.
"""
initial = pieces[0].startswith('/')
final = pieces[-1].endswith('/')
stripped = [s.strip('/') for s in pieces]
result = '/'.join(s for s in stripped if s)
if initial:
result = '/' + result
if final:
result = result + '/'
if result == '//':
result = '/'
return result |
def g(n):
"""Return the value of G(n), computed recursively.
>>> g(1)
1
>>> g(2)
2
>>> g(3)
3
>>> g(4)
10
>>> g(5)
22
"""
"*** YOUR CODE HERE ***"
if n <= 3:
return n
else:
return g(n - 1) + 2 * g(n - 2) + 3 * g(n - 3) |
def stateVec2stateIndex(sigma,N,typ = 1):
"""
Returns the index m that corresponds to the binary vector sigma_0, where m is a int between 0 and 2**N
typ determins if the neuron activation state is defined in {-1,1} or {0,1}
typ=1 --> {-1,1} typ=0 --> {0,1}
"""
k=int(0)
for i in range(0,N):
k=k+(sigma[i]+typ)/(1+typ)*2**(N-i-1) # typ=1 --> [-1,1] typ=0 --> [0,1]
return int(k) |
def description(d, i, r):
"""Get the description from the item.
:param d: Report definition
:type d: Dict
:param i: Item definition
:type i: Dict
:param r: Meter reading
:type r: usage.reading.Reading
:return: Description from item
:rtype: String
"""
return i.get('description', '') |
def _GenericRetrieve(root, default, path):
"""Given a list of dictionary keys |path| and a tree of dicts |root|, find
value at path, or return |default| if any of the path doesn't exist."""
if not root:
return default
if not path:
return root
return _GenericRetrieve(root.get(path[0]), default, path[1:]) |
def areaTriangle(base: float, height: float) -> float:
"""Finds area of triangle"""
area: float = (height * base) / 2
return area |
def rx_band(freq):
"""
Associate a waveguide band with a frequency
"""
# Which front end channel is this for?
if freq < 2000.:
band = 'L'
elif freq < 5000.:
band = 'S'
elif freq < 10000.:
band = 'X'
elif freq < 40000.:
band = 'Ka'
else:
band = None
return band |
def name_from_canonical_parts(prefix, controller, action, args=None):
"""
Returns the route's name ('admin-users-edit') from the canonical
parts ('admin','users','edit')
"""
route_parts = [prefix, controller, action]
route_parts = [x for x in route_parts if x]
route_name = ':'.join(route_parts)
return route_name |
def get_inplace_score(arr):
"""Reward based on position of item"""
score = 0
for i, val in enumerate(arr):
score += 1 if i == val else 0
return score |
def format_field_display(fields):
"""format the display of missing fields"""
num_fields = len(fields)
if num_fields == 1:
return fields[0]
if num_fields == 2:
return "{} and {}".format(fields[-2], fields[-1])
# field length greater than 2
return "{} and {}".format(", ".join(fields[:-1]), fields[-1]) |
def calc_luminance(cos_a, cos_b, cos_phi, cos_theta, sin_a, sin_b, sin_phi, sin_theta):
"""
Luminance should be equal to:
cosphi*costheta*sinB - cosA*costheta*sinphi -
sinA*sintheta + cosB*(cosA*sintheta - costheta*sinA*sinphi);
:param cos_a:
:param cos_b:
:param cos_phi:
:param cos_theta:
:param sin_a:
:param sin_b:
:param sin_phi:
:param sin_theta:
:return:
"""
return cos_phi * cos_theta * sin_b - \
cos_a * cos_theta * sin_phi - \
sin_a * sin_theta + cos_b * (
cos_a * sin_theta - cos_theta * sin_a * sin_phi
) |
def calculate_s_upper(len_of_auction: float,
quantity_auctioned: int,
l: float,
pa: float) -> float:
"""
Summary line.
Extended description of function.
Parameters
----------
len_of_auction: description
quantity_auctioned: description
l: description
pa: description
Returns
-------
The appropriate integer for that selection.
"""
return min(len_of_auction, quantity_auctioned/l/pa) |
def case_name_to_folder(name):
"""Convert name of case to case folder."""
return name.replace('/', '_') |
def singleline_diff_format(line1, line2, idx):
"""
Inputs:
line1 - first single line string
line2 - second single line string
idx - index of first difference between the lines
Output:
Returns a three line formatted string showing the location
of the first difference between line1 and line2.
If either input line contains a newline or carriage return,
then returns an empty string.
If idx is not a valid index, then returns an empty string.
"""
shorter_length = min(len(line1),len(line2))
lines = line1+line2
# Check for valid input (ie single line & index in range)
if '\n' in lines or '\r' in lines:
return ""
elif idx < 0 or shorter_length < idx:
return ""
# create separator and return output
else:
separator = '=' * idx + '^'
return '\n'.join([line1, separator, line2]) + '\n' |
def lookup_charset(in_charset_name):
""" Provides some additional aliases for text encoding names. """
out_charset_name = in_charset_name
if out_charset_name is not None:
out_charset_name = out_charset_name.lower()
out_charset_name = out_charset_name.replace("-", "_")
if out_charset_name == "windows-1252":
out_charset_name = "cp1252"
return out_charset_name |
def verbosityTranslator(marlinLogLevel):
"""Translate the verbosity level from Marlin to a Gaudi level.
Marlin log level can end with numbers, e.g., MESSAGE4
"""
logLevelDict = {'DEBUG': 'DEBUG',
'MESSAGE': 'INFO',
'WARNING': 'WARNING',
'ERROR': 'ERROR',
'SILENT': 'FATAL',
}
for level, trans in logLevelDict.items():
if marlinLogLevel.startswith(level):
return trans |
def is_vcf_chrom_header(line):
"""
Returns ``True`` if ``line`` is a VCF chrom-definition header line, ``False`` otherwise.
:param line: line from VCF file
:return: ``bool``
"""
if line.startswith('##contig='):
return True
else:
return False |
def create_buckets(lower_bound, upper_bound, bins):
"""
Create a dictionary with bins
:param lower_bound: low range
:param upper_bound: high range
:param bins: number of buckets
:return:
"""
range_value = (upper_bound - lower_bound) / bins
low = lower_bound
buckets = []
if bins == 1:
buckets.append({"lower": low, "upper": low + 1, "bucket": 0})
else:
for i in range(0, bins):
high = low + range_value
buckets.append({"lower": low, "upper": high, "bucket": i})
low = high
# ensure that the upper bound is exactly the higher value.
# Because floating point calculation it can miss the upper bound in the final sum
buckets[bins - 1]["upper"] = upper_bound
return buckets |
def generate_paths(source):
"""
Generate full paths for nested dictionary or alike object
:param source: Input object
:return: List of paths
"""
paths = []
if isinstance(source, dict):
for k, v in source.items():
paths.append([k])
paths += [[k] + x for x in generate_paths(v)]
return paths |
def count_construct_rec(target, word_bank):
"""Counts the number of ways that 'target' can be constructed.
Args:
target (str): The string to be constructed.
word_bank (Iterable[str]): Collection of string from which 'target'
can be constructed.
Returns:
int: The number of ways that the 'target' can be constructed by
concatenating elements of the 'word_bank' array.
"""
if target == '': return 1
total_count = 0
for word in word_bank:
if target.find(word) == 0:
num_ways_rest = count_construct_rec(target[len(word):], word_bank)
total_count += num_ways_rest
return total_count |
def word(a):
"""
This function turns the_word into dashed-word.
:param a: str, a random word chose from the function random_word()
:return: str, the random word as a dashed word.
"""
ans = ''
for i in range(len(a)):
ans += '-'
return ans |
def convert_arg_to_int(cmd_args):
"""Convert str to int as much as possible
:param cmd_args: the sequence of args
:return the sequence of args
"""
args = []
for arg in cmd_args:
if isinstance(arg, str): # Int will cause TypeError
try:
arg = int(arg, 0)
except ValueError:
pass # Unable to convert
args.append(arg)
return args |
def get_file_name(suffix=""):
"""Return report file name with date appended."""
return "hwsurvey-weekly" + suffix + ".json" |
def _get_tensor_name(node_name, output_slot):
"""Get tensor name given node name and output slot index.
Args:
node_name: Name of the node that outputs the tensor, as a string.
output_slot: Output slot index of the tensor, as an integer.
Returns:
Name of the tensor, as a string.
"""
return "%s:%d" % (node_name, output_slot) |
def find_grey_code_bits(num_bits):
"""
Takes in the number of bits and returns a list of unique grey code combinations
"""
if type(num_bits) is not int:
return None
if num_bits <= 0:
return []
final_bits = []
initial_bit = "0" * num_bits
length = 2 if num_bits is 1 else num_bits * num_bits
def make_new_bit(bit_str):
new_bit = bit_str
initial_one = True if bit_str[0] == "1" else False
for i in range(len(bit_str) - 1, -1, -1):
if initial_one and bit_str[i] == "1":
new_bit = bit_str[:i] + "0"
if i + 1 < len(bit_str):
new_bit += bit_str[i+1:]
break
if not initial_one and bit_str[i] == "0":
new_bit = bit_str[:i] + "1"
if i + 1 < len(bit_str):
new_bit += bit_str[i+1:]
break
return new_bit
for i in range(0, length):
temp_bit = initial_bit if i == 0 else final_bits[i - 1]
if i > 0:
temp_bit = make_new_bit(temp_bit)
if i > 0 and temp_bit == initial_bit:
break
final_bits.append(temp_bit)
return final_bits |
def calculate_delays_between_slaves(load_chunks, delay_per_req):
""" Calculate amount of delay to insert between slave invocations"""
delays = []
for chunk in load_chunks:
num_reqs = len(chunk)
delay_for_this_slave = delay_per_req * num_reqs
delays.append(delay_for_this_slave)
return delays |
def clamp(minimum: float, value: float, maximum: float) -> float:
"""Clamp value between given minimum and maximum."""
return max(minimum, min(value, maximum)) |
def sort_dict_keys_by_date(dict_in):
"""dict_in should have a structure dict_in[some_key]["datetime"]; this function
will return a list of some_key.s ordered by the content of the "datetime" entry
under it."""
list_key_datetime = []
for crrt_key in dict_in:
crrt_datetime = dict_in[crrt_key]['datetime']
list_key_datetime.append((crrt_key, crrt_datetime))
sorted_keys = sorted(list_key_datetime, key=lambda x: x[1])
sorted_keys = [x for (x, y) in sorted_keys]
return(sorted_keys) |
def calculate_theory_score(user_answers, actual_answers):
""" Takes 2 dictionaries and compares them for
differences. The result is a percentage and the incorrect answers
"""
total = len(actual_answers)
correct = 0
incorrect_answers = {}
for k in actual_answers.keys():
#If there isn't an answer, set it to someting that will not be correct
if actual_answers[k] == user_answers.get(k, "E"):
correct +=1
else:
incorrect_answers[k] = [actual_answers[k], user_answers.get(k)]
percentage = round(correct / total * 100, 1)
return percentage, incorrect_answers |
def d_sig(f): # pragma: no cover
"""
Calculates the derivative of a sigmoid function
"""
return f * (1 - f) |
def merge_clause_merge_properties(merge_properties):
"""
{sid: properties.sid}
:param merge_properties: The merge properties
:return:
"""
merge_strings = []
for u in merge_properties:
merge_strings.append("{0}: properties.{0}".format(u))
merge_string = ', '.join(merge_strings)
return merge_string |
def validate_tag(string):
""" Extracts a single tag in key[=value] format """
result = {}
if string:
comps = string.split('=', 1)
result = {comps[0]: comps[1]} if len(comps) > 1 else {string: ''}
return result |
def average_error(decay_constant: float, num_qubits: int = 1) -> float:
"""Calculates the average error from the depolarization decay constant.
Args:
decay_constant: Depolarization decay constant.
num_qubits: Number of qubits.
Returns:
Calculated average error.
"""
N = 2 ** num_qubits
return (1 - decay_constant) * (1 - 1 / N) |
def compare_ri_param(registers, params):
"""Return from registers register/immediate parameters for compare."""
return registers[params[0]], params[1], params[2] |
def leap_year(year):
"""
checks year parameter to see if the given year is a leap year.
:param year: accepts INT between 0-9999
:return: BOOLEAN True or False
"""
if year % 400 == 0:
return True
elif year % 100 == 0:
return False
elif year % 4 == 0:
return True |
def check_for_sudoku_success(sudo_list):
"""Check for success of SUDOKU list of list"""
sudo_col_list = []
for row_lst in sudo_list:
if "".join(sorted(row_lst)) != "123456789":
return False
for col_index in range(0, 9):
col_lst = [item[col_index] for item in sudo_list]
sudo_col_list.append(col_lst)
if "".join(sorted(col_lst)) != "123456789":
return False
row_index = 0
col_index = 0
while row_index < 9:
col_index = 0
while col_index < 9:
small_sqr_list = []
for row_internal_index in range(row_index, row_index+3):
for col_internal_index in range(col_index, col_index+3):
small_sqr_list.append(sudo_list[row_internal_index][col_internal_index])
if "".join(sorted(small_sqr_list)) != "123456789":
return False
col_index += 3
row_index += 3
return True |
def ensure_scripts(linux_scripts):
"""Creates the proper script names required for each platform
(taken from 4Suite)
"""
from distutils import util
if util.get_platform()[:3] == 'win':
scripts_ = [script + '.bat' for script in linux_scripts]
else:
scripts_ = linux_scripts
return scripts_ |
def staying_alive_reward(nobs, agent_id):
"""
Return a reward if the agent with the given id is alive.
:param nobs: The game state
:param agent_id: The agent to check
:return: The reward for staying alive
"""
#print(nobs[0]['position'][0])
if agent_id in nobs[0]['alive']:
return 1.0
else:
return 0.0 |
def distance(strand_a, strand_b):
"""Return the hamming distance of given strands of DNA"""
if len(strand_a) != len(strand_b):
raise ValueError("Strand length doesn't match")
return sum(1 for a,b in zip(strand_a, strand_b) if a != b) |
def _wsURL(url):
"""internal"""
return "/1.0/" + url |
def change_label2idx(train_meta, label2idx={}):
""" change label to index
Parameters
----------
train_meta
label2idx
Returns
-------
"""
for name, train in train_meta.items():
for i, vs in enumerate(train):
train_meta[name][i] = (vs[0], vs[1], vs[2], label2idx[vs[2]]) # (video_path, feature, y_label, y_idx)
return train_meta |
def decode_varint(buffer, pos=0):
""" Decode an integer from a varint presentation. See
https://developers.google.com/protocol-buffers/docs/encoding?csw=1#varints
on how those can be produced.
Arguments:
buffer (bytearry): buffer to read from.
pos (int): optional position to read from
Returns:
(int, int): Decoded int value and next read position
"""
result = buffer[pos]
if not (result & 0x81):
return (result >> 1), pos + 1
if not (result & 0x80):
return (result >> 1) ^ (~0), pos + 1
result &= 0x7f
pos += 1
shift = 7
while 1:
b = buffer[pos]
result |= ((b & 0x7f) << shift)
pos += 1
if not (b & 0x80):
return ((result >> 1) ^ -(result & 1), pos)
shift += 7
if shift >= 64:
raise ValueError("Out of int64 range") |
def int_to_padded_hex_byte(integer):
"""
Convert an int to a 0-padded hex byte string
example: 65 == 41, 10 == 0A
Returns: The hex byte as string (ex: "0C")
"""
to_hex = hex(integer)
xpos = to_hex.find('x')
hex_byte = to_hex[xpos+1 : len(to_hex)].upper()
if len(hex_byte) == 1:
hex_byte = ''.join(['0', hex_byte])
return hex_byte |
def center_move(possible_moves):
"""A player marks the center.
>>> center_move([2, 5, 8])
>>> 5
"""
if 5 in possible_moves:
return 5 |
def check_sofware_if_exists(package_name, package_names, packages):
""" A function to check if the package exists already in the json
:returns none if doesn't exist
:returns package already defined if exists
"""
# If we already have the package
if package_name in package_names:
for temp_package in packages:
if temp_package.package_name == package_name:
return temp_package
return None |
def make_new_get_user_response(row):
""" Returns an object containing only what needs to be sent back to the user. """
return {
'userName': row['userName'],
'categories': row['categories'],
'imageName': row['imageName'],
'refToImage': row['refToImage'],
'imgDictByTag': row['imgDictByTag'],
'canView': row['canView'],
'imgDictByImage': row['imgDictByImage']
} |
def find_replace(search_dict, field_value, replace=None):
"""
Takes a dict with nested lists and dicts,
and searches all dicts for a value of the field
provided, replacing if desired.
"""
fields_found = []
for key, value in search_dict.items():
if value == field_value:
fields_found.append(value)
if replace:
search_dict[key] = replace
elif isinstance(value, dict):
results = find_replace(value, field_value, replace)
for result in results:
fields_found.append(result)
elif isinstance(value, list):
for item in value:
if isinstance(item, dict):
more_results = find_replace(item, field_value, replace)
for another_result in more_results:
fields_found.append(another_result)
return fields_found |
def in_green(s: str) -> str:
"""Return string formatted in red."""
return f"\033[92m{str(s)}\033[0m" |
def build_data_pipeline(chain, **kwargs):
"""
Chain of responsibility pattern
:param chain: array of callable
:param **kwargs: any kwargs you like
"""
kwargdict = kwargs
for call in chain:
kwargdict = call(**kwargdict)
return kwargdict |
def concatenate_payload_settings(settings):
"""Takes a list of dictionaries, removed duplicate entries and concatenates an array of settings for the same key
"""
settings_list = []
settings_dict = {}
for item in settings:
for key, value in item.items():
if isinstance(value, list):
settings_dict.setdefault(key, []).append(value[0])
else:
settings_dict.setdefault(key, value)
if item not in settings_list:
settings_list.append(item)
return [settings_dict] |
def schema_to_json(schema: dict, indent: int = 2) -> str:
"""Convert the given JSON schema (dict) into a JSON string."""
import json
return json.dumps(schema, indent=indent) |
def dflt_label_weighter(test_label, gold_label):
"""
Return score corresponding to the weight to add for matching
test_label and gold_label in the default Smatch setting.
"""
if test_label.lower() == gold_label.lower():
return 1.0
else:
return 0.0 |
def func_namespace(func):
"""Generates a unique namespace for a function"""
kls = None
if hasattr(func, 'im_func'):
kls = func.im_class
func = func.im_func
if kls:
return '%s.%s' % (kls.__module__, kls.__name__)
else:
return func.__module__ |
def translate_severity(sev):
"""
Translates Prisma Cloud Compute alert severity into Demisto's severity score
"""
sev = sev.capitalize()
if sev == 'Critical':
return 4
elif sev == 'High':
return 3
elif sev == 'Important':
return 3
elif sev == 'Medium':
return 2
elif sev == 'Low':
return 1
return 0 |
def len_float_or_list(var):
"""
Helper function for handling cases where only one epoch was run.
These abnormal cases result in a float instead of a list, hence len() would create an exception.
"""
if type(var) == list:
return len(var)
elif type(var) == float:
return 1
else:
return len(var) |
def arange(a, b, inc=1):
"""
Generate an array of integers from (a, b) with increment of inc
@param a int start of range (inclusive)
@param b int end of range (inclusive)
@param inc float
"""
x = [a]
i = 0
while x[i]+inc <= b:
x.append(x[i]+inc)
i += 1
return x |
def get_bounds(points):
"""
return bounding box of a list of gpxpy points
"""
min_lat = None
max_lat = None
min_lon = None
max_lon = None
min_ele = None
max_ele = None
for point in points:
if min_lat is None or point.latitude < min_lat:
min_lat = point.latitude
if max_lat is None or point.latitude > max_lat:
max_lat = point.latitude
if min_lon is None or point.longitude < min_lon:
min_lon = point.longitude
if max_lon is None or point.longitude > max_lon:
max_lon = point.longitude
if min_ele is None or point.elevation < min_ele:
min_ele = point.elevation
if max_ele is None or point.elevation > max_ele:
max_ele = point.elevation
if min_lat and max_lat and min_lon and max_lon:
return {'min_latitude': min_lat, 'max_latitude': max_lat,
'min_longitude': min_lon, 'max_longitude': max_lon,
'min_elevation': min_ele, 'max_elevation': max_ele,
}
return None |
def isnan(x):
"""Is x 'Not a Number'? fail-safe version"""
from numpy import isnan
try: return isnan(x)
except: return True |
def greedyAdvisor(subjects, maxWork, comparator):
"""
Returns a dictionary mapping subject name to (value, work) which includes
subjects selected by the algorithm, such that the total work of subjects in
the dictionary is not greater than maxWork. The subjects are chosen using
a greedy algorithm. The subjects dictionary should not be mutated.
subjects: dictionary mapping subject name to (value, work)
maxWork: int >= 0
comparator: function taking two tuples and returning a bool
returns: dictionary mapping subject name to (value, work)
"""
select_subs = {}
left = maxWork
while left > 0:
best = None
for name in subjects.keys():
if name in select_subs:
continue
work = subjects.get(name)[1]
if (best == None or comparator(subjects[name], subjects[best])) and work <= left:
best = name
if best == None or subjects[best][1] > left:
break
select_subs[best] = subjects[best]
left = left - subjects[best][1]
return select_subs |
def replace_spaces_list(s):
"""In-place replacement using a list."""
n = len(s)
if n == 0:
return s
s_list = list(s)
old = ' '
new = list('%20')
i = 0
while i < n:
if s_list[i] == old:
# Shift right two characters
s_list.extend(['', ''])
for j in range(n-1, i, -1):
s_list[j+2] = s_list[j]
s_list[i: i+3] = new
i += 3
n += 2
else:
i += 1
return ''.join(s_list) |
def get_version_tag(api_major):
"""Args:
api_major: int DataONE API major version. Valid versions are currently 1 or 2.
Returns: str: DataONE API version tag. Valid version tags are currently ``v1`` or
``v2``.
"""
return "v{}".format(api_major) |
def is_status(byte):
"""Return True if the given byte is a MIDI status byte, False otherwise."""
return (byte & 0x80) == 0x80 |
def find_min(node):
"""Find min value node"""
while node and node.left:
node = node.left
return node |
def column2list(matrix: list, column_idx: int) -> list:
"""
Convert column from features 2D matrix to 1D list of
that feature.
:param matrix: 2D square array of number
:param column_idx: column index in the matrix
:return:
"""
if len(matrix) <= 1:
return matrix if matrix else []
if column_idx >= len(matrix[0]):
return [-1]
new_column = []
for line in matrix:
new_column.append(line[column_idx])
return new_column |
def round_time(time_string, base=5):
"""
Round time to the nearest base so that minute hand on time will look nicer in db
Parameters
----------
time_string: str
minute hand you wish to round: 08 -> 05
base: int
round to the nearest base
"""
rounded = str(base * round(int(time_string)/base))
if len(rounded) == 1:
rounded = "0" + rounded
return rounded |
def find(haystack, needle):
"""
>>> find("ll", "hello")
-1
>>> find("", "")
0
>>> find("hello", "ll")
2
>>> find("aaaaabba", "bba")
5
>>> find("bbaaaaaa", "bba")
0
>>> find("aaaaa", "bba")
-1
"""
m = len(haystack)
n = len(needle)
if m < n:
return -1
if m == n == 0:
return 0
i = j = 0
while i < m and j < n:
if haystack[i] == needle[j]:
j += 1
else:
i -= j
j = 0
if j == n:
return i-j+1
i += 1
return -1 |
def remove_es_keys(hit):
"""
Removes ES keys from a hit object in-place
Args:
hit (dict): Elasticsearch hit object
Returns:
dict: modified Elasticsearch hit object
"""
del hit['_id']
if '_type' in hit:
del hit['_type']
return hit |
def is_empty(content: str):
"""
:param content:
:return: is empty
"""
if content is None or len(content.strip()) == 0:
return True
return False |
def is_normal_triple(triples, is_relation_first=False):
"""
normal triples means triples are not over lap in entity.
example [e1,e2,r1, e3,e4,r2]
:param triples
:param is_relation_first
:return:
>>> is_normal_triple([1,2,3, 4,5,0])
True
>>> is_normal_triple([1,2,3, 4,5,3])
True
>>> is_normal_triple([1,2,3, 2,5,0])
False
>>> is_normal_triple([1,2,3, 1,2,0])
False
>>> is_normal_triple([1,2,3, 4,5,0], is_relation_first=True)
True
>>> is_normal_triple([1,2,3, 4,5,3], is_relation_first=True)
False
>>> is_normal_triple([1,2,3, 2,5,0], is_relation_first=True)
True
>>> is_normal_triple([1,2,3, 1,2,0], is_relation_first=True)
False
"""
entities = set()
for i, e in enumerate(triples):
key = 0 if is_relation_first else 2
if i % 3 != key:
entities.add(e)
return len(entities) == 2 * len(triples) // 3 |
def create_validator_config(name, options={}): # lint-amnesty, pylint: disable=dangerous-default-value
"""
This function is meant to be used for testing purposes to create validators
easily. It returns a validator config of the form:
{
"NAME": "common.djangoapps.util.password_policy_validators.SymbolValidator",
"OPTIONS": {"min_symbol": 1}
}
Parameters:
name (str): the path name to the validator class to instantiate
options (dict): The dictionary of options to pass in to the validator.
These are used to initialize the validator with parameters.
If undefined, the default parameters will be used.
Returns:
Dictionary containing the NAME and OPTIONS for the validator. These will
be used to instantiate an instance of the validator using Django.
"""
if options:
return {'NAME': name, 'OPTIONS': options}
return {'NAME': name} |
def ensure_sequence(obj):
"""If `obj` isn't a tuple or list, return a tuple containing `obj`."""
if isinstance(obj, (tuple, list)):
return obj
else:
return (obj,) |
def change_interface(step):
""" Changes the html.Div of whole page according to the step selected """
if step == 1:
return {'textAlign': 'center'}
else:
return {'display': 'none'} |
def is_self_eating(snake):
"""input must be list or tuple"""
head = snake[0]
for segment in snake[1:]:
if head == segment:
return True
return False |
def get_outer_boundaries(regions, cls, rest_cls):
"""
Assuming rest periods alternate with other classes, find the
outer boundaries of the rest regions enclosing all regions for cls
>>> l = [0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 2, 0, 3, 3, 0, 4]
>>> d = get_regions(l)
>>> get_outer_boundaries(d, 1, 0)
(0, 12)
>>> get_outer_boundaries(d, 2, 0)
(10, 14)
>>> get_outer_boundaries(d, 4, 0)
(16, 18)
"""
my_start = regions[cls][0][0]
my_end = regions[cls][-1][-1]
first = my_start # the rest region preceding will end at this point
last = my_end # the following rest region will start at this point
for r in regions[rest_cls]:
if r[1] == my_start:
first = r[0]
if r[0] == my_end:
last = r[1]
break
return (first, last) |
def make_modifier_resized(target_size):
"""Make a string designating a resize transformation.
Note that the final image size may differ slightly from this size as
it only reflects the size targeted.
Args:
target_size: Target size of rescaling in x,y,z.
Returns:
String designating the resize transformation.
"""
return "resized({},{},{})".format(*target_size) |
def clamp(value, low, high):
"""Returns a value that is no lower than 'low' and no higher than 'high'."""
return max(min(value, high), low) |
def getToken(tokenList, expected):
""" removes the expected token from the token list """
if tokenList[0] == expected:
del tokenList[0]
return True
else:
return False |
def _slider_range_to_slice(range_value_tuple, max):
"""Transform a tuple into a slice accounting for overlapping"""
if range_value_tuple[0] != range_value_tuple[1]:
return slice(*range_value_tuple)
if range_value_tuple[1] != max:
return slice(range_value_tuple[0], range_value_tuple[1]+1)
return slice(range_value_tuple[0]-1, range_value_tuple[1]) |
def second_largest(numbers): #found online, link unavailable
""" return the second highest number of a list"""
count = 0
m1 = m2 = float('-inf')
for x in numbers:
count += 1
if x > m2:
if x >= m1:
m1, m2 = x, m1
else:
m2 = x
return m2 if count >= 2 else None |
def decode(data):
"""
Decode byte to string in utf-8
:param data: Byte or str
:return: Decoded string
:raises: TypeError
"""
if isinstance(data, str):
return data
elif isinstance(data, bytes):
return bytes.decode(data)
else:
return str(data) |
def _var_length_field(field: bytes) -> bytes:
"""Returns the message representation of a variable length field
(currently just length + field)"""
if len(field) > 255:
# Length has to be representable by one byte
raise ValueError("Var fields cannot exceed 255 bytes")
return bytes([len(field)]) + field |
def name_to_id(s):
"""Generate block identifier from url string
Example input:
al/2013/100cm/rgb/30085/m_3008501_ne_16_1_20130928.tif
"""
# cell: 30085
# stem: m_3008501_ne_16_1_20130928.tif
cell, stem = s.split('/')[4:]
# Keep text before date
# m_3008501_ne_16_1_
stem = stem[:18]
# Concatenate
return f'{cell}/{stem}' |
def formatlink(value):
"""
>>> formatlink({'url': 'https://example.com'})
'https://example.com'
>>> formatlink({'url': 'https://example.com', 'title': 'Example'})
'[Example](https://example.com)'
"""
if value.get('title') is None:
return value['url']
return '[{title}]({url})'.format_map(value) |
def unique_count(value):
"""Count the number of unique characters in the string representation of a
scalar value.
Parameters
----------
value: scalar
Scalar value in a data stream.
Returns
-------
int
"""
unique = set()
for c in str(value):
unique.add(c)
return len(unique) |
def transfer_mac(mac):
"""Transfer MAC address format from xxxx.xxxx.xxxx to xx:xx:xx:xx:xx:xx"""
mac = ''.join(mac.split('.'))
rslt = ':'.join([mac[e:e + 2] for e in range(0, 11, 2)])
return rslt |
def move_left(point):
"""Return a copy of `point`, moved left along the X-axis by 1.
This function returns a tuple, not a Vector2D instance, and should only be
used if performance is essential. Otherwise, the recommended alternative is
to write `point + LEFT`.
"""
x, y = point
return x - 1, y |
def pythonize_path(path):
""" Replace argument to valid python dotted notation.
ex. foo/bar/baz -> foo.bar.baz
"""
return path.replace('/', '.') |
def f_missing(a, b):
"""Function f
Parameters
----------
a : int
Parameter a
Returns
-------
c : list
Parameter c
"""
c = a + b
return c |
def aa_and(x, y, nx, ny):
"""Dimensionless production rate for a gene regulated by two
activators with AND logic in the absence of leakage.
Parameters
----------
x : float or NumPy array
Concentration of first activator.
y : float or NumPy array
Concentration of second activator.
nx : float
Hill coefficient for first activator.
ny : float
Hill coefficient for second activator.
Returns
-------
output : NumPy array or float
x**nx * y**ny / (1 + x**nx) / (1 + y**ny)
"""
return x ** nx * y ** ny / (1.0 + x ** nx) / (1.0 + y ** ny) |
def get_resource_id(fhir_instance):
"""
Get the resource id stored in the meta field of a fhir document
"""
try:
return fhir_instance["meta"]["tag"][1]["code"]
except (KeyError, IndexError):
return None |
def get_latest(results):
"""Select the latest results"""
if results:
latest = results[0]
for result in results[1:]:
current_version = result['version'][1:] if 'v' in result['version'] else result['version']
latest_version = latest['version'][1:] if 'v' in latest['version'] else latest['version']
if float(current_version) > float(latest_version):
latest = result
else:
latest = []
return latest |
def one_tone_up(freq, amount=1):
"""
Returns the key, one tone up
:param freq: the frequency in hz
:param amount: the amount of tones up
:return: the frequency one tone up in hz
"""
return freq * 2 ** (2 * amount / 12) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.