content stringlengths 42 6.51k |
|---|
def has_equal_letters(word_2):
"""
To check whether the number of vowels is equal to the number of consonants or not .
"""
n=0
for i in range(len(word_2)):
if(word_2[i]=="a" or word_2[i]=="e" or word_2[i]=="i" or word_2[i]=="o" or word_2[i]=="u"):
n+=1;
m=len(word_2)-n
if(m==n):
return(True)
else:
return(False) |
def distance(x_0, y_0, x_1, y_1):
"""Return distance between 2 points (x_0, y_0) and (x_1, y_1)
"""
x_dist = x_0 - x_1
y_dist = y_0 - y_1
return(x_dist ** 2 + y_dist ** 2) ** 0.5 |
def is_available(resource):
"""
Helper to check if resource is available.
"""
return resource.get("status") == "ready" |
def find_divisor(x):
"""Find all divisor of an integer
Args:
x (int)
Returns:
list: list of divisor
"""
divisors = []
for i in range(1, x + 1):
if x % i == 0:
divisors.append(i)
divisors.reverse()
return divisors |
def request_path(environ):
"""Get a requested path from environ"""
path = environ.get('PATH_INFO', '/')
# default index.html
if path == '' or path == '/':
path = '/index.html'
return path |
def cyclic_shift(input_list, n=1):
"""
Applies a cyclic permutation to a list.
:param input_list:
:param n:
:return:
"""
shifted_list = input_list[n:] + input_list[:n]
return shifted_list |
def _get_yaml_from_user_properties(user_properties):
"""Gets yaml text from test report user properties"""
test_yaml = ''
for i, e in enumerate(user_properties):
if e[0] == 'test_yaml':
test_yaml = e[1]
return test_yaml |
def inclusion_explicit_no_context(arg):
"""Expected inclusion_explicit_no_context __doc__"""
return {"result": "inclusion_explicit_no_context - Expected result: %s" % arg} |
def shift_sensitive_region(record: dict, original_name: str, new_name: str):
"""
Function to demote sensitive country names to `area_covered` from `country_territory_area`.
Parameters
----------
record : dict
Input record.
original_name : str
Original country name from provider dataset.
new_name : str
New WHO-recognised country name.
Returns
-------
type
Record with sensitive countries changed.
"""
if record['country_territory_area'] == original_name:
record['area_covered'] = record['country_territory_area']
record['country_territory_area'] = new_name
return(record) |
def process_actor(api_actor):
"""Parse an actor definition from an API result."""
api_actor = api_actor or {}
return {
'id': api_actor.get('id'),
'name': api_actor.get('displayName'),
'url': api_actor.get('url'),
'image_url': api_actor.get('image', {}).get('url'),
} |
def value_or_none(dictionary: dict, key: str):
"""returns value of key from dictionary otherwise if not found None"""
return dictionary[key] if key in dictionary else None |
def binarysearch(array, element):
""" returns index of found element """
# validation
if type(array) != list:
raise TypeError("param @array should be list.")
if type(element) != int:
raise TypeError("param @element should be int.")
left = 0
right = len(array) - 1
while left <= right:
index = (left + right) >> 1
if array[index] == element:
return index
elif array[index] > element:
right = index - 1
else:
left = index + 1
# no element found
return -1 |
def get_create_success_message(name: str, uid: str) -> str:
"""
Returns the templated message for successfully creating a `Student`
"""
msg = f"Student <span class=\"text-primary font-weight-medium\">{name}</span> with\
UID <span class=\"text-secondary font-weight-medium\">{uid}</span>\
was successfully created."
return msg |
def getThingData(serialNumber):
"""Look up data tied to the button. Maps a button serial number to a Machine code in Leading2Lean"""
machineCodeLineMatrix = {
'BUTTON-01-SERIAL': 'GreenMachine',
'BUTTON-02-SERIAL': 'BlueMachine',
'BUTTON-03-SERIAL': 'YellowMachine',
'BUTTON-04-SERIAL': 'OrangeMachine'
}
return {
'machineCode': machineCodeLineMatrix[serialNumber]
} |
def score_purity(memberships, predicted_memberships):
"""
Scores the predicted clustering labels vs true labels using purity.
Parameters
----------
memberships: actual true labels
predicted_memberships: clustering labels
Output
------
a percentage of correct labels
"""
num_nodes = len(memberships)
#identify unique labels
true_labels = set(memberships)
predicted_labels = set(predicted_memberships)
# make a set for each possible label
true_label_sets = {}
predicted_label_sets = {}
for label in true_labels.union(predicted_labels):
true_label_sets[label] = set()
predicted_label_sets[label] = set()
# go through each vertex and assign it to a set based on label
for i in range(num_nodes):
true_label = memberships[i]
predicted_label = predicted_memberships[i]
true_label_sets[true_label].add(i)
predicted_label_sets[predicted_label].add(i)
# now can perfrom purity algorithm
score = 0
for true_label, true_label_set in true_label_sets.items():
max_intersection = 0
for predicted_label, predicted_label_set in predicted_label_sets.items():
intersection = len(set.intersection(predicted_label_set,true_label_set))
if max_intersection < intersection:
max_intersection = intersection
score += max_intersection
# divide score by total vertex count
score = score / num_nodes
return score |
def map_nested(f, itr):
"""apply a function to every element in a 2D nested array"""
return [[f(pt)
for pt in lst]
for lst in itr] |
def create_sorted_weight_history(weight_history, reverse=False):
"""Sorts the provided history by date and returns a list"""
sorted_list = sorted(weight_history, key=lambda x: x[1], reverse=reverse)
return sorted_list |
def get_ndim_first(x, ndim):
"""Return the first element from the ndim-nested list x.
"""
return (x if ndim == 0 else get_ndim_first(x[0], ndim - 1)) |
def _buildTrackLine(id, trackType, trackDict):
"""Builds a mkvMerge -I style track ID line from inputs"""
# Our goal is to construct this:
# Track ID 0: video (V_MPEG4/ISO/AVC) [number:1 uid:1493619965 codec_id:V_MPEG4/ISO/AVC language:eng pixel_dimensions:1920x1080 display_dimensions:1920x1080 default_track:1 forced_track:0 enabled_track:1 packetizer:mpeg4_p10_video default_duration:41708332 content_encoding_algorithms:3]
# From just the id, type and dict. We don't actually care about the codec
# We need to go from:
# {'okay': 'then', 'hello': 'goodbye'}
# To:
# [okay:then hello:goodbye]
trackDict = str(trackDict)
trackDict = trackDict[1:-1] # Remove {}
trackDict = trackDict.replace("'", '')
trackDict = trackDict.replace(': ', ':')
trackDict = trackDict.replace(',', '')
trackDict = '[{trackDict}]'.format(trackDict=trackDict)
trackLine = "Track ID {id}: {trackType} (AWESOME) {trackDict}\r\n".format(
id=id,
trackType=trackType,
trackDict=trackDict
)
return trackLine |
def extend_dictionary(dictionary,titles):
"""
Function to add missing indices to dictionary
:param dictionary: dictionary with given indices
:param titles: titles to add as keys to dictionary
"""
for title in titles:
if not title in dictionary:
dictionary[title] = "NaN"
for title in dictionary:
if title not in titles:
print(title)
return dictionary |
def clean_text(my_str):
"""Removes line-breaks for cleaner CSV storage. Handles string or null value.
Returns string or null value
Param my_str (str)
"""
try:
my_str = my_str.replace("\n", " ")
my_str = my_str.replace("\r", " ")
my_str = my_str.strip()
except AttributeError as err:
pass
return my_str |
def htk_to_sec(htk_time):
"""
Convert time in HTK (100 ns) units to sec
"""
if type(htk_time)==type("string"):
htk_time = float(htk_time)
return htk_time / 10000000.0 |
def serialize_options(options: dict):
"""
given a dict and return html options
:param options: dict with {key1: {'label': 'Label', 'selected': False}}
:return: html options
"""
res = []
for k, v in options.items():
cur = '<option value="{value}" {selected}>{label}</option>'.format(
value=str(k),
selected='selected="selected"' if v.get('selected') else '',
label=str(v.get('label') or k)
)
res.append(cur)
return '\n'.join(res) |
def triangular_wave(x, period, amplitude):
"""
Returns a triangular wave evaluated at x, given its period and amplitude.
Equation source: https://en.wikipedia.org/wiki/Triangle_wave
"""
return (4*amplitude/period) * abs(((x - period/4) % period) - period/2) - amplitude |
def rntoi(numeral_string):
"""roman numeral to decimal integer conversion function."""
if not numeral_string:
return 0
d = { "I" : 1, "V" : 5, "X" : 10, "L" : 50, "C" : 100, "D" : 500, "M" : 1000 }
for ch in numeral_string:
if ch not in d:
return 0
sum = 0
lower_sum = 0
last = numeral_string[0]
lower_sum += d[last]
for ch in numeral_string[1:]:
if d[ch] > d[last]:
sum += d[ch]-lower_sum
lower_sum = 0
elif d[ch] < d[last]:
sum += lower_sum
lower_sum = d[ch]
else:
lower_sum += d[ch]
last = ch
return sum + lower_sum |
def date_range(calstyle, date):
"""Get the date range that the calendar would have when showing a
given date.
"""
if calstyle == 'year':
return date[:4] + '-01-01', date[:4] + '-12-31'
elif calstyle == 'month':
return date[:7] + '-01', date[:7] + '-31'
elif calstyle == 'day':
return date, date |
def str_to_address(v):
"""
:type v: str
"""
if not v:
return None
host, port = v.split(":", 1)
return host, int(port) |
def infer_type(value):
"""Used when loading data into a Mongo collection"""
try:
return int(value)
except ValueError:
pass
try:
return float(value)
except ValueError:
pass
# try:
# return parser.parse(value)
# except ValueError:
# pass
if not len(value):
return None
return value |
def calc_bbox(coordinates, edge=0.15):
""" Calculates bounding box with frame by finidng pair of max and min coordinates
and adding/subtracting edge degrees as the frame
Args:
coordinates (list): list of coordinates
edge (float, optional): Amount to expand/diminish the bounding box by. Defaults to 0.15.
Returns:
bbox (list): A bounding box for the given coordinates
"""
# Create bounding box with frame by finidng pair of max and min coordinates and adding/subtracting edge degrees as the frame
bbox = [[max([item[0] for item in coordinates]) + edge, max([item[1] for item in coordinates]) + edge],
[min([item[0] for item in coordinates]) - edge, min([item[1] for item in coordinates]) - edge]]
return bbox |
def isprime(n):
"""Returns True if n is prime."""
if n == 2:
return True
if n == 3:
return True
if n % 2 == 0:
return False
if n % 3 == 0:
return False
i = 5
w = 2
while i ** 2 <= n:
if n % i == 0:
return False
i += w
w = 6 - w
return True |
def get_file_mode_for_reading(context_tar):
"""Get file mode for reading from tar['format'].
This should return r:*, r:gz, r:bz2 or r:xz. If user specified something
wacky in tar.Format, that's their business.
In theory r:* will auto-deduce the correct format.
"""
format = context_tar.get('format', None)
if format or format == '':
mode = f"r:{format}"
else:
mode = 'r:*'
return mode |
def Main(a, b):
"""
:param a:
:param b:
:return:
"""
if a > b:
return 3
return 2 |
def divide_up(num):
"""
takes num (int) e.g. 1234567 and outputs [1, 234, 567]
"""
num_str = '{:,d}'.format(num)
return(num_str.split(',')) |
def merge_s2_threshold(log_area, gap_thresholds):
"""Return gap threshold for log_area of the merged S2
with linear interpolation given the points in gap_thresholds
:param log_area: Log 10 area of the merged S2
:param gap_thresholds: tuple (n, 2) of fix points for interpolation
"""
for i, (a1, g1) in enumerate(gap_thresholds):
if log_area < a1:
if i == 0:
return g1
a0, g0 = gap_thresholds[i - 1]
return (log_area - a0) * (g1 - g0) / (a1 - a0) + g0
return gap_thresholds[-1][1] |
def idx2rowcol(idx,shape):
"""
Given a flat matrix index and a 2D matrix shape, return the (row,col)
coordinates of the index.
"""
assert len(shape) == 2
rows,cols = shape
return idx/cols,idx%cols |
def remTeamBranchUsage(err=''):
""" Prints the Usage() statement for this method """
m = ''
if len(err):
m += '%s\n\n' %err
m += 'Unlink(s) a Task Branch (TB) from a Team Branch (TmB) on Salesforce.\n'
m += '\n'
m += 'Usage:\n'
m += ' teamunlnbr -s <stream> -n <team name> -t<team Branch> -b <task branch>\n'
m += '\n'
return m |
def _copy_docstring(lib, function):
"""Extract docstring from function."""
import importlib
try:
module = importlib.import_module(lib)
func = getattr(module, function)
doc = func.__doc__
except ImportError:
doc = "Failed to import function {} from {}".format(function, lib)
return doc |
def generate_list(start, stop, step):
"""
>>> generate_list(0, 5, 1)
[0, 1, 2, 3, 4]
>>> generate_list(0, 0, 1)
[]
>>> generate_list(5, 10, 2)
[5, 7, 9]
>>> generate_list(10, 5, -2)
[10, 8, 6]
"""
idx = start
lst = []
if idx < stop:
while idx < stop:
lst.append(idx)
idx += step
else:
while idx > stop:
lst.append(idx)
idx += step
return lst |
def identifier_to_string(identifier):
"""Take an identifier and return in a formatted in single string"""
_id = identifier.get('identifier')
_type = identifier.get('type') or ''
return _type.lower() + ":" + _id |
def _reverse_search_options(search_options):
"""
Reverse the search_options to map a UID to its numeric version
>>> search_options = {1: {'uid': 'Computer.name'}}
>>> _reverse_search_options(search_options)
{'Computer.name': 1, 'name': 1, 1: 1}
"""
rev = {}
for k, v in search_options.items():
try:
rev[v['uid']] = k
rev[v['uid'].split('.', 1)[1]] = k
rev[k] = k
except (KeyError, TypeError):
pass
return rev |
def cigar_to_lens(cigar):
"""Extract lengths from a CIGAR string.
Parameters
----------
cigar : str
CIGAR string.
Returns
-------
int
Alignment length.
int
Offset in subject sequence.
Notes
-----
This function significantly benefits from LRU cache because high-frequency
CIGAR strings (e.g., "150M") are common and redundant calculations can be
saved.
"""
align, offset = 0, 0
n = '' # current step size
for c in cigar:
if c in 'MDIHNPSX=':
if c in 'M=X':
align += int(n)
elif c in 'DN':
offset += int(n)
n = ''
else:
n += c
return align, align + offset |
def _pytype(dtype):
""" return a python type for a numpy object """
if dtype in ("int8", "int16", "int32", "int64", "uint8", "uint16", "uint32", "uint64"):
return int
elif dtype in ("float16", "float32", "float64", "float128"):
return float
elif dtype in ("complex64", "complex128", "complex256"):
return complex
else:
raise TypeError("not a recognized dtype: {0}".format(dtype)) |
def unnest_paths(paths: list) -> list:
"""Unnest a nested list of paths. Also removes paths that consist
entirely of None values.
"""
def unnest_recursive(list_: list):
"""Recursive checking if a list contains no list elements."""
if type(list_) is list:
if all([type(sub_l) is not list for sub_l in list_]):
# remove lists comprising of just None values
if not all([sub_l is None for sub_l in list_]):
unnested_list.append(list_)
else:
for sub_l in list_:
unnest_recursive(sub_l)
unnested_list: list = []
unnest_recursive(paths)
return unnested_list |
def get_unique_features(router_features):
"""
Convert router feature triplets to unique config features
:param router_features: Iterable of router feature triplets
:return: Set of unique features
"""
return set([feature for (router, feature, arg) in router_features]) |
def determine_if_dups_are_sister(subtree_tips: list):
"""
determine if dups are sister to one another
"""
# get first set of subtree tips
first_set_of_subtree_tips = subtree_tips[0]
# set if duplicate sequences are sister as True
are_sisters = True
# check if duplicate sequences are sister
for set_of_subtree_tips in subtree_tips[1:]:
if first_set_of_subtree_tips != set_of_subtree_tips:
are_sisters = False
if not are_sisters:
break
return are_sisters |
def linear_search(lst: "list[int]", n: int) -> int:
"""Find a element in the list and return index if found otherwise return -1
Args:\n
lst (list[int]): List of elements
n (int): number to find
Returns:\n
int: index of the element
"""
for index, element in enumerate(lst):
if element == n:
return index
return -1 |
def assignments_to_string(assdict):
""" Returns a semicolon-delimited string from a dictionary of assignment
expressions. """
return '; '.join(['%s=%s' % (k, v) for k, v in assdict.items()]) |
def build_complement(dna):
"""
:param dna: The original DNA strand input by user.
:return: The complement strand of the original DNA.
"""
new_dna = ''
for nucleotide in dna:
if nucleotide == "A":
new_dna = new_dna + "T"
elif nucleotide == "T":
new_dna = new_dna + "A"
elif nucleotide == "C":
new_dna = new_dna + "G"
elif nucleotide == "G":
new_dna = new_dna + "C"
return new_dna |
def get_country(x):
""" returns the int value for the ordinal value class
:param x: a value that is either 'crew', 'first', 'second', or 'third'
:return: returns 3 if 'crew', 2 if first, etc.
"""
if x == 'United-States':
return 1
elif x == 'Philippines':
return 2
elif x == 'Puerto-Rico':
return 3
elif x == 'Mexico':
return 4
elif x == 'Dominican-Republic':
return 5
elif x == 'Portugal':
return 6
elif x == 'Canada':
return 7
elif x == 'Taiwan':
return 8
elif x == 'Cuba':
return 9
elif x == 'Jamaica':
return 10
else:
return 0 |
def niceNumber(v, maxdigit=6):
"""Nicely format a number, with a maximum of 6 digits."""
assert(maxdigit >= 0)
if maxdigit == 0:
return "%.0f" % v
fmt = '%%.%df' % maxdigit
s = fmt % v
if len(s) > maxdigit:
return s.rstrip("0").rstrip(".")
elif len(s) == 0:
return "0"
else:
return s |
def is_single_bit(num):
"""
True if only one bit set in num (should be an int)
"""
num &= num - 1
return num == 0 |
def _parse_phone_number(phone_number: str) -> str:
"""Parse the digits from a string and format as +1xxxxxxxxxx"""
phone_number = "".join(filter(str.isdigit, phone_number))
if len(phone_number) == 10:
phone_number = f"1{phone_number}"
return f"+{phone_number}" |
def is_int(string_to_check):
"""
Checks if string is an integer value.
:param string_to_check: String to check
:return: True if string is an integer, False otherwise
"""
try:
int(string_to_check)
result = True
except ValueError:
result = False
return result |
def check_user_logged_in(request):
"""
check user logged in
:param request:
:return:
"""
if not request:
return False
return True |
def concat_strings(string_list):
"""
Concatenate all the strings in possibly-nested string_list.
@param list[str]|str string_list: string(s) to concatenate
@rtype: str
>>> list_ = 'cat'
>>> concat_strings(list_)
'cat'
>>> list_ = ['cat', 'dog']
>>> concat_strings(list_)
'catdog'
>>> list_ = ["how", ["now", "brown"], "cow"]
>>> concat_strings(list_)
'hownowbrowncow'
"""
# if this isn't a list, ie. it's an innermost element, don't recurse
if not isinstance(string_list, list):
return string_list
else:
return ''.join([concat_strings(x) for x in string_list]) |
def choose_preprocessing_mode(preprocessing_mode, image_model_name):
""" Choose preprocessing for specific pretrained weights
it is very important to preprocess
in exactly the same way the model
was originally trained
"""
if preprocessing_mode is None:
if 'densenet' in image_model_name:
preprocessing_mode = 'torch'
elif 'nasnet' in image_model_name:
preprocessing_mode = 'tf'
elif 'vgg' in image_model_name:
preprocessing_mode = 'caffe'
elif 'inception_resnet' in image_model_name:
preprocessing_mode = 'tf'
elif 'resnet' in image_model_name:
preprocessing_mode = 'caffe'
else:
raise ValueError('You need to explicitly set the preprocessing mode to '
'torch, tf, or caffe for these weights')
return preprocessing_mode |
def multi_find(s: str, f: str):
"""Finds every occurrence of substring F in string S.
Returns a list of indexes where each occurence starts."""
res = []
scanned = 0
while len(s) > 0:
found = s.find(f)
if found == -1: break
res.append(found + scanned)
s = s[found + 1:]
scanned += found + 1
return res |
def r_sa_check(template, tag_type, is_standalone):
"""Do a final checkto see if a tag could be a standalone"""
# Check right side if we might be a standalone
if is_standalone and tag_type not in ['variable', 'no escape']:
on_newline = template.split('\n', 1)
# If the stuff to the right of us are spaces we're a standalone
if on_newline[0].isspace() or not on_newline[0]:
return True
else:
return False
# If we're a tag can't be a standalone
else:
return False |
def get_tz_suffix(tz_input):
"""Return the suffix to be added for time zone information."""
if tz_input == "":
return ""
elif tz_input == "+0000":
return "Z"
# Add column between hour and date to make it work with XSD format
return "{}:{}".format(tz_input[:3], tz_input[3:]) |
def rev_comp(seq):
"""
return the reverse complement of seq
the sequence must be in lower case
"""
complement = {'a' : 't',
'c' : 'g',
'g' : 'c',
't' : 'a'}
rev_seq = seq[::-1]
rev_comp = ''
for nt in rev_seq:
rev_comp += complement[nt]
return rev_comp |
def get_dict_key(dic: dict):
"""
return the dictionary key
the dictionary must contain only a single entry
"""
assert len(dic) == 1
return list(dic.keys())[0] |
def conv_out_size(n, k, p, s):
"""Compute the output size by given input size n (width or height),
kernel size k, padding p, and stride s
Return output size (width or height)
"""
return (n - k + 2 * p)//s + 1 |
def reverseString(aStr):
"""
Given a string, recursively returns a reversed copy of the string.
For example, if the string is 'abc', the function returns 'cba'.
The only string operations you are allowed to use are indexing,
slicing, and concatenation.
aStr: a string
returns: a reversed string
"""
if len(aStr) == 0:
return ''
else:
return aStr[-1] + reverseString(aStr[:-1]) |
def process_all_dictionary_content(dictionary, function):
"""
Function that aplies a function or a list of functions to every single value in a dictionary
"""
for k, v in dictionary.items():
if isinstance(function, list):
for f in function:
dictionary[k] = f(v)
else:
dictionary[k] = function(v)
return dictionary |
def filter_migration_segment_len(x, hmin=0, hmax=float("inf"), dmin=0,
dmax=float("inf")):
"""
Filter migration segment by home segment length and destination length.
x: ['migration_list']
hmin: min_home_segment_len
hmax: max_home_segment_len
dmin: min_des_segment_len
dmax: max_des_segment_len
"""
home_segment = x[0]
des_segment = x[1]
home_len = home_segment[1]-home_segment[0]+1
des_len = des_segment[1]-des_segment[0]+1
if (hmin <= home_len <= hmax) and (dmin <= des_len <= dmax):
return 1
else:
return 0 |
def nth_eol(src: str, lineno: int) -> int:
"""
Compute the ending index of the n-th line (before the newline,
where n is 1-indexed)
>>> nth_eol("aaa\\nbb\\nc", 2)
6
"""
assert lineno >= 1
pos = -1
for _ in range(lineno):
pos = src.find('\n', pos + 1)
if pos == -1:
return len(src)
return pos |
def convert_stop_id_for_request(stop_id):
"""Convert stop_id to format for REST request
"""
string_as_list = stop_id.split(":")
string_as_list[1] = str(int(string_as_list[1]))
string_as_list[2] = str(int(string_as_list[2]))
return ":".join(string_as_list) |
def parse_storage_mappings(storage_mappings):
""" Given the 'storage_mappings' API field, returns a tuple with the
'default' option, the 'backend_mappings' and 'disk_mappings'.
"""
# NOTE: the 'storage_mappings' property is Nullable:
if storage_mappings is None:
return None, {}, {}
backend_mappings = {
mapping['source']: mapping['destination']
for mapping in storage_mappings.get("backend_mappings", [])}
disk_mappings = {
mapping['disk_id']: mapping['destination']
for mapping in storage_mappings.get("disk_mappings", [])}
return (
storage_mappings.get("default"), backend_mappings, disk_mappings) |
def _caclulate_device_type_name(device_type: str, hardware_version: str, firmware_version: str) -> str:
"""
Calculates the name of the dynamic-type for a specific class of devices
:param device_type:
:param hardware_version:
:param firmware_version:
:return:
"""
return f"{device_type}:{hardware_version}:{firmware_version}" |
def reverse_letter(string):
"""
Given a string str, reverse it omitting all non-alphabetic characters.
"""
return ''.join([ch for ch in string if ch.isalpha()][::-1]) |
def _bmz(pHI,pFA):
"""recursive private function for calculating A_{MZS}"""
# use recursion to handle
# cases below the diagonal defined by pHI == pFA
if pFA > pHI:
return _bmz(1-pHI, 1-pFA)
if pFA <= .5 <= pHI:
return (5-4*pHI)/(1+4*pFA)
elif pFA < pHI < .5:
return (pHI**2+pHI)/(pHI**2+pFA)
elif .5 < pFA < pHI:
return ((1-pFA)**2+(1-pHI))/((1-pFA)**2+(1-pFA))
else: # pHI == pFA
return 1. |
def deep_update(d, d_update):
"""
Updates the values (deep form) of a given dictionary
Parameters:
-----------
d : dict
dictionary that contains the values to update
d_update : dict
dictionary to be updated
"""
for k, v in list(d_update.items()):
if isinstance(v, dict):
if k in d:
deep_update(d[k], v)
else:
d[k] = v
elif isinstance(d, list):
d.append({k: v})
else:
d[k] = v
return d |
def mdi_power(x: bytes):
""" Power Via MDI decode
Args:
x: source bytestring
Returns:
Information about power capabilities support
"""
mdi: dict = {}
if x[0] == 2:
if (x[1] & 1) > 0:
mdi["Port Class"] = "Power Source Equipment (PSE)"
else:
mdi["Port Class"] = "Powered Device (PD)"
if (x[1] & 2) > 0:
mdi["PSE MDI Power Support"] = 1
else:
mdi["PSE MDI Power Support"] = 0
if (x[1] & 4) > 0:
mdi["PSE MDI Power Enabled"] = 1
else:
mdi["PSE MDI Power Enabled"] = 0
if (x[1] & 8) > 0:
mdi["PSE Pairs Control Ability"] = 1
else:
mdi["PSE Pairs Control Ability"] = 0
if x[2] == 1:
mdi["PSE power_pair"] = "Signal pair"
elif x[2] == 2:
mdi["PSE power_pair"] = "Spare pair"
if x[3] > 0:
mdi["Power class"] = x[3] - 1
return mdi |
def mie(r, eps, sig, m=12, n=6):
"""Mie pair potential. """
prefactor = (m / (m - n)) * (m / n) ** (n / (m - n))
return prefactor * eps * ((sig / r) ** m - (sig / r) ** n) |
def update_dictionary(d, target_key=None, value=None):
"""
:param d: dictionary
:param target_key:
:param value:
:return:
"""
for key, item in d.items():
if key == target_key:
d[key] = value
elif isinstance(item, dict):
update_dictionary(item,
target_key=target_key,
value=value)
return d |
def get_end_paranteza(paranteza):
""" Returneaza opusul unei paranteze deschide """
if paranteza == '(':
return ')'
elif paranteza == '[':
return ']'
elif paranteza == '{':
return '}' |
def de_tokenizer_pos(tokens, tokens_tags, tokens_original):
"""
Rezips the 2 tokenized lists of the tokenizer_pos into a list of pos tuples
:param tokens: List of str, word tokens
:param tokens_tags: List of str, pos tags
:param tokens_original: List of str, the original tokens as generated by tokenizer_pos
:return: pos_tuplets, List of pos tuplets
"""
tokens = [x if x in tokens else None for x in tokens_original]
pos_tuplets = [(x, y) for x, y in zip(tokens, tokens_tags) if x is not None]
return pos_tuplets |
def collatz_sequence(n):
"""
Returns a list with the Collatz sequence given n
"""
collatz_sequence_list = [n]
while n > 1:
if n % 2 == 0:
n = int(n / 2)
collatz_sequence_list.append(n)
else:
n = int(3 * n + 1)
collatz_sequence_list.append(n)
return collatz_sequence_list |
def tally_by_field_value(database,key):
""" Extract a given field from a list of records.
Arguments:
database (list of dict) : list of database entries
key (...) : key identifying field of interest
Returns:
(dict) : map (field value) -> (number of occurrences)
"""
extractor = lambda entry : entry[key]
tally = dict()
for entry in database:
value = extractor(entry)
tally[value] = tally.get(value,0)+1
return tally |
def find_largest(line: str) ->int:
"""Return the largest value in line, which is a whitespace-delimited string
of integers that each end with a '.'.
>>> find_largest('1. 3. 2. 5. 2.')
5
"""
#The largest value seen so far.
largest = -1
for value in line.split():
#Remove the trailing period.
v = int(value[:-1])
# if we find a larger value, remeber it.
if v > largest:
largest = v
return largest |
def decodeBase40(val):
"""
Given a value representing a base-40 number, return a list of three items
containing the decoded base-40 number. Each ``val`` holds 3 base-40
characters.
Used for decoding call signs.
Args:
val (int): Integer holding 3 base-40 characters.
Returns:
list: List of 3 items, each containing the numeric value of a base-40
number.
"""
if val == 0:
return [0,0,0]
ret = []
while val:
ret.append(int(val % 40))
val //= 40
while len(ret) < 3:
ret.append(0)
return ret[::-1] |
def urlify_gallery(f):
"""Takes 'gallery/demo.js' -> 'demo'"""
return f.replace('gallery/', 'gallery/#g/').replace('.js', '') |
def get_range(context, range_str):
"""Should be given a range_str like '<start_index>:<end_index', e.g. '1:4'
returns a string: e.g. 1,2,3
"""
rargs = [int(s) for s in range_str.split(':')]
return ','.join([str(d) for d in range(*rargs)]) |
def break_inside(keyword):
"""``break-inside`` property validation."""
return keyword in ('auto', 'avoid', 'avoid-page', 'avoid-column') |
def hex2Bin ( hexVal ):
"""
This function will convert the given hex string to a binary string.
Parameters
----------
hexVal:
An hex string without the leading '0x'
Returns
-------
binVal:
A binary string without the leading '0b'
"""
binVal = ''.join( bin( int( val, 16 ) )[ 2: ].zfill( 4 ) for val in hexVal )
return binVal |
def icon_mapping(icon, size):
"""
https://darksky.net/dev/docs has this to say about icons:
icon optional
A machine-readable text summary of this data point, suitable for selecting
an icon for display. If defined, this property will have one of the
following values: clear-day, clear-night, rain, snow, sleet, wind, fog,
cloudy, partly-cloudy-day, or partly-cloudy-night. (Developers should
ensure that a sensible default is defined, as additional values, such as
hail, thunderstorm, or tornado, may be defined in the future.)
Based on that, this method will map the Dark Sky icon name to the name of
an icon in this project.
"""
if icon == 'clear-day':
icon_path = 'icons/{}/clear.png'.format(size)
elif icon == 'clear-night':
icon_path = 'icons/{}/nt_clear.png'.format(size)
elif icon == 'rain':
icon_path = 'icons/{}/rain.png'.format(size)
elif icon == 'snow':
icon_path = 'icons/{}/snow.png'.format(size)
elif icon == 'sleet':
icon_path = 'icons/{}/sleet.png'.format(size)
elif icon == 'wind':
icon_path = 'icons/alt_icons/{}/wind.png'.format(size)
elif icon == 'fog':
icon_path = 'icons/{}/fog.png'.format(size)
elif icon == 'cloudy':
icon_path = 'icons/{}/cloudy.png'.format(size)
elif icon == 'partly-cloudy-day':
icon_path = 'icons/{}/partlycloudy.png'.format(size)
elif icon == 'partly-cloudy-night':
icon_path = 'icons/{}/nt_partlycloudy.png'.format(size)
else:
icon_path = 'icons/{}/unknown.png'.format(size)
# print(icon_path)
return icon_path |
def UnderToCamel(under):
"""Converts underscore_separated strings to CamelCase strings."""
return ''.join(word.capitalize() for word in under.split('_')) |
def closenr(n, m) :
"""Find the number closest to n and divisible by m"""
q = int(n / m)
n1 = m * q
if((n * m) > 0) :
n2 = (m * (q + 1))
else :
n2 = (m * (q - 1))
if (abs(n - n1) < abs(n - n2)) :
return n1
return n2 |
def delete_root_with_unichild(ast):
"""
delete root node with only a child
because in such way, head node might be Program/Function/Error and its child is the code's AST
"""
for idx in sorted([idx for idx in ast.keys()], key=int):
if (ast[idx]['parent'] is None) and len(ast[idx]['children']) == 1:
child_idx = ast[idx]['children'][0]
ast[str(child_idx)]['parent'] = None
ast.pop(idx)
else:
break
return ast |
def readable_time(delta_seconds):
"""Returns a human-readable string for delta seconds.
"""
hours, remainder = divmod(int(delta_seconds), 3600)
minutes, seconds = divmod(remainder, 60)
days, hours = divmod(hours, 24)
if days:
fmt = '{d}d {h}hr {m}min {s}sec'
elif hours:
fmt = '{h}hr {m}min {s}sec'
else:
fmt = '{m}min {s}sec'
return fmt.format(d=days, h=hours, m=minutes, s=seconds) |
def detect(source):
"""Detects whether `source` is P.A.C.K.E.R. coded."""
return source.replace(' ', '').startswith('eval(function(p,a,c,k,e,r') |
def split_to_grapheme_phoneme(inp_dictionary):
"""Split input dictionary into two separate lists with graphemes and phonemes.
Args:
inp_dictionary: input dictionary.
"""
graphemes, phonemes = [], []
for line in inp_dictionary:
split_line = line.strip().split()
if len(split_line) > 1:
graphemes.append(list(split_line[0]))
phonemes.append(split_line[1:])
return graphemes, phonemes |
def _blank_text(active):
"""Return text for line history"""
text = []
for value in active:
if value:
text.append(" |")
else:
text.append(" ")
return "".join(text) |
def inverse_mod(a, m):
"""Inverse of a mod m."""
if a < 0 or m <= a:
a = a % m
# From Ferguson and Schneier, roughly:
c, d = a, m
uc, vc, ud, vd = 1, 0, 0, 1
while c != 0:
q, c, d = divmod(d, c) + (c,)
uc, vc, ud, vd = ud - q*uc, vd - q*vc, uc, vc
# At this point, d is the GCD, and ud*a+vd*m = d.
# If d == 1, this means that ud is a inverse.
assert d == 1
if ud > 0:
return ud
else:
return ud + m |
def __not_empty(data: dict, field_name: str) -> bool:
""" Check if field exists and contaits data in data dictionary """
if data and \
field_name in data and \
data[field_name] and \
data[field_name] != 'None':
return True
else:
return False |
def average_hold_time(request):
"""Return the average hold time for current user, in json"""
awt = 0 #request.user.HelplineUser.get_average_wait_time()
return awt |
def calc_num_subframes(tot_samples, frame_length, overlap_samples, zeropad=False):
"""Assigns total frames needed to process entire noise or target series
This function calculates the number of full frames that can be
created given the total number of samples, the number of samples in
each frame, and the number of overlapping samples.
Parameters
----------
tot_samples : int
total number of samples in the entire series
frame_length : int
total number of samples in each frame / processing window
overlap_samples : int
number of samples in overlap between frames
zeropad : bool, optional
If False, number of subframes limited to full frames. If True,
number of subframes extended to zeropad the last partial frame.
(default False)
Returns
-------
subframes : int
The number of subframes necessary to fully process the audio samples
at given `frame_length`, `overlap_samples`, and `zeropad`.
Examples
--------
>>> calc_num_subframes(30,10,5)
5
>>> calc_num_subframes(30,20,5)
3
"""
import math
if overlap_samples == 0:
if zeropad:
subframes = int(math.ceil(tot_samples/frame_length))
else:
subframes = int(tot_samples/frame_length)
return subframes
trim = frame_length - overlap_samples
totsamps_adjusted = tot_samples-trim
if zeropad:
subframes = int(math.ceil(totsamps_adjusted / overlap_samples))
else:
subframes = int(totsamps_adjusted / overlap_samples)
return subframes |
def det_dedupe(l):
""" Deterministically deduplicate a list
Returns a deduplicated copy of `l`. That is, returns a new list that contains one instance of
each element in `l` and orders these instances by their first occurrence in `l`.
Costs O(n), where n is the length of `l`.
Args:
l (:obj:`list`): a list with hashable elements
Returns:
:obj:`list`: a deterministically deduplicated copy of `l`
Raises:
`TypeError` if `l` contains an unhashable (mutable) type
"""
s = set()
t = []
for e in l:
if e not in s:
t.append(e)
s.add(e)
return t |
def format_channel_names(channel_names, n_ch):
"""
Format channel names and ensure number of channel names matches number of channels or default
to C1, C2, C3, etc.
Parameters
----------
channel_names:list
list of str that are channel names
n_ch: int
number of channels detected in image
Returns
-------
channel_names:
list of str that are formatted
"""
if channel_names is None or n_ch != len(channel_names):
channel_names = ["C{}".format(idx) for idx in range(n_ch)]
return channel_names |
def get_cell(m, cell_num, x_player, y_player):
"""
:param m:
:param cell_num:
:param x_player:
:param y_player:
:return:
"""
# Your code here
sq_size = m / cell_num
row = int(y_player / sq_size)
col = int(x_player / sq_size)
return (row, col) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.