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)... |
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 == s... |
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 nu... |
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["chromSta... |
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 re... |
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" : "UNK... |
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... |
def performanceCalculator(count, avg, std, maxv, countref, avgref, stdref, maxvref):
"""
===========================================================================
Performance calculator function
===========================================================================
Calculate performance bas... |
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.Pag... |
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 +... |
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... |
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 T... |
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... |
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 = [
{
'... |
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"
... |
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... |
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 isinstan... |
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:
linea... |
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
"""
... |
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 us... |
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 dict... |
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': {
... |
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,
... |
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.... |
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... |
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:... |
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_... |
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 = {}
... |
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'],
... |
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):
... |
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 th... |
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)
... |
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_none... |
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": ... |
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
:retu... |
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):
... |
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
"""
# ... |
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:
ret... |
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(... |
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 = ... |
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 = []
... |
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')
c... |
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
... |
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)... |
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' # S... |
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(... |
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 re... |
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 = []
... |
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_prim... |
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_typ... |
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 $1... |
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", "{}"... |
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... |
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#c... |
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
... |
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 = (("'", '''),
('"', '"'),
('>', '>'),
('<', '<'),
('&', '&'))... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.