content stringlengths 42 6.51k |
|---|
def check_month_validation(month):
"""check if month is validate
:param month: input month
:return: if month is validate
"""
return int(month) in range(1, 13) |
def mel2hz(mel):
"""
Convert a value in Mels to Hertz
Args:
mel: a value in Mels. This can also be a numpy array, conversion
proceeds element-wise.
Returns:
a value in Hertz. If an array was passed in, an identical sized array is
returned.
"""
return 700*(10**(mel/2595.0)-1) |
def coordinate_length_ok(latitude, longitude):
"""
A valid coordinate should be a float of certain length (i.e. usually 8-9 characters including the dot).
E.g. ['60.388098', '25.621308']
Explicitly check the length of a float and discard clearly invalid coordinates. There seems to be an issue
with some of the coordinates having a high confidence value, but the coordinate is still clearly wrong (too short).
"""
if len(str(latitude)) > 6 and len(str(longitude)) > 6:
return True
return False |
def has_keys(needles, haystack):
"""
Searches for the existence of a set of needles in a haystack
"""
return all(item in haystack for item in needles) |
def _is_array(value):
""" Is the provided value an array of some sorts (list, tuple, set)? """
return isinstance(value, (list, tuple, set, frozenset)) |
def base_repr(number, base=2, padding=0):
"""
Return a string representation of a number in the given base system.
Parameters
----------
number : int
The value to convert. Positive and negative values are handled.
base : int, optional
Convert `number` to the `base` number system. The valid range is 2-36,
the default value is 2.
padding : int, optional
Number of zeros padded on the left. Default is 0 (no padding).
Returns
-------
out : str
String representation of `number` in `base` system.
See Also
--------
binary_repr : Faster version of `base_repr` for base 2.
Examples
--------
>>> np.base_repr(5)
'101'
>>> np.base_repr(6, 5)
'11'
>>> np.base_repr(7, base=5, padding=3)
'00012'
>>> np.base_repr(10, base=16)
'A'
>>> np.base_repr(32, base=16)
'20'
"""
digits = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
if base > len(digits):
raise ValueError("Bases greater than 36 not handled in base_repr.")
elif base < 2:
raise ValueError("Bases less than 2 not handled in base_repr.")
num = abs(number)
res = []
while num:
res.append(digits[num % base])
num //= base
if padding:
res.append('0' * padding)
if number < 0:
res.append('-')
return ''.join(reversed(res or '0')) |
def parse_email(ldap_entry):
"""
Returns the user's email address from an ldapentry
"""
if "mail" in ldap_entry:
email = ldap_entry['mail'][0]
else:
email = ldap_entry['uid'][0] + "@pdx.edu"
return email |
def compute_closest_coordinate(value, range_min, range_max):
"""
Function for computing closest coordinate for the neighboring hyperplane.
Parameters
----------
value : float
COORDINATE VALUE (x or y) OF THE TARGET POINT.
range_min : float
MINIMAL COORDINATE (x or y) OF THE NEGHBORING HYPERPLANE.
range_max : float
MAXIMAL COORDINATE (x or y) OF THE NEGHBORING HYPERPLANE..
Returns
-------
v : float
x or y coordinate.
"""
v = None
if range_min < value < range_max:
v = value
elif value <= range_min:
v = range_min
elif value >= range_max:
v = range_max
return v |
def makeSystemCall(args, shell=False):
"""
make a system call
@param args must be an array, the first entry being the called program
@shell turns on or off shell based features. Warning: using shell=True
might be a potential security hazard.
@return returns a tuple with communication from the called system process,
consisting of stdoutdata, stderrdata
"""
import subprocess
proc = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=shell)
msg = proc.communicate()
try:
proc.kill()
except:
pass
#msg = subprocess.call(args) - recommended version; we don't use it, since we want to get back the system message
return msg |
def get_attr(item, name, default=None):
"""
similar to getattr and get but will test for class or dict
:param item:
:param name:
:param default:
:return:
"""
try:
val = item[name]
except (KeyError, TypeError):
try:
val = getattr(item, name)
except AttributeError:
val = default
return val |
def GetVSSNumber(event_object):
"""Return the vss_store_number of the event."""
if not hasattr(event_object, 'pathspec'):
return -1
return getattr(event_object.pathspec, 'vss_store_number', -1) |
def _get_states(rev, act):
"""Determines the initial state and the final state based on boolean inputs
Parameters
----------
rev : bool
True if the reaction is in the reverse direction.
act : bool
True if the transition state is the final state.
Returns
-------
initial_state : str
Initial state of the reaction. Either 'reactants', 'products' or
'transition state'
final_state : str
Final state of the reaction. Either 'reactants', 'products' or
'transition state'
"""
if rev:
initial_state = 'products'
final_state = 'reactants'
else:
initial_state = 'reactants'
final_state = 'products'
# Overwrites the final state if necessary
if act:
final_state = 'transition state'
return initial_state, final_state |
def int_to_str(num, max_num=0):
"""
Converts a number to a string. Will add left padding based on the max value to ensure numbers
align well.
"""
if num is None:
num_str = 'n/a'
else:
num_str = '{:,}'.format(num)
max_str = '{:,}'.format(int(max_num))
return num_str.rjust(len(max_str)) |
def make_category_query(category):
"""Creates a search query for the target audio category"""
# mediatype:(audio) subject:"radio"
return f"mediatype:(audio) subject:{category}" |
def _convert_results_to_dict(r):
"""Takes a results from ElasticSearch and returns fields."""
if 'fields' in r:
return r['fields']
if '_source' in r:
return r['_source']
return {'id': r['_id']} |
def prune_small_terms(hpo_counts, min_samples):
"""
Drop HPO terms with too few samples
"""
filtered_counts = {}
for term, count in hpo_counts.items():
if count >= min_samples:
filtered_counts[term] = count
return filtered_counts |
def array_equals(a, b):
""" Checks to see that two arrays
are completely equal, regardless of order
Complexity: O(n^2)
"""
i = 0
# Check all values in A
while i < len(a): # This loop runs N times
flag = False
j = 0
# Search for that value in B
while j < len(b): # This loop runs N times
if a[i] == b[j]:
flag = True
break
j+=1
if not flag:
return False
i+=1
return True |
def sizeof_fmt(mem_usage, suffix='B'):
"""
Returns the memory usage calculation of the last function.
Parameters
----------
mem_usage : int
memory usage in bytes
suffix: string, optional, default 'B'
suffix of the unit
Returns
-------
str
A string of the memory usage in a more readable format
"""
for unit in ['', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi']:
if abs(mem_usage) < 1024.0:
return '{:3.1f} {}{}'.format(mem_usage, unit, suffix)
mem_usage /= 1024.0
return '{:.1f} {}{}'.format(mem_usage, 'Yi', suffix) |
def t_weighted_mean_temp(T_pelagic, T_bottom, t_frac_pelagic):
"""Compute the time-weighted mean temperature.
Parameters
----------
T_pelagic : numeric
Pelagic temperature.
T_bottom : numeric
Bottom temperature.
t_frac_pelagic : numeric
Fraction of time spent in the pelagic.
"""
return (T_pelagic * t_frac_pelagic) + (T_bottom * (1.0 - t_frac_pelagic)) |
def sortData(data):
"""sort data into a specific index"""
sortedData = []
for i in data:
for j in i:
temp = []
i2c = j["i2c"]
temp.append(j["time"])
temp.append(i2c[0])
temp.append(i2c[1][0]["x"])
temp.append(i2c[1][0]["y"])
temp.append(i2c[1][0]["z"])
temp.append(i2c[1][1]["x"])
temp.append(i2c[1][1]["y"])
temp.append(i2c[1][1]["z"])
temp.append(i2c[1][2])
temp.append(i2c[2])
temp.append(i2c[3])
temp.append(i2c[4])
sortedData.append(temp)
return sortedData |
def template_validation(template_dest, template_reference):
"""Validates a stream template against the current version.
@param template_dest The new stream template
@param template_reference The old stream template
@return True if the templates match, False otherwise
"""
if len(template_dest) != len(template_reference):
return False
try:
for key in template_dest:
k = key.strip()
if template_dest[k] != template_reference[k]["type"]:
return False
except KeyError:
return False
return True |
def utf8(astring):
"""Ensure string is utf8"""
return astring.strip().encode("utf-8").decode("utf-8","ignore") |
def is_palindrome_string(string):
"""Return whether `string` is a palindrome, ignoring the case.
Parameters
----------
string : str
The string to check.
Returns
-------
bool
A boolean representing whether `string` is a palindrome or not.
"""
# begin solution
return string.lower() == string[::-1].lower()
# end solution |
def insertionSort(ll=[]):
"""The in-place insertionSort algorithm
"""
for i in range(1, len(ll)):
for j in range(0, i):
if ll[i] < ll[j]:
t = ll[i]
for k in range(i, j, -1):
ll[k] = ll[k-1]
ll[j] = t
break
return ll |
def format_time(elapsed):
"""Formats elapsed seconds into a human readable format."""
hours = int(elapsed / (60 * 60))
minutes = int((elapsed % (60 * 60)) / 60)
seconds = int(elapsed % 60)
rval = ""
if hours:
rval += "{0}h".format(hours)
if elapsed > 60:
rval += "{0}m".format(minutes)
rval += "{0}s".format(seconds)
return rval |
def _get_length_length(_bytes):
"""Returns a count of bytes in an Ion value's `length` field."""
if (_bytes[0] & 0x0F) == 0x0E:
# read subsequent byte(s) as the "length" field
for i in range(1, len(_bytes)):
if (_bytes[i] & 0x80) != 0:
return i
raise Exception("Problem while reading VarUInt!")
return 0 |
def get_filters(content):
"""
Get filter names from the token's content.
WARNING: Multiple filters can be used simultaneously, e.g.:
{{ some_list|safeseq|join:", " }}
:content: String; the token's content
:returns: a list of filter names
"""
filters = []
split_content = content.split('|')
for item in split_content[1:]:
if ':' in item:
item = item[:item.index(':')]
filters.append(item)
return filters |
def transform_none(val, *none_vals):
"""
Transform to None
<dotted>|none None if not val else val
<dotted>|none::hello None if val in ('', 'hello') else val
"""
if not none_vals:
return None if not val else val
return None if val in none_vals else val |
def _DocToArgs(doc):
"""Converts a docstring documenting arguments into a dict.
.. image:: _static/adb.common_cli._DocToArgs.CALLER_GRAPH.svg
Parameters
----------
doc : str
The docstring for a method; see `MakeSubparser`.
Returns
-------
out : dict
A dictionary of arguments and their descriptions from the docstring ``doc``.
"""
offset = None
param = None
out = {}
for l in doc.splitlines():
if l.strip() == 'Parameters':
offset = len(l.rstrip()) - len(l.strip())
elif offset:
# The "----------" line
if l.strip() == '-' * len('Parameters'):
continue
if l.strip() in ['Returns', 'Yields', 'Raises']:
break
# start of a parameter
if len(l.rstrip()) - len(l.strip()) == offset:
param = l.strip().split()[0]
out[param] = ''
# add to a parameter
elif l.strip():
if out[param]:
out[param] += ' ' + l.strip()
else:
out[param] = l.strip()
return out |
def fib(n):
""" F(n) = F(n - 1) + F(n - 2) """
if n < 2:
return n
else:
return fib(n-1) + fib(n-2) |
def part_device(part_number):
"""Given partition number (but string type), return the device for that
partition."""
return "/dev/mmcblk0p" + part_number |
def freq_to_maf(freq):
""" Convert allele frequency to minor allele freq
"""
return min(freq, 1-freq) |
def split_spec(spec, sep):
"""Split a spec by separator and return stripped start and end parts."""
parts = spec.rsplit(sep, 1)
spec_start = parts[0].strip()
spec_end = ''
if len(parts) == 2:
spec_end = parts[-1].strip()
return spec_start, spec_end |
def negative_accounts(row):
"""
After joining accounts payable and receivable, check for negative values.
Convert negative values to positive to move to the opposite cashflow type.
Example: Accounts payable on June 2021 is -100 while accounts receivable is 50.
Then set accounts payable that month to 0 and accounts receivable to 150.
This goes into .apply() on `cashflow`, so `row` is a row from `cashflow`
"""
tmp_payable = 0
tmp_receivable = 0
if row['Accounts Payable'] < 0:
tmp_payable = -row['Accounts Payable']
row['Accounts Payable'] = 0
if row['Accounts Receivable'] < 0:
tmp_receivable = -row['Accounts Receivable']
row['Accounts Receivable'] = 0
row['Accounts Payable'] += tmp_receivable
row['Accounts Receivable'] += tmp_payable
return row |
def split_and_sum(expression) -> float:
"""Avoid using literal_eval for simple addition expressions."""
split_vals = expression.split('+')
float_vals = [float(v) for v in split_vals]
total = sum([v for v in float_vals if v > 0.0])
return total |
def empty(obj):
""" * is the object empty?
* returns true if the json object is empty
"""
if not obj:
# Assume if it has a length property with a non-zero value
# that that property is correct.
return True
if len(obj) > 0:
return False
if len(obj) == 0:
return True
# Otherwise, does it have any properties of its own?
# if type(obj) == dict:
# for key in obj.keys():
# if hasattr(obj,key):
# return False
return True |
def flatten(v):
"""
Flatten a list of lists/tuples
"""
return [x for y in v for x in y] |
def retrieve_all_parameters(parameter_info_dict):
"""Retrieve all parameters from parameter dictionary."""
return sorted({x for v in parameter_info_dict.values() for x in v}) |
def serialise_colour(colour, context=None):
"""Serialise a Colour value.
colour -- 'b' or 'w'
"""
if colour not in ('b', 'w'):
raise ValueError
return colour.upper().encode('ascii') |
def GetProQ3Option(query_para):#{{{
"""Return the proq3opt in list
"""
yes_or_no_opt = {}
for item in ['isDeepLearning', 'isRepack', 'isKeepFiles']:
if item in query_para and query_para[item]:
yes_or_no_opt[item] = "yes"
else:
yes_or_no_opt[item] = "no"
proq3opt = [
"-r", yes_or_no_opt['isRepack'],
"-deep", yes_or_no_opt['isDeepLearning'],
"-k", yes_or_no_opt['isKeepFiles'],
"-quality", query_para['method_quality'],
"-output_pdbs", "yes" #always output PDB file (with proq3 written at the B-factor column)
]
if 'targetlength' in query_para:
proq3opt += ["-t", str(query_para['targetlength'])]
return proq3opt |
def pythonize_options(options):
"""
convert string based options into python objects/types
Args:
options: flat dict
Returns:
dict with python types
"""
def parse_string(item):
"""
check what kind of variable string represents and convert accordingly
Args:
item: string
Returns:
parsed obj in correct type
"""
# assert flat
assert not isinstance(item, dict)
# hack: is that correct?
if isinstance(item, (list, tuple)):
return item
if not isinstance(item, str):
return item
# do not use bool(...) to convert!
if item.lower() == 'true':
return True
if item.lower() == 'false':
return False
try:
return int(item)
except:
pass
try:
return float(item)
except:
pass
return item
return {k : parse_string(v) for k, v in options.items()} |
def selectflagpage(place, results):
"""Given a list of wikipedia page names, selects one with 'flag' or 'coat of arms' in the
title and returns it
:param place: The place who's flag is being searched for
:type plae: String
:param results: A list of search results
:type results: [String]
:return: The selected result
:rtype: String
"""
for result in results:
if "flag" in result.lower():
return result
for result in results:
if "coat of arms" in result.lower():
return result |
def remove_duplicates(li):
"""Removes duplicates of a list but preserves list order
Parameters
----------
li: list
Returns
-------
res: list
"""
res = []
for e in li:
if e not in res:
res.append(e)
return res |
def ctestReportCPUTime(cpuTime, oss=None):
"""write ctest tag for timing"""
tag = '<DartMeasurement name="CPUTime" type="numeric/double"> %f </DartMeasurement>'%(cpuTime)
if oss is not None:
oss.write(tag)
return tag |
def lays_in(a, b):
""" Lays cube a completely in cube b? """
axf, axt, ayf, ayt, azf, azt = a
bxf, bxt, byf, byt, bzf, bzt = b
return(
bxf <= axf <= axt <= bxt and
byf <= ayf <= ayt <= byt and
bzf <= azf <= azt <= bzt) |
def GetRegionFromZone(zone):
"""Returns the GCP region that the input zone is in."""
return '-'.join(zone.split('-')[:-1]) |
def _convert_to_float_if_possible(s):
"""
A small helper function to convert a string to a numeric value
if appropriate
:param s: the string to be converted
:type s: str
"""
try:
ret = float(s)
except (ValueError, TypeError):
ret = s
return ret |
def normalize_response(response):
"""Normalize the given response, by always returning a 3-element tuple
(status, headers, body). The body is not "resolved"; it is safe
to call this function multiple times on the same response.
"""
# Get status, headers and body from the response
if isinstance(response, tuple):
if len(response) == 3:
status, headers, body = response
elif len(response) == 2:
status = 200
headers, body = response
elif len(response) == 1:
status, headers, body = 200, {}, response[0]
else:
raise ValueError(f"Handler returned {len(response)}-tuple.")
else:
status, headers, body = 200, {}, response
# Validate status and headers
if not isinstance(status, int):
raise ValueError(f"Status code must be an int, not {type(status)}")
if not isinstance(headers, dict):
raise ValueError(f"Headers must be a dict, not {type(headers)}")
return status, headers, body |
def get_destination_from_obj(destination):
"""Helper to get a destination from a destination, event, or tour.
For events and tours, return the first related destination, if any."""
if hasattr(destination, 'first_destination'):
# tour with related destination(s); use the ordered first
return destination.first_destination
else:
# not an event or tour
return destination |
def pil_coord_to_tesseract(pil_x, pil_y, tif_h):
""" Convert PIL coordinates into Tesseract boxfile coordinates:
in PIL, (0,0) is at the top left corner and
in tesseract boxfile format, (0,0) is at the bottom left corner.
"""
return pil_x, tif_h - pil_y |
def index_first_char_not_equal_to(value: str, char: str, start_index: int = 0) -> int:
"""Returns the index of the first character in string 'value' not containing the character provided by 'char' starting at index start_index."""
for i in range(start_index, len(value)):
if value[i] != char:
return i
return -1 |
def rstrip_line(line):
"""Removes trailing whitespace from a string (preserving any newline)"""
if line[-1] == '\n':
return line[:-1].rstrip() + '\n'
return line.rstrip() |
def next_nuc(seq, pos, n):
""" Returns the nucleotide that is n places from pos in seq. Skips gap symbols.
"""
i = pos + 1
while i < len(seq):
if seq[i] != '-':
n -= 1
if n == 0: break
i += 1
if i < len(seq) :
return seq[i]
else :
return 'N' |
def AlignMatches(matches):
"""
Tallys up each dif's song id frequency and returns the song id with highest count diff
Args:
matches: list of tuples containing (song id, relative offset) matched from known song
Returns:
songId (int)
"""
diffMap = {}
largestCount = 0
songId = -1
for sid, diff in matches:
if diff not in diffMap:
diffMap[diff] = {}
if sid not in diffMap[diff]:
diffMap[diff][sid] = 0
diffMap[diff][sid] += 1
if diffMap[diff][sid] > largestCount:
largestCount = diffMap[diff][sid]
songId = sid
return songId |
def remove_dot_segments(path):
"""Remove '.' and '..' segments from a URI path.
Follows the rules specified in Section 5.2.4 of RFC 3986.
"""
output = []
while path:
if path.startswith('../'):
path = path[3:]
elif path.startswith('./'):
path = path[2:]
elif path.startswith('/./') or path == '/.':
path = '/' + path[3:]
elif path.startswith('/../') or path == '/..':
path = '/' + path[4:]
if len(output) > 0:
del output[-1]
elif path in ['.', '..']:
path = ''
else:
if path.startswith('/'):
slash = path.find('/', 1)
else:
slash = path.find('/')
if slash < 0:
slash = len(path)
output.append(path[:slash])
path = path[slash:]
return ''.join(output) |
def list_strip_all_newline(list_item: list) -> list:
"""
Strips all newline characters '\n' from all list_items in list object.
:param list_item: A list object to be cleaned from newline characters.
:return list: A list object which has been cleaned.
"""
return list(map(lambda x: x.strip('\n'), list_item)) |
def set_accuracy_95(num: float) -> float:
"""Reduce floating point accuracy to 9.5 (xxxx.xxxxx).
Used by Hedron and Dihedron classes writing PIC and SCAD files.
:param float num: input number
:returns: float with specified accuracy
"""
# return round(num, 5) # much slower
return float(f"{num:9.5f}") |
def inteiro_para_peca(n):
"""
Funcao de alto nivel.
Recebe um inteiro e devolve um jogador 'X', 'O', ou ' ' (livre), dependendo se o inteiro e
1, -1 ou 0 (livre), respetivamente.
:param n:
:return:
"""
int_peca = {1: 'X', -1: 'O', 0: ' '}
return int_peca[n] |
def is_iterable(x):
"""Check if variable is iterable
"""
try:
iter(x)
except TypeError:
return False
else:
return True |
def min_conv(time):
""" converts time into minutes, used for sort and format
"""
hh, mm = time.split(":")
minutes = (int(hh)*60 + int(mm))
return minutes |
def load_cands(path, lines_have_ids=False, cands_are_replies=False):
"""Load global fixed set of candidate labels that the teacher provides
every example (the true labels for a specific example are also added to
this set, so that it's possible to get the right answer).
"""
if path is None:
return None
cands = []
cnt = 0
with open(path) as read:
for line in read:
line = line.strip().replace('\\n', '\n')
if len(line) > 0:
cnt = cnt + 1
# If lines are numbered we strip them of numbers.
if cnt == 1 and line[0:2] == '1 ':
lines_have_ids = True
# If tabs then the label_candidates are all the replies.
if '\t' in line and not cands_are_replies:
cands_are_replies = True
cands = []
if lines_have_ids:
space_idx = line.find(' ')
line = line[space_idx + 1:]
if cands_are_replies:
sp = line.split('\t')
if len(sp) > 1 and sp[1] != '':
cands.append(sp[1])
else:
cands.append(line)
else:
cands.append(line)
return cands |
def set_bit(value: int, bit: int) -> int:
"""Set n-th bit of value.
Args:
value: Number to set bit.
bit: Bit number.
Returns:
Value with set n-th bit.
Example:
>>> bin(set_bit(0b11011, 2))
'0b11111'
"""
return value | (1 << bit) |
def word_idx(sentences):
"""
sentences should be a 2-d array like [['a', 'b'], ['c', 'd']]
"""
word_2_idx = {}
for sentence in sentences:
for word in sentence:
if word not in word_2_idx:
word_2_idx[word] = len(word_2_idx)
idx_2_word = dict(zip(word_2_idx.values(), word_2_idx.keys()))
num_unique_words = len(word_2_idx)
return word_2_idx, idx_2_word, num_unique_words |
def get_taskid_atmptn(key_name):
"""
get jediTaskID and attemptNr from task attempt key name
"""
tmp_list = key_name.split('#')
jediTaskID = int(tmp_list[0])
attemptNr = int(tmp_list[1])
return jediTaskID, attemptNr |
def block_distance(p1, p2):
"""
Returns the Block Distance of a particular point from rest of the points in dataset.
"""
distance = 0
for i in range(len(p1)-1):
distance += abs(p1[i]-p2[i])
return distance |
def build_subprotocol_list(protocols):
"""
Unparse a ``Sec-WebSocket-Protocol`` header.
This is the reverse of :func:`parse_subprotocol_list`.
"""
return ', '.join(protocols) |
def gauss(x, sig):
"""
Samples the value at a single point from the Gaussian Curve, parameterized
using the sig value as its sigma.
x - Relative positioning along the curve, which is centered at x = 0.
sig - Sigma parameter.
"""
from math import pi as PI;
from math import exp;
return exp(-(x ** 2 / 2 * sig ** 2)) / (2 * PI * sig ** 2) |
def digits_to_int(D,B=10,bigendian=False):
"""
Convert a list of digits in base B to an integer
"""
n = 0
p = 1
if bigendian:
for d in D:
n += d*p
p *= B
return n
else:
for d in reversed(D):
n += d*p
p *= B
return n |
def get_wonderful_numbers(given_str):
"""
Return all of the wonderful numbers for the given numeric string
"""
wonderfuls = []
# get permutations
# add permutation to wonderfuls if greater than given_str
return wonderfuls |
def extract_first_authors_name(author_list):
"""
Extract first name from a string including list of authors in form Author1; Author2; ...; AuthorN
"""
return author_list.split(';')[0].split(' ')[0] |
def int_sqrt(n: int) -> int:
"""
Returns the integer square root of n.
:param n: an int value
:return: the integer square root
"""
try:
from math import isqrt
return isqrt(n)
except ImportError:
# For Python <=3.7
if n < 0:
raise ValueError("Square root is not defined for negative numbers.")
if n == 0:
return 0
if n <= 3:
return 1
a = 1 << ((1 + n.bit_length()) >> 1)
while True:
b = (a + n // a) >> 1
if b >= a:
return a
a = b |
def replace_list(text_string: str):
"""Quick formatting of Gamma point"""
substitutions = {'GAMMA': u'$\\Gamma$'}
for item in substitutions.items():
text_string = text_string.replace(item[0], item[1])
return text_string |
def extrap_total_training_time(time_unit, percent_complete):
"""
10 * (1/0.01) => 100
#
10 seconds in 1% 0.01
->
1000 seconds in 100% 1.0
:param time_unit:
:param percent_complete:
:return:
"""
assert 0. <= percent_complete <= 1.
total_time_unit = time_unit * (1./percent_complete)
return total_time_unit |
def m12_to_mc(m1, m2):
"""convert m1 and m2 to chirp mass"""
return (m1 * m2) ** (3.0 / 5.0) / (m1 + m2) ** (1.0 / 5.0) |
def fp_field_name(name):
"""Translates literal field name to the sanitized one feedparser will use."""
return name.replace(':', '_').lower() |
def worker_should_exit(message):
"""Should the worker receiving 'message' be terminated?"""
return message['should_exit'] |
def format_size(bytes_):
"""
Format a size in bytes with binary SI prefixes.
:param bytes_:
:return:
"""
suffixes = ['B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB']
index = 0
start = 1
while bytes_ >= start * 1024:
start *= 1024
index += 1
return "%.2f %s" % (bytes_ / start, suffixes[index]) |
def _select_index_code(code):
"""
1 - sh
0 - sz
"""
code = str(code)
if code[0] == '3':
return 0
return 1 |
def sleeping_func(arg, secs=10, result_queue=None):
"""This methods illustrates how the workers can be used."""
import time
time.sleep(secs)
if result_queue is not None:
result_queue.put(arg)
else:
return arg |
def decimal_to_ip(ip_decimal):
"""
Submit a decimal ip value between 0 and 2*32 - 1.
Returns the ip_address as a zeros padded string: nnn.nnn.nnn.nnn
If ip_decimal is invalid returns -1
"""
# Test it is decimal and in range, else return -1
try:
ip_decimal = int(ip_decimal)
except ValueError as e:
print("ValueError: {}".format(e))
return -1
if ip_decimal < 0 or ip_decimal > 4294967295: #(2**32 - 1)
return -1
# Convert. E.g. 511 returns 000.000.001.255
s = ""
for i in reversed(range(4)):
s += "{:>03}.".format(ip_decimal // 256**i)
ip_decimal = ip_decimal % 256**i
return s[:-1]
"""
# To check function: decimal_to_ip()
test_data = [0,1,255,256,511,512,4294967294,4294967295,-1,4294967296,"qwerty"]
for i in range(len(test_data)):
print("{}: {}".format(test_data[i], decimal_to_ip(test_data[i])))
sys.exit()
""" |
def unzip(lll):
"""Does the opposite of zip"""
return list(zip(*lll)) |
def _to_datauri(
mimetype, data, charset: str = 'utf-8', base64: bool = False, binary: bool = True
) -> str:
"""
Convert data to data URI.
:param mimetype: MIME types (e.g. 'text/plain','image/png' etc.)
:param data: Data representations.
:param charset: Charset may be any character set registered with IANA
:param base64: Used to encode arbitrary octet sequences into a form that satisfies the rules of 7bit. Designed to be efficient for non-text 8 bit and binary data. Sometimes used for text data that frequently uses non-US-ASCII characters.
:param binary: True if from binary data False for other data (e.g. text)
:return: URI data
"""
parts = ['data:', mimetype]
if charset is not None:
parts.extend([';charset=', charset])
if base64:
parts.append(';base64')
from base64 import encodebytes as encode64
if binary:
encoded_data = encode64(data).decode(charset).replace('\n', '').strip()
else:
encoded_data = encode64(data).strip()
else:
from urllib.parse import quote_from_bytes, quote
if binary:
encoded_data = quote_from_bytes(data)
else:
encoded_data = quote(data)
parts.extend([',', encoded_data])
return ''.join(parts) |
def match_outside(x, y, i, j):
"""
Match whether the token is outside the entity
:param x: The start of the entity
:param y: The end of the entity
:param i: The start of the token
:param j: The end of the token
"""
return i <= x and j >= y |
def normalize_url(url):
"""Return url after stripping trailing .json and trailing slashes."""
if url.endswith('.json'):
url = url[:-5]
if url.endswith('/'):
url = url[:-1]
return url |
def try_except(success, failure):
"""A try except block as a function.
Note:
This is very similar to toolz.functoolz.excepts, but this version is
simpler if you're not actually passing in any arguments. So, I can't
bring myself to change existing uses of this to use
toolz.itertoolz.excepts
Args:
success (function): 0 argument function to try first
failure: Either a function to run in the case of failure, or a value to
return in the case of failure.
Returns:
The result of success, unless success raised an exception. In that
case, the result or value of failure, depending on whether failure is a
function or not.
Examples:
>>> try_except(lambda: 0/0, 'kasploosh')
'kasploosh'
>>> try_except(lambda: 0/1.0, 'kasploosh')
0.0
>>> try_except(lambda: 0/0, lambda: 'kasploosh')
'kasploosh'
"""
# Using toolz.functoolz.excepts:
# if not callable(failure):
# eat_argument_failure = lambda _: failure
# else:
# eat_argument_failure = lambda _: failure()
# return excepts(Exception, lambda _: success(), failure)
# Original implementation:
try:
return success()
except:
if callable(failure):
return failure()
else:
return failure |
def _TaskPathToId(path):
"""Transforms the pathname in YAML to an id for a task.
Args:
path: Path name.
Returns:
id of the task.
"""
return '<joiner>'.join(path) |
def _expSum(x, iterations=1000):
"""Calculate e^x using power series.
exp x := Sum_{k = 0}^{inf} x^k/k! = 1 + x + x^2/2! + x^3/3! + x^4/4! + ...
Which can be rewritten as:
= 1 + ((x/1)(1 + (x/2)(1 + (x/4)(...) ) ) )
This second way of writting it is easier to calculate than the first one
as it does not need to directly calculate the factorial of each term.
Arguments:
iterations: Times to iterate over the exponential power series.
The minimum valid number is 1 (one), and it'll return the
equivalent to perform 1 + x.
Default is 1000 as it does not take much time to complete
(even for big numbers such as e^500) and going beyond that
does not make a significative difference.
e^500, e^2, e^50, and some other tried examples get the
same number up to 14 decimal places using 1000 (the
default) and 1000000 (the default value squared)
iterations.
Returns:
Floating point number.
Raises:
ArithmeticError: When trying to iterate less than one time.
"""
if type(x) is (not int or not float):
raise ArithmeticError('Please provide an int or float.')
if (iterations < 1):
raise ArithmeticError('At least one iteration needed to calculate e^x')
# e^0 = 1
if (x == 0):
return float(1.0)
isNegative = False
# The algorithm always calculates e^x (x > 0) and then divides 1 by the
# result if x < 0. This avoids missing extra precission due to floating
# point.
if (x < 0):
isNegative = True
x *= -1
result = float(1.0)
for num in range(iterations, 0, -1):
# In the power series: = 1 + ((x/1)(1 + (x/2) (1 + (x/4) (...) ) ) )
# x/num is the same as (x/4), or (x/2), (x/1); result is the rightmost
# part of the series, which has been already calculated.
result = 1 + ((x * result)/num)
if isNegative:
result = float(1/result)
return float(result) |
def func_b(y):
"""
This function takes one param y
:param y: Takes any input
:return: Returns the same input
"""
print("Inside func_b")
return y |
def create_inventory(items):
"""
:param items: list - list of items to create an inventory from.
:return: dict - the inventory dictionary.
"""
return {item: items.count(item) for item in list(dict.fromkeys(items))} |
def _deep_merge_dictionaries(a, b, path=None):
"""merges b into a. Adapted from
https://stackoverflow.com/questions/7204805/how-to-merge-dictionaries-of-dictionaries/7205107#7205107"""
if path is None:
path = []
for key in b:
if key in a:
if isinstance(a[key], dict) and isinstance(b[key], dict):
_deep_merge_dictionaries(a[key], b[key], path + [str(key)])
else:
a[key] = b[key]
else:
a[key] = b[key]
return a |
def get_parent_language_code(parent_object):
"""
.. versionadded:: 1.0
Return the parent object language code.
Tries to access ``get_current_language()`` and ``language_code`` attributes on the parent object.
"""
if parent_object is None:
return None
try:
# django-parler uses this attribute
return parent_object.get_current_language()
except AttributeError:
pass
try:
# E.g. ContentItem.language_code
return parent_object.language_code
except AttributeError:
pass
return None |
def list_contains(lst: list, items_to_be_matched: list) -> bool:
"""Helper function for checking if a list contains any elements of another list"""
for item in items_to_be_matched:
if item in lst:
return True
return False |
def _replace_third_person(narrative: str, given_name: str, narr_metadata: dict) -> str:
"""
Update the text to change 3rd person instances of full name, given name + maiden name and
given name + surname to "Narrator", and the possessive form to "Narrator's".
@param narrative: String holding the narrative text
@param given_name: The narrator's given name
@param narr_metadata: Dictionary of metadata information - Keys are: Source,Title,Person,Type,
Given,Given2,Surname,Maiden,Maiden2,Gender,Start,End,Remove,Header,Footer
@return: String with the updated text
"""
new_text = narrative
maiden_name = narr_metadata['Maiden']
maiden2_name = narr_metadata['Maiden2']
surname = narr_metadata['Surname']
new_text = new_text.replace(f"{given_name}'s ", "Narrator's ")
if maiden_name and surname:
new_text = new_text.replace(f"{given_name} ({maiden_name}) {surname}'s ", "Narrator's ").\
replace(f"{given_name} {maiden_name} {surname}'s ", "Narrator's ")
new_text = new_text.replace(f"{given_name} ({maiden_name}) {surname} ", 'Narrator ').\
replace(f"{given_name} {maiden_name} {surname} ", 'Narrator ')
if maiden2_name and surname:
new_text = new_text.replace(f"{given_name} ({maiden2_name}) {surname}'s ", "Narrator's ").\
replace(f"{given_name} {maiden2_name} {surname}'s ", "Narrator's ")
if surname and not maiden_name and not maiden2_name:
new_text = new_text.replace(f"{given_name} {surname}'s ", "Narrator's ").\
replace(f"{given_name} {surname} ", 'Narrator ')
new_text = new_text.replace(f"{given_name} ", 'Narrator ')
return new_text |
def not_equal(a,b):
""" return 1 if True, else 0 """
if(a != b):
return 1
else:
return 0 |
def even_modulo(value: int) -> int:
"""
Returns a value if it is even
:param value: the value to check
:return: the even value or -1 if not even
"""
if not value % 2:
return value
return -1 |
def get_xpath_parent(xpath, level=1):
""" Get the parent xpath at any level, 1 is parent just above the input xpath.
Args:
xpath (str): Input xpath
level (int, optional): Parent level. Defaults to 1.
Returns:
str: Parent xpath
"""
if not xpath.startswith("/"):
raise ValueError('"get_xpath_parent" must recieve an xpath as argument!')
if len(xpath.split("/")) - 1 <= level:
raise ValueError("No parent available at this level")
return "/".join(xpath.split("/")[:-level]) |
def convertToRavenComment(msg):
"""
Converts existing comments temporarily into nodes.
@ In, msg, string contents of a file
@ Out, string, converted file contents as a string (with line seperators)
"""
msg=msg.replace('<!--','<ravenTEMPcomment>')
msg=msg.replace('-->' ,'</ravenTEMPcomment>')
return msg |
def _parent(node):
"""
Args:
node: index of a binary tree node
Returns:
index of node's parent
"""
return (node - 1) // 2 |
def mock_dag_literal_module_complex():
"""Creates a mock DAG."""
dag_ldict = [
{
"frame": {"name": "A", "type": "function"},
"metrics": {"time (inc)": 130.0, "time": 1.0, "module": "main"},
"children": [
{
"frame": {"name": "B", "type": "function"},
"metrics": {"time (inc)": 20.0, "time": 1.0, "module": "foo"},
"children": [
{
"frame": {"name": "C", "type": "function"},
"metrics": {
"time (inc)": 6.0,
"time": 1.0,
"module": "graz",
},
"children": [
{
"frame": {"name": "D", "type": "function"},
"metrics": {
"time (inc)": 1.0,
"time": 1.0,
"module": "graz",
},
}
],
}
],
},
{
"frame": {"name": "E", "type": "function"},
"metrics": {"time (inc)": 55.0, "time": 1, "module": "bar"},
},
],
}
]
return dag_ldict |
def find_duplicate_num_array(l1):
""" an array contains n numbers ranging from 0 to n-1. there are some numbers duplicated, but it is
not clear how many. this code find a duplicate number in the array. """
""" A naive solution is to sort the input array, costing O(nlogn). Another solution is the utilization of a hash set. When the number is scanned, it is either in or not. It costs O(n) auxiliary memory to accomodate a hash set. A third solution, that only costs O(1) is consider that indexes in an array with length n are in the range n-1. If there were no duplication in the n numbers from 0 to n-1, we could rearange them sorted, so that each i has its ith number. Since there are duplicates, some locations are occupied by multiple numbers, other are vacant. So every number is scanned one by one, if it the number is not in the right i, it is compared to that from i, and the duplicate can be found, or we swap. Continue until a duplicate is found."""
for i in range(len(l1)):
if l1[i] == i: continue
elif l1[i] < 0 or l1[i] > len(l1)-1:
return None
elif l1[i] == l1[l1[i]]:
return True
else:
aux = l1[l1[i]]
l1[l1[i]] = l1[i]
l1[i] = aux
else:
return False |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.