content stringlengths 42 6.51k |
|---|
def get_unique_elements_as_dict(list_):
"""
Given a list, obtain a dictionary with unique elements as keys and integer as values.
Parameters
----------
list_: list
A generic list of strings.
Returns
-------
dict
Unique elements of the sorted list with assigned integer.
"""
all_elements = set.union(*[set(smiles) for smiles in list_])
unique_elements = sorted(list(all_elements))
return {unique_elem: i for i, unique_elem in enumerate(unique_elements)} |
def check_crc(data):
"""
Check CRC Value of received data.
Parameters
----------
data : bytes
received data
Returns
-------
bool
crc correct?
"""
if data != 0:
crc = 0
for i in data[2:81]:
crc += i
return data[81] == (crc & 255)
return False |
def try_get_model_prop(m, key, default=None):
""" The todoist models don't seem to have the `get()` method and throw KeyErrors """
try:
return m[key]
except KeyError:
return default |
def parse_string_time_to_seconds(strtime):
"""
String like 1h 52m 55s to seconds
:param strtime:
:return:
"""
strlist = strtime.strip().split(' ')
secs = float(0)
for strk in strlist:
if strk.endswith('h'):
num = int(float(strk[:-1]))
secs += 60 * 60 * num
elif strk.endswith('m'):
num = int(float(strk[:-1]))
secs += 60 * num
elif strk.endswith('ms'):
num = int(float(strk[:-2]))
secs += num / 1000
elif strk.endswith('s'):
num = int(float(strk[:-1]))
secs += num
else:
raise Exception(f"not recognized format strtime={strtime}")
return secs |
def reverse_list(head):
"""
:param head: head
:return: new head
"""
node = head
pre = None
while node:
node.next, pre, node = pre, node, node.next
return pre |
def factorialTrailingZeros(n):
"""
Function to count the number of trailing 0s in a factorial number.
Parameters:
n (int); the number for which the factorial and trailing 0s are to be calculated.
Returns:
trailingZeros (int); the number of 0s in the calculated factorial number.
"""
try:
if not(isinstance(n,int)) or (n<0): #If n is not a positive int
raise TypeError
ans = 1
trailingZeros = 0
# Calculating the factorial of 'n'
while n >= 1: # Loop stops when n becomes 0
ans *= n
n -= 1
# Calculating the number of 0s in 'ans'
while float(ans % 10) == 0: # Loop stops when 'ans' is not divisible by 10, in other words it no longer has 0s in it.
trailingZeros += 1
ans = ans // 10
return trailingZeros
except:
print("Error: Invalid input. Please try again with a positive integer only.")
return "Failed" |
def list_xor(list1, list2):
"""
returns list1 elements (xor) list2 elements
"""
list3 = []
for i in range(len(list1)):
list3.append(list1[i] ^ list2[i])
return list3 |
def dict_merge(*dicts):
"""
Merge all provided dicts into 1 dict.
"""
merged = {}
for d in dicts:
if not isinstance(d, dict):
raise ValueError('Value should be of dict type')
else:
merged.update(d)
return merged |
def escape(s, quote=None):
"""
SGML/XML escape an unicode object.
"""
s = s.replace("&", "&").replace("<", "<").replace(">", ">")
if not quote:
return s
return s.replace('"', """) |
def add_line_to_csv(file_path, line, linebreak="\n"):
"""Add a line to a CSV file."""
try:
with open(file_path, "a") as file:
file.write(line + linebreak)
return 1
except:
return 0 |
def unflatten_verifications(old_verifications):
""" Convert verifications from v2 to v1 """
new_verifications = {}
for verification in old_verifications:
key = verification['key']
del verification['key']
new_verifications[key] = verification
return new_verifications |
def liouville_avg(n):
"""
Returns the average order of liouville function for the positive integer n
Parameters
----------
n : int
denotes positive integer
return : float
return liouville function average
"""
if(n!=int(n) or n<1):
raise ValueError(
"n must be positive integer"
)
return 1.0 |
def gf2_rank(rows):
"""
Find rank of a matrix over GF(2)
The rows of the matrix are given as nonnegative integers, thought
of as bit-strings.
This function modifies the input list. Use gf2_rank(rows.copy())
instead of gf2_rank(rows) to avoid modifying rows.
Source: https://stackoverflow.com/a/56858995
"""
rank = 0
while rows:
pivot_row = rows.pop()
if pivot_row:
rank += 1
lsb = pivot_row & -pivot_row
for index, row in enumerate(rows):
if row & lsb:
rows[index] = row ^ pivot_row
return rank |
def encode(nickname, message):
"""Encodes a message as a comma separated list to be sent to the chat server"""
# Construct the payload
payload = '%s,%s' % (nickname, message)
# Encode the payload as utf-8 byte stream, so it can be sent to the chat server
return str.encode(payload, 'utf-8') |
def fibonacci(n):
"""
- recursie approach
- return the fibonacci number
at the given index
"""
# Check if n is valid
if n < 0:
print("Enter a positive number")
elif n == 0:
return 0
elif n == 1 or n == 2:
return 1
else:
return fibonacci(n - 1) + fibonacci(n - 2) |
def _flatten(orig):
"""
Converts the contents of list containing strings, lists of strings *(,lists of lists of strings,...)* to a flat
list of strings.
:param orig: the list to flatten
:return: the flattened list
"""
if isinstance(orig, str):
return [orig, ]
elif not hasattr(orig, '__iter__'):
raise ValueError("The flatten method only accepts string or iterable input")
out = []
for x in orig:
if isinstance(x, str):
out.append(x)
elif hasattr(x, '__iter__'):
out.extend(_flatten(x))
else:
raise ValueError("The flatten method encountered an invalid entry of type {}".format(type(x)))
return out |
def find_in_dict(string, dictionary):
"""
Returns True if the key is in the dictionary, False if not
"""
if string in dictionary:
return True
return False |
def get_total_numbers(items: dict):
"""
return the total number of keys and values per key in `items` as pair (n_keys, n_values).
"""
# Count values of each key.
total_values = 0
for _, v in items.items():
total_values += len(v)
return (len(items), total_values) |
def point(dataset, lon, lat, nchar):
"""This function puts lon,lat and datasetID into a GeoJSON feature"""
geojsonFeature = {
"type": "Feature",
"properties": {"datasetID": dataset, "short_dataset_name": dataset[:nchar]},
"geometry": {"type": "Point", "coordinates": [lon, lat]},
}
geojsonFeature["properties"]["style"] = {"color": "Grey"}
return geojsonFeature |
def _PrepareContainerMods(mods, private_fn):
"""Prepares a list of container modifications by adding a private data field.
@type mods: list of tuples; (operation, index, parameters)
@param mods: List of modifications
@type private_fn: callable or None
@param private_fn: Callable for constructing a private data field for a
modification
@rtype: list
"""
if private_fn is None:
fn = lambda: None
else:
fn = private_fn
return [(op, idx, params, fn()) for (op, idx, params) in mods] |
def finalize_node(node, nodes, min_cluster_size):
"""Post-process nodes to sort children by descending weight,
get full list of leaves in the sub-tree, and direct links
to the cildren nodes, then recurses to all children.
Nodes with fewer than `min_cluster_size` descendants are collapsed
into a single leaf.
"""
node["children"] = sorted(
[
finalize_node(nodes[cid], nodes, min_cluster_size)
for cid in node["children_ids"]
],
key=lambda x: x["weight"],
reverse=True,
)
if node["depth"] > 0:
node["example_ids"] = [
eid for child in node["children"] for eid in child["example_ids"]
]
node["children"] = [
child for child in node["children"] if child["weight"] >= min_cluster_size
]
assert node["weight"] == len(node["example_ids"]), print(node)
return node |
def rk4(rho, fun, dt, *args):
"""
Runge-Kutta method
"""
dt2 = dt/2.0
k1 = fun(rho, *args )
k2 = fun(rho + k1*dt2, *args)
k3 = fun(rho + k2*dt2, *args)
k4 = fun(rho + k3*dt, *args)
rho += (k1 + 2*k2 + 2*k3 + k4)/6. * dt
return rho |
def cloudfront_cache_header_behavior(header_behavior):
"""
Property: CacheHeadersConfig.HeaderBehavior
"""
valid_values = ["none", "whitelist"]
if header_behavior not in valid_values:
raise ValueError(
'HeaderBehavior must be one of: "%s"' % (", ".join(valid_values))
)
return header_behavior |
def transformStandar(value, mean, std):
"""
===========================================================================
Transform numerical input data using
Xnormalized = (X - Xmean) / Xstd
===========================================================================
**Args**:
**Returns**:
None
"""
return (value - mean) / std |
def powerlaw_model(energy_gev, k0, index, E0=1.0):
"""
Compute a PowerLaw spectrum
Parameters
----------
- energy_GeV: scalar or vector
- k0 : normalization
- E0 : pivot energy (GeV)
- index : spectral index
Outputs
--------
- spectrum
"""
return k0 * (energy_gev/E0)**(-index) |
def _family_name(set_id, name):
"""
Return the FAM object name corresponding to the unique set id and a list of subset
names
"""
return "FAM" + "_" + str(set_id) + "_" + "_".join(name) |
def create_output(name, mrn, ecg_filename, img_filename, mean_hr_bpm):
"""Interface between GUI and server
This function is called by the GUI command function attached to the "Ok"
button of the GUI. As input, it takes the data entered into the GUI.
It creates an output string that is sent back to the GUI that is
printed in the console. If no data was entered, the field will return
no data for name and a blank string for all other fields.
Args:
name (str): patient name entered in GUI
mrn (str): patient id (medical record number) entered in GUI
ecg_filename (str): filename of inputted ecg data
img_filename (str): filename of inputed image file
Returns:
str: a formatted string containing patient information from the
GUI
"""
out_string = "Patient name: {}\n".format(name)
out_string += "Patient MRN: {}\n".format(mrn)
out_string += "ECG File Uploaded: {}\n".format(ecg_filename)
out_string += "Image File Uploaded: {}\n".format(img_filename)
out_string += "Patient Heart Rate: {}\n".format(mean_hr_bpm)
return out_string |
def dms_to_decimal(degree: int, minute: int, second: float) -> float:
"""Converts a degree-minute-second coordinate to a decimal-degree coordinate."""
return degree + ((minute + (second / 60)) / 60) |
def day_to_full_date(d:str):
"""
Convert a day str 'yyyy-mm-dd' to a full date str 'yyyy-mm-dd 00:00:00'
:param d: 'yyyy-mm-dd'
:return: 'yyyy-mm-dd 00:00:00'
"""
return "{} 00:00:00".format(d) |
def decorator_wrapper(f, *args, **kwargs):
"""Wrapper needed by decorator.decorate to pass through args, kwargs"""
return f(*args, **kwargs) |
def binsearch(array, target):
"""Use binary search to find target in array.
Args:
array: A sequence of data.
target:
If target is callable, it's expected to accept a comparison
function that it uses to check it an element is a match.
If target isn't callable, it just represents a value to
find.
"""
if not callable(target):
## Since target isn't callable, it is converted to something that is.
## It accepts a comparison function which takes a single argument to
## check against.
target_val = target
def is_match(cmp):
res = cmp(target_val)
if res is NotImplemented:
return False
return res
target = is_match
lo = 0
hi = len(array) - 1
while lo <= hi:
mid = (hi + lo) // 2 # ?do we need to handle overflow in python?
#if target(array[mid]):
if target(array[mid].__eq__):
return mid
#if key(array[mid]) < target:
if target(array[mid].__lt__):
lo = mid + 1
else:
hi = mid - 1
return -1 |
def non_binary_search(data, item):
"""Return the position of query if in data."""
for index, val in enumerate(data):
if val == item:
return index
return None |
def __parse_region_from_url(url):
"""Parses the region from the appsync url so we call the correct region regardless of the session or the argument"""
# Example URL: https://xxxxxxx.appsync-api.us-east-2.amazonaws.com/graphql
split = url.split('.')
if 2 < len(split):
return split[2]
return None |
def extract_properties_values_from_json(data, keys):
"""Extracts properties values from the JSON data.
.. note::
Each of key/value pairs into JSON conventionally referred
to as a "property". More information about this convention follow
`JSON Schema documentation <https://json-schema.org/understanding-json-schema/reference/object.html>`_.
Passing ``data`` argument for an example:
.. code-block:: python
data = {
'verb': 'GET',
'endpoint': 'users',
'host': 'http://localhost:8080'
...
}
along with ``keys`` argument for an example:
.. code-block:: python
keys = ('verb', 'endpoint', 'host')
Iterating over ``keys`` parameter values and
extracts the property value of ``data`` parameter by key with the
exact same value.
Result:
.. code-block:: python
('GET', 'users, 'http://localhost:8080')
:param dict data: An arbitrary data.
:param tuple|list|set keys: Iterable with values of type `str`.
:returns: Packaged values.
:rtype: `tuple`
"""
return tuple(data[key] for key in keys if key in data) |
def get_match_quality_here(response):
"""
Returns the quality level from 0 to 1
:param response: dict - The full response from Here
:return: float
"""
try:
return response["Response"]["View"][0]["Result"][0]["Relevance"]
except:
return 0 |
def stringify(sub):
"""Returns python string versions ('' and "") of original substring"""
check_str_s = "'" + sub + "'"
check_str_d = '"' + sub + '"'
return check_str_s, check_str_d |
def acceleration(force, mass):
"""
Calculates the acceleration through force devided by mass.
@param force: force as a vector
@param mass: mass as a numeric value. This should be not 0.
@return: acc the acceleration
>>> acceleration(300, 30)
10.0
"""
#print "mass: ", mass
#print "force: ", force
acc = force/mass
return acc |
def _Int(s):
"""Try to convert s to an int. If we can't, just return s."""
try:
return int(s)
except ValueError:
assert '.' not in s # dots aren't allowed in individual element names
return s |
def stringify(iterable):
""" Convert tuple containing numbers to string
Input: iterable with numbers as values
Output: tuple with strings as values
"""
return tuple([str(i) for i in iterable]) |
def intDictToStringDict(dictionary):
"""
Converts dictionary keys into strings.
:param dictionary:
:return:
"""
result = {}
for k in dictionary:
result[str(k)] = dictionary[k]
return result |
def evaluate_poly(poly, x):
"""
Computes the polynomial function for a given value x. Returns that value.
Example:
# >>> poly = (0.0, 0.0, 5.0, 9.3, 7.0) # f(x) = 7x^4 + 9.3x^3 + 5x^2
# >>> x = -13
# >>> print evaluate_poly(poly, x) # f(-13) = 7(-13)^4 + 9.3(-13)^3 + 5(-13)^2
180339.9
poly: tuple of numbers, length > 0
x: number
returns: float
"""
# poly = input("Input poly")
# x = int(input("Input x"))
length = len(poly)
ans = 0
for y in range(length):
ans += poly[y] * x**y
return float(ans) |
def getFilterQscale(Sw, Sx, Sy):
"""
Sx: threshold_x/127
Sy: threshold_y/127
Qscale = Sw * Sx / Sy
"""
return (Sw * Sx) / Sy |
def testProbDataSumsTo1(y):
"""
prob dist must add to 1
:param y:
:return:
"""
s = sum(y)
print(s)
return s == 1 |
def metadataWhereClause(metadataIds):
"""metadataWhereClause.
Args:
metadataIds:
"""
inClause = ','.join(['%s' for s in metadataIds])
return 'where id in (' + inClause +') ' |
def get_torsscan_info(s):
"""
Returns electronic prog/method/basis as a string and energy as a float in hartree units.
Sample torsscan output
Optimized at : g09/b3lyp/sto-3g
Prog : gaussian
Method: b3lyp
Basis: sto-3g
Energy: -114.179051157 A.U.
Rotational Constants:120.49000, 23.49807, 22.51838 GHz
"""
lines = s.splitlines()
optlevel = ''
prog = ''
method = ''
basis = ''
energy = ''
for line in lines:
line = line.strip()
if 'Optimized at' in line:
optlevel = line.split()[-1]
elif line.startswith('Prog'):
s = line.split()[-1]
elif line.startswith('Method'):
method = line.split()[-1]
elif line.startswith('Basis'):
basis = line.split()[-1]
elif line.startswith('Energy'):
energy = float(line.replace('A.U.', '').split()[-1])
return optlevel, '{}/{}/{}'.format('torsscan', method, basis), energy |
def remove_substr(comp_str, str_list):
"""Remove substring."""
ret_list = []
for s in str_list:
if s in comp_str:
continue
ret_list.append(s)
return ret_list |
def _coords_to_region(tile_size, target_mpp, key, coords):
"""Return the necessary tuple that represents a region."""
return (*coords, *tile_size, target_mpp) |
def baseN(num, b, numerals="0123456789abcdefghijklmnopqrstuvwxyz"):
"""
Convert any integer to a Base-N string representation.
Shamelessly stolen from http://stackoverflow.com/a/2267428/1399279
"""
neg = num < 0
num = abs(num)
val = ((num == 0) and numerals[0]) or (baseN(num // b, b, numerals).lstrip(numerals[0]) + numerals[num % b])
return '-' + val if neg else val |
def tags_update(tags_to_add, tags_to_remove):
"""Serializes the given tag updates to a JSON string.
:param set[str] tags_to_add: list of tags
:param str[str] tags_to_remove: list of tags
:return: a dictionary suitable for JSON serialization
:rtype: dict
"""
return {
'add': sorted(tags_to_add),
'remove': sorted(tags_to_remove)
} |
def list_compare(original_list, new_list):
""" Compares 'original_list' to 'new_list' and returns two new lists,
the first of which is a list of additions to 'original_list and and the
second is a list of items to be removed from 'original_list'. """
add = []
for item in new_list:
if item not in original_list:
add.append(item)
rm = []
for item in original_list:
if item not in new_list:
rm.append(item)
return add, rm |
def generate_dest_name(src_repo, name):
""" generate dest repo image name
:param src_repo: one of
- k8s.gcr.io
- gcr.io/ml-pipeline
- quay.io/metallb
- gcr.io/knative-releases/knative.dev/eventing/cmd
:param name: image name
:return dest_image_name
"""
if src_repo.endswith('/cmd'):
t = src_repo.split('/')
if t[-1] == 'cmd':
return f'{t[-2]}-{name}'
return name |
def mL2indx(m, L, lmax, lmin=0):
"""convert mL to column index
Used for slicing the Kernel elements K.mLl (see tutorial)
*lmin is always zero. It is merely presented in the args for clarity
Usage example:
m = 0
L = 10
lmax=100
indx = cb.mL2indx(m, L, lmax)
K_mL_slice = kernel.mLl[indx]
"""
assert lmin==0
#assert 0 <= m <= L, "m is outside of the valid range 0 <= m <= L"
#assert 0 <= L <= lmax, "L is outside of the valid range 0 <= L <= lmax"
return m*(2*lmax+1-m)//2+L |
def str2bool(v):
"""
Used to parse true/false values from the command line. E.g. "True" -> True
"""
return v.lower() in ("yes", "true", "t", "1") |
def get_rank(workers, scores):
"""
spam score -> rank
"""
a = zip(scores, workers)
b = sorted(a)
dic = {}
i = 0
for s, w in b:
dic[w] = i
i+= 1
return dic |
def get_route_ids(routes_data: dict) -> list:
"""Return list of route ids from routes resp.json() data."""
route_ids = list()
for route in routes_data['Routes']:
route_ids.append(route['RouteID'])
return route_ids |
def check_knot_vector(degree, knot_vector, num_ctrlpts):
""" Checks if the input knot vector follows the mathematical rules.
:param degree: degree of the curve or the surface
:type degree: int
:param knot_vector: knot vector to be checked
:type knot_vector: list, tuple
:param num_ctrlpts: number of control points
:type num_ctrlpts: int
:return: True if the knot vector is valid, False otherwise
:rtype: bool
"""
try:
if knot_vector is None or len(knot_vector) == 0:
raise ValueError("Input knot vector cannot be empty")
except TypeError as e:
print("An error occurred: {}".format(e.args[-1]))
raise TypeError("Knot vector must be a list or tuple")
except Exception:
raise
# Check the formula; m = p + n + 1
if len(knot_vector) != degree + num_ctrlpts + 1:
return False
# Check ascending order
prev_knot = knot_vector[0]
for knot in knot_vector:
if prev_knot > knot:
return False
prev_knot = knot
return True |
def _audiocomp(P:dict) -> list:
"""select audio codec"""
return ['-c:a','aac','-b:a','160k','-ar','44100' ] |
def createSpiral(number):
"""
Create a spiral position array.
"""
number = number * number
positions = []
if (number > 1):
# spiral outwards
tile_x = 0.0
tile_y = 0.0
tile_count = 1
spiral_count = 1
while(tile_count < number):
i = 0
while (i < spiral_count) and (tile_count < number):
if (spiral_count % 2) == 0:
tile_y -= 1.0
else:
tile_y += 1.0
i += 1
tile_count += 1
positions.append([tile_x, tile_y])
i = 0
while (i < spiral_count) and (tile_count < number):
if (spiral_count % 2) == 0:
tile_x -= 1.0
else:
tile_x += 1.0
i += 1
tile_count += 1
positions.append([tile_x, tile_y])
spiral_count += 1
return positions |
def volCuboid(length: float, breadth: float, height: float) -> float:
"""Finds volume of a cuboid"""
volume: float = length * breadth * height
return volume |
def get_shortest_api(api_list):
"""
find the shortest api name (suggested name) in list.
Problems:
1. fuild - if there is any apis don't contain 'fluid' in name, use them.
2. core vs core_avx - using the 'core'.
"""
if len(api_list) == 1:
return api_list[0]
# try to find shortest path of api as the real api
api_info = [
] # {'name': name, 'fluid_in_name': True/False, 'core_avx_in_name': True/Flase', 'len': len}
for api in api_list:
fields = api.split('.')
api_info.append({
'name': api,
'fluid_in_name': 'fluid' in fields,
'core_avx_in_name': 'core_avx' in fields,
'len': len(fields),
})
def shortest(api_info):
if not api_info:
return None
elif len(api_info) == 1:
return api_info[0].get('name')
api_info.sort(key=lambda ele: ele.get('len'))
return api_info[0].get('name')
if not all([api.get('fuild_in_name') for api in api_info]):
api_info = [api for api in api_info if not api.get('fluid_in_name')]
sn = shortest([api for api in api_info if not api.get('core_avx_in_name')])
if sn is None:
sn = shortest(api_info)
return sn |
def encode_tuple(tuple_to_encode):
"""Turn size tuple into string. """
return '%s/%s' % (tuple_to_encode[0], tuple_to_encode[1]) |
def form_assignment_string_from_dict(adict):
"""
Generate a parameter-equals-value string from the given dictionary. The
generated string has a leading blank.
"""
result = ""
for aparameter in adict.keys():
result += " {}={}".format(aparameter, adict[aparameter])
return result |
def _isqrt(n):
"""Integer square root of n > 0
>>> _isqrt(1024**2)
1024
>>> _isqrt(10)
3
"""
assert n >= 0
x = n
y = (x + 1) // 2
while y < x:
x = y
y = (x + n // x) // 2
return x |
def translate_db2api(namespace, alias):
"""
>>> translate_db2api("VMC", "GS_1234")
[('sha512t24u', '1234'), ('ga4gh', 'SQ.1234')]
"""
if namespace == "NCBI":
return [("refseq", alias)]
if namespace == "Ensembl":
return [("ensembl", alias)]
if namespace == "LRG":
return [("lrg", alias)]
if namespace == "VMC":
return [
("sha512t24u", alias[3:] if alias else None),
("ga4gh", "SQ." + alias[3:] if alias else None),
]
return [] |
def normalizeTransformationScale(value):
"""
Normalizes transformation scale.
* **value** must be an :ref:`type-int-float`, ``tuple`` or ``list``.
* If **value** is a ``tuple`` or ``list``, it must have exactly two items.
These items must be instances of :ref:`type-int-float`.
* Returned value is a ``tuple`` of two ``float``\s.
"""
if not isinstance(value, (int, float, list, tuple)):
raise TypeError("Transformation scale must be an int, float, or tuple "
"instances, not %s." % type(value).__name__)
if isinstance(value, (int, float)):
value = (float(value), float(value))
else:
if not len(value) == 2:
raise ValueError("Transformation scale tuple must contain two "
"values, not %d." % len(value))
for v in value:
if not isinstance(v, (int, float)):
raise TypeError("Transformation scale tuple values must be an "
":ref:`type-int-float`, not %s."
% type(value).__name__)
value = tuple([float(v) for v in value])
return value |
def strip_paths(paths):
"""
Remove edges which are sequentially repeated in a path, e.g. [a, b, c, d, c, d, e, f] -> [a, b, c, d, e, f]
"""
res_all = []
for path in paths:
res = []
for node in path:
if len(res) < 2:
res.append(node)
continue
if node == res[-2]:
res.pop()
continue
else:
res.append(node)
res_all.append(res)
return res_all |
def _maybe_add_password(command, password):
"""
Add sudo password to command if required. Else NOOP.
in: sudo apt-get install
out: echo 'password' | sudo -S apt-get install
"""
if not password or 'sudo' not in command: # or 'sudo -S' in command:
return command
# Handle commands that are chained with &&
blocks = command.split('&&')
def fix_block(block):
"""Adds sudo and password where needed"""
if 'sudo' in block and 'sudo -S' not in block:
# Split the command string into a list of words
words = block.split()
for i, word in enumerate(words):
if word == 'sudo':
words.insert(i + 1, '-S')
break
words.insert(0, "echo '%s' |" % password)
return ' '.join(words)
return block
fixed_blocks = [fix_block(block) for block in blocks]
return '&&'.join(fixed_blocks) |
def parse_misplaced_character_inputs(misplaced_argument):
"""
example input from command line: __r__,___ac
this input would be used to show that two guesses had misplaced characters. The first guess has a misplaced
character at index 2, with a value of r. The second guess has two misplaced characters at indexes 3 and 4, with
values a and c respectively. Notice that the guesses are separated by commas.
Example: convert from ['_','_','r','_','_','_',',','_','_','_','_','a','c'] to ['__r__','___ac']
"""
return "".join(misplaced_argument).split(',') if len(misplaced_argument) > 0 else [] |
def convert_cookie_str(_str):
"""
convert cookie str to dict
"""
_list = [i.strip() for i in _str.split(';')]
cookie_dict = dict()
for i in _list:
k, v = i.split('=', 1)
cookie_dict[k] = v
return cookie_dict |
def read_last(file_name, n_lines=1):
"""
Reads the last line of a file.
Parameters
----------
:param file_name: string
Complete path of the file that you would like read.
:return last_line: string
Last line of the input file.
"""
try:
with open(file_name, mode='r') as infile:
lines = infile.readlines()
except IOError:
last_lines = 'IOEror in read_last_line: this file does not exist.'
return last_lines
try:
last_lines = lines[-n_lines:]
last_lines = '\n'.join(last_lines)
except IndexError:
last_lines = 'IndexError in read_last_line: no last line appears to exist in this file.'
return last_lines |
def ABCDFrequencyList_to_ZFrequencyList(ABCD_frequency_list):
""" Converts ABCD parameters into z-parameters. ABCD-parameters should be in the form [[f,A,B,C,D],...]
Returns data in the form
[[f,Z11,Z12,Z21,Z22],...],
inverse of ZFrequencyList_to_ABCDFrequencyList
"""
z_frequency_list=[]
for row in ABCD_frequency_list[:]:
[frequency,A,B,C,D]=row
Z11=A/C
Z12=(A*D-B*C)/C
Z21=1/C
Z22=D/C
z_frequency_list.append([frequency,complex(abs(Z11.real),Z11.imag),Z12,Z21,complex(abs(Z22.real),Z22.imag)])
return z_frequency_list |
def StretchContrast(pixlist, minmin=0, maxmax=0xff):
""" Stretch the current image row to the maximum dynamic range with
minmin mapped to black(0x00) and maxmax mapped to white(0xff) and
all other pixel values stretched accordingly."""
if minmin < 0: minmin = 0 # pixel minimum is 0
if maxmax > 0xff: maxmax = 0xff # pixel maximum is 255
if maxmax < minmin: maxmax = minmin # range sanity
min, max = maxmax, minmin
for pix in pixlist:
if pix < min and pix >= minmin:
min = pix
if pix > max and pix <= maxmax:
max = pix
if min > max: min = max
if min == max:
f = 1.0
else:
f = 255.0 / (max - min)
n = 0
newpixlist= []
for pix in pixlist:
if pix < minmin: pix = minmin
if pix > maxmax: pix = maxmax
pix = int((pix - min) * f)
newpixlist.append (pix)
return newpixlist |
def get_cmd_name(name=__name__):
"""Get command name from __name__ within a file"""
return name.split('.')[-1] |
def is_cell_markdown(cell):
"""
Is the ipynb cell Markdown?
"""
return cell['cell_type'].strip().lower().startswith('markdown') |
def sub(A,B):
"""
matrix subtraction functions which returns resultant matrix after subtracting two matrices
"""
n=len(A)
output=[]
result=[]
for i in range(n):
for j in range(n):
result.append(A[i][j]-B[i][j])
output.append(result)
result=[]
return output |
def getSegsInMap(segMap, corpus):
"""Returns a list of the full text segments in the corpus indicated by the segmap"""
textSegs = []
for i in range(0, len(segMap)):
textSegs.append(corpus[segMap[i]])
return textSegs |
def non_overlapping_claims(claims):
""" Return a list of all claims that don't overlap with others. """
unique_claims = set()
non_unique_claims = set()
for v in claims.values():
if len(v) == 1:
unique_claims = unique_claims.union(v)
else:
non_unique_claims = non_unique_claims.union(v)
return unique_claims.difference(non_unique_claims) |
def update_annotations(annotations, left_shifts):
"""Update deidentified annotations with appropriate left shifts
"""
deidentified_annotations = \
{annotation_type: [] for annotation_type in annotations.keys()}
for annotation_type, annotation_set in annotations.items():
for annotation in annotation_set:
old_start = annotation['start']
old_end = old_start + annotation['length']
new_start = old_start - left_shifts[old_start]
new_end = old_end - left_shifts[old_end]
deidentified_annotation = annotation.copy()
deidentified_annotation['start'] = new_start
deidentified_annotation['length'] = new_end - new_start
deidentified_annotations[annotation_type].append(
deidentified_annotation)
return deidentified_annotations |
def average_even_is_average_odd(hand):
"""
:param hand: list - cards in hand.
:return: bool - are even and odd averages equal?
"""
even_count = 0
even_average = 0
even_sum = 0
for i in range(0, len(hand), 2):
even_count += 1
even_sum += hand[i]
even_average = even_sum / even_count
odd_count = 0
odd_average = 0
odd_sum = 0
for i in range(1, len(hand), 2):
odd_count += 1
odd_sum += hand[i]
odd_average = odd_sum / odd_count
return even_average == odd_average |
def safe_split(indata, sepchar='|'):
"""
split string safely
"""
try:
return filter(lambda x: len(x.strip()), indata.split(sepchar))
except:
return [] |
def _normalized_coerce_fn(r):
"""
:rtype: str
"""
return r.lower().strip() |
def _get_cols_to_format(show_inference, confidence_intervals):
"""Get the list of names of columns that need to be formatted.
By default, formatting is applied to parameter values. If inference values
need to displayed, adds confidence intervals or standard erros to the list.
"""
cols = ["value"]
if show_inference:
if confidence_intervals:
cols += ["ci_lower", "ci_upper"]
else:
cols.append("standard_error")
return cols |
def multiply(*args):
"""
Helper function which multiplies the all numbers that are delivered in the function call
:param args: numbers
:return: product of all numbers
"""
product = 1
for arg in args:
product *= arg
return product |
def ngrams(word, n):
"""Creates n-grams for a string, returning a list.
:param word: str - A word or string to ngram.
:param n: - n-gram length
:returns: list of strings
"""
ans = []
word = word.split(' ')
for i in range(len(word) - n + 1):
ans.append(word[i:i + n])
return ans |
def indexValue(i_array, target):
"""
Function Docstring
"""
if(len(i_array) <= 2):
return False
else:
for i in range(len(i_array)):
first_index = i
j = i + 1
for j in range(len(i_array)):
if i_array[i] + i_array[j] == target:
second_index = j
return [first_index, second_index]
return False |
def island_perimeter(grid):
"""returns the perimeter of the island described in grid"""
p = 0
for i in range(0, len(grid), 1):
for j in range(0, len(grid[0]), 1):
if grid[i][j] == 1:
p = p + 4
if j - 1 >= 0 and grid[i][j - 1] == 1:
p = p - 2
if i - 1 >= 0 and grid[i - 1][j] == 1:
p = p - 2
return (p) |
def all_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 get_python_exec(py_num: float) -> str:
""" Get python executable
Args:
py_num(float): Python version X.Y
Returns:
str: python executable
"""
if py_num < 3:
py_str = ""
else:
py_str = "3"
return f"python{py_str}" |
def te_exp_minus1(posy, nterm):
"""Taylor expansion of e^{posy} - 1
Arguments
---------
posy : gpkit.Posynomial
Variable or expression to exponentiate
nterm : int
Number of non-constant terms in resulting Taylor expansion
Returns
-------
gpkit.Posynomial
Taylor expansion of e^{posy} - 1, carried to nterm terms
"""
res = 0
factorial_denom = 1
for i in range(1, nterm + 1):
factorial_denom *= i
res += posy**i / factorial_denom
return res |
def remove_duplicates(iterable):
"""Removes duplicates of an iterable without meddling with the order"""
seen = set()
seen_add = seen.add # for efficiency, local variable avoids check of binds
return [x for x in iterable if not (x in seen or seen_add(x))] |
def mm_as_m(mm_value):
"""Turn a given mm value into a m value."""
if mm_value == 'None':
return None
return float(mm_value) / 1000 |
def __find(element, JSON):
"""
To find the content in elasticsearch's hits based on path in element.
Arguments:
- element: a path to the content, e.g. _source.item.keywords.keyword
- JSON: a dictionary as a result of elasticsearch query
"""
try:
paths = element.split(".")
data = JSON
for count, p in enumerate(paths):
if isinstance(data[p], dict):
data = data[p]
elif isinstance(data[p], list):
data = [__find(element[element.__find(p)+len(p)+1:], lst) for lst in data[p]]
break
elif len(paths)-1 == count:
return data[p]
return data
except:
return [] |
def positive_int_to_str(value):
""" Convert a PositiveInt to a string representation to display
in the text box.
"""
if value is None:
return ""
else:
return str(value) |
def get_size(bytes, suffix="B"):
"""
Scale bytes to its proper format
e.g:
1253656 => '1.20MB'
1253656678 => '1.17GB'
"""
factor = 1024
for unit in ["", "K", "M", "G", "T", "P"]:
if bytes < factor:
return "{} {}{}".format(round(bytes), unit, suffix)
bytes /= factor |
def getQuarter(side, point):
"""
Given a 2d point, returns the corresponding quarter ID.
The path of the robot is split in 4 segments, each segment corresponds
to one edge of the square. Since the robot is not exactly on the edge, we
need a way to map any point to one of the 4 edges. To do this we split the
world into 4 quarters using the extended diagonals of the square. Each
quarter corresponds to one edge of the square. The ID of each quarter
corresponds to the order in which the robot will go through them.
side: size of one side of the square, in meters.
point: tuple containing x and y coordinates.
returns 0, 1, 2 or 3 depending on the quarter in which the point is located
"""
# Checks on which side of the bottom-left to top-right diagonal the point
# is.
posDiag = (point[1] - point[0] > 0)
# Checks on which side of the top-left to bottom-right diagonal the point
# is.
negDiag = (point[0] + point[1] - side < 0)
if posDiag:
if negDiag:
return 0
else:
return 3
else:
if negDiag:
return 1
else:
return 2 |
def yellowness_blueness_response(C, e_s, N_c, N_cb, F_t):
"""
Returns the yellowness / blueness response :math:`M_{yb}`.
Parameters
----------
C : array_like
Colour difference signals :math:`C`.
e_s : numeric
Eccentricity factor :math:`e_s`.
N_c : numeric
Chromatic surround induction factor :math:`N_c`.
N_b : numeric
Brightness surround induction factor :math:`N_b`.
F_t : numeric
Low luminance tritanopia factor :math:`F_t`.
Returns
-------
numeric
Yellowness / blueness response :math:`M_{yb}`.
Examples
--------
>>> C = (-5.3658655819965873e-05,
... -0.00057169938364687312,
... 0.00062535803946683899)
>>> e_s = 1.1108365048626296
>>> N_c = 1.0
>>> N_cb = 0.72499999999999998
>>> F_t =0.99968593951195
>>> yellowness_blueness_response(C, e_s, N_c, N_cb, F_t) # noqa # doctest: +ELLIPSIS
-0.0082372...
"""
C_1, C_2, C_3 = C
M_yb = (100 * (0.5 * (C_2 - C_3) / 4.5) *
(e_s * (10 / 13) * N_c * N_cb * F_t))
return M_yb |
def get_hue_fg_colour(h, s, v):
"""Returns the best foreground colour for a given background colour (black or white.)"""
if s > 0.6:
if h > 20 and h <= 200:
return "black"
elif s <= 0.6:
if v > 0.8:
return "black"
return "white" |
def _standardise_proc_param_keys(key: str) -> str:
"""Convert to lowercase, replace any spaces with underscore."""
return key.lower().replace(" ", "_") |
def remove_badges(text: str) -> str:
""" Remove Github badges.
:param text: Original text.
:return: Text with Github badges removed.
"""
new_text = "\n".join((line for line in text.splitlines() if "![" not in line))
return new_text |
def verify_heart_rate_info(in_dict):
"""Verifies post request was made with correct format
The input dictionary must have the appropriate data keys
and types, or be convertible to correct types, to be added
to the patient database.
Args:
in_dict (dict): input with patient ID and heart rate
Returns:
str: if error, returns error message
bool: if input verified, returns True
"""
expected_keys = ("patient_id", "heart_rate")
expected_types = (int, int)
for i, key in enumerate(expected_keys):
if key not in in_dict.keys():
return "{} key not found".format(key)
if type(in_dict[key]) is not expected_types[i]:
# if key == "patient_id" or key == "heart_rate":
try:
in_dict[key] = int(in_dict[key])
except ValueError:
return "{} value not correct type".format(key)
# else:
# return "{} value not correct type".format(key)
return True |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.