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_patter... |
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_ch... |
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 :
st... |
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 ... |
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... |
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:
... |
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... |
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"
>... |
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... |
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_li... |
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"... |
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_conf... |
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[... |
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"
... |
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 po... |
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):
... |
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... |
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)
"""
... |
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 *... |
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 app... |
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:
... |
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... |
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)
... |
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... |
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
el... |
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
... |
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
e... |
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 progra... |
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)
... |
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): selec... |
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 r... |
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 = (... |
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 ... |
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... |
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... |
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 par... |
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 sui... |
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()
retur... |
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`
... |
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 ... |
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 = []
... |
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',
... |
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
... |
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... |
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 o... |
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... |
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"}
... |
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 num... |
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)
... |
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... |
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:
... |
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
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.