content stringlengths 42 6.51k |
|---|
def trim_transform(mapping, ref_length: int):
"""
Trims mapped sequences that have a deletion operation on the ends arising from aligning a shorter sequence to a
longer one.
:param mapping: an iterable of (position, {"S", "D", "I"}, int for deletion or string for insertion)
:param ref_length:
:r... |
def get_name(c, park_name):
"""creates new column name for each row of dataframe, fills with name string from tags object
Args:
c: cython iterator object representing each row in the trails dataframe
Returns:
new column with trail name
"""
try:
name = park_name + " - " + c['tags']['name']
except Exception... |
def _actual_index(arg):
"""Turn a string in a integer or slice."""
if ':' in arg:
idxs = arg.split(':')
if len(idxs) > 3:
raise ValueError(f'{arg} is an invalid slice')
idxs[0] = int(idxs[0]) if idxs[0] else None
idxs[1] = int(idxs[1]) if idxs[1] else None
if ... |
def LimiterG2forRSU(r):
"""Return the limiter for Roe-Sweby Upwind TVD limiter function.
This limited is further used to calculate the flux limiter
function given by Equation 6-137.
Calculated using Equation 6-139 in CFD Vol. 1 by Hoffmann.
"""
# Equation 6-139
G = (r + abs(r))/(1.0... |
def generate_transitions(role_set, path_size):
"""Create an ordered list of transitions, from a set role labels.
The number of roles is exponential in the path size."""
# Each loop iteration i adds all transitions
# of size (i+1) to the list trans.
trans = ['']
for p in range(path_size):
... |
def read_from_add_translation_dict(address, tdict):
"""map an original address to x, y coords using the dictionary of unique addresses"""
x, y = tdict[address]
return x, y |
def number_unique(row: int, column: int):
"""return number of unique shortest paths from start to finish"""
if row == 1 or column == 1: # base case
return 1
else:
return number_unique(row - 1, column)\
+ number_unique(row, column - 1) |
def get_tuple(l, item):
"""Checks if an item is present in any of the tuples
Args:
l (list): list of tuples
item (object): single object which can be in a tuple
Returns:
[tuple]: tuple if the item exists in any of the tuples
"""
for entry in l:
if item in entry:
... |
def intersect_lists(lists_to_intersect):
"""
Given an iterator of lists, return a set representing their intersection.
While intersecting many sets is straightforward, intersecting many lists
requires a cast to set and then a series of intersects against it. To keep
things neat, this logic's been p... |
def YYYYDDD_datecode(year, midfix, doy):
"""
Format the datecode pattern used in many log files.
The results consists of a year and doy separated by a string. 'year' is
assumed to be a four digit integer but a two digit one should work.
'doy' does NOT have leading zeros, that is, it's a normal integer.
@p... |
def test_line(line):
"""returns true lines. Not comments or blank line"""
if not line.strip():
return False # if the last line is blank
if line.startswith("#"):
return False # comment line
return line |
def name_validator(ifallowed):
"""
Limit length of string to 40 chars
Call signature: %P
"""
if len(ifallowed) > 40:
return False
return True |
def point_dist(a, b):
""" Distance between two points. """
return ((a[0]-b[0]) ** 2 + (a[1]-b[1]) ** 2) ** 0.5 |
def sum_up_diagonals(matrix):
"""Given a matrix [square list of lists], return sum of diagonals.
Sum of TL-to-BR diagonal along with BL-to-TR diagonal:
>>> m1 = [
... [1, 2],
... [30, 40],
... ]
>>> sum_up_diagonals(m1)
73... |
def is_float(s):
"""Returns `True` is string is a valid representation of a float."""
try:
float(s)
return True
except ValueError:
return False |
def _multi_args(value):
"""Handle specifying a multi-count arg."""
val = False
multi = False
triple = False
if value and value > 0:
val = True
if value > 1:
multi = True
if value > 2:
triple = True
return val, multi, triple |
def drug_code_coding_system(input_dict, field="m_drug_code_oid"):
"""Determine from the OID the coding system for medication"""
coding_system_oid = input_dict[field]
if coding_system_oid == "2.16.840.1.113883.6.311":
return "Multum Main Drug Code (MMDC)"
elif coding_system_oid == "2.16.840.1.11... |
def maxAck(acklist):
"""Return the highest ack number from a contiguous run.
Returns 0 for an empty list."""
if len(acklist) == 0:
return 0
elif len(acklist) == 1:
return acklist[0]
ordered_acklist = sorted(acklist)
max_ack_sofar = ordered_acklist[0]
for ack in ordered_a... |
def kgtk_string(x):
"""Return True if 'x' is a KGTK plain string literal."""
return isinstance(x, str) and x.startswith('"') |
def value_validate(value, value_validator):
"""
Takes in a value and a key parser to determine if it matches
the format specified in the key parser for that item
"""
if not isinstance(value, value_validator["type"]):
return False
#recursive dict validation
if isinstance(value, dict)... |
def add(one, two):
"""Helper function for adding"""
return(one + two) |
def is_field(token):
"""Checks if the token is a valid ogc type field
"""
return token in ["name", "description", "encodingType", "location", "properties", "metadata",
"definition", "phenomenonTime", "resultTime", "observedArea", "result", "id", "@iot.id",
"resultQ... |
def last_occurence_of_tag_chain(sequence, tag_type):
"""
Takes a sequence of tags. Assuming the first N tags of the sequence are all of the type tag_type, it will return
the index of the last such tag in that chain, i.e. N-1
If the first element of the sequence is not of type tag_type, it will return -... |
def compute_IOU(boxA, boxB):
"""
Origin source:
https://www.pyimagesearch.com/2016/11/07/intersection-over-union-iou-for-object-detection/
"""
# determine the (x, y)-coordinates of the intersection rectangle
xA = max(boxA[0], boxB[0])
yA = max(boxA[1], boxB[1])
xB = min(boxA[2], boxB[2])... |
def split_using_dictionary(string, dictionary, max_key_length, single_char_parsing=False):
"""
Return a list of (non-empty) substrings of the given string,
where each substring is either:
1. the longest string starting at the current index
that is a key in the dictionary, or
2. a single char... |
def some_func(ham: str, eggs: str = "eggs") -> str:
"""This func does something
But we're not really sure of what that something is
but apparently, it does it well
really really well
but it also can collapse on itself... you have been warned.
"""
print("Annotations: ", some_func.__... |
def read_vocabulary(vocab_file, threshold):
"""read vocabulary file produced by get_vocab.py, and filter according to frequency threshold.
"""
vocabulary = set()
for line in vocab_file:
word, freq = line.strip('\r\n ').split(' ')
freq = int(freq)
if threshold == None or freq >=... |
def camel_to_snake(word: str, depublicize: bool = False):
"""Convert came case to snake case."""
word = "".join("_" + i.lower() if i.isupper() else i for i in word)
if not depublicize:
word = word.lstrip("_")
return word |
def dice_similarity_coefficient(inter, union):
"""Computes the dice similarity coefficient.
Args:
inter (iterable): iterable of the intersections
union (iterable): iterable of the unions
"""
return 2 * sum(inter) / (sum(union) + sum(inter)) |
def absolute_value(num):
"""This function returns the absolute
value of the entered number"""
if num >= 0:
return num
else:
return -num |
def gpa_scale_emoji(value):
"""Converts a score on a 4.0 scale to an emoji"""
if value is None:
return u'\U00002753'
elif value <= 0.5:
return u'\U00002620'
elif value <= 1.5:
return u'\U0001f621'
elif value <= 2.5:
return u'\U0001f641'
elif value <= 3.5:
... |
def filter_c(filelist, channels, exclusive=False):
""" return a list of filenames whose channel numbers are within trange
channels is either a single int, or an iterator with a range of channel
numbers desired
"""
# f = [f for f in filelist if parse_filename(f,'channel') == c]
# above is more ro... |
def _GetColorClass(percent_changed):
"""Returns a CSS class name for the anomaly, based on percent changed."""
if percent_changed > 50:
return 'over-50'
if percent_changed > 40:
return 'over-40'
if percent_changed > 30:
return 'over-30'
if percent_changed > 20:
return 'over-20'
if percent_ch... |
def rotate_list(numbers, cursor):
"""Rotate list such that the current start moves to the position
indicated by the cursor."""
return numbers[len(numbers) - cursor:] + numbers[:len(numbers) - cursor] |
def format_bytesize(num):
"""Convert number of bytes to human readable string"""
for x in ['bytes','KB','MB','GB']:
if num < 1024.0:
return "%3.1f%s" % (num, x)
num /= 1024.0
return "%3.1f%s" % (num, 'TB') |
def get_in(coll, path=None, default=None):
"""Returns a value at path in the given nested collection.
Args:
coll(object):
path(str):'a.0.b.c'
"""
if path is None:
return coll
for key in path.split('.'):
try:
if isinstance(coll, dict):
coll... |
def split_volume(v):
"""
If v is of the format EXTERNAL:INTERNAL, returns (EXTERNAL, INTERNAL).
If v is of the format INTERNAL, returns (None, INTERNAL).
"""
if ':' in v:
return v.split(':', 1)
else:
return (None, v) |
def _gen_alt_forms(term):
"""
Generate a list of alternate forms for a given term.
"""
if not isinstance(term, str) or len(term) == 0:
return [None]
alt_forms = []
# For one alternate form, put contents of parentheses at beginning of term
if '(' in term:
prefix = term[term.f... |
def _get_value_for_type(type_value, value):
""" Return the Value depending on the Type """
if type_value == bool:
if value.lower() in ["true", "1"]:
return True
if value.lower() in ["false", "0"]:
return False
mess = "Waiting for a boolean but value is '%s'." % va... |
def get_autoscaling_group(api, pool_obj):
"""
fetchs the aws autoscaling group name from pool
:param api:
:param pool_obj:
:return:
"""
return 'grastogi-demo-asg'
launch_cfg_ref = pool_obj['autoscale_launch_config_ref']
launch_cfg_uuid = launch_cfg_ref.split('autoScalelaunchconfig')[... |
def format_fields_for_query(fields):
"""
Format fields names to cann query module.
Arguments:
- `fields`: list of fields, exemple::
['field1','name','user']
Returns::
[
{'name':'field1'},
{'name':'name'},
{'name':'user'},
... |
def get_graph_partitioning_categories(objects):
"""
Obtain categories known to partition the graph (into components)
The most important one is usually "GEO"
:param objects:
:return: A list of partition categories
"""
return ["GEO"] |
def _is_healthy_pure(get_health_func, instance):
"""Checks to see if a component instance is running healthy
Pure function edition
Args
----
get_health_func: func(string) -> complex object
Look at unittests in test_discovery to see examples
instance: (string) fully qualified name of co... |
def sort_by_priority(element_list: list) -> list:
"""
Sort list of elements by their priority
Args:
element_list (list): List of element objects
Returns:
list: List of element objects sorted by priority
"""
return sorted(element_list, key=lambda e: e.priority) |
def assertify(text):
"""Wraps text in the (assert )."""
return '(assert ' + text + ')' |
def find_best_cost(pop):
"""
:param pop:
:return: elem co min cost
"""
min = pop[0]
for elem in pop:
if min["cost"] > elem["cost"]:
min = elem
return min |
def non_shared_get_K(Kp: int, C: int, num_params: int) -> int:
""" Inverse of non_shared_get_Kp, get back K=number of mixtures """
return Kp // (num_params * C) |
def write_header(header):
"""Write the header. Not implemented."""
return (header or []) |
def cast_int2vector(value):
"""Cast an int2vector value."""
return [int(v) for v in value.split()] |
def nbytes(frame, _bytes_like=(bytes, bytearray)):
"""Number of bytes of a frame or memoryview"""
if isinstance(frame, _bytes_like):
return len(frame)
else:
try:
return frame.nbytes
except AttributeError:
return len(frame) |
def build_header(name, value):
"""
Takes a header name and value and constructs a valid string to add to the headers list.
"""
stripped_value = value.lstrip(" ").rstrip("\r\n").rstrip("\n")
stripped_name = name.rstrip(":")
return f"{stripped_name}: {stripped_value}\r\n" |
def sort_response(response_dict, *args):
"""
Used in tests to sort responses by two or more keys.
For example if response includes experimentKey and FeatureKey, the function
will sort by primary and secondary key, depending which one you put first.
The first param will be primary sorted, second seco... |
def trim_string(string: str, max_length: int = 155) -> str:
"""
Trim string for debug purposes.
:param string: the strim to trim
:param max_length: the maximal output length of the trimmed string
:return: the trimmed string as '<first half> ... <second half>'
"""
half_length = int((... |
def marching(arg):
"""Return "The ants go marching..." part of the song.
arg - "one", "two", "three" ..."""
return "The ants go marching {} by {},".format(arg,arg) |
def bool_from_string(subject):
"""
Interpret a string as a boolean.
Any string value in:
('True', 'true', 'On', 'on', '1')
is interpreted as a boolean True.
Useful for JSON-decoded stuff and config file parsing
"""
if isinstance(subject, bool):
return subject
elif isins... |
def clean_site_name(s):
"""
Splits site name by _ (underscore), takes no more than first three parts and joins them with _.
This way site name always have at most three parts, separated by _.
First three parts represent a tier, a country and a lab/university name.
"""
split = s.split('_')
sp... |
def last_less_than(array, x):
"""array must be sorted"""
best = None
for elt in array:
if elt <= x:
best = elt
elif best is not None:
return best
return best |
def convert_from_fortran_bool(stringbool):
"""
Converts a string in this case ('T', 'F', or 't', 'f') to True or False
:param stringbool: a string ('t', 'f', 'F', 'T')
:return: boolean (either True or False)
"""
true_items = ['True', 't', 'T']
false_items = ['False', 'f', 'F']
if isi... |
def get_for_11_pipeline():
"""Test pipeline for for."""
return {
'sg1': [
{'name': 'sg1.step1',
'foreach': ['one', 'two', 'three']
},
'sg1.step2'
],
'sg2': [
'sg2.step1',
'sg2.step2'
],
'sg3': [
... |
def searchInsert(nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
def bs(left, right):
if left > right:
return left
else:
mid = (left + right) // 2
if nums[mid] == target:
return mid
elif ... |
def vect_dot(a, b):
"""
Simplified dot product of two 2D vectors.
Parameters
----------
a, b : array_like
Vectors in a 2D-euclidean space
Returns
-------
x : float
"""
x = a[0]*b[0] + a[1]*b[1]
return x |
def binaryToDecimal(list_of_digits):
"""
:param list_of_digits list:
:return total int:
Takes a list of 0s and 1s and calculates the decimal value of the binary number the list makes
"""
# Smartass way of doing this follows
# smartass_decimal = eval('0b' + ''.join(list_of_digits))
# D... |
def to_tuple(param, low=None, bias=None):
"""Convert input argument to min-max tuple
Args:
param (scalar, tuple or list of 2+ elements): Input value.
If value is scalar, return value would be (offset - value, offset + value).
If value is tuple, return value would be value + offs... |
def leap_year (year):
"""
Leap year
@param year : int
@return: int
1 if year is leap year, otherwise 0
"""
if (year % 100 == 0 ): # Gregorian fix
if (year % 400 == 0 ):
return (1)
else:
return (0)
else:
if (year % 4 == 0 ):
return (1)
else:
return (0) |
def check_palindrome(n):
"""
:type n: str
:rtype: bool
"""
i = 0
j = len(n) - 1
while i < j:
if n[i] != n[j]:
return False
i += 1
j -= 1
return True |
def find_str_in_list(l,string):
"""
Return first element that matches a string in a list
"""
for element in l:
if string in element:
return element
return '' |
def sphinx_format_header(text: str, char: str) -> str:
"""
Example output:
*******
WebUI
*******
"""
return "\n".join(
[
char * (len(text) + 2),
f" {text}",
char * (len(text) + 2),
]
) |
def joinObjects(separator, selector, items):
"""Joins a string of objects by calling the selector with each item and putting the separator in between each item.
Arguments:
separator : str - string to put between each item
selector : callable(item) - function with one parameter
items : list - the objects to join... |
def get_ak(output: bytes) -> bytes:
"""Support function to get the 48-bit anonimity key (AK) from OUT2, the
output of 3GPP f5 function.
:param output: OUT2
:returns: OUT2[0] .. OUT2[47]
"""
edge = 6 # = ceil(47/8)
return output[:edge] |
def _clean_listlike(string: str) -> list:
"""Removes commas and semicolons from SQL list-like things. i,e id, number --> ['id', 'number'] """
cols = []
for item in string:
# Check if item is in list, or if user adds ; to the end of the query
if item[-1] == ',' or item[-1] == ';' or item[-1] ... |
def van_der_corput(n_sample, base=2, start_index=0):
"""Van der Corput sequence.
Pseudo-random number generator based on a b-adic expansion.
Parameters
----------
n_sample : int
Number of element of the sequence.
base : int
Base of the sequence.
start_index : int
In... |
def ld_to_m(ld):
"""
Converts the input distance (or velocity) of the input from Lunar distances to meters.
"""
return ld * 384402 * 10**3 |
def flat_values(iterable, max_iterations=1000):
"""Return the list of values of iterable and nested iterables."""
iteration = 0
values = []
remaining_iterables = [iterable]
seen_iterables = set()
while len(remaining_iterables) != 0:
iteration += 1
# If we have a very big or n... |
def swigBuilderModifyTargets( target, source, env ):
"""
Emitter for the Swig Builder.
"""
# Assign param to dummy variable to ensure that pychecker
# doesn't complain.
_ = env
for i in source:
name = str( i )[:-2]
# If directors are enabled, then add the "*_wrap.h" file a... |
def Vowel_or_Consonant(char = ''):
"""
A boolean function, which return either True or False
"""
# Determine whether each letter in the text is a vowel or a
# consonant. if it is a vowel, set test to True, otherwise, set test to false.
for i in char:
if str(i)in 'aeiouy':
te... |
def get_slack_id(members, person):
"""Takes the list of slack members and returns the ID of the person."""
for member in members:
name_match = 'real_name' in member['profile'] and person['name'] == member['profile']['real_name']
email_match = 'email' in member['profile'] and person['email'] == m... |
def _GeneratePathStr(path):
"""Formats a path to a field for printing."""
return ((len(path) - 1) * ' ') + path[-1] if path else '' |
def term_frequency(term, tokenized_document):
"""Tokenized document is the list of tokens(words in a document)"""
return tokenized_document.count(term) |
def validateEmail(email, planb):
"""Do a basic quality check on email address, but return planb if email doesn't appear to be well-formed"""
email_parts = email.split('@')
if len(email_parts) != 2:
return planb
return email |
def Linear_Aprox_Params_Calc(B0, B1):
"""
Calculate linear approximation overall parameters.
:param B0: intercept
:type B0 : float
:param B1: slope
:type B1 : float
:return: [Wmax,Vcell_Wmax] as list
"""
Wmax = 0
Vcell_Wmax = 0
try:
Wmax = (B0**2) / (4 * B1)
exce... |
def _net_addr(addr):
"""Get network address prefix and length from a given address."""
nw_addr, nw_len = addr.split('/')
nw_len = int(nw_len)
return nw_addr, nw_len |
def linspace(first, last, n):
""" returns a linear range from first to last with n elements"""
return [(last-first)*x/(n-1)+first for x in range(n)] |
def get_value(lst, row_name, idx):
"""
:param lst: data list, each entry is another list with whitespace separated data
:param row_name: name of the row to find data
:param idx: numeric index of desired value
:return: value
"""
val = None
for l in lst:
if not l:
conti... |
def is_number(num):
"""Tests to see if arg is number. """
try:
#Try to convert the input.
float(num)
#If successful, returns true.
return True
except:
#Silently ignores any exception.
pass
#If this point was reached, the i... |
def exact_top_of_center(angle):
"""
True, if angle leads to point exactly top of center
"""
return True if angle == 270 else False |
def vertical_win(board, who):
"""
returns true if there are any vertical winning columns
"""
for col in range(3):
num = 0
for row in range(3):
if board[row * 3 + col] == who:
num += 1
if num == 3:
return True
return False |
def keyboard_consctructor(items: list) -> dict:
"""Pasting infromation from list of items to keyboard menu template."""
keyboard = {
"DefaultHeight": False,
"BgColor": "#FFFFFF",
"Type": "keyboard",
"Buttons": [{
"Columns": item[2],
"Rows": 1,
... |
def given_tags_in_result(search_tags, clarifai_tags, full_match=False):
"""Checks the clarifai tags if it contains one (or all) search tags """
if full_match:
return all([tag in clarifai_tags for tag in search_tags])
else:
return any((tag in clarifai_tags for tag in search_tags)) |
def remove_negative_sum(arr):
"""
recursive funtion to find and remove starting sequence that yeilds negative
value
"""
_sum = 0
for idx, num in enumerate(arr):
_sum += num
if _sum < 0:
return remove_negative_sum(arr[idx + 1:])
return arr |
def evaluate_frame(true_frame, pred_frame, strict=True):
"""
If strict=True,
For each dialog_act (frame), set(slot values) must match.
If dialog_act is incorrect, its set(slot values) is considered wrong.
"""
count_dict = {
'n_frames': 1,
'n_true_acts': 0,
... |
def is_oppo_clearance(event_list, team):
"""Returns whether an opponent cleared the ball"""
clearance = False
for e in event_list[:1]:
if e.type_id == 12 and e.team != team:
clearance = True
return clearance |
def lines_to_line(lines):
"""
Replaces newline with space in the pj.write(format="csv") method
"""
lines = lines.split('\n')
return (' ').join(lines) |
def _get_index_from_direction(direction):
"""Returns numerical index from direction."""
directions = ['x', 'y', 'z']
try:
# l and r are subcases of x
if direction in 'lr':
index = 0
else:
index = directions.index(direction)
except ValueError:
messa... |
def sort_012(array):
"""
Given an input array consisting on only 0, 1, and 2, sort the array in a single traversal.
Args:
array(list): List to be sorted
"""
next_index_0 = 0
next_index_2 = len(array) - 1
front_index = 0
while front_index <= next_index_2:
# Trick: front_in... |
def catch_unimplemented(c, replacement=None):
"""
Execute a callable c, returning replacement if it throws
NotImplementedError
"""
try:
return c()
except NotImplementedError:
return replacement |
def assert_is_dict(var):
"""Assert variable is from the type dictionary."""
if var is None or not isinstance(var, dict):
return {}
return var |
def as_bytes(string_array, python_version=3):
""" Transforming an array of string into an array of bytes in Python 3
"""
if python_version >= 3:
results = []
for s in string_array:
# results.append( codecs.latin_1_encode(s)[0] )
results.append( s.encode('utf-8') )
... |
def torepr(x,nchars=80):
"""limit string length using ellipses (...)"""
s = repr(x)
if len(s) > nchars: s = s[0:nchars-10-3]+"..."+s[-10:]
return s |
def getQuaternionFromDict(d):
"""
Get the quaternion from a dict describing a transform. The dict entry could be
one of orientation, rotation, quaternion depending on the convention
"""
quat = None
quatNames = ['orientation', 'rotation', 'quaternion']
for name in quatNames:
if name i... |
def weight_distrib(full, weights):
"""
Return a list of integers summing up to full weighted by weights
The items are approximately proportional to the corresponding weights.
"""
if full == 0:
return [0] * len(weights)
elif not weights:
return []
sw = float(sum(weights))
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.