content
stringlengths 42
6.51k
|
|---|
def map_labels(usecase,label):
"""This method returns the entire name of a label"""
if usecase == 'colon':
if label == 'cancer':
return "Cancer"
if label == 'hgd':
return "Adenomatous polyp - high grade dysplasia"
if label == 'lgd':
return "Adenomatous polyp - low grade dysplasia"
if label == 'hyperplastic':
return "Hyperplastic polyp"
if label == 'ni':
return "Non-informative"
elif usecase == 'cervix':
if label == 'cancer_scc_inv':
return "Cancer - squamous cell carcinoma invasive"
if label == 'cancer_scc_insitu':
return "Cancer - squamous cell carcinoma in situ"
if label == 'cancer_adeno_inv':
return "Cancer - adenocarcinoma invasive"
if label == 'cancer_adeno_insitu':
return "Cancer - adenocarcinoma in situ"
if label == 'hgd':
return "High grade dysplasia"
if label == 'lgd':
return "Low grade dysplasia"
if label == 'hpv':
return "HPV infection present"
if label == 'koilocytes':
return "Koilocytes"
if label == 'glands_norm':
return "Normal glands"
if label == 'squamous_norm':
return "Normal squamous"
if usecase == 'lung':
if label == 'cancer_scc':
return "Cancer - small cell cancer"
if label == 'cancer_nscc_adeno':
return "Cancer - non-small cell cancer, adenocarcinoma"
if label == 'cancer_nscc_squamous':
return "Cancer - non-small cell cancer, squamous cell carcinoma"
if label == 'cancer_nscc_large':
return "Cancer - non-small cell cancer, large cell carcinoma"
if label == 'no_cancer':
return "No cancer"
|
def is_valid_fit(fit):
""" Checks fit parameter """
values = ['none', 'rot+trans', 'rotxy+transxy', 'translation', 'transxy', 'progressive']
return fit in values
|
def _lcp(lst):
"""Returns the longest common prefix from a list."""
if not lst:
return ""
cleanlst = list(map(lambda x: x.replace("[", "").replace("]", ""), lst))
s1 = min(cleanlst)
s2 = max(cleanlst)
for i, c in enumerate(s1):
if c != s2[i]:
return s1[:i]
return s1
|
def position_from_instructions(instructions, path=None):
"""
Find out what position we're at after following a set of instructions.
"""
x = y = 0
heading = 0 # 0 = N, 1 = E, 2 = S, 3 = W
instructions = instructions.split(', ')
for instruction in instructions:
turn = instruction[:1]
distance = int(instruction[1:])
if turn == 'R':
heading = (heading + 1) % 4
elif turn == 'L':
heading = (heading - 1) % 4
#print("turn {turn}, heading {heading}, go {distance}".format(**locals()))
for i in range(distance):
if heading == 0:
y += 1
elif heading == 1:
x += 1
elif heading == 2:
y -= 1
elif heading == 3:
x -= 1
if path is not None:
path.append((x, y))
#print((x,y))
return (x, y)
|
def dictaddentry(idict,key,direction,newkey,nvalue):
"""
Converts a sexigesmal number to a decimal
Input Parameters
----------------
idict : dict
a dictionary
key : str
ocation in `dict` to insert the new values
direction : {'before','after'}
insertion direction relative to `key`
newkey : str
name of the new key
newvalue : any
the value associated with `newkey`
Returns
--------
dict
the original dictionary with a new entry
Procedure
---------
# https://stackoverflow.com/questions/44390818/how-to-insert-key-value-pair-into-dictionary-at-a-specified-position
Examples
--------
> dict = {'HA':1,'PA':2,'MJD':3}
> dictaddentry(dict,'MJD','before','new',4)
{'HA': 1, 'PA': 2, 'new': 4, 'MJD': 3}
> dict = {'HA':1,'PA':2,'MJD':3}
> dictaddentry(dict,'HA','after','new',(3,4))
{'HA': 1, 'new': (3, 4), 'PA': 2, 'MJD': 3}
Modification History
--------------------
2022-05-24 - Written by M. Cushing, University of Toledo.
"""
pos = list(idict.keys()).index(key)
items = list(idict.items())
if direction == 'after':
items.insert(pos+1,(newkey,nvalue))
elif direction == 'before':
items.insert(pos,(newkey,nvalue))
else:
print('Unknown direction.')
return(-1)
odict = dict(items)
return(odict)
|
def find_ingredients_graph_leaves(product):
"""
Recursive function to search the ingredients graph and find its leaves.
Args:
product (dict): Dict corresponding to a product or a compound ingredient.
Returns:
list: List containing the ingredients graph leaves.
"""
if 'ingredients' in product:
leaves = []
for ingredient in product['ingredients']:
subleaves = find_ingredients_graph_leaves(ingredient)
if type(subleaves) == list:
leaves += subleaves
else:
leaves.append(subleaves)
return leaves
else:
return product
|
def txt2html(text):
"""
Convert text to html compatible text
Add html tag <br /> to a text
@param: text ( string )
@return: text (string ) With
"""
lines = text.splitlines()
txt = ""
for line in lines:
txt = "".join([txt, line, ' <br />\n'])
return txt
|
def prettify_subpages(subpages):
"""
Replaces blank subpage (indicative of index) with "Homepage"
"""
output = subpages.copy()
for index, page in enumerate(subpages):
if page == '':
output[index] = 'Homepage'
return output
|
def merge_args_kwargs_dict(args, kwargs):
"""Takes a tuple of args and dict of kwargs.
Returns a dict that is the result of merging the first item
of args (if that item is a dict) and the kwargs dict."""
init_dict = {}
if len(args) > 0 and isinstance(args[0], dict):
init_dict = args[0]
init_dict.update(kwargs)
return init_dict
|
def makelabel(label, suffix):
#============================
"""
Helper function to generate a meaningful label for sub-properties of resources.
:param label: The label of some resource.
:param suffix: A suffix to append to the label.
:return: A string consisting of the label, a '_', and the suffix.
"""
return label + '_' + suffix
|
def find_index_from_str(delimited_string: str, fnd: str, split: str = ","):
"""Finds the rank of the string fnd in the passed delimited string
This function takes in a raw string with a known delimiter and locates
the index position of the fnd value, identifying the rank of the item.
Args:
delimited_string (str): The string to operate against.
fnd (str): The string to search for
split (str): The delimiter to use to split the source string.
Default: ","
Returns:
int: The integer value representing where the string fnd is
positioned in an array delimited by split.
"""
key = fnd.lower()
lst = [x.strip().lower() for x in str(delimited_string).split(split)]
rank = -1
for idx in range(len(lst)):
try:
lst[idx].index(key)
rank = idx+1
break
except ValueError:
continue
return rank
|
def tuple_next(xs):
"""Next tuple."""
return xs[0], xs[1:]
|
def keeponly(s, keep):
"""
py2
table = string.maketrans('','')
not_bits = table.translate(table, )
return txt.translate(table, not_bits)
"""
return ''.join([x for x in s if x in keep])
|
def make_float_list(val):
"""Check if the item is a string, and if so, apply str.split() to make a list of
floats. If it's a list of floats, return as is.
Used as a conversion function for apply_conversions above.
Inputs:
val: value, either string or list of floats
Outputs:
list of floats
This allows configuration parameters such as dispatch_order to be initialised from
a string or from a config pickle.
"""
if isinstance(val, str):
return map(float, str.split(val))
else:
return val
|
def original(string: str) -> str:
"""Get either the original of a `ReplaceString` or a string."""
return getattr(string, 'original', string)
|
def convert_to_list(value):
"""Convert value to list if not"""
if isinstance(value, list):
return value
else:
return [value]
|
def sum_tree(root):
"""Sums the nodes of a tree.
Arguments:
root (binary tree):
The root of a binary tree. A binary tree is either a 3-tuple
``(data, left, right)`` where ``data`` is the value of the root node
and ``left`` and ``right`` are the left and right subtrees or
``None`` for the empty tree.
Returns:
n (int):
The sum of the nodes of the tree.
"""
if root is None:
return 0
(data, left, right) = root
return data + sum_tree(left) + sum_tree(right)
|
def is_collision(line_seg1, line_seg2):
"""
Checks for a collision between line segments p1(x1, y1) -> q1(x2, y2)
and p2(x3, y3) -> q2(x4, y4)
"""
def on_segment(p1, p2, p3):
if (p2[0] <= max(p1[0], p3[0])) & (p2[0] >= min(p1[0], p3[0])) & (p2[1] <= max(p1[1], p3[1])) & (p2[1] >= min(p1[1], p3[1])):
return True
return False
def orientation(p1, p2, p3):
val = ((p2[1] - p1[1]) * (p3[0] - p2[0])) - ((p2[0] - p1[0]) * (p3[1] - p2[1]))
if val == 0:
return 0
elif val > 0:
return 1
elif val < 0:
return 2
p1, q1 = line_seg1[0], line_seg1[1]
p2, q2 = line_seg2[0], line_seg2[1]
o1 = orientation(p1, q1, p2)
o2 = orientation(p1, q1, q2)
o3 = orientation(p2, q2, p1)
o4 = orientation(p2, q2, q1)
if (o1 != o2) & (o3 != o4):
return True
if (o1 == 0 & on_segment(p1, p2, q1)):
return True
if (o2 == 0 & on_segment(p1, q2, q1)):
return True
if (o3 == 0 & on_segment(p2, p1, q2)):
return True
if (o4 == 0 & on_segment(p2, q1, q2)):
return True
return False
|
def kelvin2rankine(K):
"""
Convert Kelvin Temperature to Rankine
:param K: Temperature in Kelvin
:return: Temperature in R Rankine
"""
return 9.0 / 5.0 * K
|
def get_win_target(best_of):
"""
Gets the number of wins needed to win a match with the given best-of.
Arguments:
best_of {number} -- the max number of (non-tie) games in a match
Returns:
number -- the number of game wins needed to win the match
"""
return (best_of // 2) + 1
|
def _rangify(start, count, n, name='items'):
"""
Interpret start as an index into n objects; interpret count as a
number of objects starting at start. If start is negative,
correct it to be relative to n. If count is negative, adjust it
to be relative to n.
"""
if start < 0:
start = n + start
if start > n:
print('Warning: %s requested at %i, beyond available %s.' %\
(name, start, name))
start = n
if count == None:
count = n - start
if count < 0:
count = n - start + count
if start + count > n:
print('Warning: %i %s requested, exceeding available %s.' %\
(count, name, name))
count = n - start
return start, count
|
def ignore_words(txt):
"""
The results from google search have redundant words in them (happens when a crawler is extracting info).
We found this while testing and went to search online and found it.
One reference: https://productforums.google.com/forum/#!topic/webmasters/u2qsnn9TFiA
The parameter txt is modified in the function
"""
redundant_words = [ "Similar","Cached"] #Task: some more must be added
for temp in redundant_words:
txt = txt.replace(temp, "")
return txt
|
def get_endpoint(server):
"""Get the endpoint to sign the file, either the full or prelim one."""
if not server: # Setting is empty, signing isn't enabled.
return
return u'{server}/1.0/sign_addon'.format(server=server)
|
def word2id(words, vocab, UNK_ID=3):
"""Summary
Parameters
----------
words : TYPE
Description
vocab : TYPE
Description
UNK_ID : int, optional
Description
Returns
-------
TYPE
Description
"""
unked = []
for s in words:
this_sentence = [vocab.get(w, UNK_ID) for w in s]
unked.append(this_sentence)
return unked
|
def fmt_repr(fmt: str, val):
"""Append repr to a format string."""
return fmt.format(repr(val))
|
def check_is_valid_ds_name(value, raise_exception=True):
"""
Check if the value is a valid Dataset name
:param value: value to check
:param raise_exception: Indicate if an exception shall be raised (True, default) or not (False)
:type value: str
:type raise_exception: bool
:returns: the status of the check
:rtype: bool
:raises TypeError: if value is invalid
:raises ValueError: if value is not well formatted
"""
if not isinstance(value, str):
if raise_exception:
raise TypeError("Dataset shall be str, not %s" % type(value))
return False
if len(value) < 3:
if raise_exception:
raise ValueError("Dataset %s shall have characters" % value)
return False
if " " in value:
if raise_exception:
raise ValueError("Dataset %s shall not contains spaces" % value)
return False
return True
|
def get_nb_articles(bib):
"""Description of get_nb_articles
Count the number of articles in the database
"""
print("There are", len(bib), "articles referenced.")
return len(bib)
|
def reduce_to_unit(divider):
"""
Reduce a repeating divider to the smallest repeating unit possible.
This function is used by :meth:`make_div`.
:param divider: The divider.
:type divider: str
:return: Smallest repeating unit possible.
:rtype: str
:Example: 'XxXxXxX' -> 'Xx'
"""
for unit_size in range(1, len(divider) // 2 + 1):
length = len(divider)
unit = divider[:unit_size]
# Ignores mismatches in final characters:
divider_item = divider[:unit_size * (length // unit_size)]
if unit * (length // unit_size) == divider_item:
return unit
return divider
|
def bool_as_int(val: object) -> str:
"""Convert a True/False value into '1' or '0'.
Valve uses these strings for True/False in editoritems and other
config files.
"""
if val:
return '1'
else:
return '0'
|
def index(string, substr):
"""
Convenience method for getting substring index without exception.
Returns index if substring is found, -1 otherwise
"""
try:
n = string.index(substr)
except ValueError:
n = -1
return n
|
def get_2D_bounding_box(observations):
"""
Gets the maximum and minimum x and y in order to construct the bounding box.
"""
x = []
y = []
# slow but elegant! :P
for o in observations:
x.append(o[0])
y.append(o[1])
return (min(x),min(y)),(max(x),max(y))
|
def get_list_of_block_numbers(item):
""" Creates a list of block numbers of the given list/single event"""
if isinstance(item, list):
return [element["blockNumber"] for element in item]
if isinstance(item, dict):
block_number = item["blockNumber"]
return [block_number]
return list()
|
def RescaleValue(val, tup_lims_data, tup_lims_rescaled):
"""
Rescale numeric data value
Useful for "rescaling" data for plotting. Example:
tup_lims_data = (0, 100)
tup_lims_rescaled = (-10, 0)
value will be rescaled such that 0 --> -10 and 100 --> 0
Args:
val (Float) - value to be rescaled
tup_lims_data (tuple; numeric values)
tup_lims_data (tuple; numeric values)
Raises:
No error trapping currently
Returns:
rescaled value
"""
x1_new = tup_lims_rescaled[1]
x0_new = tup_lims_rescaled[0]
x1_prev = tup_lims_data[1]
x0_prev = tup_lims_data[0]
return (val - x0_prev)*((x1_new - x0_new)/(x1_prev - x0_prev)) + x0_new
|
def list_to_mask(values, base=0x0):
"""Converts the specified list of integer values into
a bit mask for those values. Optinally, the list can be
applied to an existing mask."""
for v in values:
base |= (1 << v)
return base
|
def addReading(
sensore, readingid, origin, deviceName, resourceName, profileName, valueType, value
):
"""
sensore is a dict ,origin is int number, else all string.
"""
reading = {
"id": readingid,
"origin": origin,
"deviceName": deviceName,
"resourceName": resourceName,
"profileName": profileName,
"valueType": valueType,
"value": value,
}
sensore["event"]["readings"].append(reading)
return sensore
|
def nearest_x(num, x):
""" Returns the number rounded down to the nearest 'x'.
example: nearest_x(25, 20) returns 20. """
for i in range(x):
if not (num - i) % x:
return num - i
|
def unify_projection(dic):
"""Unifies names of projections.
Some projections are referred using different names like
'Universal Transverse Mercator' and 'Universe Transverse Mercator'.
This function replaces synonyms by a unified name.
Example of common typo in UTM replaced by correct spelling::
>>> unify_projection({'name': ['Universe Transverse Mercator']})
{'name': ['Universal Transverse Mercator']}
:param dic: The dictionary containing information about projection
:return: The dictionary with the new values if needed or a copy of old one
"""
# the lookup variable is a list of list, each list contains all the
# possible name for a projection system
lookup = [['Universal Transverse Mercator',
'Universe Transverse Mercator']]
dic = dict(dic)
for l in lookup:
for n in range(len(dic['name'])):
if dic['name'][n] in l:
dic['name'][n] = l[0]
return dic
|
def transcribe(seq: str) -> str:
"""
transcribes DNA to RNA by generating
the complement sequence with T -> U replacement
"""
# replacement function
def replace_all(text, dictionary):
for key, val in dictionary.items():
text = text.replace(key, val)
return text
# create dictionary with text and replacement text, use interim letters P & Q so that C and G are properly replaced
d = { "A":"U", "T":"A", "G":"P", "C":"Q", "P":"C", "Q":"G" }
# return result of running replace_all on the sequence and the dictionary
return replace_all(seq, d)
|
def _format_error(error: list) -> dict:
"""
Convert the error type list to a dict.
Args:
error (list): a two element list with the error type and description
Returns:
dict: explicit names for the list elements
"""
return {'error_type': error[0], 'description': error[1]}
|
def build_database_url(ensembl_database):
""" Build the correct URL based on the database required
GRCh37 databases are on port 3337, all other databases are on port 3306
"""
port = 3337 if str(ensembl_database).endswith('37') else 3306
return 'mysql+mysqldb://anonymous@ensembldb.ensembl.org:{}/{}'\
.format(port, ensembl_database)
|
def generate_labels(seq, mods=None, zeroindex=1):
"""generate a list of len(seq), with position labels, possibly modified"""
i = zeroindex
if not mods:
return [str(x) for x in range(i, len(seq) + i)]
else:
if isinstance(mods, list):
mods = dict(mods)
pos_labels = []
for n in range(i, len(seq) + i):
if n in mods:
pos_labels.append(str(mods[n]))
else:
pos_labels.append(str(i))
i += 1
return pos_labels
|
def multiply(value, arg):
"""Multiplies the value by argument."""
try:
return float(value) * float(arg)
except (ValueError, TypeError):
return ''
|
def match_state(exp_state, states):
"""
Matches state values.
- exp_state:
A dictionary of expected state values, where
the key is the state name, the value the expected state.
- states:
The state content of the state change event.
Returns either True or False based on the match.
"""
for exp_state_name, exp_state_val in exp_state.items():
if exp_state_name not in states:
return False
if states[exp_state_name] != exp_state_val:
return False
return True
|
def getMacAddr(macRaw):
""" Get mac address via parameter mac raw """
byte_str = map('{:02x}'.format, macRaw)
mac_addr = ':'.join(byte_str).upper()
return mac_addr
|
def _get_dimensionality(column):
"""This function determines the dimensionality of a variable, to see if
it contains scalar, 1D, or 2D data. Current version fails on strings."""
try:
_=column[0]
try:
_=column[0][0]
return 2
except: return 1
except:
return 0
|
def recall(tp, fn, eps=1e-5):
"""
Calculates recall (a.k.a. true positive rate) for binary classification and
segmentation
Args:
tp: number of true positives
fn: number of false negatives
Returns:
recall value (0-1)
"""
return tp / (tp + fn + eps)
|
def atoi(v):
"""Convert v to an integer, or return 0 on error, like C's atoi()."""
try:
return int(v or 0)
except ValueError:
return 0
|
def compress_column(col):
"""takes a dense matrix column and puts it into OP4 format"""
packs = []
n = 0
i = 0
packi = []
while i < len(col):
#print("i=%s n=%s col[i]=%s" % (i, n, col[i]))
if col[i] == n + 1:
#print("i=n=%s" % i)
packi.append(i)
n += 1
else:
if packi:
packs.append(packi)
#print("pack = ", pack)
packi = [i]
n = col[i]
#print("pack = ", pack)
i += 1
if packi:
packs.append(packi)
#print("packs = ", packs)
return packs
|
def _radix_sort(L, i=0):
"""
Most significant char radix sort
"""
if len(L) <= 1:
return L
done_bucket = []
buckets = [ [] for x in range(255) ]
for s in L:
if i >= len(s):
done_bucket.append(s)
else:
buckets[ ord(s[i]) ].append(s)
buckets = [ _radix_sort(b, i + 1) for b in buckets ]
return done_bucket + [ b for blist in buckets for b in blist ]
|
def capitalize(text):
"""
Capitalize first non-whitespace character folling each period in string
:param str text: text to capitalize
:return: capitalized text
:rtype: str
"""
ret = list(text)
# Make sure first word is capitalized...
i = 0
while i < (len(text) - 1) and text[i].isspace():
i += 1
if text[i].isalpha() and text[i].islower():
ret[i] = ret[i].upper()
# Find all alpha characters following a period and make
# sure they are uppercase...
p = 0 # next period index
while p < (len(text) - 1):
p = text.find('.', p)
if p < 0:
break
p += 1
# index of first non-space character after period
w = p
while w < (len(text) - 1) and text[w].isspace():
w += 1
if text[w].isalpha() and text[w].islower():
ret[w] = ret[w].upper()
return ''.join(ret)
|
def parse_statement_forwarder_id(json):
"""
Extract the statement forwarder id from the post response.
:param json: JSON from the post response from LearningLocker.
:type json: dict(str, dict(str, str))
:return: The extracted statement forwarder id.
:rtype: str
"""
return json['_id']
|
def _round_to_base(x, base=5):
"""Round to nearest multiple of `base`."""
return int(base * round(float(x) / base))
|
def _create_agent_type_id(identifier_type, identifier_value):
"""Create a key-pair string for the linking_type_value in the db.
"""
return "{}-{}".format(identifier_type, identifier_value)
|
def isdistinct(seq):
""" All values in sequence are distinct
>>> isdistinct([1, 2, 3])
True
>>> isdistinct([1, 2, 1])
False
>>> isdistinct("Hello")
False
>>> isdistinct("World")
True
"""
return len(seq) == len(set(seq))
|
def ArrayOfUTF16StreamCopyToStringTable(byte_stream, byte_stream_size=None):
"""Copies an array of UTF-16 formatted byte streams to a string table.
The string table is a dict of strings with the byte offset as their key.
The UTF-16 formatted byte stream should be terminated by an end-of-string
character (\x00\x00). Otherwise the function reads up to the byte stream size.
Args:
byte_stream: The UTF-16 formatted byte stream.
byte_stream_size: The byte stream size or None if the entire byte stream
should be used.
Returns:
A dict of Unicode strings with the byte offset as their key.
"""
string_table = {}
utf16_stream_start = 0
byte_stream_index = 0
if not byte_stream_size:
byte_stream_size = len(byte_stream)
while byte_stream_index + 1 < byte_stream_size:
if (byte_stream[byte_stream_index] == b'\x00' and
byte_stream[byte_stream_index + 1] == b'\x00'):
if byte_stream_index - utf16_stream_start <= 2:
break
string = byte_stream[utf16_stream_start:byte_stream_index].decode(
'utf-16-le')
string_table[utf16_stream_start] = string
utf16_stream_start = byte_stream_index + 2
byte_stream_index += 2
return string_table
|
def make_icon_state_dict(message_icons, icon_names):
"""Extract the icon state for icon_names from message."""
def binary_sensor_value(icon_flag):
return False if icon_flag is None else bool(icon_flag)
return {k: binary_sensor_value(message_icons[k]) for k in icon_names}
|
def Alg_improved_Euclid( a, b ):
""" Simple recursive implementation (for gcd) """
if a < b: a, b = b, a
if a % b == 0: return b
#print a, b
if b == 0: return a
else: return Alg_improved_Euclid( b, a % b )
|
def transform_entry(entry):
"""
Turn the given neo4j Node into a dictionary based on the Node's type.
The raw neo4j Node doesn't serialize to JSON so this converts it into
something that will.
@param entry: the neo4j Node to transform.
"""
# This transform is used for just nodes as well so first check to see if there is a relation
if 'relation' not in entry:
node = entry
relation = {'weight':1}
elif entry['relation'] is None:
node = entry['node']
relation = {'weight':1}
else:
node = entry['node']
relation = entry['relation']
# Skip anything that isn't a dict or doesn't have an ntype property (bookmarks are skipped here)
if type(node) is not dict or 'ntype' not in node:
return None
if node['ntype'] == 'user':
return {'user':{'name':node['name'],'user_id':node['userId'], 'weight':relation['weight']}}
elif node['ntype'] == 'a':
return {'answer':{'post_id':node['postId'], 'favorite_count':node['favoriteCount'], 'score':node['score'], 'weight':relation['weight']}}
elif node['ntype'] == 'q':
return {'question':{'post_id':node['postId'], 'favorite_count':node['favoriteCount'], 'score':node['score'], 'weight':relation['weight']}}
elif node['ntype'] == 'tag':
return {'tag':{'name':node['tagName'], 'weight':relation['weight']}}
else:
return None
|
def about_view(request):
"""View for the about page."""
return {'title': 'about'}
|
def email_lowercase(backend,details, user=None,*args, **kwargs):
"""
A pipeline to turn the email address to lowercase
"""
email = details.get("email")
details['email'] = email.strip().lower() if email else None
return {"details":details}
|
def convert_class_functions(line):
"""Convert class initializer functions to the corresponding variable."""
first_paren = line.find('(')
if first_paren == -1:
return line
line = "unidentified function: " + line
return line
|
def string_escape(string):
"""
Returns an escaped string for use in Dehacked patch writing.
"""
string = string.replace('\\', '\\\\')
string = string.replace('\n', '\\n')
string = string.replace('\r', '\\r')
string = string.replace('\t', '\\t')
string = string.replace('\"', '\\"')
return string
|
def tiles(width, height, tWidth, tHeight):
"""Calculates how many tiles does one need
for given area
@param width: area's width
@param height: area's height
@param tWidth: tile's width
@param tHeight: tiles's height"""
area = width * height
tile = tWidth * tHeight
return area / tile
|
def process_host(x):
"""
:return: host, gender, age
"""
#Homo sapiens; male; age 65
#Homo sapiens; female; age 49 Homo sapiens; male; age 41
#Homo sapiens; female; age 52 Homo sapiens; male; age 61
#Homo sapiens; male Homo sapiens; hospitalized patient
raw = x.split('; ')
gender = 'unknown'
age = 'unknown'
host = raw[0]
if len(raw) == 3:
if raw[1].lower() in ['male', 'female']: gender = raw[1].lower()
if raw[2].startswith('age' ): age = raw[2].split('age ')[1]
host = host.replace('"','')
try:
if host.lower().startswith('homo'): host = 'Human'
except:
pass
return host, gender, age
|
def is_additional_rdr_table(table_id):
"""
Return True if specified table is an additional table submitted by RDR.
Currently includes pid_rid_mapping
:param table_id: identifies the table
:return: True if specified table is an additional table submitted by RDR
"""
return table_id == 'pid_rid_mapping'
|
def nested_pairs2dict(pairs):
"""Create a dict using nested pairs
>>> nested_pairs2dict([["foo",[["bar","baz"]]]])
{'foo': {'bar': 'baz'}}
:param pairs: pairs [key, value]
:type pairs: list
:returns: created dict
:rtype: dict
"""
d = {}
try:
for k, v in pairs:
if isinstance(v, list):
v = nested_pairs2dict(v)
d[k] = v
except ValueError:
return pairs
return d
|
def _find_indicies(array, value):
"""
Finds the indicies of the array elements that are the closest to `value`. If
value is present in `array` then the two indicies are the same.
Parameters
----------
value : scalar
Value of which the index is to be found.
array : list/numpy.ndarray
Sorted array.
Raises
------
ValueError
Raised if the indices are not found (i.e. the eindicies are out of bound
of the array)
Returns
-------
int, int
Returns the indicies of the elements of the array most close to value.
If the vlaue is present in the array then the function returns the same
int twice.
"""
for i, elem in enumerate(array):
if value == elem:
return i, i
elif elem < value and value < array[i+1]:
return i, i+1
raise ValueError("Indicies not found.")
|
def solution(a: list) -> int:
"""
>>> solution([1, 4, 1])
0
>>> solution([-1, -2, -3, -2])
1
>>> solution([4, 2, 2, 5, 1, 5, 8])
1
"""
start = 0
min_ = 10001
for i in range(len(a) - 1):
avg = (a[i] + a[i + 1]) / 2
if min_ > avg:
min_, start = avg, i
try:
avg = (a[i] + a[i + 1] + a[i + 2]) / 3
if min_ > avg:
min_, start = avg, i
except IndexError:
pass
return start
|
def perdidas (n_r,n_inv,n_x,**kwargs):
"""Calcula las perdidas por equipos"""
n_t=n_r*n_inv*n_x
for kwargs in kwargs:
n_t=n_t*kwargs
return n_t
|
def get_correct_message(hidden_word: str) -> str:
"""Return a output line.
Use this method when the user was correct.
:param hidden_word: str
:return:
"""
return f"Hit!\n\n" \
f"The word: {hidden_word}\n"
|
def _get_separator(num, sep_title, sep_character, sep_length):
"""Get a row separator for row *num*."""
left_divider_length = right_divider_length = sep_length
if isinstance(sep_length, tuple):
left_divider_length, right_divider_length = sep_length
left_divider = sep_character * left_divider_length
right_divider = sep_character * right_divider_length
title = sep_title.format(n=num + 1)
return "{left_divider}[ {title} ]{right_divider}\n".format(
left_divider=left_divider, right_divider=right_divider, title=title
)
|
def authorized_groups_text(authorized_groups, default_text='All') -> str:
""" Helper function that returns a string for display purposes. """
res = default_text
if authorized_groups:
res = ', '.join(authorized_groups)
return res
|
def inner_product(koyo, kuwi):
"""
Inner product between koyo kuwi.
"""
inner = sum(koyo[key] * kuwi.get(key, 0.0) for key in koyo)
return inner
|
def get_audit(info):
"""
Prints output in a format that can be parsed from a log file.
Spec: <available_peak>,
<per_day_peak_remaining>,
<today_peak_usage>,
<peak_usage_percentage>,
<available_off_peak>,
<today_off_peak_usage>
"""
return "{0},{1},{2},{3},{4},{5}".format(info['peak_available'],
info['daily_peak_remaining'],
info['peak_usage'],
info['peak_usage_percentage'],
info['off_peak_available'],
info['off_peak_usage'])
|
def format_seconds(seconds):
"""
convert a number of seconds into a custom string representation
"""
d, seconds = divmod(seconds, (60 * 60 * 24))
h, seconds = divmod(seconds, (60 * 60))
m, seconds = divmod(seconds, 60)
time_string = ("%im %0.2fs" % (m, seconds))
if h or d:
time_string = "%ih %s" % (h, time_string)
if d:
time_string = "%id %s" % (d, time_string)
return time_string
|
def equal_sign(num1, num2):
"""
returns True if the signs of two numbers are equal
"""
if num1 * num2 > 0:
return True
else:
return False
|
def sort_high_scores(scores, highest_possible_score):
"""Returns the high scores sorted from highest to lowest"""
if type(scores) != list:
raise TypeError(
"The first argument of sort_high_scores must be a list.")
if type(highest_possible_score) != int:
raise TypeError(
"The second argument of sort_high_scores must be an int.")
tracker = {}
sorted_high_scores = []
for score in scores:
if score in tracker:
tracker[score] += 1
else:
tracker[score] = 1
for score in range(highest_possible_score, -1, -1):
if score in tracker:
while tracker[score] > 0:
sorted_high_scores.append(score)
tracker[score] -= 1
return sorted_high_scores
|
def remove_digits(s):
"""
Remove digits in the given string
:param s: input string
:return: digits removed string
"""
return ''.join([c for c in s if not c.isdigit()])
|
def in_reduce(reduce_logic_func, sequence, inclusion_list) -> bool:
"""Using `reduce_logic_func` check if each element of `sequence` is in `inclusion_list`"""
return reduce_logic_func(elmn in inclusion_list for elmn in sequence)
|
def get_instrument(program):
"""Return the instrument inferred from the program number."""
if 0 <= program < 8:
return "Piano"
if 24 <= program < 32:
return "Guitar"
if 32 <= program < 40:
return "Bass"
if 40 <= program < 46 or 48 <= program < 52:
return "Strings"
if 56 <= program < 64:
return "Brass"
return None
|
def get_resample(name: str) -> str:
"""retrieves code for resampling method
Args:
name (:obj:`string`): name of resampling method
Returns:
method :obj:`string`: code of resample method
"""
methods = {
"first":
"""
import numpy as np
def first(in_ar, out_ar, xoff, yoff, xsize, ysize, raster_xsize,raster_ysize, buf_radius, gt, **kwargs):
y = np.ones(in_ar[0].shape)
for i in reversed(range(len(in_ar))):
mask = in_ar[i] == 0
y *= mask
y += in_ar[i]
np.clip(y,0,255, out=out_ar)
""",
"last":
"""
import numpy as np
def last(in_ar, out_ar, xoff, yoff, xsize, ysize, raster_xsize,raster_ysize, buf_radius, gt, **kwargs):
y = np.ones(in_ar[0].shape)
for i in range(len(in_ar)):
mask = in_ar[i] == 0
y *= mask
y += in_ar[i]
np.clip(y,0,255, out=out_ar)
""",
"max":
"""
import numpy as np
def max(in_ar, out_ar, xoff, yoff, xsize, ysize, raster_xsize,raster_ysize, buf_radius, gt, **kwargs):
y = np.max(in_ar, axis=0)
np.clip(y,0,255, out=out_ar)
""",
"average":
"""
import numpy as np
def average(in_ar, out_ar, xoff, yoff, xsize, ysize, raster_xsize,raster_ysize, buf_radius, gt, **kwargs):
div = np.zeros(in_ar[0].shape)
for i in range(len(in_ar)):
div += (in_ar[i] != 0)
div[div == 0] = 1
y = np.sum(in_ar, axis = 0, dtype = 'uint16')
y = y / div
np.clip(y,0,255, out = out_ar)
"""}
if name not in methods:
raise ValueError(
"ERROR: Unrecognized resampling method (see documentation): '{}'.".
format(name))
return methods[name]
|
def polynomial5(x):
"""Polynomial function with 5 roots in the [-1, 1] range."""
return 63 * x**5 - 70 * x**3 + 15 * x + 2
|
def fetchall(cursor):
"""
Fetch all rows from the given cursor
Params:
cursor (Cursor) : Cursor of previously executed statement
Returns:
list(dict) : List of dict representing the records selected indexed by column name
"""
if cursor:
cursor_def = [d.name for d in cursor.description]
return [dict(zip(cursor_def, r)) for r in cursor.fetchall()]
else:
return []
|
def mythdate2dbdate(mythdate):
"""Turn 20080102 -> 2008-01-02"""
return mythdate[0:4] + '-' + mythdate[4:6] + '-' + mythdate[6:8]
|
def booleanize_list(vals, null_vals=['no', 'none', 'na', 'n/a', '']):
"""Return a list of true/false from values."""
out = []
for val in vals:
val = val.strip().lower()
out.append(val and val not in null_vals)
return out
|
def strip_bot_tag(text, bot_tag):
"""Helper to strip the bot tag out of the message"""
# split on bot tag, strip trailing whitespace, join non-empty with space
return " ".join([t.strip() for t in text.split(bot_tag) if t])
|
def vsipGetType(v):
"""
Returns a tuple with True if a vsip type is found, plus a string indicating the type.
For instance for
a = vsip_vcreate_f(10,VSIP_MEM_NONE)
will return for the call getType(a) (True,'vview_f')
also returns types of scalars derived from structure. for instance
c = vsip_cscalar_d() will return for getType(c) the tuple (True, 'cscalar_d').
attr = vsip_mattr_d() will return for getType(attr) the tuple (True, 'mattr_d')
If float or int type is passed in returns (True,'scalar')
If called with a non VSIPL type returns (False, 'Not a VSIPL Type')
"""
t = repr(v).rpartition('vsip_')
if t[1] == 'vsip_':
return(True,t[2].partition(" ")[0])
elif isinstance(v,float):
return(True,'scalar')
elif isinstance(v,int):
return(True,'scalar')
else:
return(False,'Not a VSIPL Type')
|
def fiboRecursive(n):
""" Fibonacci numbers solved with binary recursion """
if n == 0 or n == 1:
return 1
else:
return fiboRecursive(n - 1) + fiboRecursive(n - 2)
|
def get_gb_person_id(acc_id, vehicle_index, person_index):
"""
Returns global person id for GB, year and index of accident.
The id is constructed as <Acc_id><Person_index>
where Vehicle_index is two digits max.
"""
person_id = acc_id * 1000
person_id += vehicle_index * 100
person_id += person_index
return person_id
|
def toLookup(object_list):
"""A helper function that take a list of two element objects and
returns a dictionary that uses the second element as the key. The
returned dictionary can be used find the id of an object based on the
key passed in. Reduces the number of database queries to one.
the items in the object list should be of the format:
("id","value"). the returned dictionary can then be used as
foo['value'] to quickly return the associated id.
"""
return {x[1]: x[0] for x in object_list}
|
def compress_gray(x):
"""Extract the gray part of a Colay code or cocode word
The function returns the 'gray' part of a Golay code or cocode
as a 6-bit number. It drops the 'colored' part of the word.
A 12-bit Golay code or cocode word can be expressed as a sum of
a 6-bit 'gray' and a 6-bit 'colored' word, see [Seysen20],
section 2.2.
A Golay code word x must be given in 'gcode' and a cocode word
must be given in 'cocode' representation.
"""
return (x & 0x0f) + ((x >> 6) & 0x30)
|
def get_provenance_record(caption, ancestor_files, **kwargs):
"""Create a provenance record describing the diagnostic data and plot."""
record = {
'caption': caption,
'authors': ['schlund_manuel'],
'references': ['acknow_project'],
'ancestors': ancestor_files,
}
record.update(kwargs)
return record
|
def is_word_end(s):
"""
Checks if a sign finishes a word
:param s: the sign to check
:return: true if the sign finishes the word
"""
if s[-1] in "-.":
return False
return True
|
def _is_single_bit(value):
"""
True if only one bit set in value (should be an int)
"""
if value == 0:
return False
value &= value - 1
return value == 0
|
def linestrings_intersect(line1, line2):
"""
To valid whether linestrings from geojson are intersected with each other.
reference: http://www.kevlindev.com/gui/math/intersection/Intersection.js
Keyword arguments:
line1 -- first line geojson object
line2 -- second line geojson object
if(line1 intersects with other) return intersect point array else empty array
"""
intersects = []
for i in range(0, len(line1['coordinates']) - 1):
for j in range(0, len(line2['coordinates']) - 1):
a1_x = line1['coordinates'][i][1]
a1_y = line1['coordinates'][i][0]
a2_x = line1['coordinates'][i + 1][1]
a2_y = line1['coordinates'][i + 1][0]
b1_x = line2['coordinates'][j][1]
b1_y = line2['coordinates'][j][0]
b2_x = line2['coordinates'][j + 1][1]
b2_y = line2['coordinates'][j + 1][0]
ua_t = (b2_x - b1_x) * (a1_y - b1_y) - \
(b2_y - b1_y) * (a1_x - b1_x)
ub_t = (a2_x - a1_x) * (a1_y - b1_y) - \
(a2_y - a1_y) * (a1_x - b1_x)
u_b = (b2_y - b1_y) * (a2_x - a1_x) - (b2_x - b1_x) * (a2_y - a1_y)
if not u_b == 0:
u_a = ua_t / u_b
u_b = ub_t / u_b
if 0 <= u_a and u_a <= 1 and 0 <= u_b and u_b <= 1:
intersects.append({'type': 'Point', 'coordinates': [
a1_x + u_a * (a2_x - a1_x), a1_y + u_a * (a2_y - a1_y)]})
# if len(intersects) == 0:
# intersects = False
return intersects
|
def is_sequence_of_uint(items):
"""Verify that the sequence contains only unsigned :obj:`int`.
Parameters
----------
items : iterable
The sequence of items.
Returns
-------
bool
"""
return all(isinstance(item, int) and item >= 0 for item in items)
|
def int_parse(s):
"""
Parse an integer string in a log file.
This is a simple variant on int() that returns None in the case of a single
dash being passed to s.
:param str s: The string containing the integer number to parse
:returns: An int value
"""
return int(s) if s != '-' else None
|
def clear_bit(target, bit):
"""
Returns target but with the given bit set to 0
"""
return target & ~(1 << bit)
|
def show_num_bins(autoValue, slider_value):
""" Display the number of bins. """
if "Auto" in autoValue:
return "# of Bins: Auto"
return "# of Bins: " + str(int(slider_value))
|
def parse_map_line(line, *args):
"""Parse a line in a simple mapping file.
Parameters
----------
line : str
Line to parse.
args : list, optional
Placeholder for caller compatibility.
Returns
-------
tuple of (str, str)
Query and subject.
Notes
-----
Only the first two columns are considered.
"""
query, found, rest = line.partition('\t')
if found:
subject, found, rest = rest.partition('\t')
return query, subject.rstrip()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.