content
stringlengths 42
6.51k
|
---|
def set_ranks(results):
"""
Add rank to results considering ties
@:param results (list): Sorted results
"""
results[0]['rank'] = 1
if len(results) > 1:
for i in range(len(results) - 1):
r1 = results[i]
r2 = results[i+1]
s1 = r1['score']
s2 = r2['score']
if s1 == s2:
r2['rank'] = r1['rank']
else:
r2['rank'] = i + 2
return results
|
def float_str(a: float) -> str:
"""
Convert float to string, for use in command line arguments.
"""
if a < 0:
# Use lots of decimal places for negative numbers because argparse
# has problems parsing option args that are negative numbers in
# exponential form.
# https://github.com/popsim-consortium/demes-python/issues/325
# https://bugs.python.org/issue9334
return format(a, ".10f")
else:
return str(a)
|
def concept_folders():
"""
Returns the folders containing concepts.
"""
return ['comorbidity', 'demographics', 'measurement', 'medication', 'organfailure', 'treatment', 'score', 'sepsis', 'firstday']
|
def mig_name(name):
"""
Returns name[0] (app name) and first 4 letters of migartion name (name[1]).
"""
return name[0], name[1][:4]
|
def replace_values(obj, replace_map):
"""
Deep replace of object values according to provided map.
:param obj: the object to have the values replaced
:param replace_map: the map of values with their replacements
:return: obj with replaced values
"""
if isinstance(obj, list):
for key, value in enumerate(obj):
obj[key] = replace_values(value, replace_map)
elif isinstance(obj, dict):
for key, value in obj.items():
obj[key] = replace_values(value, replace_map)
elif obj in replace_map:
return replace_map[obj]
return obj
|
def _extract_cmake_and_make_arguments(args, extract_catkin_make):
"""Extract arguments which are meant to be passed to CMake and GNU Make
through the catkin_tools command line interface.
:param args: system arguments from which special arguments need to be extracted
:type args: list
:returns: tuple of separate args, cmake_args, make args, and catkin make args
:rtype: tuple
"""
cmake_args = []
make_args = []
catkin_make_args = []
arg_types = {}
if '--no-cmake-args' not in args:
arg_types['--cmake-args'] = cmake_args
if '--no-make-args' not in args:
arg_types['--make-args'] = make_args
if extract_catkin_make and '--no-catkin_make_args' not in args:
arg_types['--catkin-make-args'] = catkin_make_args
arg_indexes = {}
for k in arg_types.keys():
if k in args:
arg_indexes[args.index(k)] = k
def split_arguments(args, splitter_name):
if splitter_name not in args:
return args, None
index = args.index(splitter_name)
return args[0:index], args[index + 1:]
for index in reversed(sorted(arg_indexes.keys())):
arg_type = arg_indexes[index]
args, specific_args = split_arguments(args, arg_type)
arg_types[arg_type].extend(specific_args)
# classify -D* and -G* arguments as cmake specific arguments
if '--cmake-args' in arg_types:
implicit_cmake_args = [a for a in args if a.startswith('-D') or a.startswith('-G')]
args = [a for a in args if a not in implicit_cmake_args]
cmake_args = implicit_cmake_args + cmake_args
if '--no-cmake-args' not in args and len(cmake_args) == 0:
cmake_args = None
if '--no-make-args' not in args and len(make_args) == 0:
make_args = None
if extract_catkin_make and '--no-catkin_make_args' not in args and len(catkin_make_args) == 0:
catkin_make_args = None
return args, cmake_args, make_args, catkin_make_args
|
def truncate_name(string, size):
""" Truncate an str whose length is greater than size,
and add ellipsis at the end. """
return f"{string[:size]}..."
|
def propose(prop, seq):
"""wrapper to access a dictionary even for non-present keys"""
if seq in prop:
return prop[seq]
else:
return None
|
def transpose_sample(sample):
"""Transpose the sample.
By default, a sample should be a list of tuples of the form::
S = [(x_1, y_1), ..., (x_n, y_n)]
For most algorithms, we need to isolate the sample components (e.g. all x's).
This function converts a sample from a list of tuples to a tuple of lists::
S_T = ([x_1, ..., x_n], [y_1, ..., y_n])
This can then be unpacked as: ``X, Y = S_T``
Args:
sample: list of tuples
Returns:
tuple of lists
"""
return tuple(map(list, zip(*sample)))
|
def convert_frag_id_save(frag_id):
"""Converts a mmLib fragment_id to a TLSOUT fragment id.
"""
if len(frag_id) == 0:
return "."
if frag_id[-1].isdigit():
frag_id += "."
return frag_id
|
def Get_Weapon_Service_Mod(item, year, date1, date2):
"""
Get_Weapon_Service_Mod(item, year, date1, date2):
provides a multiplier for stock rates based upon the current year and weapon service period.
Results in increased stock int he middile of a service period,
dwindling stock at the end, and low stock at the beginning
"""
if date2 >= year >= date1:
#we're in service now
mod1a = (year - date1 + 2) / 6 #entering service modifier
mod1b = (date2 - year) / 4 #exiting service modifier
mod2a = (year - date1) / 100
mod2b = 0
if mod1a > 0 and mod1a < mod1b:
mod1 = mod1a
elif mod1b > 0 and mod1a > mod1b:
mod1 = mod1b
else:
mod1 = 0
if mod1 > 1:
mod1 = 1
if mod2a > 0 and mod2a < 0.1:
mod2 = mod2a
elif mod2a >= 0.1:
mod2 = 0.1
else:
mod2 = 0
mod = mod1 + mod2
else:
mod = 0
if mod < 0:
mod = 0
return mod
|
def get_timeout(backoff_factor: float, number_of_retries: int) -> float:
"""
Gets timeout based on backoff_factor
:param backoff_factor: value of backoff factor
:param number_of_retries: current number of retries made
Examples:
>>> __backoff_factor, __number_of_retries = 0.1, 1
>>> timeout = get_timeout(__backoff_factor, __number_of_retries)
>>> assert timeout == 0.1
>>>
>>> __backoff_factor, __number_of_retries = 0.1, 2
>>> timeout = get_timeout(__backoff_factor, __number_of_retries)
>>> assert timeout == 0.2
"""
return backoff_factor * (2 ** (number_of_retries - 1))
|
def get_current_IP(splited_ip):
"""
Incrementa la IP recibida en 1 en la posicion menos significativa
Cuida que al llegar a 255 cualquiera de las posiciones, se haga el cambio
debido.
Devuelve la lista de enteros ya incrementada
"""
splited_ip[3] += 1
if splited_ip[3] > 255:
splited_ip[3] = 0
splited_ip[2] += 1
if splited_ip[2] > 255:
splited_ip[2] = 0
splited_ip[1] += 1
if splited_ip[1] > 255:
splited_ip[1] = 0
splited_ip[0] += 1
return splited_ip
|
def text2short(text, max_length=20):
""" long text to short text """
if text is None:
return ''
text = str(text)
return text[:max_length] + '...' if len(text) > max_length else text
|
def _test_common_make_dtw_function(distance_mode, normalize, dtw_functions):
"""
Used during testing to construct (if needed) the DTW function for the requested distance mode.
:param distance_mode: A string used to lookup the requested DTW function (typically either 'cosine' or 'euclidean').
:param normalize: Whether DTW distances should be length normalized.
:param dtw_functions: The dictionary of DTW function constructors to use to get the requested DTW function
implementation.
:return: The requested DTW function implementation.
"""
assert isinstance(distance_mode, str)
assert isinstance(normalize, bool)
assert isinstance(dtw_functions, dict)
assert len(dtw_functions) > 0
assert distance_mode in dtw_functions
return dtw_functions[distance_mode]()
|
def create_promise_command(
string: str, *args) -> str:
"""Use a `string` as template command and fill in the options using
possible promised `args`
"""
return string.format(*args)
|
def vp2vs(vp,ref='brocher',mafic=False):
"""
Good fit all lithologies for 1.5<vp<8.0 EXCEPT Ca-rich, mafic, gabbros, serpentines (overpredics)
"""
if mafic: # 5.25<vp<7.25
vs = 2.88 + 0.52*(vp - 5.25)
else:
vs = 0.7858 - 1.2344*vp + 0.7949*vp**2 - 0.1238*vp**3 + 0.0064*vp**4
return vs
|
def create_criteria(label,
help_txt,
crit_type,
standalone_impact,
disable_processing,
section,
input_type,
rating,
universe,
mem_funcs,
dtypes,
init_value=None,
max_value=None,
min_value=None
):
"""
Create criterion JSON format from input values
@retuns criterion JSON structure
"""
crit = {"label": label,
"universe": universe,
"mem_funcs": mem_funcs,
"rating": list(rating.keys()),
"type": crit_type,
"dtypes": dtypes,
"rules": {
"standalone_impact": standalone_impact,
"disable_processing": disable_processing
},
"frontend": {
"type": input_type,
"section": section,
"help": help_txt,
"rating": rating
}}
if input_type not in ["list", "text"]:
assert init_value is not None, "Initial value for frontend must be given for number/range inputs."
assert max_value is not None, "Max value for frontend must be given for number/range inputs."
assert min_value is not None, f"Min value for frontend must be given for number/range inputs. ({min_value})"
crit["frontend"]["initialValue"] = init_value
crit["frontend"]["max"] = max_value
crit["frontend"]["min"] = min_value
crit["frontend"]["range_min"] = list(rating.values())[0]
crit["frontend"]["range_max"] = list(rating.values())[-1]
return crit
|
def sort_by_key(dictionary):
"""We need to sort the dictionaries by key to ensure that questions are
presented in the correct order
"""
sorted_dictionary = {}
for key in sorted(dictionary):
sorted_dictionary[key] = dictionary[key]
return sorted_dictionary
|
def numonly(tovalidate):
"""Returns T or F depending on whether the input is a single character in 0-9, ., or and empty string"""
return tovalidate.isdecimal() | (tovalidate == '.') | (tovalidate == '')
|
def convert_polynomial(degree, polynomial_num):
"""convert_irreducible_polynomial
Example
=======
>>> degree = 8
>>> polynomial_num = 14
# coeffs = (1(001110)1)
>>> 0b10011101 = convert_polynomial(degree, polynomial_num)
"""
return ((1 << degree)
+
(polynomial_num << 1)
+
1)
|
def cyclic_index_i_minus_1(i: int) -> int:
"""A helper function for cyclic indexing rotor scans"""
return i - 1 if i - 1 > 0 else -1
|
def sort_categories(revenue_data):
"""
Need to sort the category data so that its matches what is
showed in the national budget.
"""
revenue = []
duties_total = 0
other_total = 0
for r in revenue_data:
if ('Customs duties' in r['category_two']) or ('excise duties' in r['category_two']):
duties_total += int(r['amount'])
elif 'income tax' in r['category_two']:
revenue.append(
{
'category': r['category_two'].title(),
'amount': r['amount']
}
)
elif 'Value-added tax' in r['category_two']:
revenue.append(
{
'category': r['category_two'].title(),
'amount': r['amount']
}
)
elif 'General fuel levy' in r['category_two']:
revenue.append(
{
'category': 'Fuel Levies',
'amount': r['amount']
}
)
else:
other_total += int(r['amount'])
revenue.append(
{
'category': 'Customs and Excise Duties',
'amount': str(duties_total)
}
)
revenue.append(
{
'category': 'Other',
'amount': str(other_total)
}
)
return revenue
|
def color_mark(mark):
"""Add color to the mark output."""
return "\033[38;5;36m{}\033[0;0m".format(mark)
|
def to_dict(l):
"""Given a line of the form Key0: Value0;Key2: Valuue2; Return a dict"""
fields = l.split(';')
result = {}
for f in fields:
if f:
v = f.split(':')
assert len(v) == 2
result[v[0].strip()] = v[1].strip()
return result
|
def in_between(now, start, end):
"""Finding out if given time is between two ranges
Args:
now (time): given time
start (time): start time (lower bound)
end (time): end time (upper time)
Returns:
bool: Checks if time is between upper and lower bounds
"""
if start <= end:
return start <= now < end
else:
return start <= now or now < end
|
def max_exval(v1, v2):
""" Return the larger one between two extended values. """
if v1 >= v2:
return v2
return v1
|
def _quotify(mystr):
"""
quotifies an html tag attribute value.
Assumes then, that any ocurrence of ' or " in the
string is escaped if original string was quoted
with it.
So this function does not altere the original string
except for quotation at both ends, and is limited just
to guess if string must be quoted with '"' or "'"
"""
quote = '"'
l = len(mystr)
for i in range(l):
if mystr[i] == "\\" and i + 1 < l and mystr[i+1] == "'":
quote = "'"; break
elif mystr[i] == "\\" and i + 1 < l and mystr[i+1] == '"':
quote = '"'; break
elif mystr[i] == "'":
quote = '"'; break
elif mystr[i] == '"':
quote = "'"; break
return quote + mystr + quote
|
def pin_list_to_board_dict(capability_query_response):
"""
Capability Response codes:
INPUT: 0, 1
OUTPUT: 1, 1
ANALOG: 2, 10
PWM: 3, 8
SERV0: 4, 14
I2C: 6, 1
"""
board_dict = {
'digital': [],
'analog': [],
'pwm': [],
'servo': [],
'i2c': [],
'disabled': [],
}
# i split pins of list:
pin_list = [[]]
for b in capability_query_response:
if b == 127:
pin_list.append([])
else:
pin_list[-1].append(b)
pin_list.pop() # removes the empty [] on end
# Finds the capability of each pin
for i, pin in enumerate(pin_list):
if not pin:
board_dict['disabled'] += [i]
board_dict['digital'] += [i]
continue
for j, _ in enumerate(pin):
# Iterate over evens
if j % 2 == 0:
# This is safe. try: range(10)[5:50]
if pin[j:j + 4] == [0, 1, 1, 1]:
board_dict['digital'] += [i]
if pin[j:j + 2] == [2, 10]:
board_dict['analog'] += [i]
if pin[j:j + 2] == [3, 8]:
board_dict['pwm'] += [i]
if pin[j:j + 2] == [4, 14]:
board_dict['servo'] += [i]
if pin[j:j + 2] == [6, 1]:
board_dict['i2c'] += [i]
# We have to deal with analog pins:
# - (14, 15, 16, 17, 18, 19)
# + (0, 1, 2, 3, 4, 5)
diff = set(board_dict['digital']) - set(board_dict['analog'])
board_dict['analog'] = [n for n, _ in enumerate(board_dict['analog'])]
# Digital pin problems:
# - (2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15)
# + (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13)
board_dict['digital'] = [n for n, _ in enumerate(diff)]
# Based on lib Arduino 0017
board_dict['servo'] = board_dict['digital']
# Turn lists into tuples
# Using dict for Python 2.6 compatibility
board_dict = dict([
(key, tuple(value))
for key, value
in board_dict.items()
])
return board_dict
|
def Guinier(q,I0,Rg):
"""Returns Guinier approximation to the SAXS intensity distribution, as
parameterized by I0 and Rg, as a function of q."""
from numpy import exp
return I0*exp(-(q*Rg)**2/3)
|
def rreplace(text: str, cut: str, place: str):
""" right replace: https://stackoverflow.com/a/9943875/1506477
>>> 'XXX'.join('mississippi'.rsplit('iss', 1))
'missXXXippi'
"""
return place.join(text.split(cut, 1))
|
def length_gte(value, arg):
"""Returns a boolean of whether the value's length is greater than or equal
to the argument.
"""
return len(value) >= int(arg)
|
def sum(a, b):
"""
Retorna a + b.
>>> sum(5, 7)
12
>>> sum(5, "Python")
Traceback (most recent call last):
...
TypeError
"""
for n in (a, b):
if not isinstance(n, int) and not isinstance(n, float):
raise TypeError
return a + b
|
def check_date(d):
"""Check if a string is a valide date of the form "YYYY-MM-DD".
:param d: The date string that is checked.
:return: True if it is a not valid date string.
"""
if len(d) != 10:
return True
split = d.split("-")
return len(split) != 3 or not split[0].isdecimal() or not split[1].isdecimal() or not split[2].isdecimal()
|
def prime_factor(x):
""" Return the prime factor of input x
Parameters
----------
x (int): input natural number > 1
Return
------
sorted_pf (set): list of prime factor of x """
if not x:
raise ValueError("Empty input.")
if not isinstance(x, int):
raise ValueError("Input value must be integer.")
if x < 2:
return None
pf = set()
while x > 1:
for i in range(2, x + 1):
if x % i == 0:
x = int(x / i)
pf.add(i)
break
sorted_pf = sorted(pf)
return sorted_pf
|
def widget_input_type(field):
"""This function takes a form field and extracts a field type."""
try: # CharField ==> "text"
input_type = field.field.widget.input_type
except AttributeError: # Workaround for the fact that Textarea does not have an input type.
input_type = 'textarea'
return input_type
|
def nested_sum(nlist):
"""
Return the sum of nested lists. Can handle multiple levels of nesting and integers
alongside nested lists.
"""
total = 0
for list_item in nlist:
if isinstance(list_item, list):
total += nested_sum(list_item)
elif isinstance(list_item, int):
total += list_item
else:
print(list_item, ' is not an integer or list.')
return total
|
def shard_weight(w, num_cores):
"""Apply XLA sharding to a weight `w`."""
del num_cores
return w
|
def escapeHtml(data):
"""
Escape &, <, > and line breaks in a unicode string of data.
"""
# must do ampersand first
return data.replace(u"&", u"&").replace(u">", u">").\
replace(u"<", u"<").replace(u"\n", u"<br />\n")
|
def avarageOfBest3(arg1: float, arg2:float, arg3:float, arg4:float) -> float:
"""
The function takes four arguments, it returns the avarage value of the best three grades.
Example :
>>> avarageOfBest3(3,4,4,5)
4.333333333333333
>>>
"""
"""
grades = [arg1,arg2,arg3,arg4]
grades = sorted(grades)
grades = grades[-3:]
sum = 0
for i in grades :
sum = sum + i
return sum/3
"""
minGrade = min(arg1,arg2,arg3,arg4)
sumOfThreeGrades = ( arg1 + arg2 + arg3 + arg4 ) - minGrade
return sumOfThreeGrades / 3
|
def flatten_list(l):
"""
Flattens a list one level.
"""
flattened_l = []
for ele in l:
if type(ele) == list or type(ele) == tuple:
flattened_l.extend(ele)
else:
flattened_l.append(ele)
return flattened_l
|
def email_middle(content):
"""
Generates the middle section with the provided content.
Arguments:
content - html content of the middle section
Returns:
html_content - html code
"""
html_content = "<div style=\"background:url("
html_content += "'https://www.gstatic.com/android/market_images/"
html_content += "email/email_mid.png') repeat-y;width:100%;"
html_content += "display:block\">"
html_content += (
'<div style="padding-left:50px;padding-right:50px;padding-bottom:1px">'
)
html_content += '<div style="border-bottom:1px solid #ededed"></div>'
html_content += '<div style="margin:20px 0px;font-size:20px;'
html_content += 'line-height:30px;text-align:left">'
html_content += content
html_content += "</div>"
html_content += '<div style="text-align:left"></div>'
html_content += '<div style="border-bottom:1px solid #ededed"></div>'
html_content += "<br>"
html_content += "<div>This is an automated email notification sent from "
html_content += "the Turing Research Compute Platforms cloud platform - "
html_content += "please do not reply to it.</div></div></div>"
return html_content
|
def manhattan_dist(pose1, pose2):
""" Returns manhattan distance between two poses """
return abs(pose1[0] - pose2[0]) + abs(pose1[1] - pose2[1])
|
def to_rna(dna_strand: str) -> str:
"""Return the RNA complement of a given DNA strand."""
transcription = dna_strand.maketrans('GCTA', 'CGAU')
return dna_strand.translate(transcription)
|
def anonymize_str(s):
""" Anonymize a string but leave its first and last characters visible.
:param str s: a string
:return: string with all non-extreme characters replaced by *
:rtype: str
"""
if len(s) < 3:
return s
return s[0] + ("*" * (len(s) - 2)) + s[-1]
|
def get_output_path(bucket, output_prefix):
"""Maps path variables into a new S3 URL to store predictions"""
output_path = 's3://' + '/'.join([bucket, output_prefix])
return output_path
|
def sort_parts(wf):
"""Sort jobs and job uses to make test deterministic"""
for job in wf["jobs"]:
job["uses"].sort(key=lambda u: u["lfn"])
wf["jobs"].sort(key=lambda j: j["id"])
return wf
|
def to_str_with_pad(number, n_char=0, pad_value=0):
"""Convert number to string representation with zero padding.
Args:
i (int): number.
n_char (int, optional): zero padding. Defaults to 0.
Returns:
[type]: [description]
"""
return f"{number:{pad_value}{n_char}d}"
|
def my_strip(thing):
"""Safely strip `thing`.
"""
try:
return thing.strip()
except:
return thing
|
def get_rns_from_ec_dict(ec_dict: dict, list_of_ecs=None):
"""get unique list of reactions from ecs in dictionary output by
`KEGG_parser.downloader.get_kegg_record_dict` that are in
*list_of_ecs* or all if *list_of_ecs* is None.
"""
if not list_of_ecs:
list_of_ecs = ec_dict.keys()
rns = set()
for ec in list_of_ecs:
try:
ec_record = ec_dict[ec]
if "ALL_REAC" in ec_record:
rns.update(ec_record["ALL_REAC"])
except KeyError:
pass
return list(rns)
|
def calc_intensity_diff(R_c, I):
"""Computes distance between the image intensity
and R_c as in eq:8
"""
R_min, R_max = R_c
Ihi = (I - R_max) * (I > R_max)
Ilo = (R_min - I) * (R_min > I)
return Ihi + Ilo
|
def getBucketForDomain(domain):
""" get the bucket for the domain or None
if no bucket is given
"""
if not domain:
return None
if domain[0] == '/':
# no bucket specified
return None
index = domain.find('/')
if index < 0:
# invalid domain?
return None
return domain[:index]
|
def create_vocab(corpus):
"""
This function creates a set of unique
and preprocessed words from a corpus
Arguments
corpus : pandas df column or list-like
Returns
vocab : dictionary with the words as keys
and a unique integer for each as values
"""
vocab = set()
for doc in corpus:
vocab.update(set(doc))
return {word:idx for idx, word in enumerate(vocab)}
|
def to_camel_case(snake_case_str):
"""Converts a SNAKE_CASE string into a CamelCase string."""
return ''.join(s.lower().title() for s in snake_case_str.split('_'))
|
def resolve_acl(atypes):
"""Resolves the bits of accesstypes into single int and externals to unique set"""
ret = {
'bits': int(0),
'externals': set(),
}
for at in atypes:
ret['bits'] |= 1 << at.bit
ret['externals'].add(at.external_id)
ret['externals'] = list(ret['externals'])
return ret
|
def line_split(line):
"""Fastest line-splitter (should be fast for IronPython)"""
line_list = []
[line_list.append('"' + chunk + '"') if i%2==1 else line_list.extend(chunk.split()) for i, chunk in enumerate(line.split('"'))]
return line_list
|
def divide(numbers):
"""
Returns the division of the provided list of numbers (> float)
"""
final_result = numbers[0]
list = numbers
del list[0]
for number in list:
if number == 0:
return "Error: Division by zero"
else:
final_result = final_result / number
return final_result
|
def thermalcond(x, So, Gb):
"""
Calculate thermal conductivity of wood at moisture content, volumetric
shrinkage, and basic specific gravity.
Example:
k = thermalcond(12, 12.3, 0.54)
Inputs:
x = moisture content, %
So = volumetric shrinkage, Table 4-3, %
Gb = basic specific gravity, Table 4-7 or Table 5-3
Outputs:
k = thermal conductivity, W/(m*k)
Reference:
Glass and Zelinka, 2010. Wood Handbook, Ch. 4, pp. 1-19.
"""
mcfs = 30 # fiber staturation point estimate, %
# shrinkage from green to final moisture content, Eq. 4-7, %
Sx = So*(1 - x/mcfs)
# specific gravity based on volume at given moisture content, Eq. 4-9
Gx = Gb / (1 - Sx/100)
# thermal conductivity, Eq. 4-15, W/(m*K)
A = 0.01864
B = 0.1941
C = 0.004064
k = Gx*(B + C*x) + A
return k
|
def is_an_oak(name):
""" Returns True if name is starts with 'quercus' or with one mistake
>>> is_an_oak('Fagus sylvatica')
False
>>> is_an_oak("Quercus robur")
True
>>> is_an_oak("Quercuss robur")
False
>>> is_an_oak("Quaercus robur")
False
>>> is_an_oak("Qurcus robur")
False
>>> is_an_oak("alaufsadfrasdfuafdefddasfrasdfufdascdfasdq")
False
>>> is_an_oak("qalauf")
False
>>> is_an_oak("qreusci albati")
False
"""
if all( [len(set(list(name)) & set(list("quercus"))) >=4,name.lower().startswith('qu'),len(name.split( )[0]) <=9] ): return True
# if all( [name.lower().startswith('quercus'), len(name.split( )[0]) ==7] ): return True
return False
|
def get_ls(omega_list):
"""Return the array of the Solar longitude of each OMEGA/MEx observation in omega_list.
Parameters
==========
omega_list : array of OMEGAdata
The input array of OMEGA observations.
Returns
=======
ls : ndarray
The array of the omega_list Ls.
"""
ls = []
for omega in omega_list:
ls.append(omega.ls)
return ls
|
def is_almost_right(a,b,c):
""" Checks if triangle is right-angled."""
# Use sorted(), which gives a sorted list
a,b,c = sorted([a,b,c])
# Check to see if it is almost a right triangle
if abs(a**2+b**2-c**2) < 1e-12:
return True
else:
return False
|
def rotate(string, n):
"""Rotate characters in a string.
Expects string and n (int) for number of characters to move.
"""
return string[n:] + string[:n]
|
def nextyear(string_year):
"""
Takes a string year and returns a string of next year
"""
int_year = int(string_year)
next_year = int_year + 1
return str(next_year)
|
def as_ref(name, value):
"""
Generate the dict that represents a reference tag.
"""
dbname = name.upper()
if name == "ncbi_taxonomy_id":
dbname = name
return {"attrib": {"dbname": dbname, "dbkey": str(value)}}
|
def r_to_r_swap_H(params, substep, state_history, prev_state, policy_input):
"""
This function calculates and returns the quantity H after a trade between two risk assets
Under the mechanism defined June 28, 2021 there is **no change** in the quantity H
"""
H = prev_state['H']
return ('H', H)
|
def container_status(value):
"""
Returns container status as a bootstrap class
"""
cls = ''
if value:
if value.get('Running'):
cls = 'success'
elif value.get('ExitCode') == 0:
cls = 'info'
else:
cls = 'important'
return cls
|
def GetDictionaryKeys(value, keys):
""" Returns a dictionary containing `keys` from `value` if present. """
return {key: value[key] for key in keys if key in value}
|
def dateIsBefore(year1, month1, day1, year2, month2, day2):
"""Returns True if year1-month1-day1 is before
year2-month2-day2. Otherwise, returns False."""
if year1 < year2:
return True
if year1 == year2:
if month1 < month2:
return True
if month1 == month2:
return day1 < day2
return False
|
def get_mem_stats(domain, stats):
"""
Get memory stats.
.. list-table:: Memory stats
:widths: 25 75
:header-rows: 1
* - Measure
- Description
* - Total (mem_max_bytes)
- Amount of memory specified on domain creation of VM
* - Used (mem_use_bytes)
- Returns values close to total, because VM holds all the memory needed as
appears from the outside and does not reflect internal state of OS here.
* - Free (mem_free_bytes)
- Amount of memory left unused by the system (opposite)
* - Rss (mem_rss_bytes)
- Resident Set Size of the process running the domain
Limitations:
* both used and free reflect the process, but not what is seen inside VM, so it may
not be useful for user or billing. Will have to review with higher versions of
Openstack when we move on.
:param domain: libvirt domain object for extra stats.
:param dict stats: statistics data retrieved from libvirt.
:return dict: stats
"""
items = {}
try:
mem = domain.memoryStats()
items = {
'mem_use_bytes': 1000 * mem.get('available', 0) if mem.get('available', 0) >= 0 else 0,
'mem_rss_bytes': 1000 * mem.get('rss', 0) if mem.get('rss', 0) >= 0 else 0,
'mem_free_bytes': 1000 * mem.get('unused', 0) if mem.get('unused', 0) >= 0 else 0,
'mem_max_bytes': 1000 * mem.get('actual', 0) if mem.get('actual', 0) >= 0 else 0,
}
except Exception:
items = {
'mem_use_bytes': 1000 * stats.get('balloon.current', 0),
'mem_max_bytes': 1000 * stats.get('balloon.maximum', 0),
}
return items
|
def indent(text, prefix):
"""
Adds `prefix` to the beginning of non-empty lines in `text`.
"""
# Based on Python 3's textwrap.indent
def prefixed_lines():
for line in text.splitlines(True):
yield (prefix + line if line.strip() else line)
return u"".join(prefixed_lines())
|
def convert_string_to_binary (string):
"""This function attempts to convert a string to binary.
Acknowledgments:
Thanks to Minnie Kumar for finding an error in the
get_hash_of_string function and providing a solution.
Code based an answer from Elizafox on Stack Overflow:
http://stackoverflow.com/questions/34869889/what-is-the-proper-way-to-determine-if-an-object-is-a-bytes-like-object-in-pytho
"""
try:
string = string.encode()
except:
pass
return string
|
def dt_pos(v):
"""Calculate t for which pos is max"""
# x(t) = (-1/2)t^2 + (1/2 + vx)t
# x'(t) = -t + 1/2 + vx
# x'(t) = 0
# t = 1/2 + vx
# since we're working with integers, t = vx is fine
return v
|
def median(numbers):
"""if numbers not exist, we return 0"""
if not numbers:
return 0
if len(numbers) % 2 == 1:
return sorted(numbers)[len(numbers)//2]
else:
a, b = sorted(numbers)[len(numbers)//2], numbers[len(numbers)//2-1]
return round((a+b)/2, 2)
|
def get_ado(word: str):
"""
split word according to A, D, O tag
hello123world -> [(hello, A, 5), (123, D, 3), (world, A, 5)]
:param word:
:return:
"""
prev_chr_type = None
acc = ""
parts = []
for c in word:
if c.isalpha():
cur_chr_type = "A"
elif c.isdigit():
cur_chr_type = "D"
else:
cur_chr_type = "O"
if prev_chr_type is None:
acc = c
elif prev_chr_type == cur_chr_type:
acc += c
else:
parts.append((acc, prev_chr_type, len(acc)))
acc = c
prev_chr_type = cur_chr_type
parts.append((acc, prev_chr_type, len(acc)))
return parts
|
def p1(range_max, factor_list):
"""Problem 1
If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.
"""
range_min = 0
sum_multiples = 0
for num in range(range_max):
if num % factor_list[0] == 0:
sum_multiples = sum_multiples + num
elif num % factor_list[1] == 0:
sum_multiples = sum_multiples + num
# print(num)
print("Summation of multiples is: %g" % sum_multiples)
return sum_multiples
|
def ndvi705(b5, b6):
"""
Red-edge Normalized Difference Vegetation Index \
(Gitelson and Merzlyak, 1994).
.. math:: NDVI705 = (b6 - b5)/(b6 + b5)
:param b5: Red-edge 1.
:type b5: numpy.ndarray or float
:param b6: Red-edge 2.
:type b6: numpy.ndarray or float
:returns NDVI705: Index value
.. Tip::
Gitelson, A., Merzlyak, M. N. 1994. Spectral reflectance changes \
associated with autumn senescence of Aesculus hippocastanum L. and \
Acer platanoides L. leaves. Spectral features and relation to \
chlorophyll estimation. Journal of Plant Physiology 143(3), 286-292. \
doi:10.1016/S0176-1617(11)81633-0.
"""
NDVI705 = (b6 - b5)/(b6 + b5)
return NDVI705
|
def str_input_ok(text: str) -> bool:
"""Retourne False si text vide ou juste des espaces"""
return bool(text.strip())
|
def summarize(filename):
"""Return basic information about the contents of a csv file with the rows as scan instances."""
import pandas as pd
if filename.endswith('.csv'):
loaded_file = pd.read_csv(filename)
print("The head of the file is:" + "\n" + str(loaded_file.head()))
print("Summary information about the file is as follows:")
print(loaded_file.info())
number_of_scans = str(len(loaded_file.index))
print("The file contains information about " + number_of_scans + " scans.")
closing_statement = filename + " has been summarized."
return closing_statement
else:
print("The file provided is not in comma separated value format. Please convert your input file to .csv format before using this package.")
|
def sum_1_n(n: int) -> int:
"""Calculates the sum from 1 to n.
see https://en.wikipedia.org/wiki/1_%2B_2_%2B_3_%2B_4_%2B_%E2%8B%AF
:rtype: int
:param n: the integer to sum up to
:return: sum from 1 to n
"""
assert n >= 0, 'n must not be negative!'
return int(n * (n + 1) / 2)
|
def common_prefix(strings):
""" Find the longest string that is a prefix of all the strings.
http://bitbucket.org/ned/cog/src/tip/cogapp/whiteutils.py
"""
if not strings:
return ''
prefix = strings[0]
for s in strings:
if len(s) < len(prefix):
prefix = prefix[:len(s)]
if not prefix:
return ''
for i in range(len(prefix)):
if prefix[i] != s[i]:
prefix = prefix[:i]
break
return prefix
|
def ConfigToNumElectrons(config, ignoreFullD=0, ignoreFullF=0):
""" counts the number of electrons appearing in a configuration string
**Arguments**
- config: the configuration string (e.g. '2s^2 2p^4')
- ignoreFullD: toggles not counting full d shells
- ignoreFullF: toggles not counting full f shells
**Returns**
the number of valence electrons
"""
arr = config.split(' ')
nEl = 0
for i in range(1, len(arr)):
l = arr[i].split('^')
incr = int(l[1])
if ignoreFullF and incr == 14 and l[0].find('f') != -1 and len(arr) > 2:
incr = 0
if ignoreFullD and incr == 10 and l[0].find('d') != -1 and len(arr) > 2:
incr = 0
nEl = nEl + incr
return nEl
|
def decode_mac(addr):
"""
Decode readable mac address
"""
assert isinstance(addr, bytes) and len(addr) == 6, ValueError("mac address value error")
return ":".join(['%02X' % byte for byte in addr])
|
def leap(year):
"""Return true if the year was a leap year under the system of Sarkawag"""
if year < 533:
return False
return year % 4 == 0
|
def file_record_to_url(file_records) -> list:
"""
Translate a Json dictionary to an usable http url for downloading files.
Parameters
----------
file_records : dict
JSON containing a 'data_url' field
Returns
-------
list of str
A list of full data urls
"""
urls = []
for fr in file_records:
if fr['data_url'] is not None:
urls.append(fr['data_url'])
return urls
|
def choose(n, r):
"""The number of ways of choosing r items from n"""
if n < 0 or r < 0:
print('Negative values not allowed')
return 0
if r > n:
print('r must not be greater than n')
return 0
combin = 1
if r > n / 2:
r1 = n - r
else:
r1 = r
for k in range(r1):
combin = combin * (n - k) // (k + 1)
return combin
|
def match_candidates_all(images):
"""All pairwise images are candidate matches"""
# empty set
pairs = set()
# enumerate all possible pairs
for i, image in enumerate(images):
for j in range(i+1,len(images)):
pairs.add( tuple( sorted( (images[i], images[j]) )))
# store pairs as dictionary
#res = {im: [] for im in images}
#for im1, im2 in pairs:
# res[im1].append(im2)
# return
return pairs
|
def check_group1(digits):
"""
Input : Barcode
Return : L/G/R
"""
first = digits[0]
first = int(first)
if first == 0:
return 'LLLLLL'
elif first == 1:
return 'LLGLGG'
elif first == 2:
return 'LLGGLG'
elif first == 3:
return 'LLGGGL'
elif first == 4:
return 'LGLLGG'
elif first == 5:
return 'LGGLLG'
elif first == 6:
return 'LGGGLL'
elif first == 7:
return 'LGLGLG'
elif first == 8:
return 'LGLGGL'
else:
return 'LGGLGL'
|
def split_word(text, max_chars):
"""
used to split long usernames with spaces, seeks capitals as a preference to split with
>>> split_word("IAmAWaffleFiend", 6)
'IAmA Waffle Fiend'
>>> split_word("abcde12345abcde12345", 5)
'abcde 12345 abcde 12345'
>>> split_word("abc de12345", 5)
'abc de123 45'
>>> split_word("abc de12345", 0)
'abc de12345'
>>> split_word("Mr.Longname", 8)
'Mr. Longname'
"""
if max_chars <= 0:
return text
new_text = ''
current_count = 0
for i in range(len(text)):
if (text[i].isspace()):
current_count = 0
elif current_count >= max_chars:
for n in range(1, current_count):
if new_text[-n].isupper():
new_text = new_text[0:-n] + " " + new_text[-n:]
current_count = n
break
else:
new_text += ' '
current_count = 1
else:
current_count += 1
new_text += text[i]
return new_text
|
def _get_all_cwlkeys(items, default_keys=None):
"""Retrieve cwlkeys from inputs, handling defaults which can be null.
When inputs are null in some and present in others, this creates unequal
keys in each sample, confusing decision making about which are primary and extras.
"""
if default_keys:
default_keys = set(default_keys)
else:
default_keys = set(["metadata__batch", "config__algorithm__validate",
"config__algorithm__validate_regions",
"config__algorithm__validate_regions_merged",
"config__algorithm__variant_regions",
"validate__summary",
"validate__tp", "validate__fp", "validate__fn",
"config__algorithm__coverage", "config__algorithm__coverage_merged",
"genome_resources__variation__cosmic", "genome_resources__variation__dbsnp",
])
all_keys = set([])
for data in items:
all_keys.update(set(data["cwl_keys"]))
all_keys.update(default_keys)
return all_keys
|
def _GetGroupingLabel(story):
"""Computes the label used to group values when summarizing.
This used to be the 'tir_label' of the value, but that is now an obsolete
concept after the deprecation of TBMv1 metrics.
"""
if story is not None and story.grouping_keys:
# We sort by key name to make building the grouping_label deterministic.
return '_'.join(v for _, v in sorted(story.grouping_keys.iteritems()))
else:
return None
|
def _summary_table(content, platform):
"""Returns the HTML <div> component of the summary table."""
return """
<pre class="collapse" id="summary-{platform}" style="font-size:0.75em; color:gray">{content}</pre>
<br>
""".format(
platform=platform, content=content)
|
def join_section_lines(lines):
"""
The inverse of split_section_lines().
"""
return '\n'.join(lines) + '\n'
|
def intlen(n):
"""Find the length of the integer part of a number *n*."""
pos = n.find(".")
return len(n) if pos < 0 else pos
|
def decode(index_map):
"""
Decode from base64
"""
return bytes(index_map).decode('utf8')
|
def calc_image_merge_clip(x1, y1, x2, y2,
dst_x, dst_y, a1, b1, a2, b2):
"""
(x1, y1) and (x2, y2) define the extent of the (non-scaled) data
shown. The image, defined by region (a1, b1), (a2, b2) is to be
placed at (dst_x, dst_y) in the image (destination may be outside
of the actual data array).
Refines the tuple (a1, b1, a2, b2) defining the clipped rectangle
needed to be cut from the source array and scaled.
"""
#print "calc clip in dst", x1, y1, x2, y2
#print "calc clip in src", dst_x, dst_y, a1, b1, a2, b2
src_wd, src_ht = a2 - a1, b2 - b1
# Trim off parts of srcarr that would be "hidden"
# to the left and above the dstarr edge.
ex = y1 - dst_y
if ex > 0:
src_ht -= ex
dst_y += ex
#b2 -= ex
b1 += ex
ex = x1 - dst_x
if ex > 0:
src_wd -= ex
dst_x += ex
a1 += ex
# Trim off parts of srcarr that would be "hidden"
# to the right and below the dstarr edge.
ex = dst_y + src_ht - y2
if ex > 0:
src_ht -= ex
#b1 += ex
b2 -= ex
ex = dst_x + src_wd - x2
if ex > 0:
src_wd -= ex
a2 -= ex
#print "calc clip out", dst_x, dst_y, a1, b1, a2, b2
return (dst_x, dst_y, a1, b1, a2, b2)
|
def is_arraylike(x):
"""
Determine if `x` is array-like. `x` is index-able if it provides the
`__len__` and `__getitem__` methods. Note that `__getitem__` should
accept 1D NumPy integer arrays as an index
Parameters
----------
x: any
The value to test for being array-like
Returns
-------
bool
`True` if array-like, `False` if not
"""
return hasattr(x, '__len__') and hasattr(x, '__getitem__')
|
def _get_default_column_names_and_groups(model_names):
"""Get column names and groups to display in the estimation table.
Args:
model_names (list): List of model names.
Returns:
col_names (list): List of estimation column names to display in estimation
table. Same as model_names if model_names are unique. Given by column
position (counting from 1) in braces otherwise.
col_groups (list or NoneType): If defined, list of strings unique values
of which will define column groups. Not defined if model_names are unique.
"""
if len(set(model_names)) == len(model_names):
col_groups = None
col_names = model_names
else:
col_groups = model_names
col_names = [f"({i + 1})" for i in range(len(model_names))]
return col_names, col_groups
|
def findIdx(list1, list2):
"""
Return the indices of list1 in list2
"""
return [i for i, x in enumerate(list1) if x in list2]
|
def was_preemptible_vm(metadata, was_cached):
"""
Modified from: https://github.com/broadinstitute/dsde-pipelines/blob/develop/scripts/calculate_cost.py
"""
if was_cached:
return True # if call cached, not any type of VM, but don't inflate nonpreemptible count
elif "runtimeAttributes" in metadata and "preemptible" in metadata['runtimeAttributes']:
pe_count = int(metadata['runtimeAttributes']["preemptible"])
attempt = int(metadata['attempt'])
return attempt <= pe_count
else:
# we can't tell (older metadata) so conservatively return false
return False
|
def tap_type_to_target_type(csv_type):
"""Data type mapping from S3 csv to Bigquery"""
return {
'integer': 'INT64',
'number': 'NUMERIC',
'string': 'STRING',
'boolean': 'STRING', # The guess sometimes can be wrong, we'll use string for now.
'date': 'STRING', # The guess sometimes can be wrong, we'll use string for now.
'date_override': 'TIMESTAMP', # Column type to use when date_override defined in YAML
}.get(csv_type, 'STRING')
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.