content
stringlengths 42
6.51k
|
---|
def parse_for_keywords(keywords, line, dic={}):
"""determines if a keyword is in a line and if so, manipulates it to
ensure correct format"""
for x in keywords:
if line[0:len(x)+2] == "# "+x:
# removes any end of line character and any leading white space
dic[x] = line[len(x)+2:].strip()
return dic
|
def shift(s, offset):
"""
Returns a new slice whose start and stop points are shifted by `offset`.
Parameters
----------
s : slice
The slice to operate upon.
offset : int
The amount to shift the start and stop members of `s`.
Returns
-------
slice
"""
if s == slice(0, 0, None): return s # special "null slice": shifted(null_slice) == null_slice
return slice(s.start + offset, s.stop + offset, s.step)
|
def date_conv(time):
"""Change timestamp to readable date"""
import datetime
date = datetime.datetime.fromtimestamp(int(time)).strftime('%Y-%m-%d %H:%M:%S')
return date
|
def obj_box_coord_centroid_to_upleft(coord):
"""Convert one coordinate [x_center, y_center, w, h] to [x, y, w, h].
It is the reverse process of ``obj_box_coord_upleft_to_centroid``.
Parameters
------------
coord : list of 4 int/float
One coordinate.
Returns
-------
list of 4 numbers
New bounding box.
"""
if len(coord) != 4:
raise AssertionError("coordinate should be 4 values : [x, y, w, h]")
x_center, y_center, w, h = coord
x = x_center - w / 2.
y = y_center - h / 2.
return [x, y, w, h]
|
def is_sample_pair(align_bams, items):
"""Determine if bams are from a sample pair or not"""
return (len(align_bams) == 2 and all(item["metadata"].get("phenotype")
is not None for item in items))
|
def getMouseover(bed):
"""Return the mouseOver string for this bed record."""
ret = ""
ret += "Gene(s) affected: %s" % (", ".join(bed["ClinGen"]))
ret += ", Position: %s:%s-%s" % (bed["chrom"], int(bed["chromStart"])+1, bed["chromEnd"])
ret += ", Size: %d" % (int(bed["chromEnd"]) - int(bed["chromStart"]))
if bed["Variant Type"] == "copy_number_loss":
ret += ", Type: loss"
else:
ret += ", Type: gain"
ret += ", Significance: %s" % bed["Clinical Interpretation"]
ret += ", Phenotype: %s" % bed["Phenotype"]
return ret
|
def cleanup(s):
"""
Given string s, removes "#" and "*".
# is a standin for a decimal point for estimated values.
* represents a non-computable quantity.
"""
s = s.replace('#', '.')
s = s.replace('*', '')
s = s.replace(' ', '')
return s
|
def index_to_coordinates(string, index):
""" Returns the corresponding tuple (line, column) of the character at the given index of the given string.
"""
if index < 0:
index = index % len(string)
sp = string[:index+1].splitlines(keepends=True)
return len(sp), len(sp[-1])
|
def is_hashable(v):
"""Determine whether `v` can be hashed."""
try:
hash(v)
except TypeError:
return False
return True
|
def get_metadata(resource, key, default_value):
"""Retrieves from the user_metadata key in the resource the
given key using default_value as a default
"""
if ('object' in resource and 'user_metadata' in resource['object'] and
key in resource['object']['user_metadata']):
return resource['object']['user_metadata'][key]
return default_value
|
def parser_Null_Descriptor(data,i,length,end):
"""\
parser_NullDescriptor(data,i,length,end) -> dict(parsed descriptor elements).
This descriptor is not parsed at the moment. The dict returned is:
{ "type": "UNKNOWN", "contents" : unparsed_descriptor_contents }
"""
return { "type" : "UNKNOWN", "contents" : data[i+2:end] }
|
def mentionable():
"""
:return: boolean
True, if there is something mentionable to notify about
False, if not
"""
# need to be implemented
return False
|
def square_reflect_x(x, y):
"""Reflects the given square through the y-axis
and returns the co-ordinates of the new square"""
return (-x, y)
|
def spreadsheet_col_num_to_name(num):
"""Convert a column index to spreadsheet letters.
Adapted from http://asyoulook.com/computers%20&%20internet/python-convert-spreadsheet-number-to-column-letter/659618
"""
letters = ''
num += 1
while num:
mod = num % 26
letters += chr(mod + 64)
num = num // 26
return ''.join(reversed(letters))
|
def performanceCalculator(count, avg, std, maxv, countref, avgref, stdref, maxvref):
"""
===========================================================================
Performance calculator function
===========================================================================
Calculate performance based on reference values.
If some value is None return None
**Args**:
* count : actual number of samples -- (int)
* avg : actual duration average -- (float)
* std : actual duration standar desviation -- (float)
* maxv : actual duration max value -- (float)
* countref : reference number of samples -- (int)
* avgref : reference duration average -- (float)
* stdref : reference duration standar desviation -- (float)
* maxvref : reference duration max value -- (float)
**Returns**:
performance value indicator. [0-1] -- (float)
"""
if avgref == None or stdref == None or maxvref == None:
return None
# f = 0
# if maxvref == 0: maxvref = 0.1
# if maxvref < 0.2:
# f = avg / (maxvref * 10)
# if maxvref < 1:
# f = avg / (maxvref * 5)
# if maxvref < 10:
# f = avg / (maxvref * 2)
#
# f = 0
# if maxvref == 0: maxvref = 0.1
# if maxvref < 0.2:
# f = avg / (maxvref * 5)
# elif maxvref < 1:
# f = avg / (maxvref * 3)
# elif maxvref < 10:
# f = avg / (maxvref * 1.5)
# else:
# f = avg / maxvref
# f = 1-f
if stdref < 0.01: stdref = 0.01
f = (1-((avg - avgref) / (stdref*2)))*0.9
if f > 1: f=1
if f < 0: f=0
return f
|
def is_page_editor(user, page):
"""
This predicate checks whether the given user is one of the editors of the given page.
:param user: The user who's permission should be checked
:type user: ~django.contrib.auth.models.User
:param page: The requested page
:type page: ~cms.models.pages.page.Page
:return: Whether or not ``user`` is an editor of ``page``
:rtype: bool
"""
if not page:
return False
return user in page.editors.all()
|
def stringfy_list(one_list: list) -> str:
"""Stringfies a list
@type one_list: list
@param one_list: A list to be stringed
@returns str: The stringed list
"""
if not one_list:
return ''
output = ''
for i in range(len(one_list)-1):
output += f"{one_list[i]},"
output += one_list[-1]
return output
|
def merge_maps(dict1, dict2):
""" is used to merge two word2ids or two tag2ids """
for key in dict2.keys():
if key not in dict1:
dict1[key] = len(dict1)
return dict1
|
def canon_nodelims(msg):
"""
Format is:
0a00f6 (case insensitive)
"""
msg = msg.strip()
return [int(msg[i:i+2],16) for i in range(0,len(msg),2)]
|
def sanitize_module_name(modname):
"""
Sanitizes a module name so it can be used as a variable
"""
return modname.replace(".", "_")
|
def count_substring(string, sub_string):
"""
Cuenta cuantas veces aparece el sub_string
en el string
Args:
string: (string)
sub_string: (string)
rerturn : int
"""
return string.count(sub_string)
|
def parse_date(date_str):
"""
Given a date string in YYYY-MM form (or the underscore separated
equivalent), return a pair of (year, month) integers
"""
year_str, month_str = date_str.replace("_", "-").split("-")[:2]
assert len(year_str) == 4
assert len(month_str) == 2
return int(year_str), int(month_str)
|
def args_to_list(arg_string):
""" Parses argument-string to a list
"""
# Strip whitespace -> strip brackets -> split to substrings ->
# -> strip whitespace
arg_list = [x.strip() for x in arg_string.strip().strip("[]").split(',')]
return arg_list
|
def is_even(num):
"""
Returns True if a number is even
:param num:
:return:
"""
if num == 0:
raise NotImplementedError(
"Input number is 0. Evenness of 0 is not defined by this "
"function."
)
if num % 2:
return False
else:
return True
|
def extender(baseitems, charstoextend):
""" This goes through all items all the items in
:param baseitems: a sequence of strings
:param charstoextend: a string consisting of the extension characters
:return: A sequence of strings.
"""
ourextension = [baseitem+extending for baseitem in baseitems for extending in charstoextend]
return ourextension
|
def crossSet(list1, list2):
""" return the cross-set of list1 and list2
"""
return list(set(list1).intersection(list2))
|
def _hexsplit(string):
""" Split a hex string into 8-bit/2-hex-character groupings separated by spaces"""
return ' '.join([string[i:i+2] for i in range(0, len(string), 2)])
|
def format_dictlist(dictlist, features):
"""
Convert a list of dictionaries to be compatible with create_csv_response
`dictlist` is a list of dictionaries
all dictionaries should have keys from features
`features` is a list of features
example code:
dictlist = [
{
'label1': 'value-1,1',
'label2': 'value-1,2',
'label3': 'value-1,3',
'label4': 'value-1,4',
},
{
'label1': 'value-2,1',
'label2': 'value-2,2',
'label3': 'value-2,3',
'label4': 'value-2,4',
}
]
header, datarows = format_dictlist(dictlist, ['label1', 'label4'])
# results in
header = ['label1', 'label4']
datarows = [['value-1,1', 'value-1,4'],
['value-2,1', 'value-2,4']]
}
"""
def dict_to_entry(dct):
""" Convert dictionary to a list for a csv row """
relevant_items = [(k, v) for (k, v) in dct.items() if k in features]
ordered = sorted(relevant_items, key=lambda k_v: header.index(k_v[0]))
vals = [v for (_, v) in ordered]
return vals
header = features
datarows = list(map(dict_to_entry, dictlist))
return header, datarows
|
def default_logfile_names(script, suffix):
"""Method to return the names for output and error log files."""
suffix = script.split('.')[0] if suffix is None else suffix
output_logfile = '{}_out.txt'.format(suffix)
error_logfile = '{}_err.txt'.format(suffix)
return output_logfile, error_logfile
|
def map_and_filter(s, map_fn, filter_fn):
"""Returns a new list containing the results of calling map_fn on each
element of sequence s for which filter_fn returns a true value.
"""
return [map_fn(i) for i in s if filter_fn(i)]
|
def _to_variable_type(x):
"""Convert CWL variables to WDL variables, handling nested arrays.
"""
var_mapping = {"string": "String", "File": "File", "null": "String",
"long": "Float", "int": "Int"}
if isinstance(x, dict):
if x["type"] == "record":
return "Object"
else:
assert x["type"] == "array", x
return "Array[%s]" % _to_variable_type(x["items"])
elif isinstance(x, (list, tuple)):
vars = [v for v in x if v != "null"]
assert len(vars) == 1, vars
return var_mapping[vars[0]]
else:
return var_mapping[x]
|
def get_doc_id_set(current_inverted_dic):
"""
:param current_inverted_dic:
:return:
"""
doc_id_set = set()
for current_stem, current_doc_position_dic in current_inverted_dic.items():
for current_doc_id in current_doc_position_dic.keys():
doc_id_set.add(str(current_doc_id))
return doc_id_set
|
def solution(string: str, ending: str) -> bool:
"""Checks if given string ends with specific string.
Examples:
>>> assert solution("abcb", "cb")
>>> assert not solution("abcb", "d")
"""
return string.endswith(ending)
|
def _scrub(s):
"""Strip punctuation, make everything lowercase."""
if not s:
return s
return "".join([x for x in s.lower().strip() if x not in ".,"])
|
def get_label_format(val):
"""
To show only last three decimal places of the value.
:param val: Value to be formatted
:return: shorter label
"""
return "{:.3f}".format(val)
|
def intersect(probe, target):
"""Intersection of two nested dictionaries."""
intersection = {}
if probe == {}:
intersection = target
else:
for k in set(target).intersection(set(probe)):
p = probe[k]
t = target[k]
if isinstance(t, dict) and isinstance(p, dict):
if p == {}:
intersection[k] = t
else:
intersection[k] = intersect(p, t)
elif not isinstance(t, dict) and p == {}:
intersection[k] = t
elif t == p:
intersection[k] = t
else:
raise ValueError("values for common keys don't match")
return intersection
|
def inst(cls):
"""Create an instance of the given class."""
if getattr(cls, "NAME", None) is not None:
return cls("test")
return cls()
|
def srgb_to_linear(srgb):
"""
Converts sRGB float value to a linear float value
:type srgb: float
:param srgb: the sRGB value to convert
:rtype: float
:return: the calculated linear value
"""
srgb = float(srgb)
if srgb <= 0.04045:
linear = srgb / 12.92
else:
linear = pow((srgb + 0.055) / 1.055, 2.4)
return linear
|
def add_zero_to_age_breakpoints(breakpoints):
"""
append a zero on to a list if there isn't one already present, for the purposes of age stratification
:param breakpoints: list
integers for the age breakpoints requested
:return: list
age breakpoints with the zero value included
"""
return [0] + breakpoints if 0 not in breakpoints else breakpoints
|
def transform_user_info(user):
"""Converts lastfm api user data into neo4j friendly user data
Args:
user (dict): lastfm api user data
Returns:
dict - neo4j friendly user data
"""
if 'user' in user:
user = user['user']
user['image'] = [element['#text'] for element in user['image']]
user['registered'] = user['registered']['unixtime']
user['playcount'] = int(user['playcount'])
user['playlists'] = int(user['playlists'])
user['registered'] = int(user['registered'])
return user
|
def calculate_similarity(dict1,dict2):
"""
Parameters
----------
dict1: freq dict for text1
dict2: freq dict for text2
Returns
-------
float between [0,1] for similarity
"""
diff = 0
total = 0
# Uses 2 loops. This one goes through all of dictionary 1
for word in dict1.keys():
# If the word is in both dictionaries
if word in dict2.keys():
diff += abs(dict1[word]-dict2[word]) #Get the diff in frequency in + val
#Otherwise, just add the count since the word isnt in dict2
else:
diff += dict1[word]
# 2nd loop dictionary
for word in dict2.keys():
if word not in dict1.keys():
diff += dict2[word] #Add the frequency
# Calculate total: total number of words in both dictionaries
total = sum(dict1.values()) + sum(dict2.values())
difference = diff/total
similar = 1.0 - difference
# Return a number with 2 decimal places
return round(similar,2)
|
def button_share(generic_element):
"""
Creates a dict to send a web_url, can be used with generic_elements or send_buttons
:param title: Content to show the receiver
:return: dict
"""
button = {
'type': 'element_share',
'share_contents': {
'attachment': {
'type': 'template',
'payload': {
'template_type': 'generic',
'elements': generic_element
}
}
}
}
if not generic_element:
button.pop('share_contents')
return button
|
def get_peer_values(field, db_object):
"""Retrieves the list of peers associated with the cluster."""
peers = []
for entry in getattr(db_object, 'peers', []):
hosts = []
for ientry in getattr(entry, 'hosts', []):
hosts.append(ientry.hostname)
val = {'name': entry.name,
'status': entry.status,
'hosts': hosts,
'uuid': entry.uuid}
peers.append(val)
return peers
|
def extract_args(kwas, prefix):
"""Extract arguments from keyword argument dict by prefix.
Parameters
----------
kwas: dict
Dictionary with string keys.
prefix: str
Prefix to select keys (must be followed by '__').
Example
-------
>>> parser = argparse.ArgumentParser(...)
>>> parser.add_argument(..., dest="input__foo")
>>> parser.add_argument(..., dest="output__bar")
>>> kwas = vars(parser.parse_args())
>>> conf_input = extract_args(kwas, "input")
>>> conf_output = extract_args(kwas, "output")
>>> conf_input, conf_output
({"foo": ...}, {"bar": ...})
"""
conf = {}
prefix = "{}__".format(prefix)
for key, val in kwas.copy().items():
if key.startswith(prefix):
del kwas[key]
conf[key.replace(prefix, "")] = val
return conf
|
def calculate_dis_travelled(speed, time):
"""Calculate the distance travelled(in Km) in a give amount of time(s)."""
return (speed * time) / 3600.0
|
def product_4x4_vector4(matrix,vector):
"""mulipli une matrice care de 4 par un vector de 4 par"""
x = matrix[0][0]*vector[0] + matrix[1][0]*vector[1] + matrix[2][0]*vector[2] + matrix[3][0]*vector[3]
y = matrix[0][1]*vector[0] + matrix[1][1]*vector[1] + matrix[2][1]*vector[2] + matrix[3][1]*vector[3]
z = matrix[0][2]*vector[0] + matrix[1][2]*vector[1] + matrix[2][2]*vector[2] + matrix[3][2]*vector[3]
w = matrix[0][3]*vector[0] + matrix[1][3]*vector[1] + matrix[2][3]*vector[2] + matrix[3][3]*vector[3]
return [x,y,z,w]
|
def sample_var_var(std, n):
"""
The variance of the sample variance of a distribution.
Assumes the samples are normally distributed.
From: //math.stackexchange.com/q/72975
`std`: Distribution's standard deviation
`n`: Number of samples
"""
return 2.0 * std ** 4 / (n - 1.0)
|
def _log_level_from_verbosity(verbosity):
"""Get log level from verbosity count."""
if verbosity == 0:
return 40
elif verbosity == 1:
return 20
elif verbosity >= 2:
return 10
|
def is_rev_gte(left, right):
""" Return if left >= right
Args:
@param left: list. Revision numbers in a list form (as returned by
_get_rev_num).
@param right: list. Revision numbers in a list form (as returned by
_get_rev_num).
Returns:
Boolean
If left and right are all numeric then regular list comparison occurs.
If either one contains a string, then comparison occurs till both have int.
First list to have a string is considered smaller
(including if the other does not have an element in corresponding index)
Examples:
[1, 9, 0] >= [1, 9, 0]
[1, 9, 1] >= [1, 9, 0]
[1, 9, 1] >= [1, 9]
[1, 10] >= [1, 9, 1]
[1, 9, 0] >= [1, 9, 0, 'dev']
[1, 9, 1] >= [1, 9, 0, 'dev']
[1, 9, 0] >= [1, 9, 'dev']
[1, 9, 'rc'] >= [1, 9, 'dev']
[1, 9, 'rc', 0] >= [1, 9, 'dev', 1]
[1, 9, 'rc', '1'] >= [1, 9, 'rc', '1']
"""
def all_numeric(l):
return not l or all(isinstance(i, int) for i in l)
if all_numeric(left) and all_numeric(right):
return left >= right
else:
for i, (l_e, r_e) in enumerate(izip_longest(left, right)):
if isinstance(l_e, int) and isinstance(r_e, int):
if l_e == r_e:
continue
else:
return l_e > r_e
elif isinstance(l_e, int) or isinstance(r_e, int):
# [1, 9, 0] > [1, 9, 'dev']
# [1, 9, 0] > [1, 9]
return isinstance(l_e, int)
else:
# both are not int
if r_e is None:
# [1, 9, 'dev'] < [1, 9]
return False
else:
return l_e is None or left[i:] >= right[i:]
return True
|
def parity(inbytes):
"""Calculates the odd parity bits for a byte string"""
res = ""
for i in inbytes:
tempres = 1
for j in range(8):
tempres = tempres ^ ((ord(i) >> j) & 0x1)
res += chr(tempres)
return res
|
def force_utf8(raw):
"""Will force the string to convert to valid utf8"""
string = raw
try:
string = string.decode("utf-8", "ignore")
except Exception:
pass
return string
|
def bubble_sort(lis):
"""
Implementation of bubble sort.
:param lis: list to be sorted
"""
n = len(lis)
while n > 0:
temp_n = 0
for i in range(1, n):
if lis[i-1] > lis[i]:
lis[i-1], lis[i] = lis[i], lis[i-1]
temp_n = i
n = temp_n
return lis
|
def calculate_lines(x, y):
"""
Calculate lines to connect a series of points. This is used for the PW approximations. Given matching vectors of x,y coordinates. This only makes sense for monotolically increasing values.
This function does not perform a data integrity check.
"""
slope_list = {}
intercept_list = {}
for i in range(0, len(x) - 1):
slope_list[i + 1] = (y[i] - y[i + 1]) / (x[i] - x[i + 1])
intercept_list[i + 1] = y[i + 1] - slope_list[i + 1] * x[i + 1]
return slope_list, intercept_list
|
def firstline(text):
"""Any text. Returns the first line of text."""
try:
return text.splitlines(True)[0].rstrip('\r\n')
except IndexError:
return ''
|
def _to_model_dict(resource_type_name, ns_res_type_dict):
"""transform a metadef_namespace_resource_type dict to a model dict"""
model_dict = {'name': resource_type_name,
'properties_target': ns_res_type_dict['properties_target'],
'prefix': ns_res_type_dict['prefix'],
'created_at': ns_res_type_dict['created_at'],
'updated_at': ns_res_type_dict['updated_at']}
return model_dict
|
def get_paths(link, nb):
"""
Generate a list containing all URLs
Args:
link [str]: Base HTML link
nb [int]: Number of pages usingHTML link
Returns:
url [str]: [List containing all URLs]
"""
url = []
for si in range(2000, 2020):
for ti in range(1, nb+1):
result = link + str(si) + "-" + str(si+1) + "&teamId=" + str(ti)
url.append(result)
return url
|
def m12_to_symratio(m1, m2):
"""convert m1 and m2 to symmetric mass ratio"""
return m1 * m2 / (m1 + m2) ** 2
|
def nth_smallest(items, n):
"""Return the n-th smallest of the items.
For example, return the minimum if n is 1
and the maximum if n is len(items).
Don't change the order of the items.
Assume n is an integer from 1 to len(items).
"""
assert 1 <= n <= len(items)
# Reduction step: take the first item (call it the pivot)
# and put the remaining items in two partitions,
# those smaller or equal than the pivot, and those greater.
pivot = items[0]
left_unsorted = []
right_unsorted = []
for index in range(1, len(items)):
item = items[index]
if item <= pivot:
left_unsorted.append(item)
else:
right_unsorted.append(item)
smaller_equal = len(left_unsorted)
# Base case: the pivot is the n-th smallest number
# if there are exactly n-1 items smaller or equal than the pivot.
if smaller_equal == n - 1:
return pivot
# Recursive step:
# If there are n or more items smaller or equal than the pivot,
# the n-th smallest must be among them.
if smaller_equal >= n:
return nth_smallest(left_unsorted, n)
# Recursive step:
# Otherwise it's among the numbers larger than the pivot.
# Discount the numbers up to and including the pivot.
return nth_smallest(right_unsorted, n - (smaller_equal + 1))
# Inductive step: none.
|
def parseBrowserBase(base_config):
""" Parses the given option value into type and base url
@param base_config: The option value
@type base_config: C{str}
@return: The type and the base url
@rtype: C{tuple}
"""
if base_config:
tokens = base_config.split(None, 1)
if len(tokens) == 2:
return (tokens[0].lower(), tokens[1])
return (None, None)
|
def clean_nones(value):
"""
Recursively remove all None values from dictionaries and lists, and returns
the result as a new dictionary or list.
https://stackoverflow.com/questions/4255400/exclude-empty-null-values-from-json-serialization
"""
if isinstance(value, list):
return [clean_nones(x) for x in value if x is not None]
elif isinstance(value, dict):
return {key: clean_nones(val) for key, val in value.items() if val is not None}
else:
return value
|
def getMorningScheduleId(morningSchedule:str) -> int:
"""Get morningScheduleId corresponding the morningSchedule Indicator
Arguments:
morningSchedule {str} -- [description]
Returns:
int -- [description]
"""
morningScheduleMappingDict = {"B": 1, "B+SL": 2, "BC": 3, "BC+SL": 4, "SL": 5, "S": 6, "LL": 7}
return morningScheduleMappingDict[morningSchedule]
|
def stretch_factor_str(sig_sample_rate_hz: float,
wav_sample_rate_hz: float) -> str:
"""
Compute file string for speedup and slowdown options
:param sig_sample_rate_hz: input signal sample rate
:param wav_sample_rate_hz: wav sample rate; supports permitted_wav_fs_values
:return:
"""
stretch_factor = wav_sample_rate_hz / sig_sample_rate_hz
# If stretch factor is unity, no change
stretch_str = '_preserve'
if stretch_factor > 1:
stretch_str = '_speedup_' + str(int(10.*stretch_factor)/10) + 'x_to'
elif 1 > stretch_factor > 0:
stretch_str = '_slowdown_' + str(int(10./stretch_factor)/10) + 'x_to'
else:
print("Stretch factor is zero or negative, address")
return stretch_str
|
def str_equal_case_ignore(str1, str2):
"""Compare two strings ignoring the case."""
return str1.casefold() == str2.casefold()
|
def gethashvalue(key_v, tablesize):
"""
key_str must be immutable, just like the key values in dict.
if the key_str is mutable, the hash value will also be changed
:param key_v: integer, string, tuple of integer or string
:param tablesize:
:return:
"""
if isinstance(key_v, str):
return sum(ord(i) for i in key_v) % tablesize
elif isinstance(key_v, int):
return key_v % tablesize
elif isinstance(key_v, tuple):
return sum(ord(j) for i in key_v for j in str(i)) % tablesize
|
def clip_value(v: float, min_clip: float, max_clip: float):
"""
Clip seismic voxel value
:param min_clip: minimum value used for clipping
:param max_clip: maximum value used for clipping
:returns: clipped value, must be within [min_clip, max_clip]
:rtype: float
"""
# Clip value
if v > max_clip:
v = max_clip
if v < min_clip:
v = min_clip
return v
|
def correct_nonlist(to_assert_list):
"""RETURN : Transform any element to list if it's not a list
if the developer/user forgot it"""
if not isinstance(to_assert_list, list):
to_assert_list = [to_assert_list]
return to_assert_list
|
def get_mse(series1, series2):
"""
the series as is
"""
assert len(series1) == len(series2)
mse = 0.0
for index, data1 in enumerate(series1):
diff = (data1 - series2[index])
mse += diff * diff
mse /= len(series1)
return mse
|
def calculate_level_xp(level: int) -> int: # https://github.com/giorgi-o
"""Calculate XP needed to reach a level"""
level_multiplier = 750
if level >= 2 and level <= 50:
return 2000 + (level - 2) * level_multiplier
elif level >= 51 and level <= 55:
return 36500
else:
return 0
|
def create_graph(liveness):
"""Takes the liveness and transforms it to a graph (dict with key node, value set of edges"""
g = {}
for l_set in liveness:
for item in l_set:
s = (g[item] if item in g else set()) | l_set
if item in s: # remove self edge
s.remove(item)
g[item] = s
return g
|
def map_preempt_rt_kbranch(need_new_kbranch, new_kbranch, existing_kbranch):
"""
Return the linux-yocto bsp branch to use with the specified
kbranch. This handles the -preempt-rt variants for 3.4 and 3.8;
the other variants don't need mappings.
"""
if need_new_kbranch == "y":
kbranch = new_kbranch
else:
kbranch = existing_kbranch
if kbranch.startswith("standard/preempt-rt/common-pc-64"):
return "bsp/common-pc-64/common-pc-64-preempt-rt.scc"
if kbranch.startswith("standard/preempt-rt/common-pc"):
return "bsp/common-pc/common-pc-preempt-rt.scc"
else:
return "ktypes/preempt-rt/preempt-rt.scc"
|
def tokens_to_index(token_list, vocab_dict):
"""
convert word tokens to number index
INPUT:
token_list: a list of string tokens
vocab_dict: a dictionary with tokens(key)-integer(value) pairs
OUTPUT:
index_list: a list of integer indices
"""
index_list = []
for x in token_list:
try:
index_list.append(vocab_dict[x])
except:
index_list.append(1) # index for oov tokens
return index_list
|
def get_user(name, list_user):
"""
Method untuk mengembalikan user dengan user_name sesuai parameter.
Mengembalikan None jika user dengan nama tersebut tidak ditemukan.
"""
for user in list_user:
if user.get_name() == name:
return user
return None
|
def numbers_rating(pw):
"""
Takes in the password and returns a numbers-score.
Parameters:
pw (str): the password string
Returns:
num_rating (float): score produced by increments of 0.5 for every unique number in the password. [Max val- 2.5]
"""
numbers = list('123456789')
characters = list(pw)
num_rating = 0
for i in numbers:
if i in characters:
num_rating += 0.5
return 2.5 if num_rating > 2.5 else num_rating
|
def format_fold_run(rep=None, fold=None, run=None, mode="concise"):
"""Construct a string to display the repetition, fold, and run currently being executed
Parameters
----------
rep: Int, or None, default=None
The repetition number currently being executed
fold: Int, or None, default=None
The fold number currently being executed
run: Int, or None, default=None
The run number currently being executed
mode: {"concise", "verbose"}, default="concise"
If "concise", the result will contain abbreviations for rep/fold/run
Returns
-------
content: Str
A clean display of the current repetition/fold/run
Examples
--------
>>> format_fold_run(rep=0, fold=3, run=2, mode="concise")
'R0-f3-r2'
>>> format_fold_run(rep=0, fold=3, run=2, mode="verbose")
'Rep-Fold-Run: 0-3-2'
>>> format_fold_run(rep=0, fold=3, run="*", mode="concise")
'R0-f3-r*'
>>> format_fold_run(rep=0, fold=3, run=2, mode="foo")
Traceback (most recent call last):
File "reporting.py", line ?, in format_fold_run
ValueError: Received invalid mode value: 'foo'"""
content = ""
if mode == "verbose":
content += format("Rep" if rep is not None else "")
content += format("-" if rep is not None and fold is not None else "")
content += format("Fold" if fold is not None else "")
content += format("-" if fold is not None and run is not None else "")
content += format("Run" if run is not None else "")
content += format(": " if any(_ is not None for _ in [rep, fold, run]) else "")
content += format(rep if rep is not None else "")
content += format("-" if rep is not None and fold is not None else "")
content += format(fold if fold is not None else "")
content += format("-" if fold is not None and run is not None else "")
content += format(run if run is not None else "")
elif mode == "concise":
content += format("R" if rep is not None else "")
content += format(rep if rep is not None else "")
content += format("-" if rep is not None and fold is not None else "")
content += format("f" if fold is not None else "")
content += format(fold if fold is not None else "")
content += format("-" if fold is not None and run is not None else "")
content += format("r" if run is not None else "")
content += format(run if run is not None else "")
else:
raise ValueError("Received invalid mode value: '{}'".format(mode))
return content
|
def delete_nth_naive(array, n):
"""
Time complexity O(n^2)
"""
ans = []
for num in array:
if ans.count(num) < n:
ans.append(num)
return ans
|
def multinomial(lst):
"""
Returns the multinomial. Taken from
https://stackoverflow.com/questions/46374185/does-python-have-a-function-which-computes-multinomial-coefficients
"""
res, i = 1, sum(lst)
i0 = lst.index(max(lst))
for a in lst[:i0] + lst[i0 + 1 :]:
for j in range(1, a + 1):
res *= i
res //= j
i -= 1
return res
|
def string_to_hexadecimal(string):
"""Convert a byte string to it's hex string representation e.g. for output.
"""
return ''.join(["%02X " % ord(x) for x in string]).strip()
|
def compare_dict_keys(dict_1, dict_2):
"""Check that two dict have the same keys."""
return set(dict_1.keys()) == set(dict_2.keys())
|
def translate_weather_code(weather_code):
"""
translate weather code into a character
"""
if weather_code == 1:
return 'S' # Sunny
elif weather_code == 2:
return 'R' # Rainy
elif weather_code == 3:
return 'L' # Cloudy
elif weather_code == 4:
return 'W' # Snowy
else:
return '-'
|
def get_line(maxy , miny , slope , intercept):
"""
:param maxy: is down the image
:param miny: up in the image
:param slope:
:param intercept:
:return: line [ , , , ] (col , row ) , lower point will be first.
"""
# get columns.
lx = int(( maxy-intercept ) / slope)
ux = int(( miny - intercept ) / slope)
line = [lx , maxy , ux , miny]
return line
|
def build_inst_list(item_list, first_line=''):
"""return instrument list in standard format
"""
if first_line == '':
first_line = "Instruments:"
result = [first_line, '']
for ix, item in item_list:
result.append(" {:>2} {}".format(ix, item))
result.append('')
return result
|
def _extend(obj, *args):
"""
adapted from underscore-py
Extend a given object with all the properties in
passed-in object(s).
"""
args = list(args)
for src in args:
obj.update(src)
for k, v in src.items():
if v is None:
del obj[k]
return obj
|
def as_list(value, sep=" "):
"""Convert value (possibly a string) into a list.
Raises ValueError if it's not convert-able.
"""
retval = None
if isinstance(value, list) or isinstance(value, tuple):
retval = value
elif isinstance(value, str):
if not value:
retval = []
else:
retval = value.split(sep)
if retval is None:
raise ValueError("Cannot convert to list: %s" % value)
return retval
|
def recalc_subject_weight_worker(args):
"""Calculate the new weight of a subject."""
query_weights, subject_len, subject_name = args
return subject_name, sum(query_weights) / subject_len
|
def package_name_from_url(url):
"""Parse out Package name from a repo git url"""
url_repo_part = url.split('/')[-1]
if url_repo_part.endswith('.git'):
return url_repo_part[:-4]
return url_repo_part
|
def compute_primary_air_flow_2(Firepower):
"""using new flame temperature assumption"""
cp_average = 1.044
Q_dot = Firepower
T_amb = 300 # K
T_h = 1274 # K
m_dot_primary_air = (Q_dot)/(cp_average*(T_h - T_amb)) #kg/s
mw_air = 0.018 #kg/mol
mol_dot_primary_air = m_dot_primary_air/mw_air
print("mass flow rate of air:")
print(m_dot_primary_air)
print("molar flow rate of primary air:")
print(mol_dot_primary_air)
print("primary air velocty:")
return mol_dot_primary_air, m_dot_primary_air
|
def xorS(a,b):
""" XOR two strings """
assert len(a)==len(b)
x = []
for i in range(len(a)):
x.append( chr(ord(a[i])^ord(b[i])))
return ''.join(x)
|
def _get_provenance_record(caption, statistics, plot_type, ancestor_files):
"""Create a provenance record describing the diagnostic data and plot."""
record = {
'ancestors': ancestor_files,
'authors': ['koirala_sujan'],
'caption': caption,
'domains': ['global'],
'plot_type': plot_type,
'realms': ['land'],
'references': ['carvalhais14nature'],
'statistics': statistics,
'themes': ['bgchem', 'carbon', 'chem', 'ghg'],
}
return record
|
def get_method_identifier(qualified_name):
"""Takes com.some.thing.Class:method and returns Class_method."""
parts = qualified_name.split(".")
method_identifier = parts[-1]
return method_identifier.replace(":", "_")
|
def is_valid_price(price):
"""
Validate price with provided requirements
:param price: a string of the price for the ticket
:return: true if the password is acceptable, false otherwise
"""
# Verifies that price is an integer
try:
price = int(price)
# Price must be at least $10 but no more than $100
return 10 <= price <= 100
except ValueError:
return False
|
def char_analyzer(text):
"""
This is used to split strings in small lots
I saw this in an article (I can't find the link anymore)
so <talk> and <talking> would have <Tal> <alk> in common
"""
tokens = text.split()
return [token[i: i + 3] for token in tokens for i in range(len(token) - 2)]
|
def mk_sql_time_expr(time_spec, default):
"""
conver time expression the user entered in the cell
into an expression understood by sqlite
"""
if time_spec == "":
return default
if time_spec[:1] == "-": # -12345 = now - 12345 sec
return 'datetime("now", "localtime", "{}")'.format(time_spec)
return 'datetime("{}")'.format(time_spec)
|
def error_response(error, message):
"""
returns error response
"""
data = {
"status": "error",
"error": error,
"message": message
}
return data
|
def paths_to_root(tablename, root, child_to_parents):
"""
CommandLine:
python -m utool.util_graph --exec-paths_to_root:0
python -m utool.util_graph --exec-paths_to_root:1
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_graph import * # NOQA
>>> import utool as ut
>>> child_to_parents = {
>>> 'chip': ['dummy_annot'],
>>> 'chipmask': ['dummy_annot'],
>>> 'descriptor': ['keypoint'],
>>> 'fgweight': ['keypoint', 'probchip'],
>>> 'keypoint': ['chip'],
>>> 'notch': ['dummy_annot'],
>>> 'probchip': ['dummy_annot'],
>>> 'spam': ['fgweight', 'chip', 'keypoint']
>>> }
>>> root = 'dummy_annot'
>>> tablename = 'fgweight'
>>> to_root = paths_to_root(tablename, root, child_to_parents)
>>> result = ut.repr3(to_root)
>>> print(result)
{
'keypoint': {
'chip': {
'dummy_annot': None,
},
},
'probchip': {
'dummy_annot': None,
},
}
Example:
>>> # DISABLE_DOCTEST
>>> from utool.util_graph import * # NOQA
>>> import utool as ut
>>> root = u'annotations'
>>> tablename = u'Notch_Tips'
>>> child_to_parents = {
>>> 'Block_Curvature': [
>>> 'Trailing_Edge',
>>> ],
>>> 'Has_Notch': [
>>> 'annotations',
>>> ],
>>> 'Notch_Tips': [
>>> 'annotations',
>>> ],
>>> 'Trailing_Edge': [
>>> 'Notch_Tips',
>>> ],
>>> }
>>> to_root = paths_to_root(tablename, root, child_to_parents)
>>> result = ut.repr3(to_root)
>>> print(result)
"""
if tablename == root:
return None
parents = child_to_parents[tablename]
return {parent: paths_to_root(parent, root, child_to_parents)
for parent in parents}
|
def is_tls_record_magic(d):
"""
Returns:
True, if the passed bytes start with the TLS record magic bytes.
False, otherwise.
"""
d = d[:3]
# TLS ClientHello magic, works for SSLv3, TLSv1.0, TLSv1.1, TLSv1.2
# http://www.moserware.com/2009/06/first-few-milliseconds-of-https.html#client-hello
return (
len(d) == 3 and
d[0] == 0x16 and
d[1] == 0x03 and
0x0 <= d[2] <= 0x03
)
|
def _from_rgb(rgb):
"""translates an rgb tuple of int to a tkinter friendly color code
"""
if type(rgb) is tuple:
pass
else:
rgb = tuple(rgb)
return "#%02x%02x%02x" % rgb
|
def bitlist_to_int(bitlist: list) -> int:
"""encodes bit list to int"""
result = 0
for bit in bitlist:
result = (result << 1) | bit
return result
|
def softmax(series):
"""Return softmax %"""
return [round(100*(val/sum(series)),2) for val in series]
|
def limiting_ldcs(c1, c2, c3, c4):
"""
To compute limiting LDCs from
Espinoza & Jordan (2015)
-----------------------------
Parameters:
-----------
c1, c2, c3, c4 : float, or numpy.ndarray
non-linear LDCs
-----------
return:
-----------
float, or numpy.ndarray
limiting LDCs
"""
u1 = (12./35.)*c1 + c2 + (164./105.)*c3 + 2.*c4
u2 = (10./21.)*c1 - (34./63.)*c3 - c4
return u1, u2
|
def html_decode(s):
"""
Returns the ASCII decoded version of the given HTML string. This does
NOT remove normal HTML tags like <p>.
"""
html_codes = (("'", '''),
('"', '"'),
('>', '>'),
('<', '<'),
('&', '&'))
for code in html_codes:
s = s.replace(code[1], code[0])
return s
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.