content stringlengths 42 6.51k |
|---|
def splitFilename(fn):
"""Split filename into base and extension (base+ext = filename)."""
if '.' in fn:
base, ext = fn.rsplit('.', 1)
else:
ext = ''
base = fn
return base, ext |
def _get_parent_scope(scope):
"""Removes the final leaf from a scope (`a/b/c/` -> `a/b/`)."""
parts = scope.split('/')
return '/'.join(parts[:-2] + parts[-1:]) |
def combine_sigma(sig1, sig2):
""" Combine the sigma values of two species.
:param sig1: sigma of species 1
:type sig1: float
:param sig2: sigma of species 2
:type sig2: float
:return: sig_comb
:rtpye: float
"""
if sig1 is not None and sig2 is not None:
sig_comb = (2.0 * sig1) - sig2
else:
sig_comb = None
return sig_comb |
def floatToFixed(value, precisionBits):
"""Converts a float to a fixed-point number given the number of
precisionBits. Ie. int(round(value * (1<<precisionBits))).
>>> floatToFixed(0.8, 14)
13107
>>> floatToFixed(1.0, 14)
16384
>>> floatToFixed(1, 14)
16384
>>> floatToFixed(0, 14)
0
"""
return int(round(value * (1<<precisionBits))) |
def isInPar(db, chrom, start, end):
""" return None if not in PAR or "1" or "2" if genome is hg19 or hg38 and chrom:start-end is in a PAR1/2 region """
if db not in ("hg19", "hg38"):
return None
if not chrom in ("chrX", "chrY"):
return None
# all coordinates are from https://en.wikipedia.org/wiki/Pseudoautosomal_region
# and look like they're 1-based
if db=="hg38":
if chrom=="chrX":
if start >= 10001 and end < 2781479:
return "1"
if start >= 155701383 and end < 156030895:
return "2"
elif chrom=="chrY":
if start >= 10001 and end < 2781479:
return "1"
if start >= 56887903 and end < 57217415:
return "2"
elif db=="hg19":
if chrom=="chrX":
if start >= 60001 and end < 2699520:
return "1"
if start >= 154931044 and end < 155260560:
return "2"
elif chrom=="chrY":
if start >= 10001 and end < 2649520:
return "1"
if start >= 59034050 and end < 59363566:
return "2"
return None |
def parse_redirect_params(redirect_str):
"""
Parse a redirect string into it's url reverse key and optional kwargs
"""
if not redirect_str:
return None, None
redirect_key = redirect_str
redirect_kwargs = {}
redirect_key_parts = redirect_str.split("|")
if len(redirect_key_parts) == 2:
redirect_key, redirect_kwargs_spec = redirect_key_parts
redirect_kwargs = dict([redirect_kwargs_spec.split("=")])
return redirect_key, redirect_kwargs |
def helper(n, max_n):
"""
:param n: (int) number n for pick largest digit
:param max_n: (int) largest digit
:return: (int) largest digit
"""
# Base Case
if n == 0: # return largest digit
return max_n
# Recursive Case
else:
remainder = n % 10 # pick digit
if remainder > max_n:
return helper(n//10, remainder) # replace largest digit then recurs
else:
return helper(n//10, max_n) |
def win_or_block(board, win_rows, test_mark, move_mark):
"""
Check for both a possible winning move or a possible
blocking move that the machine should make & makes
that move. Differentiate these moves with the space
marking characters used for test_mark and move_mark.
To check for a winning move the machine_mark is used for
both. The check for a block use the player_mark for the
test_mark.
"""
msg = 'Blocking'
if test_mark == move_mark:
msg = 'Winning'
print('\nChecking for ' + msg + ' move')
move = False
for row in win_rows:
# print '\n>>> Row: ' + str(row)
ms = -1
c = 0
row_string = ''
for i in row:
mark = board[i]
# print 'mark: ' + mark
row_string = row_string + mark
# print ('row_string = ' + row_string)
if mark == '-':
ms = i
####
if mark == test_mark:
c = c + 1
# print 'c = ' + str(c)
if c == 2:
move = True
c = 0
if move:
# print('Attempting ' + msg + ' Move')
# print 'ms = ' + str(ms)
if ms >= 0:
board[ms] = move_mark
ms = -1
break
else:
print('OK, No open space found in row,' +
'board is not being updated')
move = False
else:
pass
# print ('No ' + msg + ' move found in row\n')
# needs to return game_status, right? No ...
return board, move |
def rot13(string):
"""
Rot13 for only A-Z and a-z characters
"""
try:
return ''.join(
[chr(ord(n) + (13 if 'Z' < n < 'n' or n < 'N' else -13)) if ('a' <= n <= 'z' or 'A' <= n <= 'Z') else n for
n in
string])
except TypeError:
return None |
def binary_search(a, value):
"""
Searches a value in a (sorted) list. Return the index if found, otherwise
returns <None>.
"""
start = 0
end = len(a) - 1
while (start <= end):
i = (start + end) // 2 # Middle point
# If found the value
if (a[i] == value):
return i
# If not found the value
else:
if (a[i] > value):
end = i - 1 # Check left side
else:
start = i + 1 # Check right side
return None |
def create_result(m, d, y):
""" Creates result """
result = ''
if m < 10:
result += '0' + str(m)
else:
result += str(m)
result += '/'
if d < 10:
result += '0' + str(d)
else:
result += str(d)
result += '/' + str(y)
return result |
def deduce(control, length, arr):
"""Return the only number left."""
matches = list(
filter(
lambda x: len(x) == length and x not in arr,
control))
if len(matches) != 1:
raise ValueError('Something went wrong. No deduction possible.')
return matches[0] |
def test_1(input):
"""
>>> test_1("hijklmmn")
True
>>> test_1("abcdffaa")
True
>>> test_1("")
False
>>> test_1("abdfasdf")
False
"""
alphabet = "abcdefghijklmnopqrstuvwxyz"
for i in range(len(input)-3):
if input[i:i+3] in alphabet:
return True
return False |
def cents_to_string(cents):
"""
Convert an integer number of cents into a string representing a dollar
value.
"""
return '%d.%02d' % divmod(cents, 100) |
def listToStr(list, seperator=" "):
""" Return a string consists of elements in list seperated by
seperator.
"""
return seperator.join(map(str,list)) |
def pathfinder_auxiliary(row, col, M):
"""
Find the maximum path from the longest path's location
@param row The row index in the matrix of where to find the longest path
@param col The column index in the matrix of where to find the longest path to
@param M The Matrix, as an array
@return maxpath The path taken as a list of tuples
@complexity Time: Worst-case - O(NM) where N and M are the dimensions of the matrix M
Space: Worst - case - O(NM) (all points in M visited)
"""
# Initialise the two lists
pc = []
maxpath = []
### Straight horizontal or vertical:
# Across 1:
if col < len(M[0]) - 1 and (M[row][col] < M[row][col + 1]):
pc = pathfinder_auxiliary(row, col + 1, M)
if len(pc) > len(maxpath):
maxpath = pc
# Across -1:
if col > 0 and (M[row][col] < M[row][col - 1]):
pc = pathfinder_auxiliary(row, col - 1, M)
if len(pc) > len(maxpath):
maxpath = pc
# Down 1:
if row < len(M) - 1 and (M[row][col] < M[row + 1][col]):
pc = pathfinder_auxiliary(row + 1, col, M)
if len(pc) > len(maxpath):
maxpath = pc
# Down -1:
if row > 0 and (M[row][col] < M[row - 1][col]):
pc = pathfinder_auxiliary(row - 1, col, M)
if len(pc) > len(maxpath):
maxpath = pc
### Diagonals
# Across 1 Down 1:
if col < len(M[0]) - 1 and row < len(M) - 1 and (M[row][col] < M[row + 1][col + 1]):
pc = pathfinder_auxiliary(row + 1, col + 1, M)
if len(pc) > len(maxpath):
maxpath = pc
# Across -1 Down 1:
if col > 0 and row < len(M) - 1 and (M[row][col] < M[row + 1][col - 1]):
pc = pathfinder_auxiliary(row + 1, col - 1, M)
if len(pc) > len(maxpath):
maxpath = pc
# Across 1 Down -1:
if col < len(M[0]) - 1 and row > 0 and (M[row][col] < M[row - 1][col + 1]):
pc = pathfinder_auxiliary(row - 1, col + 1, M)
if len(pc) > len(maxpath):
maxpath = pc
# Across -1 Down -1:
if col > 0 and row > 0 and (M[row][col] < M[row - 1][col - 1]):
pc = pathfinder_auxiliary(row - 1, col - 1, M)
if len(pc) > len(maxpath):
maxpath = pc
# Add self to max path (this can also be called the base case in this context)
maxpath = [(row, col)] + maxpath
return maxpath |
def needs_write_barrier(obj):
""" We need to emit write barrier if the right hand of assignment
is in nursery, used by the JIT for handling set*_gc(Const)
"""
if not obj:
return False
# XXX returning can_move() here might acidentally work for the use
# cases (see issue #2212), but this is not really safe. Now we
# just return True for any non-NULL pointer, and too bad for the
# few extra 'cond_call_gc_wb'. It could be improved e.g. to return
# False if 'obj' is a static prebuilt constant, or if we're not
# running incminimark...
return True |
def sizeFormat(sizeInBytes):
"""
Format a number of bytes (int) into the right unit for human readable
display.
"""
size = float(sizeInBytes)
if sizeInBytes < 1024:
return "%.0fB" % (size)
if sizeInBytes < 1024 ** 2:
return "%.3fKb" % (size / 1024)
if sizeInBytes < 1024 ** 3:
return "%.3fMb" % (size / (1024 ** 2))
else:
return "%.3fGb" % (size / (1024 ** 3)) |
def below(prec, other_prec):
"""Whether `prec` is entirely below `other_prec`."""
return prec[1] < other_prec[0] |
def escape(string):
"""Escape strings to be SQL safe"""
if '"' in string:
raise Exception("Can't escape identifier {} because it contains a backtick"
.format(string))
return '"{}"'.format(string) |
def fibonacci(n):
"""
FIBONACCI SEQUENCE
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ...
Info about its calculation:
https://stackoverflow.com/questions/18172257/efficient-calculation-of-fibonacci-series
Calculate them using recursive function
This is a primitive recursive solution
"""
if n <= 1:
return n
else:
return fibonacci(n-1) + fibonacci(n-2) |
def f1_score(precision, recall):
"""
Compute f1 score.
"""
if precision or recall:
return 2 * precision * recall / (precision + recall)
return 0 |
def create_biomarker_schema(schema: dict) -> dict:
"""
Factory method for creating a schema object.
Arguments:
schema {dict} -- Cerberus schema dictionary.
Returns:
dict -- EVE endpoint definition.
"""
base_dict = {
"public_methods": [],
"resource_methods": ["GET", "POST"],
"allowed_roles": ["user", "uploader", "admin", 'system'],
"allowed_item_roles": ["user", "uploader", "admin", 'system'],
"schema": {
"trial": {"type": "objectid", "required": True},
"assay": {"type": "objectid", "required": True},
"record_id": {"type": "objectid", "required": True},
},
}
base_dict["schema"].update(schema)
return base_dict |
def not_none(input_value, replacement_value=""):
""" If the given input value is None, replace it with something else """
if input_value is None:
return replacement_value
return input_value |
def flatten_list(l):
"""
Flatten a list recursively without for loops or additional modules
Parameters
---------
l : list
List to flatten
Example Usage:
.. code-block:: python
from autoprotocol_utilities.misc_helpers import flatten_list
temp_flattened_list = flatten_list(params["source"])
milliq_water_id = "rs17gmh5wafm5p"
lysis_buffer = createMastermix(protocol, "Water", "micro-1.5",\
reactions=len(temp_flattened_list),resources={milliq_water_id: Unit(50, "ul")})
protocol.transfer(source=lysis_buffer, dest=temp_flattened_list, volume="50:ul")
Returns
-------
list
Flat list
Raises
------
ValueError
If l is not of type list
"""
if isinstance(l, list):
return [x for sublist in l for x in flatten_list(sublist)]
else:
return [l] |
def sci_to_float(s):
"""
Converts a string of the form 'aEb' into an int given by a*10^b
"""
s = s.replace("e", "E")
if 'E' in s:
s = s.split('E')
return float(s[0]) * 10**float(s[1])
return s |
def count_yes( answers, part2=False ):
"""
For Part 1:
-----------
This function returns the count of questions to which atleast one
person in the group answered yes.
For Part 2:
-----------
This function returns the count of questions to which every
person in the group answered yes.
"""
count_any = 0
count_all = 0
for group in answers:
yes_any = set( [result for item in group for result in item] )
count_any += len(yes_any)
yes_all = set(group[0]).intersection( *group[1:] )
count_all += len(yes_all)
if not part2:
return count_any
else:
return count_all |
def midpoints(vec):
"""
:param vec: list of N coordinates
:return: list of N-1 points that represent the midpoint between all pairwise N coordinates
"""
return [vec[i] + abs(vec[i+1] - vec[i]) / 2.0 for i in range(len(vec)-1)] |
def get_url_for_exhibition(after, before, apikey):
"""
This function writes a url(a string) for Harvard Art Museums API to get a dataset with all exhibitions information, held in the selected years.
Parameters
----------
after: str
A string of a starting year of a period when exhibitions were held
before: str
A string of an ending year of a period when exhibitions were held
apikey: str
A string of your apikey, given by Harvard Art Museums;
https://harvardartmuseums.org/collections/api
Returns
-------
str
A url to put into the get_exhibitions() function, which will give you the dataset.
Examples
--------
>>> from harvardartmuseums_pkg import harvardartmuseums_pkg
>>> after = '1975'
>>> before = '2005'
>>> apikey = "yourapikey"
>>> harvardartmuseums_pkg.get_url_for_exhibition(after, before, apikey)
'https://api.harvardartmuseums.org/exhibition?after=1975&before=2005&apikey=yourapikey'
"""
your_url= "https://api.harvardartmuseums.org/exhibition?after=" + after + "&before=" + before + "&apikey=" + apikey
return your_url |
def find_interval(value, intervals):
"""
Find the interval in which value exists in.
Returns the index where the interval interval_ends.
"""
for index, interval in enumerate(intervals):
if interval[0] <= value <= interval[1]:
return index
return -1 |
def dB_function(dB):
""" Convert dB into linear units """
linear = 10**(dB/10.)
return linear |
def factorial(n):
"""
Given an integer value,
return its factorial without using resursive approach
"""
facto = 1 # Assignment Takes constant time: O(1)
while n > 1: # This loop will run n times: O(n)> Because the loop has 2 lines to execute, it will be O(2n)
facto *= n # Takes constant time: O(1)
n -= 1 # Takes constant time: O(1)
return facto |
def calculation(m, d, n):
"""
Calculates m**d mod(n) more efficiently
"""
value = 1
for _ in range(d):
value = (value * m) % n
return value |
def write_output(best_solution):
"""
Parses best_solution's path and returns desired strings
"""
output_data = str(best_solution[1]) + ' ' + str(1) + '\n'
output_data += ' '.join([i[1] for i in best_solution[0] if int(i[1]) != -1])
return output_data |
def getCollectionForId(obj_id):
""" return groups/datasets/datatypes based on id """
if not isinstance(obj_id, str):
raise ValueError("invalid object id")
collection = None
if obj_id.startswith("g-"):
collection = "groups"
elif obj_id.startswith("d-"):
collection = "datasets"
elif obj_id.startswith("t-"):
collection = "datatypes"
else:
raise ValueError("not a collection id")
return collection |
def fahrenheit(value: float, target_unit: str) -> float:
"""
Utility function for Fahrenheit conversion in Celsius or in Kelvin
:param value: temperature
:param target_unit: Celsius, Kelvin or Fahrenheit
:return: value converted in the right scale
"""
if target_unit == "C":
# Convert in Celsius scale
return (value - 32) / 1.8
else:
# Convert in Kelvin scale
return (value - 32) / 1 - 8 + 273.15 |
def Main(a, b):
"""
:param a:
:param b:
:return:
"""
j = a & b
q = j | b
m = a ^ q
return m |
def _to_module_name(fn):
# type: (str) -> str
"""
Try to guess imported name from file descriptor path
"""
fn = fn.replace('/', '_dot_')
fn = fn[:-len('.proto')] # strip suffix
fn += '__pb2' # XXX: might only be one underscore?
return fn |
def hyperheader2dic(head):
"""
Convert a hypercomplex block header into a Python dictionary.
"""
dic = dict()
dic["s_spare1"] = head[0]
dic["status"] = head[1]
dic["s_spare2"] = head[2]
dic["s_spare3"] = head[3]
dic["l_spare1"] = head[4]
dic["lpval1"] = head[5]
dic["rpval1"] = head[6]
dic["f_spare1"] = head[7]
dic["f_spare2"] = head[8]
# unpack the status bits
dic["UHYPERCOMPLEX"] = (dic["status"] & 0x2) // 0x2
return dic |
def apache_client_convert(client_dn, client_ca=None):
"""
Convert Apache style client certs.
Convert from the Apache comma delimited style to the
more usual slash delimited style.
Args:
client_dn (str): The client DN
client_ca (str): [Optional] The client CA
Returns:
tuple: The converted client (DN, CA)
"""
if not client_dn.startswith('/'):
client_dn = '/' + '/'.join(reversed(client_dn.split(',')))
if client_ca is not None:
client_ca = '/' + '/'.join(reversed(client_ca.split(',')))
return client_dn, client_ca |
def get_lr(lr, epoch, steps, factor):
"""Get learning rate based on schedule."""
for s in steps:
if epoch >= s:
lr *= factor
return lr |
def interpret_word_seg_results(char_seq, label_seq):
"""Transform model output into user-friendly contents.
Example: In CWS, convert <BMES> labeling into segmented text.
:param char_seq: list of string,
:param label_seq: list of string, the same length as char_seq
Each entry is one of ('B', 'M', 'E', 'S').
:return output: list of words
"""
words = []
word = ""
for char, label in zip(char_seq, label_seq):
if label[0] == "B":
if word != "":
words.append(word)
word = char
elif label[0] == "M":
word += char
elif label[0] == "E":
word += char
words.append(word)
word = ""
elif label[0] == "S":
if word != "":
words.append(word)
word = ""
words.append(char)
else:
raise ValueError("invalid label {}".format(label[0]))
return words |
def is_droppedaxis(slicer):
"""Return True if the index represents a dropped axis"""
return isinstance(slicer, int) |
def convert_chars_to_unicode(lst):
"""
Given a list of characters, convert any unicode variables to its unicode repr
Input: List of characters
Output: List of characters, with the ones specified as variable names replaced
with the actual unicode representation
"""
output = []
for ch in lst:
try:
output.append(globals()[ch])
except KeyError:
output.append(ch)
return output |
def vue(item):
"""Filter out vue templates.
For example: {{ "message.text" | vue }} will be transformed to just {{ "message.text" }} in HTML
Parameters:
item (str): The text to filter.
Returns:
item (str): Text that jinja2 will render properly.
"""
return f"{{{{ {item} }}}}" |
def IntToRGB(intValue):
""" Convert an FL Studio Color Value (Int) to RGB """
blue = intValue & 255
green = (intValue >> 8) & 255
red = (intValue >> 16) & 255
return (red, green, blue) |
def arg_valid_val(args_array, opt_valid_val):
"""Function: arg_valid_val
Description: Validates data for options based on a dictionary list.
Arguments:
(input) args_array -> Array of command line options and values.
(input) opt_valid_val -> Dictionary of options & their valid values
(output) status -> True|False - If format is valid.
"""
args_array = dict(args_array)
opt_valid_val = dict(opt_valid_val)
status = True
# Intersects the keys in args_array and opt_valid_val.
for item in set(args_array.keys()) & set(opt_valid_val.keys()):
# If passed value is valid for this option.
if not args_array[item] in opt_valid_val[item]:
print("Error: Incorrect value ({0}) for option: {1}".
format(args_array[item], item))
status = False
return status |
def get_term_class(go, alias, is_a):
"""Find the class (P, C or F) of the given GO term."""
x = alias.get(go, go)
while x:
if x in ["GO:0008150", "obsolete_biological_process"]:
return "P"
elif x in ["GO:0005575", "obsolete_cellular_component"]:
return "C"
elif x in ["GO:0003674", "obsolete_molecular_function"]:
return "F"
try:
x = is_a[x]
except KeyError:
return "?" |
def get_family_name_from(seq_name_and_family):
"""Get family accession from concatenated sequence name and family string.
Args:
seq_name_and_family: string. Of the form `sequence_name`_`family_accession`,
like OLF1_CHICK/41-290_PF00001.20. Assumes the family does not have an
underscore.
Returns:
string. PFam family accession.
"""
return seq_name_and_family.split('_')[-1] |
def _try_rsplit(text, delim):
"""Helper method for splitting Email Received headers.
Attempts to rsplit ``text`` with ``delim`` with at most one split.
returns a tuple of (remaining_text, last_component) if the split was
successful; otherwise, returns (text, None)
"""
if delim in text:
return [x.strip() for x in text.rsplit(delim, 1)]
else:
return (text, None) |
def _animal_id_suffixed(prev_id: float, num: int, addition_base=0.5) -> float:
"""adds a decimal number to make a new animal_id distinct from prev_id"""
if num == 0:
return prev_id
else:
return prev_id + addition_base ** num |
def too_large(e):
""" Check if file size is too large """
return "File is too large", 413 |
def convert_to_value(item, target_values, value, matching=True):
"""Convert target strings to NaN.
Converts target strings listed in target_values to value so they can be
processed within a DataFrame, such as for removing specific rows. If
matching=False, strings that do not those listed in values are converted to
value. Note that it cannot take None as a value in values.
Args:
item (str): String to be checked. item is converted to a string if
necessary.
target_values (list): Values to be checked. If found, value is returned
(if matching=True) or item is returned. If matching=False, this is
reversed.
value (str): Value that is to be returned if taget_values check is
positive (respective to matching)
matching (bool): If True, matching values are returned as value and
non-matching are returned as passed (item). If False, non-matching
values are returned as NaN and matching values are returned as passed
(item).
Returns:
item or value (str): Depending on status of matching and if found or
not.
"""
# Convert to value if item is found in taget_values
if matching:
if str(item) in map(str, target_values):
return value
else:
return item
# Convert item to value if not found in values
else:
if str(item) in map(str, target_values):
return item
else:
return value |
def delete(old_string, starting_index, ending_index):
""" Removes portion from old_string from starting_index to ending_index"""
# in log, index starts at 1
starting_index -= 1
return old_string[:starting_index] + old_string[ending_index:] |
def add_suffix_to_fp(file_path, suffix, path_separator='/'):
"""
Add a suffix to a file name (not a new file type; e.g. 'file' becomes 'file_name').
Return new filepath.
"""
new_file_path = ''
new_file_path = file_path.split(path_separator)
file_name = new_file_path[-1].split('.')
file_name[0] += suffix
file_name = '.'.join(file_name)
new_file_path[-1] = file_name
new_file_path = '/'.join(new_file_path)
return new_file_path |
def backward_substitution(matrix_u, matrix_y):
""" Backward substitution method for solution of linear systems.
Solves the equation :math:`Ux = y` using backward substitution method
where :math:`U` is a upper triangular matrix and :math:`y` is a column matrix.
:param matrix_u: U, upper triangular matrix
:type matrix_u: list, tuple
:param matrix_y: y, column matrix
:type matrix_y: list, tuple
:return: x, column matrix
:rtype: list
"""
q = len(matrix_y)
matrix_x = [0.0 for _ in range(q)]
matrix_x[q - 1] = float(matrix_y[q - 1]) / float(matrix_u[q - 1][q - 1])
for i in range(q - 2, -1, -1):
matrix_x[i] = float(matrix_y[i]) - sum([matrix_u[i][j] * matrix_x[j] for j in range(i, q)])
matrix_x[i] /= float(matrix_u[i][i])
return matrix_x |
def isGoodRun(goodRunList, run):
"""
_isGoodRun_
Tell if this is a good run
"""
if goodRunList is None or goodRunList == {}:
return True
if str(run) in goodRunList.keys():
# @e can find a run
return True
return False |
def extract_md_header(file):
"""Extract the header from the input markdown file.
Paramters
---------
file : generator
A generator that generates lines.
Returns
-------
string | None
The extracted header content or `None`.
"""
first_line = True
header_content = ""
for line in file:
if first_line:
if line.strip() != "<!--":
return None
first_line = False
continue
if line.strip() == "-->":
return header_content
header_content += line
return None |
def num_to_text(num):
# Make sure we have an integer
"""
Given a number, write out the English representation of it.
:param num:
:return:
>>> num_to_text(3)
'three'
>>> num_to_text(14)
'fourteen'
>>> num_to_text(24)
'twenty four'
>>> num_to_text(31)
'thirty one'
>>> num_to_text(49)
'fourty nine'
>>> num_to_text(56)
'fifty six'
>>> num_to_text(156)
'one hundred and fifty six'
>>> num_to_text(700)
'seven hundred'
>>> num_to_text(999)
'nine hundred and ninety nine'
>>> num_to_text(123456)
'one hundred and twenty three thousand four hundred and fifty six'
>>> num_to_text(123456789)
'one hundred and twenty three million four hundred and fifty six thousand seven hundred and eighty nine'
>>> num_to_text(123456789000)
'one hundred and twenty three billion four hundred and fifty six million seven hundred and eighty nine thousand'
>>> num_to_text(12000000000000000)
'twelve million billion'
>>> num_to_text(12000000000000000000000)
'twelve thousand billion billion'
>>> num_to_text(-79)
'negative seventy nine'
"""
num = int(num)
BASE_CASES = {i: word for i, word in enumerate(['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven',
'eight', 'nine', 'ten', 'eleven', 'twelve', 'thirteen'])}
BASE_CASES.update({15: 'fifteen', 20: 'twenty', 30: 'thirty', 50: 'fifty', 80: 'eighty'})
def rem_zero(str_):
if str_.endswith(' and zero'):
return str_[:-9]
elif str_.endswith(' zero'):
return str_[:-5]
else:
return str_
# Handle negative numbers
if num < 0:
return 'negative {}'.format(num_to_text(- num))
name = BASE_CASES.get(num)
if name is not None:
return name
numstr = str(num)
if len(numstr) == 2:
# Teens are special case
if numstr[0] == '1':
return num_to_text(numstr[1]) + 'teen'
elif numstr[1] == '0':
# We're not a teen and we're not a base case, so we must be x0 for x in [4, 6, 7, 9]
return num_to_text(numstr[0]) + 'ty'
else:
return num_to_text(numstr[0] + '0') + ' ' + num_to_text(numstr[1])
if len(numstr) == 3:
return rem_zero('{} hundred and {}'.format(num_to_text(numstr[0]), num_to_text(numstr[1:])))
# Sort out the thousands and billions
if len(numstr) > 9:
return rem_zero(num_to_text(numstr[:-9]) + ' billion ' + num_to_text(numstr[-9:]))
elif len(numstr) > 6:
return rem_zero(num_to_text(numstr[:-6]) + ' million ' + num_to_text(numstr[-6:]))
elif len(numstr) > 3:
return rem_zero(num_to_text(numstr[:-3]) + ' thousand ' + num_to_text(numstr[-3:]))
return 'ERROR' |
def _create_issue_result_json(issue_id, summary, key, **kwargs):
"""Returns a minimal json object for an issue."""
return {
"id": "%s" % issue_id,
"summary": summary,
"key": key,
"self": kwargs.get("self", "http://example.com/%s" % issue_id),
} |
def covert_if_not_ascii(value):
"""converts a value if it is not a ascii supported str"""
try:
value.encode("ascii")
return value
except (AttributeError, UnicodeEncodeError):
return str(value) |
def image_search(inlist, filename, debug=False):
"""
Args:
inlist: List of filepaths
filename: Suffix to match to
debug: Extra info required?
Returns: Single filepath
"""
if debug:
print(inlist)
print(filename)
im = [i for i in inlist if i.split("/")[-1] == filename]
assert len(im) == 1, f"Match is not unique: {im}"
return im[0] |
def identify_slack_event(event):
"""Identify the Slack event type given an event object.
Parameters
----------
event : `dict`
The Slack event object.
Returns
-------
slack_event_type : `str`
The name of the slack event, one of https://api.slack.com/events.
"""
primary_type = event['event']['type']
if primary_type == 'message':
channel_type = event['event']['channel_type']
if channel_type == 'channel':
return 'message.channels'
if channel_type == 'im':
return 'message.im'
elif channel_type == 'group':
return 'message.groups'
elif channel_type == 'mpim':
return 'message.mpim'
else:
raise RuntimeError(f'Unknown channel type {channel_type!r}')
else:
return primary_type |
def pip_has_version(package):
"""
For pip install strings: Checks if there is a part that mentions the version
"""
for c in ["<", "=", ">"]:
if c in package:
return True
return False |
def setup_config(config):
"""
Make config arguments the proper type!
"""
config['num_req_to_send'] = int(config['num_req_to_send'])
return config |
def full_adder(a,b,c=0):
"""Single bit addition with carry"""
s = (a+b+c)%2
cout = a*b + (c*(a+b)%2)
return s,cout |
def parse_hex_color(value):
"""
Convert a CSS color in hexadecimal notation into its R, G, B components.
:param value: A CSS color in hexadecimal notation (a string like '#000000').
:return: A tuple with three integers (with values between 0 and 255)
corresponding to the R, G and B components of the color.
:raises: :exc:`~exceptions.ValueError` on values that can't be parsed.
"""
if value.startswith('#'):
value = value[1:]
if len(value) == 3:
return (
int(value[0] * 2, 16),
int(value[1] * 2, 16),
int(value[2] * 2, 16),
)
elif len(value) == 6:
return (
int(value[0:2], 16),
int(value[2:4], 16),
int(value[4:6], 16),
)
else:
raise ValueError() |
def fix_opcode_names(opmap):
"""
Python stupidly named some OPCODES with a + which prevents using opcode name
directly as an attribute, e.g. SLICE+3. So we turn that into SLICE_3 so we
can then use opcode_23.SLICE_3. Later Python's fix this.
"""
return dict([(k.replace('+', '_'), v)
for (k, v) in opmap.items()]) |
def get_output(filename: str) -> str:
"""Gets the relative file path for the provided output file."""
return "./output/" + filename |
def infer_app_url(headers: dict, register_path: str) -> str:
"""
ref: github.com/aws/chalice#485
:return: The Chalice Application URL
"""
host: str = headers["host"]
scheme: str = headers.get("x-forwarded-proto", "http")
app_url: str = f"{scheme}://{host}{register_path}"
return app_url |
def stacks_dna_dna(inseq, temp=37):
"""Calculate thermodynamic values for DNA/DNA hybridization.
Input Arguments:
inseq -- the input DNA sequence of the DNA/DNA hybrid (5'->3')
temp -- in celcius for Gibbs free energy calc (default 37degC)
salt -- salt concentration in units of mol/L (default 0.33M)
Return [enthalpy, entropy] list in kcal/mol and cal/(mol*Kelvin)
"""
# SantaLucia 98 parameters for DNA Hybridization (Table 2)
delH = {'aa':-7.9, 'ac':-8.4, 'ag':-7.8, 'at':-7.2,
'ca':-8.5, 'cc':-8.0, 'cg':-10.6,'ct':-7.8,
'ga':-8.2, 'gc':-9.8, 'gg':-8.0, 'gt':-8.4,
'ta':-7.2, 'tc':-8.2, 'tg':-8.5, 'tt':-7.9} # kcal/mol
delS = {'aa':-22.2, 'ac':-22.4, 'ag':-21.0, 'at':-20.4,
'ca':-22.7, 'cc':-19.9, 'cg':-27.2, 'ct':-21.0,
'ga':-22.2, 'gc':-24.4, 'gg':-19.9, 'gt':-22.4,
'ta':-21.3, 'tc':-22.2, 'tg':-22.7, 'tt':-22.2} # cal/(mol*Kelvin)
# sum enthalpy and entropy of DNA-DNA base stacks
dH = sum([delH[inseq[i:i+2]] for i in range(len(inseq)-1)]) # kcal/mol
dS = sum([delS[inseq[i:i+2]] for i in range(len(inseq)-1)]) # cal/(mol*Kelvin)
return [dH, dS] |
def get_tn(num_bases, tp, fp, fn):
"""
This functions returns the number of true negatives.
:param num_bases: Number of bases
:type num_bases: int
:param tp: Number of true positives
:type tp: int
:param fp: Number of false positives
:type fp: int
:param fn: Number of false negatives
:type fn: int
:return: Number of true negatives
:rtype: int
"""
return num_bases - (tp + fp + fn) |
def remove_file(filename, recursive=False, force=False):
"""Removes a file or directory."""
import os
try:
mode = os.stat(filename)[0]
if mode & 0x4000 != 0:
# directory
if recursive:
for file in os.listdir(filename):
success = remove_file(
filename + '/' + file, recursive, force)
if not success and not force:
return False
os.rmdir(filename) # PGH Work like Unix: require recursive
else:
if not force:
return False
else:
os.remove(filename)
except:
if not force:
return False
return True |
def curry(tup_fn, x, y):
"""``curry :: ((a, b) -> c) -> a -> b -> c``
Converts an uncurried function to a curried function.
"""
return tup_fn((x, y)) |
def implode(list):
"""
Takes list and returns standardized version of it.
:param list: list
:return: standardized list
"""
return ', '.join([str(i) for i in list]) |
def popup(message, title):
"""
Function that returns UR script for popup
Args:
message: float. tooltip offset in mm
title: float. tooltip offset in mm
Returns:
script: UR script
"""
script = 'popup("%s","%s") \n' %(message,title)
return script |
def normalize_job_id(job_id):
"""Convert the job id into job_id, array_id."""
return str(int(job_id)), None |
def gather_word_info(hot_posts, wordlist,
posts_len=None,
counter=0,
words_info=None):
"""does the recursion to grab word info from wordlist and posts
"""
if hot_posts is None:
return
# generate defaults
if posts_len is None:
posts_len = len(hot_posts)
if words_info is None:
words_info = {key: 0 for key in wordlist}
# base case
if counter == posts_len - 1:
return words_info
# parse this title and move to next
data = hot_posts[counter].get('data')
if data is None:
return words_info
title = data.get('title')
if title is None:
return words_info
# im sorry im not doing recursion for text parsing that's rediculous
for word in title.split(' '):
word = word.lower()
if word in wordlist:
words_info[word] += 1
counter += 1
return gather_word_info(
hot_posts, wordlist, posts_len,
counter, words_info
) |
def check_form(media: dict, form: list, allow_null=[]):
""" Obsolete function """
if media == None:
return False
media_list = list(media)
for i in form:
if None in media_list or i not in media_list:
return False
for x in media:
if media.get(x) == None and x not in allow_null:
return False
return True |
def funtion_0(x, a):
"""
"""
if x < a:
return 0.0
return 1.0 |
def convert_truelike_to_bool(input_item, convert_float=False, convert_nontrue=True):
"""Converts true-like values ("true", 1, True", "WAHR", etc) to python boolean True.
Parameters
----------
input_item : string or int
Item to be converted to bool (e.g. "true", 1, "WAHR" or the equivalent in several languagues)
convert_float: bool
Convert floats to bool.
If True, "1.0" will be converted to True
convert_nontrue : bool
If True, the output for input_item not recognised as "True" will be False.
If True, the output for input_item not recognised as "True" will be the original input_item.
Returns
-------
return_value : True, or input_item
If input_item is True-like, returns python bool True. Otherwise, returns the input_item.
Usage
-----
# convert a single value or string
convert_truelike_to_bool("true")
# convert a column in a pandas DataFrame
df["column_name"] = df["column_name"].apply(convert_truelike_to_bool)
"""
list_True_items = [True, 'True', "true","TRUE","T","t",'wahr', 'WAHR', 'prawdziwy', 'verdadeiro', 'sann', 'istinit',
'veritable', 'Pravda', 'sandt', 'vrai', 'igaz', 'veru', 'verdadero', 'sant', 'gwir', 'PRAWDZIWY',
'VERDADEIRO', 'SANN', 'ISTINIT', 'VERITABLE', 'PRAVDA', 'SANDT', 'VRAI', 'IGAZ', 'VERU',
'VERDADERO', 'SANT', 'GWIR', 'bloody oath', 'BLOODY OATH', 'nu', 'NU','damn right','DAMN RIGHT']
# if you want to accept 1.0 as a true value, add it to the list
if convert_float:
list_True_items += [1.0,"1.0"]
# check if the user input string is in the list_True_items
input_item_is_true = input_item in list_True_items
# if you want to convert non-True values to "False", then nontrue_return_value = False
if convert_nontrue:
nontrue_return_value = False
else:
# otherwise, for strings not in the True list, the original string will be returned
nontrue_return_value = input_item
# return True if the input item is in the list. If not, return either False, or the original input_item
return_value = input_item_is_true if input_item_is_true == True else nontrue_return_value
return return_value |
def is_empty_row(row):
"""Returns True if all cells in a row evaluate to False
>>> is_empty_row(['', False, ''])
True
>>> is_empty_row(['', 'a', ''])
False
"""
return not any(row) |
def prefer_lnc_over_anti(rna_type, _):
"""
This will remove antisense_RNA to use lncRNA if we have both. This is
because the term antisense_RNA usually but not always means
antisense_lnc_RNA. Until we switch to SO terms which can express this we
will switch.
"""
if rna_type == set(["antisense_RNA", "lncRNA"]):
return set(["lncRNA"])
return rna_type |
def upper_first(s):
""" uppercase first letter """
s = str(s)
return s[0].upper() + s[1:] |
def divide(a, b):
""" Return result of dividing a by b """
print("=" * 20)
print("a: ", a, "/ b: ", b)
try:
return a/b
except (ZeroDivisionError, TypeError):
print("Something went wrong!")
raise |
def __vertical_error_filters(
vertical_error: int
) -> tuple:
"""Make filters that correct for a vertical error between the cameras"""
if vertical_error > 0:
# Right video is too low
ve_left = 'crop=iw:ih-{}:0:{},'.format(vertical_error, vertical_error)
ve_right = 'crop=iw:ih-{}:0:0,'.format(vertical_error)
return ve_left, ve_right, vertical_error
if vertical_error < 0:
# Left image is too low
ve_left = 'crop=iw:ih-{}:0:0,'.format(-vertical_error)
ve_right = 'crop=iw:ih-{}:0:{},'.format(-vertical_error, -vertical_error)
return ve_left, ve_right, -vertical_error
return '', '', abs(vertical_error) |
def split_system_subsystem(system_name):
"""Separate system_name and subsystem_name str from the input
Ex: system_name=NE1[cli,dip,if1] will be separate into
system_name=NE1
subsystem_name str = 'cli, dip, if1'"""
new_system_name = system_name.split('[')
system_name = new_system_name[0]
subsystem_name = None if len(new_system_name) == 1 else \
new_system_name[1].split(']')[0]
return system_name, subsystem_name |
def unquoted(term):
"""unquoted - unquotes string
Args:
term: string
Returns:
term: without quotes
"""
if term[0] in ["'", '"'] and term[-1] in ["'", '"']:
return term[1:-1]
else:
return term |
def self_ensemble_hyperparams(lr=1e-3, unsupervised_weight=3.0, wd=5e-5, scheduler=False):
"""
Return a dictionary of hyperparameters for the Self-Ensemble algorithm.
Default parameters are the best ones as found through a hyperparameter search.
Arguments:
----------
lr: float
Learning rate.
unsupervised_weight: float
Weight of the unsupervised loss.
wd: float
Weight decay for the optimizer.
scheduler: bool
Will use a OneCycleLR learning rate scheduler if set to True.
Returns:
--------
hyperparams: dict
Dictionary containing the hyperparameters. Can be passed to the `hyperparams` argument on ADDA.
"""
hyperparams = {'learning_rate': lr,
'unsupervised_weight': unsupervised_weight,
'weight_decay': wd,
'cyclic_scheduler': scheduler
}
return hyperparams |
def parse(s:str):
"""Get the next space separated word from a string. Return (word,remainder)"""
s=s.strip()
i=s.find(" ")
if i<0:
i=len(s)
result=s[0:i].strip()
remain=s[i+1:].strip()
return (result,remain) |
def all(iterable):
"""
Return True if all elements are set to True. This
function does not support predicates explicitly,
but this behavior can be simulated easily using
list comprehension.
>>> from sympy import all
>>> all( [True, True, True] )
True
>>> all( [True, False, True] )
False
>>> all( [ x % 2 == 0 for x in [2, 6, 8] ] )
True
>>> all( [ x % 2 == 0 for x in [2, 6, 7] ] )
False
NOTE: Starting from Python 2.5 this a built-in.
"""
for item in iterable:
if not item:
return False
return True |
def _get_inner_type(typestr):
""" Given a str like 'org.apache...ReversedType(LongType)',
return just 'LongType' """
first_paren = typestr.find('(')
return typestr[first_paren + 1 : -1] |
def square_helper(start, finish, expand1, expand2, size_limit):
"""
This function can expand one axis of the size of the bounding box.
Parameters:
start (int): the coordinate of the start point.
finish (int): the coordinate of the finish point.
expand1 (int): the number of pixels used to expand the starting point.
expand2 (int): the number of pixels used to expand the finishing point.
size_limit (int): the maximum length of this expansion.
Returns:
new_start (int): the coordinate of the expanded start point.
new_finish (int): the coordinate of the expanded finish point.
"""
new_start = max(0, start - expand1)
expand1_rem = expand1 - (start - new_start)
new_finish = min(size_limit , finish + expand2)
expand2_rem = expand2 - (new_finish - finish)
# print('expand1_rem = ', expand1_rem, ' expand2_rem = ', expand2_rem)
if expand1_rem > 0 and expand2_rem == 0:
new_finish = min(size_limit, new_finish + expand1_rem)
elif expand1_rem == 0 and expand2_rem > 0:
new_start = max(0, new_start - expand2_rem)
return new_start, new_finish |
def remove_soft_hyphens(line):
"""Removes any soft hyphens or middle dots"""
line = line.replace(u'\u00AC', '') # not sign (Word's soft hyphen)
line = line.replace(u'\u00AD', '') # soft hyphen
line = line.replace(u'\u00B7', '') # middle dot
return line |
def prime_factors(n):
"""
Compute the prime factors of the given number
:param n: Number you want to compute the prime factors (intger)
:return: Prime factors of the given number (list of integer)
"""
i = 2
factors = []
while i * i <= n:
if n % i:
i += 1
else:
n //= i
factors.append(i)
if n > 1:
factors.append(n)
return factors |
def isSBMLModel(obj):
"""
Tests if object is a libsbml model
"""
cls_stg = str(type(obj))
if ('Model' in cls_stg) and ('lib' in cls_stg):
return True
else:
return False |
def list_to_set24(l):
"""Convert a bit vector to an integer"""
res = 0
for x in l: res ^= 1 << x
return res & 0xffffff |
def _flatten_index(i, alpha, num_symbols):
"""
Map position and symbol to index in
the covariance matrix.
Parameters
----------
i : int, np.array of int
The alignment column(s).
alpha : int, np.array of int
The symbol(s).
num_symbols : int
The number of symbols of the
alphabet used.
"""
return i * (num_symbols - 1) + alpha |
def getValuesInInterval(dataTupleList, start, stop):
"""
Gets the values that exist within an interval
The function assumes that the data is formated as
[(t1, v1a, v1b, ...), (t2, v2a, v2b, ...)]
"""
intervalDataList = []
for dataTuple in dataTupleList:
time = dataTuple[0]
if start <= time and stop >= time:
intervalDataList.append(dataTuple)
return intervalDataList |
def _transpose(x):
"""The transpose of a matrix
:param x: an NxM matrix, e.g. a list of lists
:returns: a list of lists with the rows and columns reversed
"""
return [[x[j][i] for j in range(len(x))] for i in range(len(x[0]))] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.