content stringlengths 42 6.51k |
|---|
def fixup(ocr_text, pattern):
"""Fix spacing and numerics in ocr text"""
cleaned_pattern = pattern.replace("4", "A").replace("1","l").replace(" ","")
#print(f"{pattern}\t\t{cleaned_pattern}")
#print("{0:<30} {1:<10}".format(pattern, cleaned_pattern))
return ocr_text.replace(pattern, cleaned_pattern) |
def get_lr_decay(epoch_nr):
"""
Calc what lr_decay is need to make lr be 1/10 of original lr after epoch_nr number of epochs
"""
target_lr = 0.1 # should be reduced to 1/10 of original
return target_lr ** (1 / float(epoch_nr)) |
def ensure_slash(text):
"""
Prepend a slash to a string, unless it starts with one already.
"""
if text.startswith('/'):
return text
return '/' + text |
def dots_if_needed(s, max_chars):
"""If string `s` is longer than `max_chars`, return an abbreviated string
with ellipsis.
e.g.
dots_if_needed('This is a very long string.', 12)
#=> 'This is a ve...'
"""
if s is None or len(s) <= max_chars:
return s
return s[: (max_chars - 3)] + "..." |
def resolve_kernel_loops(loop):
""" Return a sequence, structure pair from kernel format.
"""
sequen = []
struct = []
for dom in loop :
if isinstance(dom, str):
sequen.append(dom)
if dom == '+' :
struct.append('+')
else :
struct.append('.')
elif isinstance(dom, list):
struct[-1] = '('
old = sequen[-1]
se, ss = resolve_kernel_loops(dom)
sequen.extend(se)
struct.extend(ss)
sequen.append(old + '*' if old[-1] != '*' else old[:-1])
struct.append(')')
return sequen, struct |
def probability_by_degree_of_polymerization(p, N):
"""
Computes the probability for a chain of degree of polymerization
N based on the extend of reaction p for linear condensation reactions.
See Colby and Rubinstein Polymer Physics.
"""
return N*p**(N-1)*(1-p)**2. |
def clean_locals(params):
"""
Clean up locals dict, remove empty and self params.
:param params: locals dicts from a function.
:type params: dict
:returns: cleaned locals dict to use as params for functions
:rtype: dict
"""
return dict((k, v) for k, v in params.items() if v is not None and k != 'self') |
def isPalindrome(n):
"""
Check if [n] is a palindrome
:param n:
:return:
"""
return n >= 0 and str(n) == str(n)[::-1] |
def parser_announcement_support_Descriptor(data,i,length,end):
"""\
parser_announcement_support_Descriptor(data,i,length,end) -> dict(parsed descriptor elements).
This descriptor is not parsed at the moment. The dict returned is:
{ "type": "announcement_support", "contents" : unparsed_descriptor_contents }
(Defined in ETSI EN 300 468 specification)
"""
return { "type" : "announcement_support", "contents" : data[i+2:end] } |
def dump(chrom, starts, ends, names, strands, profiles):
"""Dump the txStarts, txEnds, names, strands of genes along with their profiles.
"""
txt = ''
# go only if starts, ends, anmes, strands, and profiles are NOT empty.
if starts and ends and names and strands and profiles:
for start, end, name, strand, profile in zip(starts, ends, names, strands, profiles):
# convert the profile into a string
s = list(map(str, profile))
# print out the regions
txt += "%s\t%d\t%d\t%s\t%s\t%s\n" %(chrom, start, end, name, strand, ','.join(s)+',')
return txt |
def fahrenheit_from(celsius):
"""Convert Celsius to Fahrenheit degrees."""
try:
fahrenheit = float(celsius) * 9 / 5 + 32
fahrenheit = round(fahrenheit, 3) # Round to three decimal places
return str(fahrenheit)
except ValueError:
return "invalid input" |
def capture_field(field, value):
"""
Macro to create text format field
:param field: register name
:param value: register value
:return: string of definition
"""
try:
_test_value = int(value, 16)
except (ValueError, AttributeError):
# Can't convert string to int, assumed to be string
return " '{}': '{}',\n".format(field, value)
return " '{}': {},\n".format(field, value) |
def pretty_list(the_list, conjunction = "and", none_string = "nothing"):
"""
Returns a grammatically correct string representing the given list. For
example...
>>> pretty_list(["John", "Bill", "Stacy"])
"John, Bill, and Stacy"
>>> pretty_list(["Bill", "Jorgan"], "or")
"Bill or Jorgan"
>>> pretty_list([], none_string = "nobody")
"nobody"
"""
the_list = list(the_list)
# Replace underscores with spaces to make coherent sentences.
the_list[:] = [i.replace("_", " ") for i in the_list]
if len(the_list) == 0:
return none_string
elif len(the_list) == 1:
return str(the_list[0])
elif len(the_list) == 2:
return str(the_list[0]) + " " + conjunction + " " + str(the_list[1])
else:
# Add every item except the last two together seperated by commas
result = ", ".join(the_list[:-2]) + ", "
# Add the last two items, joined together by a command and the given
# conjunction
result += "%s, %s %s" % \
(str(the_list[-2]), conjunction, str(the_list[-1]))
return result |
def tokenize_text(text):
"""
The tokenize_text function returns the tokens from text, always start token is <sos>, end token is <eos>
Args:
text (str): The text will be tokenized
Returns:
list(str): The tokens from input text
"""
return ['<sos>'] + list(text) + ['<eos>'] |
def mean(num_list):
"""
Computes the mean of a list of numbers
Parameters
----------
num_list : list
List of number to calculate mean of
Returns
-------
mean : float
Mean value of the num_list
"""
# Check that input is of type list
if not isinstance(num_list, list):
raise TypeError('Invalid input %s - must be type list' % (num_list))
list_sum = 0.0
list_len = len(num_list)
# Check that the list is not empty
if list_len == 0:
raise ValueError("Num list is empty")
for el in num_list:
list_sum += el
return list_sum / list_len |
def maximum_number_of_live_cells(letter):
"""Defines the maximum nuber of cells that can be counted in each area, in Knuth's neighbour counting scheme"""
assert letter in ["a", "b", "c", "d", "e", "f", "g", None], "Letter not used in Knuth's scheme"
if letter == "a":
return 8
elif letter in ["b", "c"]:
return 4
elif letter in ["d", "e", "f", "g"]:
return 2
elif letter == None:
return 1 |
def one_param(arg):
"""Expected one_param __doc__"""
return "one_param - Expected result: %s" % arg |
def render_io_exception(e):
"""
Return a formatted string for an I/O-related exception.
Parameters:
e: the exception to render
"""
return 'Details: [Errno {0}] {1}'.format(e.errno, e.strerror) |
def _flash_encryption_tweak_range(flash_crypt_config=0xF):
""" Return a list of the bit indexes that the "key tweak" applies to,
as determined by the FLASH_CRYPT_CONFIG 4 bit efuse value.
"""
tweak_range = []
if (flash_crypt_config & 1) != 0:
tweak_range += range(67)
if (flash_crypt_config & 2) != 0:
tweak_range += range(67, 132)
if (flash_crypt_config & 4) != 0:
tweak_range += range(132, 195)
if (flash_crypt_config & 8) != 0:
tweak_range += range(195, 256)
return tweak_range |
def construct_name(user):
""" Helper function for search. Not used in requests."""
name = []
if 'fname' in user.keys():
name.append(user['fname'])
if 'lname' in user.keys():
name.append(user['lname'])
return ' '.join(name) |
def disambiguateJcnStr(chr_seq, start, end):
"""
Will use splice site sequence to infer strand
If no strand can be determined, returns '.'
This function is from disambiguate_junctions.py by Angela Brooks
"""
strand = '.'
# extract the sequence from the chromosome
intron_seq = chr_seq[start-1:end].upper()
if intron_seq.startswith("GT") and intron_seq.endswith("AG"):
strand = "+"
elif intron_seq.startswith("CT") and intron_seq.endswith("AC"):
strand = "-"
# Other common splice site sequence
elif intron_seq.startswith("GC") and intron_seq.endswith("AG"):
strand = "+"
elif intron_seq.startswith("CT") and intron_seq.endswith("GC"):
strand = "-"
# minor spliceosome
elif intron_seq.startswith("AT") and intron_seq.endswith("AC"):
strand = "+"
elif intron_seq.startswith("GT") and intron_seq.endswith("AT"):
strand = "-"
# Priority to 5' splice site since there is more information
elif intron_seq.startswith("GT"):
strand = "+"
elif intron_seq.endswith("AC"):
strand = "-"
elif intron_seq.endswith("AG"):
strand = "+"
elif intron_seq.startswith("CT"):
strand = "-"
# else:
# print >>sys.stderr, "Cannot find strand for {}-{}".format(start, end)
return strand |
def decode_gt_string(gt_string):
"""
Tries to work out the genotype from a vcf genotype entry. 9 for missing [or not in {0,1,2}]
"""
gt=gt_string.split(":")[0]
if len(gt)==1:
if gt=="0": # haploid
return "2"
elif gt=="1":
return "0"
else:
return "9"
elif len(gt)==3:
if gt[0]=="0" and gt[2]=="0":
return "2"
if gt[0]=="0" and gt[2]=="1":
return "1"
if gt[0]=="1" and gt[2]=="0":
return "1"
if gt[0]=="1" and gt[2]=="1":
return "0"
else:
return "9"
raise Exception("Unknown genotype: "+gt) |
def getPointIndex(x, y, pointsPerWidth, pointsPerHeight):
"""Returns the index of the given point in a poinsPerWidth*pointsPerHeight grid.
pointsPerWidth and pointsPerHeight should be odd numbers"""
# These calculations take the top left corner as the (0;0) point
# and both axes increase from that point.
originRow = int(pointsPerHeight/2)
originColumn = int(pointsPerWidth/2)
# A positive x value increases the column, and vice versa
# A positive y value decrease the row since the above calculations took the row as increasing
# when going downwards.
pointRow = originRow - y
pointColumn = originColumn + x
index = pointRow*pointsPerWidth+pointColumn
return index |
def unescape(s):
"""
Replace special characters "&", "<" and ">" with normal characters
"""
if (type(s) != str):
return s
if (s.find("&") >= 0):
s = s.replace("<", "<")
s = s.replace(">", ">")
s = s.replace("&", "&")
return s |
def get_digits(revision_str):
"""Return a tuple of the first integer characters of a revision (which
may be empty) and the remains."""
# If the string is empty, return (0,'')
if not revision_str:
return 0, ''
# get the index of the first non-digit
for i, char in enumerate(revision_str):
if not char.isdigit():
if i == 0:
return 0, revision_str
return int(revision_str[0:i]), revision_str[i:]
# string is entirely digits
return int(revision_str), '' |
def create_primes_5(max_n):
""" creating primes up to a maximum value using a sieve algorithm. All
multiples of a prime are flagged as 'no prime'. In addition there
is an optimization by ignoring values flagged as none prime when
proceeding to next value."""
sieve = [False, True] * (int(max_n / 2))
sieve += [True]
if not max_n % 2 == 0:
sieve += [False]
sieve[1] = False
sieve[2] = True
primes = [2]
val = 3
while val <= max_n:
# now we have one prime
primes.append(val)
# strike out values not being a prime
noprime = val + val
while noprime <= max_n:
sieve[noprime] = False
noprime += val
# next value
val += 1
while val <= max_n and sieve[val] == False:
val += 1
return primes |
def create_clip_xml_info(readlen, adapl, adapr, quall, qualr):
"""Takes the clip values of the read and formats them into XML
Corrects "wrong" values that might have resulted through
simplified calculations earlier in the process of conversion
(especially during splitting of paired-end reads)
"""
to_print = [""]
# if right borders are >= to read length, they don't need
# to be printed
if adapr >= readlen:
adapr = 0
if qualr >= readlen:
qualr = 0
# BaCh
# when called via split_paired_end(), some values may be < 0
# (when clip values were 0 previously)
# instead of putting tons of if clauses for different calculations there,
# I centralise corrective measure here
# set all values <0 to 0
if adapr < 0:
adapr = 0
if qualr < 0:
qualr = 0
if adapl < 0:
adapl = 0
if quall < 0:
quall = 0
if quall:
to_print.append(" <clip_quality_left>")
to_print.append(str(quall))
to_print.append("</clip_quality_left>\n")
if qualr:
to_print.append(" <clip_quality_right>")
to_print.append(str(qualr))
to_print.append("</clip_quality_right>\n")
if adapl:
to_print.append(" <clip_vector_left>")
to_print.append(str(adapl))
to_print.append("</clip_vector_left>\n")
if adapr:
to_print.append(" <clip_vector_right>")
to_print.append(str(adapr))
to_print.append("</clip_vector_right>\n")
return "".join(to_print) |
def reverse_dict(dict_):
"""Reverse the key/value status of a dict"""
return dict([[v, k] for k, v in dict_.items()]) |
def filesizeformat(bytes):
"""
Formats the value like a 'human-readable' file size (i.e. 13 KB, 4.1 MB,
102 bytes, etc).
"""
try:
bytes = float(bytes)
except TypeError:
return u"0 bytes"
if bytes < 1024:
return "%(size)d bytes" % {'size': bytes}
if bytes < 1024 * 1024:
return "%.1f KB" % (bytes / 1024)
if bytes < 1024 * 1024 * 1024:
return "%.1f MB" % (bytes / (1024 * 1024))
return "%.1f GB" % (bytes / (1024 * 1024 * 1024)) |
def first_and_last(word):
"""Return the first and last letters of a word
:param word: String Can be a word or sentence
"""
return word[0], word[-1] |
def expand_mins_secs(mins, secs):
"""Format string expansion of `mins`, `secs` to the appropriate units up to (days, hours)
Parameters
----------
mins: Integer
Number of minutes to be expanded to the appropriate string format
secs: Integer
Number of seconds to be expanded to the appropriate string format
Returns
-------
String
Formatted pair of one of the following: (minutes, seconds); (hours, minutes); or
(days, hours) depending on the appropriate units given `mins`
Examples
--------
>>> assert expand_mins_secs(34, 57) == "34m57s"
>>> assert expand_mins_secs(72, 57) == "01h12m"
>>> assert expand_mins_secs(1501, 57) == "01d01h"
>>> assert expand_mins_secs(2880, 57) == "02d00h"
"""
if mins < 60:
return "{:>02d}m{:>02d}s".format(int(mins), int(secs))
else:
hours, mins = divmod(mins, 60)
if hours < 24:
return "{:>02d}h{:>02d}m".format(int(hours), int(mins))
else:
days, hours = divmod(hours, 24)
return "{:>02d}d{:>02d}h".format(int(days), int(hours)) |
def filmc_curve(x):
"""The fitted ACES tone mapping curve by Krzysztof Narkowicz.
https://knarkowicz.wordpress.com/2016/01/06/aces-filmic-tone-mapping-curve/
"""
return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14) |
def elem_C(w,C):
"""
Simulation Function: -C-
Inputs
----------
w = Angular frequency [1/s]
C = Capacitance [F]
"""
return 1/(C*(w*1j)) |
def cross_prod(px, py, qx, qy, rx, ry):
"""
Returns twice the signed area of the triangle defined by the three points.
"""
return (qx - px) * (ry - py) - (qy - py) * (rx - px) |
def one_matrix(snames, gen, reflexive=0):
"""Create a distance matrix with the given generator."""
distm = {}
for name1 in snames:
distm[name1] = {}
for name2 in snames:
if name1 == name2:
distm[name1][name2] = reflexive
else:
try:
distm[name1][name2] = distm[name2][name1]
except KeyError:
distm[name1][name2] = gen()
return distm |
def format(name: str, sequence: str, quality: str) -> str:
"""
Format a FastQ entry.
:param name: the read name
:param sequence: the read sequence
:param quality: the read quality
:return: a formatted fastq entry
"""
return "@{name}\n{seq}\n+\n{qual}\n".format(
name=name,
seq=sequence,
qual=quality) |
def _calc_effect(index, props, mesh, data):
"""
Calculate the effect of cell mesh[index] with physical properties prop for
each data set.
"""
cell = mesh[index]
return [d.effect(cell, props) for d in data] |
def sci_notation(number, sig_fig=2):
""" Convert a number to scientific notation for pasting into Latex.
e.g. 4.32342342e-10 --> 4.3 * 10^{-10}
"""
ret_string = "{0:.{1:d}e}".format(number, sig_fig)
a, b = ret_string.split("e")
# remove leading "+" and strip leading zeros
b = int(b)
return f"${a} \\times 10^{{{b}}}$" |
def nthSuperUglyNumber(n, primes):
"""
:type n: int
:type primes: List[int]
:rtype: int
"""
if n==1:
return 1
res=[1]*n
count=[0]*len(primes)
for __index in range(1,n):
nextNum=min([prime*res[count[index]] for index,prime in enumerate(primes)])
for index,prime in enumerate(primes):
if nextNum==prime*res[count[index]]:
count[index]+=1
res[__index]=nextNum
return res[-1] |
def calc_sl_price(contract_price, sl_percent):
"""Returns price that is sl_percent below the contract price"""
return round(contract_price * (1 - sl_percent), 2) |
def format_none_and_zero(value):
"""Return empty string if the value is None, zero or Not Applicable
"""
return "" if (not value) or (value == 0) or (value == "0") or (value == 'Not Applicable') else value |
def is_video(file_path):
"""
Checks whether the file is a video.
"""
import mimetypes
type = mimetypes.guess_type(file_path)[0]
return type and type.startswith('video') |
def scan(data):
"""
Scans data for words, filling the global variable WORDS
"""
words = []
data_str = ''.join(data)
words = words + data_str.split()
return words |
def calc_free_transfers(num_transfers, prev_free_transfers):
"""
We get one extra free transfer per week, unless we use a wildcard or
free hit, but we can't have more than 2. So we should only be able
to return 1 or 2.
"""
if num_transfers == "W" or num_transfers == "F":
return 1
elif isinstance(num_transfers, int):
return max(1, min(2, 1 + prev_free_transfers - num_transfers))
elif (num_transfers.startswith("B") or num_transfers.startswith("T")) and len(
num_transfers
) == 2:
# take the 'x' out of Bx or Tx
num_transfers = int(num_transfers[-1])
return max(1, min(2, 1 + prev_free_transfers - num_transfers))
else:
raise RuntimeError(
"Unexpected argument for num_transfers {}".format(num_transfers)
) |
def _tostr(x):
"""
Convert a value to the native string format.
Parameters
----------
x : str or bytes
value to convert to a native string.
Returns
-------
str
"""
if isinstance(x, bytes):
return x.decode()
else:
return str(x) |
def is_document(object):
"""
Check object is mongoengine document
:param object:
:return:
"""
return getattr(object, "_is_document", False) |
def extract_monomers(complex_patterns):
"""Constructs a list of monomer names contained in complex patterns.
Multiplicity of names corresponds to the stoichiometry in the complex.
Arguments:
specie: (list of) complex pattern(s) @type pysb.core.ComplexPattern
Returns:
list of monomer names
Raises:
"""
if not isinstance(complex_patterns, list):
complex_patterns = [complex_patterns]
return [
mp.monomer.name
for cp in complex_patterns
if cp is not None
for mp in cp.monomer_patterns
] |
def transpose_board(board):
"""Transpose the board --> change row to column"""
return [list(col) for col in zip(*board)] |
def _calc_rsa_length(rsa_bit: int) -> int:
"""
Calculates the length of the RSA key.
:param rsa_bit: indicates how many bits of rsa
:return: returns the length of the rsa key. If -1 means an error.
"""
if rsa_bit == 4096:
length = 684
elif rsa_bit == 3072:
length = 512
elif rsa_bit == 2048:
length = 344
elif rsa_bit == 1024:
length = 172
else:
length = -1
return length |
def cdf_chainid_to_stride_chainid(cdf_chainid):
"""
Convert a CDF (CATH Domall File) chainid to a STRIDE chainid.
STRIDE uses '-' for a 'blank' chainid while PDB uses ' ' (space)
and CATH (CDF) uses '0' where PDB has a blank (space) chain identfifer.
We use the STRIDE convention ('-') in this program.
So all this does is return the cdf_chainid unless it is '0', then
it returns '-'.
Parameters:
pdb_chainid - the PDB chain identifier
Return value:
STRIDE chain identifier corresponding to supplied pdb_chainid
"""
if cdf_chainid == '0':
return '-'
else:
return cdf_chainid |
def uid_5bits_to_char(number: int) -> str:
"""Converts 5 bits from UID to ASCII character.
Keyword arguments:
number -- byte for conversion
"""
if number < 0 or number >= 32:
return "#"
if number < 10:
return chr(ord("0") + number)
char = chr(ord("A") + number - 10)
return "Z" if char == "O" else char |
def _parse_value_in_header(header, name):
"""For parsing complex header values splitted by ;
EX: multipart/mixed;charset=utf-8;boundary="""
value = header.split("%s=" % name)[1]
posend = value.find(";")
if posend == -1:
return value
else:
return value[:posend] |
def abshumidity(T, equationSelect = 1):
""" Atmopsheric absolute humidity [g/m3] for temperature in [K] between 248 K and 342 K.
This function provides two similar equations, but with different constants.
Args:
| temperature (np.array[N,] or [N,1]): in [K].
| equationSelect (int): select the equation to be used.
Returns:
| absolute humidity (np.array[N,] or [N,1]): abs humidity in [g/m3]
Raises:
| No exception is raised.
"""
#there are two options, the fist one seems more accurate (relative to test set)
if equationSelect == 1:
#http://www.vaisala.com/Vaisala%20Documents/Application%20notes/Humidity_Conversion_Formulas_B210973EN-D.pdf
return ( 1325.2520998 * 10 **(7.5892*(T - 273.15)/(T -32.44)))/T
else:
#http://www.see.ed.ac.uk/~shs/Climate%20change/Data%20sources/Humidity%20with%20altidude.pdf
return (1324.37872 * 2.718281828459046 **(17.67*(T - 273.16)/(T - 29.66)))/T |
def construct_path(u,v,discovered):
"""Use the discovered dictionary from
depth-first search to reconstruct
a path from node u to node v.
"""
path = []
# Deal with empty case
if v not in discovered:
return path
# build list of edges
# that connect v to u,
# then reverse it.
path.append(v)
walk = v
while walk is not u:
e = discovered[walk]
parent = e.opposite(walk)
path.append(parent)
walk = parent
path.reverse()
return path |
def index_storage_mode_to_param(value, default="plasma"):
"""Converts the index storage mode to what Couchbase understands"""
if value == "default":
return default
elif value == "memopt":
return "memory_optimized"
else:
return value |
def find_message(text: str) -> str:
"""Find a secret message"""
s = ''
for i in text:
if i.isupper():
s += i
return s |
def calc_stdev(my_list):
"""
Parameters
----------
my_list : list
A list of numeric values.
Returns
-------
stdev :
"""
avg_val = sum(my_list)/len(my_list)
diff_sqr = []
for i in my_list:
val = (i - avg_val)**2.0
diff_sqr.append(val)
stdev = (sum(diff_sqr)/len(diff_sqr))**0.5
return stdev |
def assign_min_max_params(in_params, center=1):
"""
Adjust input parameters for ops.
"""
if isinstance(in_params, (list, tuple)):
min_param = in_params[0]
max_param = in_params[1]
else:
min_param = max(0, center - in_params)
max_param = center + in_params
return min_param, max_param |
def slow_mult_polynoms(a, b):
"""Multiply two polynoms in GF(2^8) using X^8+X^4+X^3+X+1 (=0x1b)
NB. This is NOT constant-time and leaks secret values in timing differences.
DO NOT USE THIS CODE TO IMPLEMENT SECURE APPLICATIONS
"""
m = 0
assert 0 <= a < 0x100
assert 0 <= b < 0x100
while b:
if b & 1 == 1:
m ^= a
a <<= 1
if a & 0x100:
a ^= 0x11b
b >>= 1
assert 0 <= m < 0x100
return m |
def add_request_headers(headers):
"""Add headers for 3rd party providers which we access data from."""
# Pass our abuse policy in request headers for third-party site admins.
headers["X-Abuse-Policy"] = "https://web.hypothes.is/abuse-policy/"
headers["X-Complaints-To"] = "https://web.hypothes.is/report-abuse/"
return headers |
def complex_permittivity_to_tan_delta(real_permittivity: float,
imag_permittivity: float) -> float:
"""Computes loss tangent from complex relative permittivity
This is a simple and straightforward calculation of a material's loss
tangent from the real and imaginary parts of its complex relative
permittivity.
Args:
real_permittivity: A `float` value for te real part of the
complex relative permittivity.
imag_permittivity: A `float` value for the imaginary part of the
complex relative permittivity.
Returns:
The value for the loss tangent.
Raises:
ZeroDivisionError: If you specify 0 Hz, i.e. DC, for the real part
of the permittivity.
"""
try:
tan_delta = imag_permittivity / real_permittivity
except ZeroDivisionError as error:
raise ZeroDivisionError('Real part must be > 0'). \
with_traceback(error.__traceback__)
return tan_delta |
def xstr(s):
"""
Function for casting a value to string and None to a empty string
:param s: Value to be converted
:return: a string value
"""
if s is None:
return ""
else:
return str(s) |
def parse_case_results(results, var_names):
"""
"""
if isinstance(var_names, str) or len(var_names) == 1:
results = tuple((r,) for r in results)
return results |
def int_or_none(val, default=None):
"""
Arguments:
- `x`:
"""
if val is None:
return default
else:
try:
ret = int(val)
except ValueError:
ret = default
return ret |
def fizzy(in_list):
"""
Cheeky one-liner solution
"""
return ["FizzBuzz" if i%3==0 and i%5==0 else "Fizz" if i%3==0 else "Buzz" if i%5==0 else i for i in in_list] |
def remote_db_val_from_raw_val(grpc_address: str) -> bytes:
"""Format a remote db value from it's grpc address string
Parameters
----------
grpc_address : str
IP:PORT where the grpc server can be accessed
Returns
-------
bytes
formated representation of the grpc address suitable for storage in lmdb.
"""
return grpc_address.encode() |
def mysql_to_dict_id_as_key_info_as_dict(mysql_fetchall, columns):
"""returns a dict with the ID as the key and the info is stored in the nested dict with the column being the key"""
return {info[0]: {column: info for column, info in zip(columns[1:], info[1:])} for info in mysql_fetchall} |
def has_upper(s: str) -> bool:
"""
Returns True if the string consists of one or more upper case characters, True otherwise.
"""
if isinstance(s, str):
return len(s) > 0 and not s.islower()
raise TypeError("invalid input - not a string") |
def is_numerical(url):
""" Predicate for create_request
Is the URL an already resolved numeric ip address?
"""
if url in ["192.168.1.254"]:
return False
return not ([k for k in url if k not in "0123456789."]) |
def int_to_big_endian_byte_array(val): # CAUTION: the result array contains the bytes in big endian order!
"""
:param val: int
:rtype: (int, [int])
"""
nbytes = 0
res = []
while val > 0:
nbytes += 1
res.append(int(val % 256))
val /= 256
res.reverse()
return nbytes, res |
def isdominated(fitnesses1, fitnesses2):
"""Returns whether or not *wvalues1* dominates *wvalues2*.
:param wvalues1: The weighted fitness values that would be dominated.
:param wvalues2: The weighted fitness values of the dominant.
:returns: :obj:`True` if wvalues2 dominates wvalues1, :obj:`False`
otherwise.
"""
not_equal = False
for self_fitnesses, other_fitnesses in zip(fitnesses1,fitnesses2):
if self_fitnesses > other_fitnesses:
return False
elif self_fitnesses < other_fitnesses:
not_equal = False
return not_equal |
def b2s(n):
"""Convertes a binary long into a string. ASCII only
Args:
n: binary data as a long
Returns:
A string of ASCII characters
"""
#start a list
s = []
#while there is data
while n > 0:
#convert 8 bits of the data to an ascii character and append to the list
s.append( chr(n & 0xFF) )
#shift the data right by 8 bits
n = n >> 8
#return the reversed list
return ''.join(reversed(s)) |
def normalize_text(text):
"""
Replace some special characters in text.
"""
# NOTICE: don't change the text length.
# Otherwise, the answer position is changed.
text = text.replace("''", '" ').replace("``", '" ')
return text |
def getColor(index, colors):
""" returns the colour at the position of an array which contains colours """
return colors[index%len(colors)] |
def list_by_list(blist, slist):
"""Sort list of block indexes, by another list.
Argument:
List:blist -- List of block indexes.
List:slist -- Secondary list of blocks.
Returns:
List -- List of block indexes matching slist from blist.
"""
slist_blocks = []
for block in blist:
if block in slist:
slist_blocks.append(block)
return slist_blocks |
def numToTxt(num):
""" Integer < 10 to textual representation """
lookup = {0: 'zero',
1: 'one',
2: 'two',
3: 'three',
4: 'four',
5: 'five',
6: 'six',
7: 'seven',
8: 'eight',
9: 'nine',
10: 'ten'}
dayTxt = lookup.get(num, str(num))
return dayTxt |
def check_not_finished_board(board: list) -> bool:
"""
Check if skyscraper board is not finished, i.e., '?' present on the game board.
Return True if finished, False otherwise.
>>> check_not_finished_board(['***21**', '4?????*', '4?????*', '*?????5', '*?????*', \
'*?????*', '*2*1***'])
False
>>> check_not_finished_board(['***21**', '412453*', '423145*', '*543215', '*35214*', \
'*41532*', '*2*1***'])
True
>>> check_not_finished_board(['***21**', '412453*', '423145*', '*5?3215', '*35214*', \
'*41532*', '*2*1***'])
False
"""
for line in board:
if '?' in line:
return False
return True |
def gregorian_date(year, month, day):
"""Return a Gregorian date data structure."""
return [year, month, day] |
def area(box):
"""Calculate area of a box."""
if box is None:
return 0
x0, y0, x1, y1 = box
return (x1 - x0) * (y1 - y0) |
def binary_search_h5_dset(dset, x, l=None, r=None, side='left'):
"""
Binary search for a timestamp in an HDF5 event file, without
loading the entire file into RAM
@param dset The HDF5 dataset
@param x The timestamp being searched for
@param l Starting guess for the left side (0 if None is chosen)
@param r Starting guess for the right side (-1 if None is chosen)
@param side Which side to take final result for if exact match is not found
@returns Index of nearest event to 'x'
"""
l = 0 if l is None else l
r = len(dset)-1 if r is None else r
while l <= r:
mid = l + (r - l)//2;
midval = dset[mid]
if midval == x:
return mid
elif midval < x:
l = mid + 1
else:
r = mid - 1
if side == 'left':
return l
return r |
def find_output_value(name, outputs):
""" Finds a specific output within a collection. """
return next(
output['value'] for output in outputs if output['name'] == name
) |
def _IsAcceptableRowId(row_id, last_row_id):
"""Checks whether the given row id (aka revision) is not too large or small.
For each data series (i.e. TestMetadata entity), we assume that row IDs are
monotonically increasing. On a given chart, points are sorted by these
row IDs. This way, points can arrive out of order but still be shown
correctly in the chart.
However, sometimes a bot might start to use a different *type* of row ID;
for example it might change from revision numbers or build numbers to
timestamps, or from timestamps to build numbers. This causes a lot of
problems, including points being put out of order.
If a sender of data actually wants to switch to a different type of
row ID, it would be much cleaner for them to start sending it under a new
chart name.
Args:
row_id: The proposed Row entity id (usually sent as "revision")
last_row_id: The previous Row id, or None if there were none previous.
Returns:
True if acceptable, False otherwise.
"""
if row_id <= 0:
return False
if last_row_id is None:
return True
# Too big of a decrease.
if row_id < 0.5 * last_row_id:
return False
# Too big of an increase.
if row_id > 2 * last_row_id:
return False
return True |
def distance_to(from_cell, to_cell):
"""
Compute Manhattan distance between two cells in a rectangular maze.
"""
return abs(from_cell[0] - to_cell[0]) + abs(from_cell[1] - to_cell[1]) |
def _special_round(num):
"""
Returns the round number:
- if decimal is equal or higher than .85 it is rounded up
- else it is rounded down.
"""
from math import floor
num_int = floor(num)
decimal = num - num_int
if num_int < 1:
return 1
else:
if decimal >= 0.85:
return num_int + 1
else:
return num_int |
def measure_type(x):
"""Takes Numeric Code and returns String API code
Input Values: 1:"Base", 2:"Advanced", 3:"Misc", 4:"Four Factors", 5:"Scoring", 6:"Opponent", 7:"Usage"
Used in:
"""
measure = {1: "Base", 2: "Advanced", 3: "Misc", 4: "Four Factors", 5: "Scoring", 6: "Opponent", 7: "Usage"}
try:
return measure[x]
except:
raise ValueError("Please enter a number between 1 and " + str(len(measure))) |
def F_value (ER:float,EF:float,dfnum:float,dfden:float)->float:
"""
Returns an F-statistic given the following:
ER = error associated with the null hypothesis (the Restricted model)
EF = error associated with the alternate hypothesis (the Full model)
dfR-dfF = degrees of freedom of the numerator
dfF = degrees of freedom associated with the denominator/Full model
Usage: lF_value(ER,EF,dfnum,dfden)
"""
return ((ER-EF)/float(dfnum) / (EF/float(dfden))) |
def is_empty(_str):
"""
Convenient function to check if a str is empty
Examples
is_empty(None) = True
is_empty("") = True
is_empty(" ") = False
is_empty("abc") = False
is_empty("1") = False
is_empty(1) = False
"""
return not bool(_str) |
def get_size_in_gb(size_in_bytes):
"""convert size in gbs"""
return size_in_bytes / (1024 * 1024 * 1024) |
def _fastWhere(eve, objs):
"""
like np.where but a bit faster because data checks are skipped
"""
an = next(nu for nu, obj in enumerate(objs) if eve == obj)
return an |
def specificity(TN, FP):
"""Specificity or true negative rate"""
return (TN) / (FP + TN) |
def _pick_best(gene_string):
"""
Example
-------
>>> _pick_best('TRAV12-2*01,TRAV12D-1*01')
TRAV12-2*01
>>>_pick_best('TRAV12-2*01'
'TRAV12-2*01'
"""
return gene_string.split(",")[0] |
def liberty_bool(b):
"""
>>> liberty_bool(True)
'true'
>>> liberty_bool(False)
'false'
>>> liberty_bool(1.0)
'true'
>>> liberty_bool(1.5)
Traceback (most recent call last):
...
ValueError: 1.5 is not a bool
>>> liberty_bool(0.0)
'false'
>>> liberty_bool(0)
'false'
>>> liberty_bool(1)
'true'
>>> liberty_bool("error")
Traceback (most recent call last):
...
ValueError: 'error' is not a bool
"""
try:
b2 = bool(b)
except ValueError:
b2 = None
if b2 != b:
raise ValueError("%r is not a bool" % b)
return {True: 'true', False: 'false'}[b] |
def left_to_right_check(input_line: str, pivot: int):
"""
Check row-wise visibility from left to right.
Return True if number of building from the left-most hint is visible looking to the right,
False otherwise.
input_line - representing board row.
pivot - number on the left-most hint of the input_line.
>>> left_to_right_check("412453*", 4)
True
>>> left_to_right_check("452453*", 5)
False
"""
row = input_line[1:-1]
last_num = -1
visiable = 0
for num in row:
if int(num) > last_num:
visiable += 1
last_num = int(num)
if visiable == pivot:
return True
return False |
def check_susbstrings(link, substrings):
"""
Checks if link contains one of the substrings.
"""
is_valid = False
for sub in substrings:
if sub in link:
is_valid = True
break
return is_valid |
def convert_bit_index(x):
"""
Transform x into a bit index
"""
x_string = str(x)
sum = 0
if x == 6666:#if it is a no-data pixel
return 255
for i in range(1,6):
if str(i) in x_string:
sum += 2**i
return sum |
def merge_kwargs(x, y):
"""Merge dictionaries `x` and `y`.
By conflicts, `y` wins."""
z = {}
overlapping_keys = x.keys() & y.keys()
for key in overlapping_keys:
if isinstance(x[key], dict) and isinstance(y[key], dict):
z[key] = merge_kwargs(x[key], y[key])
else:
z[key] = y[key]
for key in x.keys() - overlapping_keys:
z[key] = x[key]
for key in y.keys() - overlapping_keys:
z[key] = y[key]
return z |
def primes(limit):
""" Returns a list of primes < limit """
sieve = [True] * limit
for i in range(3, int(limit ** 0.5) + 1, 2):
if sieve[i]:
sieve[i * i::2 * i] = [False] * ((limit - i * i - 1) // (2 * i) + 1)
return [2] + [i for i in range(3, limit, 2) if sieve[i]] |
def equals(str1, str2):
"""
compares 2 Strings, case insensitive and without leading or trailing whitespaces.
"""
return str1.strip().casefold() == str2.strip().casefold() |
def is_event(attribute):
"""
Test if a method is an event.
"""
return attribute.startswith('on_') |
def search(str1, str2):
"""
The function finds the sequence has highest similarity.
:param str1: the long DNA sequence.
:param str2: the short DNA sequence.
:return: the sequence has highest similarity.
"""
highest_similarity_seq = 'No match' # similarity = 0
highest_correct = 0
for i in range(len(str1)-len(str2)+1): # total runs
correct = 0 # how many nucleotides match
for j in range(len(str2)): # loop over the sequence
if str1[i+j] == str2[j]:
correct += 1
if correct > highest_correct: # keep higher number and the sequence
highest_correct = correct
highest_similarity_seq = str1[i:i+len(str2)]
return highest_similarity_seq |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.