content stringlengths 42 6.51k |
|---|
def cdm2_to_nl(m):
"""Convert candelas/m2 to nl.
Formula taken from https://converter.eu/luminance/#1_Candela/Square_Meter_in_Lambert
"""
return 0.000314159265358979*m*(1000000000) |
def replace_pad(l, new_symbol='-'):
"""<pad> refers to epsilon in CTC replace with another symbol for readability"""
new_l = []
for x in l:
if x == "<pad>":
new_l.append(new_symbol)
else:
new_l.append(x)
return new_l |
def filter_output_columns(output_columns, filter_columns):
"""
Filters a list of columns and only keeps those present in a list of allowed columns.
Returns original list of columns if no allowed columns specified.
:param output_columns: a column list to filter
:param filter_columns: a list of allowed columns
:return: a filtered list of columns
"""
if filter_columns:
return [column for column in output_columns if column in filter_columns]
return output_columns |
def tags(fs):
"""Extract tags from a collection of features."""
return type(fs)(f.tag for f in fs) |
def round_time_worked(time_worked, block_size=15 * 60):
"""
Round a period of time worked to the nearest block.
Typically this is used to round time worked to the closest 15 minute
block.
Args:
time_worked:
The time period to round, in seconds.
block_size:
The block size to round to, in seconds. Defaults to 15
minutes.
Returns:
The time worked, in seconds, rounded to the nearest block.
"""
time_worked += block_size / 2
return time_worked - (time_worked % block_size) |
def partition(mylist, p, r):
"""
Purpose: return a position of the pivot
Invariant: after the call, everything left of pivot is <= pivot
everything right of pivot is >= pivot
"""
# what if the list passed is empty?
# what if the list passed is singleton?
if r == p:
return r
smaller = []
greater = []
pivot = mylist[r]
for item in mylist[p:r]:
if item > pivot:
greater.append(item)
else:
smaller.append(item)
pivotPos = p + smaller.__len__()
# merge into a long list:
# put back into the original list
currentPos = p
for item in smaller:
mylist[currentPos] = item
currentPos += 1
mylist[pivotPos] = pivot
currentPos += 1
for item in greater:
mylist[currentPos] = item
currentPos += 1
return pivotPos |
def bytes_isalpha(x: bytes) -> bool:
"""Checks if given bytes object contains only alphabetic elements.
Compiling bytes.isalpha compiles this function.
This function is only intended to be executed in this compiled form.
Args:
x: The bytes object to examine.
Returns:
Result of check.
"""
if len(x) == 0:
return False
for i in x:
if not (ord('A') <= i <= ord('Z') or ord('a') <= i <= ord('z')):
return False
return True |
def decode(text):
"""Decode DNA"""
dna = []
end = len(text) - 1
for i, char in enumerate(text):
if char.isnumeric():
continue
elif i == end:
dna.append(char)
elif text[i + 1].isnumeric():
dna.append(char * int(text[i + 1]))
else:
dna.append(char)
return ''.join(dna) |
def dot(v,w):
"""v_1*w_1+...+v_n*w_n"""
return sum(v_i*w_i for v_i,w_i in zip(v,w)) |
def substract(v1, v2):
"""
Returns the difference of a two 2-D vectors.
"""
return (v2[0] - v1[0], v2[1] - v1[1]) |
def contains(list1, list2):
""" Check if some elements of list1 appear in list2
Return the intersection of the two lists
"""
return [ it1 for it1 in list1 if it1 in list2 ] |
def find_all_indexes(text=str, pattern=str) -> list:
"""Return a list of starting indexes of all occurrences of pattern in text,
or an empty list if not found.
- Best case: O(1) If there is no pattern and one char in the text
- Worse Case: O(n) if we have to loop to the end
- If there is a pattern:
- O(n*j) - n being the outer loop and j being the inner loop"""
assert isinstance(text, str), 'text is not a string: {}'.format(text)
assert isinstance(pattern, str), 'pattern is not a string: {}'.format(text)
if not pattern:
return [i for i in range(len(text))]
# * \\ Does not utilize string slicing (FASTER IN THE LONG RUN) // *
index_pos = []
for i in range(len(text) - len(pattern) + 1):
for j in range(len(pattern)):
if text[i+j] != pattern[j]:
break
else:
index_pos.append(i)
return index_pos
# * \\ Utilizes string slicing (SLOWER because it has to slice)// *
# for i in range(len(text) - len(pattern) + 1):
# if text[i:(i + len(pattern))] == pattern:
# index_pos.append(i)
# continue
# return index_pos |
def _repr_strip(mystring):
"""
Returns the string without any initial or final quotes.
"""
r = repr(mystring)
if r.startswith("'") and r.endswith("'"):
return r[1:-1]
else:
return r |
def myfuncPrimeSieve(n):
"""
This function generates and returns prime numbers from 2 up to n
via the Sieve of Eratosthenes algorithm.
Example of usage:
getAns = myfuncPrimeSieve( 20 )
print(getAns)
"""
thelist = list(range(3, n, 2)) #generates odd numbers starting from 3
theprimes = [2]
while thelist: # True as long as list thelist has elements
temp = thelist.pop(0)
theprimes = theprimes + [temp]
if (temp*temp > n):
theprimes = theprimes + thelist
thelist = []
else:
for x in thelist:
if (x % temp) == 0:
thelist.remove(x)
return theprimes |
def _to_list(key_values_dict, sort = True):
"""Converts a `dict` to a flattened key-value `list`.
Args:
key_values_dict: A `dict` whose key-values will be written to the
`list`.
sort: Optional. Specifies whether the keys should be sorted before
serializing the key-value pairs to the `list`.
Returns:
A `list` consisiting of the keys at even index numbers and the
corresponding value is the next item.
"""
keys = key_values_dict.keys()
if sort:
keys = sorted(keys)
iterable = []
for key in keys:
iterable.extend([key, key_values_dict[key]])
return iterable |
def non_adjusted_weight(k0, k1):
"""
Normalised un-adjusted weight based on kappas.
:param k0: Kappa 0, the primary kappa for this weight computation
:param k1: Kappa 1, secondry kappa (alternate cue)
"""
return k0 / (k1 + k0) |
def strComp(s1, s2):
"""Compares string1 vs string2
returns a tuple (a, b)
a = number of common caracters at the same position
b = number of common caracters at different position
"""
a, b = 0, 0
## Count of common caracters at the same position
i = 0
while i < len(s1) and i < len(s2):
if s1[i] == s2[i]:
a += 1
s1 = s1[:i] + s1[i+1:]
s2 = s2[:i] + s2[i+1:]
else:
i += 1
## Count of common caracters at different position
i = 0
while i < len(s1) and i < len(s2):
j = s2.find(s1[i])
if j != -1:
b += 1
s1 = s1[:i] + s1[i+1:]
s2 = s2[:j] + s2[j+1:]
else:
i += 1
return (a, b) |
def format_metrics(metrics):
"""
Method to return dict with formatted metrics keys.
From tuple of strings to string with dunder ('__') between values
:param metrics: unformatted metrics. keys looks like ('test', 'AUC')
:type metrics: dict
:return: formatted metrics. keys looks like 'test__AUC'
:rtype: dict
"""
formatted_metrics = dict()
for key, value in metrics.items():
formatted_metrics['{}__{}'.format(key[0], key[1])] = value
return formatted_metrics |
def bounding_box(coords):
"""Runs through a collection of x,y tuple pairs and
extracts the values (xmin,ymin),(xmax,ymax)."""
xmin = coords[0][0] ; xmax = coords[0][0]
ymin = coords[0][1] ; ymax = coords[0][1]
for xy in coords[1:]:
x, y, *_ = xy # if coordinates are not 2D then if only considers first two
if x < xmin: xmin = x
if x > xmax: xmax = x
if y < ymin: ymin = y
if y > ymax: ymax = y
return [(xmin, ymin),(xmax, ymax)] |
def _D0N2_Deg1_2_linear(k1, k2):
""" from 1d knots, return int_0^2 x b**2(x) dx """
return (k2 - k1) / 6. |
def handler(msg):
"""
Writes input argument back-out to the standard output returning input as
output.
Generated by: `SQL Server Big Data Cluster`
:param msg: The message to echo.
:type msg: str
:return: The input message `msg` as output `out`.
"""
print(msg)
out = msg
return out |
def make_elastic_uri(schema: str, user: str, secret: str, hostname: str, port: int) -> str:
"""Make an Elasticsearch URI.
:param schema: the schema, e.g. http or https.
:param user: Elasticsearch username.
:param secret: Elasticsearch secret.
:param hostname: Elasticsearch hostname.
:param port: Elasticsearch port.
:return: the full Elasticsearch URI.
"""
return f"{schema}://{user}:{secret}@{hostname}:{port}" |
def convert(name: str) -> str:
"""Convert path name into valid JSON.
Parameters
----------
name : str
a path name
Returns
-------
str
valid JSON path
"""
if ('-' in name or ' ' in name):
return '["{}"]'.format(name[1:])
return name |
def sectionNofTotal (inputList, currentSection, numSections):
"""Returns the appropriate sublist given the current section
(1..numSections)"""
currentSection -= 1 # internally, we want 0..N-1, not 1..N
size = len (inputList)
perSection = size // numSections
extra = size % numSections
start = perSection * currentSection
num = perSection
if currentSection < extra:
# the early sections get an extra item
start += currentSection
num += 1
else:
start += extra
stop = start + num
return inputList[ start:stop ] |
def what(func, addr):
"""Return the item for which we are looking."""
if func:
return "func '%s'" % func
return "address '%s'" % hex(addr) |
def set_up_default_claims(clean_up=False):
"""Block of text to populate a Text widget."""
claims = ["this-is-a-fake-claim",
"livestream-tutorial:b",
"abcd0000efgh0000ijkl0000mopq0000rstu0000",
"8e16d91185aa4f1cd797f93d7714de2a22622759",
"LBRYPlaylists#d"]
if clean_up:
claims = ["abcd0000efgh0000ijkl0000mopq0000rstu0000",
"LBRYPlaylists#d",
"this-is-a-fake-claim",
"livestream-tutorial:b",
"8e16d91185aa4f1cd797f93d7714de2a22622759"]
claims = "\n".join(claims)
return claims |
def get_slice_stride(index_slice, dim_size):
"""Get slice stride info"""
step = 1 if index_slice.step is None else index_slice.step
start_default = 0
stop_default = dim_size
if step < 0:
start_default = -1
stop_default = -(dim_size + 1)
start = start_default if index_slice.start is None else index_slice.start
stop = stop_default if index_slice.stop is None else index_slice.stop
return start, stop, step |
def get_label_color(status):
"""
Get a customized color of the status
:param status: The requested status to get a customized color for
:return: customized color
"""
colors = {'NEW':'grey',
'ASSIGNED':'blue',
'OPEN': 'orange',
'FIXED': 'purple',
'RETEST':'cyan',
'REOPENED':'orange',
'VERIFIED': 'green',
'BLOCKED': 'red',
'CLOSED':'black',
}
return colors[status] |
def semicircles_to_degrees(semicircles):
"""Positional data conversion for *.fit files
https://github.com/kuperov/fit/blob/master/R/fit.R
"""
return (semicircles * 180 / 2**31 + 180) % 360 - 180 |
def can_collapse(row):
"""
returns true if the given row
can be collapsed to the left
can also be a column
"""
for a,b in zip(row[1:], row):
if a==0:
continue
if b==0 or a==b:
return True
return False |
def _read_varint(raw_hex):
"""
Reads the weird format of VarInt present in src/serialize.h of bitcoin core
and being used for storing data in the leveldb.
This is not the VARINT format described for general bitcoin serialization
use.
"""
n = 0
pos = 0
while True:
data = raw_hex[pos]
pos += 1
n = (n << 7) | (data & 0x7f)
if data & 0x80 == 0:
return n, pos
n += 1 |
def get_sympy_short_version(version):
"""
Get the short version of SymPy being released, not including any rc tags
(like 0.7.3)
"""
parts = version.split('.')
# Remove rc tags
# Handle both 1.0.rc1 and 1.1rc1
if not parts[-1].isdigit():
if parts[-1][0].isdigit():
parts[-1] = parts[-1][0]
else:
parts.pop(-1)
return '.'.join(parts) |
def get_skolem(base_url: str, count: int) -> str:
"""Get skolem according to base URL."""
return base_url + ".well-known/skolem/" + str(count) |
def format_num(val):
"""Return a suitable format string depending on the size of the value."""
if val > 50:
return ".0f"
if val > 1:
return ".1f"
else:
return ".2f" |
def merge_sort_counting(A):
"""Perform Merge Sort and return #comparisons."""
aux = [None] * len(A)
def rsort(lo, hi):
if hi <= lo:
return (0,0)
mid = (lo+hi) // 2
(lefts, leftc) = rsort(lo, mid)
(rights, rightc) = rsort(mid+1, hi)
(nswap, ncomp) = merge(lo, mid, hi)
return (lefts+rights+nswap, leftc+rightc+ncomp)
def merge(lo, mid, hi):
# copy results of sorted sub-problems into auxiliary storage
aux[lo:hi+1] = A[lo:hi+1]
i = lo # starting index into left sorted sub-array
j = mid+1 # starting index into right sorted sub-array
numc = 0
nums = 0
for k in range(lo, hi+1):
if i > mid:
if A[k] != aux[j]: nums += 0.5
A[k] = aux[j]
j += 1
elif j > hi:
if A[k] != aux[i]: nums += 0.5
A[k] = aux[i]
i += 1
elif aux[j] < aux[i]:
numc += 1
if A[k] != aux[j]: nums += 0.5
A[k] = aux[j]
j += 1
else:
numc += 1
if A[k] != aux[i]: nums += 0.5
A[k] = aux[i]
i += 1
return (nums, numc)
return rsort( 0, len(A)-1) |
def _is_json(q):
"""Check if q is JSON.
Parameters
----------
q : str
Query string.
Returns
-------
bool
True if q starts with "{" and ends with "}".
"""
return q.strip().startswith("{") and q.strip().endswith("}") |
def get_rna_types_from(xrefs, name):
"""
Determine the rna_types as annotated by some database.
Parameters
----------
xrefs : iterable
The list of xrefs to fitler to extract the rna types from.
name : str
The name of the database to use.
Returns
-------
rna_types : set
A set of rna types that is annotated by the given database.
"""
rna_types = set()
for xref in xrefs:
if xref.db.name == name:
rna_types.add(xref.accession.get_rna_type())
return rna_types |
def find_first(d, aliases, default="<unknown>"):
"""
Returns the value of the first key found in "aliases"
"""
for a in aliases:
if a in list(d.keys()):
return d[a]
return default |
def write_int_ranges(int_values, in_hex=True, sep=" "):
"""From a set or list of ints, generate a string representation that can
be parsed by parse_int_ranges to return the original values (not order_preserving)."""
if not int_values:
return ""
num_list = []
int_values = iter(sorted(int_values))
start = prev = next(int_values)
single_fmt = "%04x" if in_hex else "%d"
pair_fmt = single_fmt + "-" + single_fmt
def emit():
if prev == start:
num_list.append(single_fmt % prev)
else:
num_list.append(pair_fmt % (start, prev))
for v in int_values:
if v == prev + 1:
prev += 1
continue
else:
emit()
start = prev = v
emit()
return sep.join(num_list) |
def flop_gemm(n, k):
"""# of + and * for matmat of nxn matrix with nxk matrix, with accumulation
into the output."""
return 2*n**2*k |
def hypara_check(start, end, num_data):
"""true:ok, false:out"""
ans = True
if start > end:
ans = False
print("####### INVERSE start <=> end ??")
elif (start > num_data) or (end > num_data):
ans = False
print("####### PLEASE INPUT NUMBER:(start,end) UNDER " + str(num_data))
return ans |
def list_to_dict(dicts):
""" Convert a list of dictionaries to a dictionary of list """
new_dict = dict()
if isinstance(dicts, list):
for key in dicts[0]:
new_dict[key] = [d[key] for d in dicts]
return new_dict |
def flip_ith_occurrence_of_zero(given_string, index):
"""
:param given_string:
:param index:
:return:
"""
local_index = 0
string_builder = ""
for item in given_string:
if item == "0":
local_index += 1
if local_index == index:
string_builder += "1"
else:
string_builder += item
# print("Given string: {}".format(given_string))
# print("Given index: {}".format(index))
# print("Flipped string: {}".format(string_builder))
return string_builder |
def fmt_dft_token(val):
"""Generate obfuscated default token argument description
This secondary utility function is supporting formatting of command line argument help string
"""
if val is None:
return ""
token_len = len(val)
char_cnt = max(int((token_len-4)/6), 0)
token = "{0:s}{1:s}{2:s}".format(
val[:char_cnt], "*"*(token_len-char_cnt*2), val[token_len-char_cnt:])
return " (default: {0})".format(token) |
def parse_bdist_wininst(name):
"""Return (base.css,pyversion) or (None,None) for possible .exe name"""
lower = name.lower()
base, py_ver, plat = None, None, None
if lower.endswith('.exe'):
if lower.endswith('.win32.exe'):
base = name[:-10]
plat = 'win32'
elif lower.startswith('.win32-py', -16):
py_ver = name[-7:-4]
base = name[:-16]
plat = 'win32'
elif lower.endswith('.win-amd64.exe'):
base = name[:-14]
plat = 'win-amd64'
elif lower.startswith('.win-amd64-py', -20):
py_ver = name[-7:-4]
base = name[:-20]
plat = 'win-amd64'
return base, py_ver, plat |
def numToLetter(N, ABC=u'ABCDEFGHIJKLMNOPQRSTUVWXYZ' ):
"""
Converts a number in to a letter, or set of letters, based on the contents of
ABC. If ABC contains the alphabet (which is the default behaviour) then for a
number n this will result in the same string as the name of the nth column in
a normal spreadsheet.
INPUTS
N - integer - any number.
OPTIONAL INPUTS
ABC - string - any string of characters (or any other symbols I believe).
OUTPUTS
L - string - the number converted to a string.
EXAMPLES
numToLetter(1)
u'A'
numToLetter(26)
u'Z'
numToLetter(27)
u'AA'
numToLetter(345)
u'MG'
numToLetter(345, ABC='1234567890')
u'345'
"""
L = ''
sA = len(ABC)
div = int(N)
while div > 0:
R = int((div-1)%sA)
L = ABC[R] + L
div = int((div-R)/sA)
return L |
def isTIFF(filename: str) -> bool:
"""Check if file name signifies a TIFF image."""
if filename is not None:
if(filename.casefold().endswith('.tif') or filename.casefold().endswith('.tiff')):
return True
return False |
def set_lineage_cube(data: dict, dict_tables: dict):
"""
"name": "",
"description": "",
"columns": [...],
"partitions": [...],
"measures": [...],
"annotations": [...]
"""
print()
print(79 * '*')
print(f"Configuring parameters in {(data['model']['name'])}")
print(79 * '*')
for table in range(0, len(data['model']['tables'])):
print(f"\n----- table = {table + 1} {data['model']['tables'][table]['name']} -----")
# description -> data lineage
data['model']['tables'][table]['description'] = \
dict_tables.get(data['model']['tables'][table]['name'].lower())
for col in range(0, len(data['model']['tables'][table]['columns'])):
print(f"col = {col + 1} {(data['model']['tables'][table]['columns'][col]['name'])}")
data['model']['tables'][table]['columns'][col]['description'] = \
dict_tables.get(data['model']['tables'][table]['name'].lower())
print(data['model']['tables'][table]['columns'][col]['description'])
return data |
def ka_cont(T):
""" Thermal conductivity of air, neglecting non-continuum effects.
See :func:`ka` for details.
Parameters
----------
T :
ambient air temperature surrounding droplet, K
Returns
-------
float
:math:`k_a(T)` in J/m/s/K
See Also
--------
ka : includes correction for non-continuum effects.
"""
return 1e-3*(4.39 + 0.071*T) |
def lmap(f, x):
"""list(map(f, x)). Converts a map into a list containing (key,value) pairs."""
return list(map(f, x)) |
def va_from_string(value):
"""
Convert HEX string to int
:param str value: int as string
:return int: virtual address
"""
try:
return int(value.rstrip("L"), 16)
except ValueError:
return 0 |
def prettify_url(url):
"""Return a URL without its schema
"""
if not url:
return url
split = url.split('//', 1)
if len(split) == 2:
schema, path = split
else:
path = url
return path.rstrip('/') |
def largest_prime_factor(n: int) -> int:
"""
Gets largest prime factor of :param n:
"""
largest = 1
for d in range(2, n+1):
if n % d == 0:
largest = max(largest, d)
while n % d == 0:
n //= d
if d * d > n:
# n doesnt have at two non-trivial divisors here
break
# n may be 1 or prime by this point
largest = max(largest, n)
return largest |
def kma(lbm):
"""
The Katch-McArdle Formula for resting daily energy expenditure (RDEE). This formula takes lean body mass/fat-free mass (in kilograms) as the only argument.
McArdle, W (2006). Essentials of Exercise Physiology. Lippincott Williams & Wilkins. p. 266. ISBN 9780495014836.
"""
return 370 + (21.6 * lbm) |
def parse_line(line):
"""
line is in the format distance,zipcode,city,state,gender,race,income,price
"""
line = line.strip().split(",")[3:]
state = str(line[0])
gender = str(line[1])
race = str(line[2])
income = str(line[3])
price = str(line[4])
return [state, gender, race, income, price] |
def get_points_to_next_level(current_level):
""" returns the number of average points needed to advance to the next level """
if current_level == 1:
return 50
elif current_level == 2:
return 125
elif current_level == 3:
return 225 |
def deblank(s):
"""
Returns: s but with blanks removed
Parameter: s the string to edit
Precondition s is a string
for example: deblank(' 1 23 4') returns '1234'
"""
if s == '':
return s
elif len(s) == 1:
if s != ' ':
return s
else:
return ''
left = deblank(s[0])
right = deblank(s[1:])
return left + right |
def fs_join(*args):
"""Like os.path.join, but never returns '\' chars"""
from os.path import join
return join(*args).replace('\\','/') |
def glossary_term_decorator(props):
"""
Draft.js ContentState to database HTML.
"""
# return DOM.create_element('span', {
# 'data-term_id': props['term_id'],
# }, props['children'])
return '{}'.format(
props['children']
) |
def make_mmi_cmd(fa):
"""Return a minimap2 cmd string to build mmi index.
"""
return 'minimap2 -x map-pb -d {fa}.mmi {fa}'.format(fa=fa) |
def coord(row, col):
""" returns coordinate values of specific cell within Sudoku Puzzle"""
return row*9+col |
def ns_between(l, r, ns):
"""Checks if all ns are between l and r (inclusive)."""
return all(l <= n <= r for n in ns) |
def gbslve(shift, a, b):
"""this procedure performs elimination to solve for the
n-th component of the solution delta to the equation
(jn - shift*identity) * delta = en,
where en is the vector of all zeroes except for 1 in
the n-th position.
the matrix jn is symmetric tridiagonal, with diagonal
elements a(i), off-diagonal elements b(i). this equation
must be solved to obtain the appropriate changes in the lower
2 by 2 submatrix of coefficients for orthogonal polynomials."""
alpha = a[0] - shift
for ii in range(1,len(a)-1):
alpha = a[ii] - shift - b[ii-1]**2/alpha
return 1./alpha |
def _is_file_valid(name):
"""Decide if a file is valid."""
return not name.startswith('.') |
def generate_file_path(package_path, file_name):
"""
Dynamically generate full path to file, including filename and extension.
:param package_path: (array) ordered list of packages in path to test file
:param file_name: (string) name of the file w/ test, including the extension
:return: (string) full path to file, including filename and extension
"""
file_path = ""
for package in package_path:
file_path += package + "/"
return file_path + file_name |
def try_parse_ticket_ids(title):
"""Get ticket id from PR title.
Assumptions:
- ticket id or special prefix before PR title
- no whitespace before ticket id
- whitespace between ticket id and PR title
Transformations (for the worst case):
"ggrc-1234/1235: Do something" -> ["GGRC-1234", "GGRC-1235"]
Special prefixes:
"QUICK-FIX", "DOCS", "MERGE", "BACKMERGE"
Returns:
a list of string ticket ids.
"""
ticket = title.split()[0]
ticket = ticket.upper()
ticket = ticket.rstrip(":")
if ticket in ("QUICK-FIX", "DOCS", "MERGE", "BACKMERGE"):
return [ticket]
ticket = ticket.replace("/", ",")
tickets = []
for ticket in ticket.split(","):
if not ticket.startswith("GGRC-"):
ticket = "GGRC-" + ticket
tickets.append(ticket)
return tickets |
def get_dir_delta(beforelisting, afterlisting):
"""Determines which files were added, removed, or remained the same in a directory."""
deltas=[]
# Find files added.
for a in afterlisting:
added=1
for b in beforelisting:
added=added and b!=a
deltas.append((added, a))
# Find the files removed (if any):
for b in beforelisting:
removed=1
for a in afterlisting:
removed=removed and b!=a
if removed:
deltas.append((-1, b))
return deltas |
def find_cutlag(weight):
"""Compute the maximum valid lag time from trajectory weights.
Parameters
----------
weights : (n_frames,) ndarray
Weight of each configuration in a trajectory.
Returns
-------
int
Maximum valid lag time in units of frames.
"""
last = len(weight) - 1 # index of last element
# index of first nonzero element in the reversed list
# is the number of zeros at the end
for lag in range(len(weight)):
if weight[last - lag] != 0.0:
return lag
return len(weight) |
def m(x0: float, x1: float, y0: float, y1: float) -> float:
"""
Simple gradient function.
Parameters
----------
x0 : float
x co-ordinate at time 0.
x1 : float
x co-ordinate at time 1.
y0 : float
y co-ordinate at time 0.
y1 : float
y co-ordinate at time 1.
Returns
-------
grad : float
Gradient value.
Notes
-----
"""
grad = (y1 - y0) / (x1 - x0)
return grad |
def is_quoted(value):
"""
Return a single or double quote, if a string is wrapped in extra quotes.
Otherwise return an empty string.
"""
ret = ""
if (
isinstance(value, str)
and value[0] == value[-1]
and value.startswith(("'", '"'))
):
ret = value[0]
return ret |
def flatten(list):
"""Flatten a list of elements into a unique list
Author: Christophe Simonis
Examples:
>>> flatten(['a'])
['a']
>>> flatten('b')
['b']
>>> flatten( [] )
[]
>>> flatten( [[], [[]]] )
[]
>>> flatten( [[['a','b'], 'c'], 'd', ['e', [], 'f']] )
['a', 'b', 'c', 'd', 'e', 'f']
>>> t = (1,2,(3,), [4, 5, [6, [7], (8, 9), ([10, 11, (12, 13)]), [14, [], (15,)], []]])
>>> flatten(t)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
"""
def isiterable(x):
return hasattr(x, "__iter__")
r = []
for e in list:
if isiterable(e):
map(r.append, flatten(e))
else:
r.append(e)
return r |
def scale_up(threshold, dim):
"""Rescale up to actual values"""
out = int(dim * threshold)
return out |
def checked_etag(etag, *, allow_none=False):
"""Validate etag string to ensure propare comparison.
This function is used to assert that `DAVResource.get_etag()` does not add
quotes, so it can be passed as `ETag: "<etag_value>"` header.
Note that we also reject weak entity tags (W/"<etag_value>"), since WebDAV
servers commonly use strong ETags.
"""
if etag is None and allow_none:
return None
etag = etag.strip()
if not etag or '"' in etag or etag.startswith("W/"):
# This is an internal server error
raise ValueError(f"Invalid ETag format: '{etag!r}'.")
return etag |
def get_verify_listener_ports(module, listener_ports=None):
"""
Validate and get listener ports
:param module: Ansible module object
:param listener_ports: list of ports to for which backend server health status is required
:return: formatted listener ports
"""
if listener_ports:
if len(listener_ports) > 0:
for port in listener_ports:
try:
port = int(port)
except Exception as ex:
module.fail_json(msg='Invalid port value')
else:
listener_ports = None
return listener_ports |
def range_factorial(num):
"""Solution that iterates over a range"""
result = 1
i = iter(range(1, num + 1))
try:
while True:
result *= next(i)
except StopIteration:
pass
return result |
def classname(value, options=''):
"""
Returns classname.
If options is given, checks if class name is in there before returning,
else it returns None.
"""
cn = value.__class__.__name__.lower()
if not options or cn in options:
return cn
return '' |
def xor(x, y):
"""N.B.: not lazy like `or` ..."""
return bool(x) != bool(y) |
def _get_arg_index(line: str, cursor_pos: int) -> int:
"""Return which argument the cursor is currently on"""
arg_idx = -1
i = 0
while i < cursor_pos:
if line[i] == " ":
arg_idx += 1
# Multiple spaces are treated as a single delimiter
while i < cursor_pos and line[i] == " ":
i += 1
continue
i += 1
return arg_idx |
def find(elemento, lista):
"""Devuelve el indice donde se encuentra el @elemento en la @lista.
Si no lo encuentra devuelve -1.
"""
index = 0
while True:
try:
if lista[index] == elemento:
return index
except IndexError:
return -1
index += 1 |
def is_nvme_device(dev):
"""check whether the device path belongs to an NVMe drive. """
return "/dev/nvme" in dev |
def similar_values_iter(v1, v2, e=1e-6):
"""Return True if iterables v1 and v2 are nearly the same."""
if v1 == v2:
return True
for v1, v2 in zip(v1, v2):
if (v1 != v2) and ((abs(v1 - v2) / max(abs(v1), abs(v2))) > e):
return False
return True |
def is_true(str_value: str) -> bool:
"""Returns True if string represents True value else return False.
:param str_value: String to evaluate.
"""
return str_value.lower() in ("true", "yes", "1", "::ixnet::ok") |
def sample_frames_uniform(
frame_rate,
total_frame_count=None,
support=None,
fps=None,
max_fps=None,
always_sample_last=False,
):
"""Returns a list of frame numbers sampled uniformly according to the
provided parameters.
Args:
frame_rate: the video frame rate
total_frame_count (None): the total number of frames in the video
support (None): a ``[first, last]`` frame range from which to sample
fps (None): a frame rate at which to sample frames
max_fps (None): a maximum frame rate at which to sample frames
always_sample_last (False): whether to always sample the last frame
Returns:
a list of frame numbers, or None if all frames should be sampled
"""
if support is not None:
first, last = support
elif total_frame_count is None:
return None
else:
first = 1
last = total_frame_count
if frame_rate is None:
if support is None:
return None
return list(range(first, last + 1))
if last < first:
return []
ifps = frame_rate
if fps is not None:
ofps = fps
else:
ofps = ifps
if max_fps is not None:
ofps = min(ofps, max_fps)
if ofps >= ifps:
if support is None:
return None
return list(range(first, last + 1))
x = first
fn_last = first
beta = ifps / ofps
sample_frames = [x]
while x <= last:
x += beta
fn = int(round(x))
if fn_last < fn <= last:
sample_frames.append(fn)
fn_last = fn
if always_sample_last and fn_last < last:
sample_frames.append(last)
return sample_frames |
def html_escape(text: str) -> str:
"""Escape < and >."""
return text.replace("<", "<").replace(">", ">") |
def rescan(context, uri=None):
"""
*musicpd.org, music database section:*
``rescan [URI]``
Same as ``update``, but also rescans unmodified files.
"""
return {"updating_db": 0} |
def rgb_to_ansi256(r, g, b):
"""
Convert RGB to ANSI 256 color
"""
if r == g and g == b:
if r < 8:
return 16
if r > 248:
return 231
return round(((r - 8) / 247.0) * 24) + 232
ansi_r = 36 * round(r / 255.0 * 5.0)
ansi_g = 6 * round(g / 255.0 * 5.0)
ansi_b = round(b / 255.0 * 5.0)
ansi = 16 + ansi_r + ansi_g + ansi_b
return ansi |
def B1_rel_diff(v0w, b0w, b1w, v0f, b0f, b1f, prefact, weight_b0, weight_b1):
"""
Returns the reletive difference in the derivative of the bulk modulus.
THE SIGNATURE OF THIS FUNCTION HAS BEEN CHOSEN TO MATCH THE ONE OF ALL THE OTHER FUNCTIONS
RETURNING A QUANTITY THAT IS USEFUL FOR COMPARISON, THIS SIMPLIFIES THE CODE LATER.
Even though several inputs are useless here.
"""
return prefact*2*(b1w-b1f)/(b1w+b1f) |
def _get_pre(level):
"""Get prefix indicating a header GO or a user GO."""
if level == 0:
return ">"
if level == 1:
return "-"
return "" |
def sorted_maybe_numeric(x):
"""
Sorts x with numeric semantics if all keys are nonnegative integers.
Otherwise uses standard string sorting.
"""
all_numeric = all(map(str.isdigit, x))
if all_numeric:
return sorted(x, key=int)
else:
return sorted(x) |
def calculate_total_number_of_travel_requests_in_timetables(timetables):
"""
Calculate the total number of travel_requests in timetables.
:param timetables: [timetable_document]
:return: total_number_of_travel_requests: int
"""
total_number_of_travel_requests = 0
for timetable in timetables:
travel_requests = timetable.get('travel_requests')
number_of_travel_requests_of_timetable = len(travel_requests)
total_number_of_travel_requests += number_of_travel_requests_of_timetable
return total_number_of_travel_requests |
def __set_aperture(ap_in):
"""
Make sure that aperture dictionary has correct format.
Parameters
----------
ap_in: dict
Aperture as defined by user.
Returns
-------
ap_out: dict
Correctly formated and complete aperture dictionary
"""
sides = ['top', 'right', 'bottom', 'left']
ap_out = {}
for side in sides:
if ap_in and side in ap_in:
ap_out[side] = ap_in[side]
else:
ap_out[side] = 0
return ap_out |
def _from_hex(value):
"""INTERNAL. Gets a bytearray from hex data."""
return bytearray.fromhex(value) |
def walk(node, key_match):
"""recursive node walk, returns None if nothing found, returns the value if a key matches key_match"""
if isinstance(node, dict):
for key, item in node.items():
# print('searching {} for {}'.format(key, key_match))
if str(key) == str(key_match):
# print('found {}: {}'.format(key, item))
return item
result = walk(item, key_match)
if not result is None:
return result
return None
if isinstance(node, list):
for item in node:
if isinstance(item, dict) or isinstance(item, list):
result = walk(item, key_match)
if not result is None:
return result
return None
return None |
def get_key(j, key):
"""
Get the key value from the dictionary object
@param j: The dictionary object
@param key: The key value (or empty string)
"""
return j[key] if key in j else ''; |
def unique_list(list_redundant):
"""Select only unique elements in a list
"""
list_unique_elements = []
for element in list_redundant:
if element in list_unique_elements:
continue
else:
list_unique_elements.append(element)
return list_unique_elements |
def crossproduct(vector1, vector2):
"""Returns the crossproduct of two vectors"""
if not len(vector1) == len(vector2):
print("Error in MDP.crossproduct(v1, v2)... vectors are not of equal length.")
return None
else:
total = 0
for i in range(len(vector1)):
total += vector1[i] * vector2[i]
return total |
def _normalize(file):
"""Convenience function to support path objects."""
if 'Path' in type(file).__name__:
return str(file)
else:
return file |
def record(episode, episode_reward, worker_idx, global_ep_reward, total_loss, num_steps, log_print):
"""Helper function to store score and print statistics.
Arguments:
episode: Current episode
episode_reward: Reward accumulated over the current episode
worker_idx: Which thread (worker)
global_ep_reward: The moving average of the global reward
total_loss: The total loss accumualted over the current episode
num_steps: The number of steps the episode took to complete
"""
if global_ep_reward == 0:
global_ep_reward = episode_reward
else:
global_ep_reward = global_ep_reward * 0.99 + episode_reward * 0.01
text = (
f"Episode: {episode} | "
f"Moving Average Reward: {int(global_ep_reward)} | "
f"Episode Reward: {int(episode_reward)} | "
f"Loss: {int(total_loss / float(num_steps) * 1000) / 1000} | "
f"Steps: {num_steps} | "
f"Worker: {worker_idx}"
)
log_print(text)
return global_ep_reward |
def unique(value):
"""Check that there is only one value in the list, and return it.
>>> kb = KB({'John':{'eye_color': ['blue']}})
>>> unique(kb.get_attribute('John', 'eye_color'))
'blue'
This is handy in the context of KB, where everything's a list but
it's common to expect that there's only one value.
"""
if not value: return None
if len(value)!=1:
raise ValueError('Expected a single value, got multiple (%s)' % len(value))
return value[0] |
def _process_string(value):
"""Strip a few non-ascii characters from string"""
return value.strip('\x00\x16') |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.