content
stringlengths 42
6.51k
|
|---|
def fix_surf_el(variables):
"""change variables if surf_el is contained"""
if "surf_el" in set(variables):
_variables = variables.copy()
_variables.remove("surf_el")
return _variables, "surf_el"
else:
return variables, None
|
def is_rate(keyword):
"""Check if rate keyword
Args:
Profiles keyword
Returns:
True if rate keyword
"""
if keyword[0] == 'L':
z2 = keyword[3:5]
else:
z2 = keyword[2:4]
return bool(z2 == 'PR' or z2 == 'SR' or z2 == 'IR' or z2 == 'FR')
|
def class_is_interesting(name: str):
"""Checks if a jdeps class is a class we are actually interested in."""
if name.startswith('org.chromium.'):
return True
return False
|
def isclose(a, b, rel_tol=1e-05, abs_tol=0.0):
"""Like math.isclose() from Python 3.5"""
return abs(a - b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol)
|
def convert_to_bundleClass_format(samcc_selection):
"""converts samcc selection from this library to original format used by bundleClass
input: samcc-ready selection, list of helices, each helix a list of format [ chain_id(string), start_residue(int), stop_residue(int) ]
output: BundleClass-ready selection, list of helices, each helix a tuple of format ( start_residue(int), stop_residue(int), chain_id(string), antiparallel(bool) )
"""
input_helices = []
for helix in samcc_selection:
if helix[1] < helix[2]:
input_helices.append((helix[1], helix[2], helix[0], False))
else:
input_helices.append((helix[2], helix[1], helix[0], True))
return input_helices
|
def handle_number_input(args):
"""
Format any command argument that is supposed to be a number from a string to an int.
parameter: (dict) args
The command arguments dictionary
returns:
The arguments dict with field values transformed from strings to numbers where necessary
"""
# Command args that should be numbers
number_args = [
'requester_id', 'status', 'priority', 'responder_id',
'email_config_id', 'group_id', 'product_id', 'source', 'company_id'
]
# Convert cmd args that are expected to be numbers from strings to numbers
for num_arg in number_args:
if num_arg in args.keys():
args[num_arg] = int(args.get(num_arg))
return args
|
def escape(text):
"""Return text as an HTML-safe sequence."""
text = text.replace("&", "&")
text = text.replace("<", "<")
text = text.replace(">", ">")
text = text.replace('"', """)
text = text.replace("'", "'")
return text
|
def fibonacci(n):
"""
fibonacci
@param n:
@return:
"""
if n in (0, 1):
return n
return fibonacci(n - 2) + fibonacci(n - 1)
|
def format_table(table_lines: list):
"""
Find and format table with the docstring
:param table_lines: Docstring containing a table within
"""
tidy_table_lines = [line[1:-1].split('|') for line in table_lines]
table = []
for row in tidy_table_lines:
cols = []
for col in row:
cols.append(col.strip())
table.append(cols)
return table
|
def get_dimers(seq):
"""Extract NN dimers from sequence.
Args:
seq (str): nucleic acid sequence.
Returns:
list: NN dimers.
"""
return [seq[i : (i + 2)] for i in range(len(seq) - 1)]
|
def triplet_occurrence(iterable, triplet_sum):
"""
A triplet is said to be present if any of the three numbers in the iterable is equal to given triplet_sum
:param iterable: Iterable should be either of the types list or tuple of minimum length 3 with numbers
:param triplet_sum: Triplet sum should be a number
:return: True if triplet is present, else False
Eg: triplet_occurrence([1, 4, 45, 10, 6, 8], 22) gives True
Here 4, 10 and 8 adds up to give 22 which is the given triplet_sum.
"""
# To check whether the given iterable is list or tuple
if type(iterable) == list or type(iterable) == tuple:
pass
else:
raise TypeError("Iterable should be of either list or tuple")
# To check whether all the given items in the iterable are numbers only
for item in iterable:
if not isinstance(item, int):
raise ValueError("Only numbers are accepted in the iterable")
# To check whether the given triplet_sum is a number
if not isinstance(triplet_sum, int):
raise ValueError("Triplet sum should be a number")
# The length of the iterable should be of minimum length 3
if len(iterable) < 3:
raise Exception("Length of the given iterable should be of minimum length 3")
# Iterable of any type is converted to list type to perform sort operation
iterable = list(iterable)
# First we sort the list which takes O(n log n) time complexity
iterable.sort()
# Initially considering first, second and last elements of iterable as the triplets
low = 0
mid = 1
high = len(iterable) - 1
current_sum = iterable[low] + iterable[mid] + iterable[high]
# Dictionary for storing the previous sum values
occur = dict()
occur[iterable[low] + iterable[high]] = [iterable[low], iterable[high]]
occur[iterable[mid] + iterable[high]] = [iterable[mid], iterable[high]]
# Here a single element is accessed at most two times in the worst case which may be O(2n)
# Hence the complexity for below loop is O(n)
while mid < high:
# If we got the current sum is equal to the triplet sum, we are returning True
if current_sum == triplet_sum:
return True
# If the current sum is less than triplet sum
elif current_sum < triplet_sum:
# If mid is very next to low, we are incrementing the index of mid
if mid - low == 1:
mid += 1
if triplet_sum - iterable[mid] in occur.keys():
return True
occur[iterable[high] + iterable[mid]] = [iterable[mid], iterable[high]]
occur[iterable[low] + iterable[mid]] = [iterable[low], iterable[mid]]
current_sum += iterable[mid] - iterable[mid - 1]
# If they are not adjacent we are incrementing the index of low
else:
low += 1
if triplet_sum - iterable[low] in occur.keys():
return True
occur[iterable[high] + iterable[low]] = [iterable[low], iterable[high]]
occur[iterable[mid] + iterable[low]] = [iterable[low], iterable[mid]]
current_sum += iterable[low] - iterable[low - 1]
# If the current sum greater than triplet sum, we are decrementing index of high and modifying current sum
else:
high -= 1
occur[iterable[high] + iterable[low]] = [iterable[low], iterable[high]]
occur[iterable[high] + iterable[mid]] = [iterable[mid], iterable[high]]
if triplet_sum - iterable[high] in occur.keys():
return True
current_sum += iterable[high] - iterable[high + 1]
# If the code comes out of while loop, then no triplet sum is present
return False
|
def _get_anisotropic_kernel_params(p):
"""Get anisotropic convolution kernel parameters from the given parameter
vector."""
return p[0], p[1], p[2] * p[1]
|
def _BisectHashList(ls, left, right, value):
"""Select the server that allocates 'value' using a binary search."""
if right < left:
return None
if left == right:
return ls[left]
middle = left + (right - left) / 2
middleval = ls[middle]
start = middleval.interval.start
end = middleval.interval.end
if start <= value < end:
return middleval
if value >= end:
return _BisectHashList(ls, middle + 1, right, value)
if value < start:
return _BisectHashList(ls, left, middle - 1, value)
|
def publics(obj):
"""Return all objects in __dict__ not starting with '_' as a dict"""
return dict((name, obj) for name, obj in vars(obj).items() if not name.startswith('_'))
|
def get_nested_attr(obj, attr_name):
"""Same as getattr(obj, attr_name), but allows attr_name to be nested
e.g. get_nested_attr(obj, "foo.bar") is equivalent to obj.foo.bar"""
for name_part in attr_name.split('.'):
if hasattr(obj, name_part):
obj = getattr(obj, name_part)
else:
raise AttributeError("module has no " + name_part + " attribute")
return obj
|
def get_frame_name(frame):
"""Gets the frame name for a frame number.
Args:
frame (int): Frame number.
Returns:
str: 0-padded frame name (with length 6).
"""
return str(frame).rjust(6, "0")
|
def styblinski_bounds(d):
"""
Parameters
----------
d : int
dimension
Returns
-------
"""
return [(-5., 5.) for _ in range(d)]
|
def shift_left_ascii(ascii_text, size):
""" left shift the big text with specified
before:
BIG_TEXT
after:
--------->(size) BIG_TEXT
"""
if type(size) != int:
raise TypeError
if type(ascii_text) != str:
raise TypeError
if not "\n" in ascii_text:
raise ValueError
lines = ascii_text.split("\n")
lines = [" " * size + line for line in lines]
lines = "\n".join(lines)
return lines
|
def attn_weight_core_fetch(attn_weight, peptide):
"""Accoding to attn_weight to fetch max 9 position
Note: we don consider padded sequenc after valid
"""
max_weight = -float('Inf')
core_bind = ''
for start_i in range(0, len(peptide) - 9 + 1):
sum_weight = sum(attn_weight[start_i: start_i + 9])
if sum_weight > max_weight:
max_weight = sum_weight
core_bind = peptide[start_i: start_i + 9]
return core_bind
|
def d_opt(param,value,extra_q=0):
"""
Create string "-D param=value"
"""
sym_q=""
if extra_q==1:
sym_q="\""
return("-D "+param+"="+sym_q+value+sym_q+" ")
|
def readFile(name):
"""
Reads a text file.
Args:
name (str): The name of the file
Returns:
str: The content of the file.
"""
with open(name, "rt") as f:
return ''.join(f)
|
def fletcher(barray):
"""Return the two Fletcher-16 sums of a byte array."""
assert isinstance(barray, bytes) or isinstance(barray, bytearray)
a = 0
b = 0
for c in barray:
a = (a + c) % 255
b = (a + b) % 255
return (a, b)
|
def _analyse_gdal_output(output):
"""analyse the output from gpt to find if it executes successfully."""
# return false if "Error" is found.
if b'error' in output.lower():
return False
# return true if "100%" is found.
elif b'100 - done' in output.lower():
return True
# otherwise return false.
else:
return False
|
def checkGuess(guess, secretNum):
"""Prints a hint showing relation of `guess` to `secretNum`"""
if guess < secretNum:
return "Your guess is too low."
elif guess > secretNum:
return "Your guess is too high."
else:
return "You got it!!"
|
def split_string(mystring, sep, keep_sep=True):
"""Splits a string, with an option for keeping the separator in
>>> split_string('this-is-a-test', '-')
['this-', 'is-', 'a-', 'test']
>>> split_string('this-is-a-test', '-', keep_sep=False)
['this', 'is', 'a', 'test']
Parameters
----------
mystring : str
The string to split
sep : str
The separator to split at
keep_sep : bool, optional
Whether to keep the separator, by default True
Returns
-------
list
The parts of the string
"""
if keep_sep == False:
keep_sep = ''
elif keep_sep == True:
keep_sep = sep
items = mystring.split(sep)
for i in range(len(items) - 1):
items[i] += keep_sep
return items
|
def remove_null_kwargs(**kwargs):
"""
Return a kwargs dict having items with a None value removed.
"""
return {k: v for k, v in kwargs.items() if v is not None}
|
def make_xy_proportional_in_window(width, height, x_low, x_high, y_low, y_high):
"""Pad the x or y range to keep x and y proportional to each other in the window.
Parameters
----------
width : int
The width of the window,
equivalent to the number of bins on the x dimension.
height : int
The height of the window,
equivalent to the number of bins on the y dimension.
x_low : float
The position of the left edge of the window,
equivalent to the lower range of the x bins.
E.g. x_vals.min().
x_high : float
The position of the right edge of the window,
equivalent to the lower range of the x bins.
E.g. x_vals.max().
y_low : float
The position of the bottom edge of the window,
equivalent to the lower range of the y bins.
E.g. y_vals.min().
y_high : float
The position of the top edge of the window,
equivalent to the upper range of the y bins.
E.g. y_vals.max().
Returns
-------
x_low_, x_high_, y_low_, y_high_ : float, float, float, float
The new, padded, ranges, that allow the window to fit to
the x and y ranges, while keeping x and y to scale
with each other.
Notes
-----
There are three possibilities:
case 1:
No padding needs to be done.
case 2:
The x range is scaled to the full window width.
The y range is padded, to keep y to scale with x.
case 3:
The y range is scaled to the full window height.
The x range is padded, to keep x to scale with y.
"""
delta_x = x_high - x_low
delta_y = y_high - y_low
if delta_x == 0 or delta_y == 0:
return x_low, x_high, y_low, y_high
elif delta_y / delta_x < height / width:
k = 0.5 * (delta_x * height / width - delta_y)
return x_low, x_high, y_low - k, y_high + k
else:
k = 0.5 * (delta_y * width / height - delta_x)
return x_low - k, x_high + k, y_low, y_high
|
def get_size_and_checksum(data):
"""Calculates the size and md5 of the passed data
Args:
data (byte): data to calculate checksum for
Returns:
tuple (int,str): size of data and its md5 hash
"""
from hashlib import md5 as _md5
md5 = _md5()
md5.update(data)
return (len(data), str(md5.hexdigest()))
|
def test_sequence_length(sequence):
"""
Tests if sequence is not longer than 36 residues.
Parameters
----------
sequences: peptide sequence
Returns
-------
Boolean: True
if length of sequence <= 36 residues.
"""
if len(sequence) < 36: return True
else:
msg = "Please provide a sequence with a maximum of 36 residues. " +\
"The provided sequence length is {}.".format(len(sequence))
raise RuntimeError(msg)
|
def is_leap(year,print_=False):
""" returns true if year is leap year, otherwise returns False and prints the output per assignment of print_"""
if year % 4 == 0:
if year % 100 == 0:
if year % 400 == 0:
if print_: print("Leap year")
return True
else:
if print_: print("Leap yearNot a leap year")
return False
else:
if print_: print("Leap year")
return True
else:
if print_:print("Not a leap year")
return False
|
def _get_headers_from_args(
method=None,
url=None,
body=None,
headers=None,
retries=None,
redirect=None,
assert_same_host=True,
timeout=None,
pool_timeout=None,
release_conn=None,
chunked=False,
body_pos=None,
**response_kw
):
"""
extract headers from arguments
"""
# pylint: disable=unused-argument
# not using '_' in arg names so unrolling will be smoother
return headers
|
def total_norm(tensors, norm_type=2):
""" Computes total norm of the tensors as if concatenated into 1 vector. """
if norm_type == float('inf'):
return max(t.abs().max() for t in tensors)
return sum(t.norm(norm_type) ** norm_type
for t in tensors) ** (1. / norm_type)
|
def is_correct_bracket_seq(string: str) -> bool:
"""
>>> is_correct_bracket_seq('{}()[]')
True
>>> is_correct_bracket_seq('{}}')
False
>>> is_correct_bracket_seq(')(')
False
>>> is_correct_bracket_seq('([)]')
False
"""
unclosed_brackets_stack = ''
pairs_to_close = {
'}': '{',
')': '(',
']': '[',
}
for symbol in string:
if (symbol in '([{'
or not unclosed_brackets_stack):
unclosed_brackets_stack += symbol
if (symbol in '}])'
and unclosed_brackets_stack[-1] == pairs_to_close[symbol]):
unclosed_brackets_stack = unclosed_brackets_stack[:-1]
return unclosed_brackets_stack == ''
|
def NewtonSolver(f, xstart, C=0.0):
"""
Solve f(x) = C by Newton iteration.
- xstart starting point for Newton iteration
- C constant
"""
f0 = f(xstart) - C
x0 = xstart
dx = 1.0e-6
n = 0
while n < 200:
ff = f(x0 + dx) - C
dfdx = (ff - f0)/dx
step = - f0/dfdx
# avoid taking steps too large
if abs(step) > 0.1:
step = 0.1*step/abs(step)
x0 += step
emax = 0.00001 # 0.01 mV tolerance
if abs(f0) < emax and n > 8:
return x0
f0 = f(x0) - C
n += 1
raise Exception('no root!')
|
def __bytes2str(b) -> str:
"""Convert object `b` to string."""
if isinstance(b, str):
return b
if isinstance(b, (bytes, bytearray)):
return b.decode()
elif isinstance(b, memoryview):
return b.tobytes().decode()
else:
return repr(b)
|
def is_part_of(L1, L2):
"""Return True if *L2* contains all elements of *L1*, False otherwise."""
for i in L1:
if i not in L2:
return False
return True
|
def get_filename(file_path):
"""This gets just the filename of a filepath
Args:
file_path: The file path you wish to get the filename from
Returns:
"""
return file_path.split("/")[-1]
|
def get_f_2p(var1, var2):
"""
"""
f = var1 / var2
return f
|
def tv(p, q):
""" Total variance distance """
return max([abs(p[i] - q[i]) for i in range(len(p))])
|
def split(func, iterable):
"""split an iterable based on the truth value of the function for element
Arguments
func -- a callable to apply to each element in the iterable
iterable -- an iterable of element to split
Returns
falsy, truthy - two tuple, the first with element e of the itrable where
func(e) return false, the second with element of the iterable that are True
"""
falsy, truthy = [], []
for e in iterable:
if func(e):
truthy.append(e)
else:
falsy.append(e)
return tuple(falsy), tuple(truthy)
|
def _filter_by_date(journal, after, before):
"""return a list of entries after date
:param before: A naive datetime representing a UTC time.
:param after: A naive datetime representing a UTC time
"""
if after is None and before is None:
return journal
return [item for item in journal
if (after is None or item['Creation Date'] >= after) and
(before is None or item['Creation Date'] < before)]
|
def tokenise(text):
"""
Input:
text (string)
Returns:
A list of tokens
"""
return text.split()
|
def check_data_dict_identical(data_dict_1, data_dict_2):
"""
Check whether data_dicts are identical.
Used by TestDataUnchanged below.
"""
result = True # assume True, unless proven otherwise
if data_dict_1.keys() != data_dict_2.keys():
result = False
for key in data_dict_1.keys():
if data_dict_1[key].identical(data_dict_2[key]) is not True:
result = False
return result
|
def gh_userpwd(gh_username, gh_oauth_key):
""" Returns string version of GitHub credentials to be passed to GitHub API
Args:
gh_username: GitHub username for GitHub API
gh_oauth_key: (String) GitHub oauth key
"""
return('%s:%s' %(gh_username, gh_oauth_key))
|
def isRetweet(text):
"""
Classifies whether a tweet is a retweet based on how it starts
"""
if text[:4] == "RT @":
return True
if text[:4] == "MT @":
return True
return False
|
def has_children(elem):
"""Check if elem has any child elements."""
if type(elem) == list:
return True
try:
for child in elem:
if type(child) == list:
return True
except TypeError:
return False
return False
|
def eigsrt(eigv, x, neq):
"""
Sort the eigenvalues in ascending order
"""
#
for i in range(neq-1):
k = i
p = eigv[i]
# search for lowest value
for j in range(i+1, neq):
if abs(eigv[j]) < abs(p) :
k = j
p = eigv[j]
# L11:
# re-arrange vectors
if k != i :
eigv[k] = eigv[i]
eigv[i] = p
for j in range(neq):
p = x[j][i]
x[j][i] = x[j][k]
x[j][k] = p
# L12:
# L13:
#
return eigv, x
|
def radar_band_name(wavelength):
"""
Get the meteorological frequency band name.
Parameters:
===========
wavelength: float
Radar wavelength in mm.
Returns:
========
freqband: str
Frequency band name.
"""
if wavelength >= 100:
return "S"
elif wavelength >= 40:
return "C"
elif wavelength >= 30:
return "X"
elif wavelength >= 20:
return "Ku"
elif wavelength >= 7:
return "Ka"
else:
return "W"
return None
|
def fahrenheit_to_celsius(temp):
"""Converts temperature units F to C
PARAMETERS
----------
temp : float
Scalar temp in Fahrenheit
RETURNS
-------
float
Scalar temp in Celsius
"""
return (5/9)*(temp - 32)
|
def _get_clean_selection(remove_known_configs, remove_unknown_configs):
""" Get Clean Selection """
clean_selection = "given_config"
if remove_known_configs and remove_unknown_configs:
clean_selection = "all_configs"
elif remove_known_configs and not remove_unknown_configs:
clean_selection = "known_configs"
elif not remove_known_configs and remove_unknown_configs:
clean_selection = "unknown_configs"
return clean_selection
|
def skip(list, current_index, increase_index):
"""
Increases the current index with a specific number of steps
given by increase_index and returns the value at that position
"""
current_index += increase_index
return current_index, list[current_index]
|
def split_image_name ( image_name ):
""" Splits a specified **image_name** into its constituent volume and file
names and returns a tuple of the form: ( volume_name, file_name ).
"""
col = image_name.find( ':' )
volume_name = image_name[ 1: col ]
file_name = image_name[ col + 1: ]
if file_name.find( '.' ) < 0:
file_name += '.png'
return ( volume_name, file_name )
|
def sanitize_option(option):
"""
Format the given string by stripping the trailing parentheses
eg. Auckland City (123) -> Auckland City
:param option: String to be formatted
:return: Substring without the trailing parentheses
"""
return ' '.join(option.split(' ')[:-1]).strip()
|
def construct_existor_expr(attrs):
"""Construct a exists or LDAP search expression.
:param attrs: List of attribute on which we want to create the search
expression.
:return: A string representing the expression, if attrs is empty an
empty string is returned
"""
expr = ""
if len(attrs) > 0:
expr = "(|"
for att in attrs:
expr = "%s(%s=*)"%(expr,att)
expr = "%s)"%expr
return expr
|
def RGBStringToTuple(rgb_str, make7bit = True):
"""Takes a color string of format #ffffff and returns an RGB tuple.
By default the values of the tuple are converted to 7-bits.
Pass False as the second parameter for 8-bits."""
rgb_tuple = (0, 0, 0)
if (len(rgb_str) >= 7) and (rgb_str[0] == "#"):
red = int(rgb_str[1:3], 16)
green = int(rgb_str[3:5], 16)
blue = int(rgb_str[5:7], 16)
if make7bit:
red = red // 2
green = green // 2
blue = blue // 2
rgb_tuple = (red, green, blue)
return rgb_tuple
|
def _get_updated_roles_data(role_id, person_ids, role_list):
"""Get person email for the updated roles"""
data = []
for person_id in person_ids:
for role in role_list:
if role['ac_role_id'] == role_id and role['person_id'] == person_id:
if 'person_email' in role:
data.append(role['person_email'])
return data
|
def coord2int(x, y, size=3):
"""
Converts a pair of coordinates to a scalar/index value
:param x:
:param y:
:param size: the width/height of a perfect square
:return:
"""
return (x*size) + y
|
def convert_to_int(val):
"""
Converts string to int if possible, otherwise returns initial string
"""
#print("WHAT?",val)
try:
return int(val)
except ValueError:
#print("DDDDDDDDDDD",val)
pass
try:
return float(val)
except ValueError:
return val
|
def gaussianQuadrature(function, a, b):
"""
Perform a Gaussian quadrature approximation of the integral of a function
from a to b.
"""
# Coefficient values can be found at pomax.github.io/bezierinfo/legendre-gauss.html
A = (b - a)/2
B = (b + a)/2
return A * (
0.2955242247147529*function(-A*0.1488743389816312 + B) + \
0.2955242247147529*function(+A*0.1488743389816312 + B) + \
0.2692667193099963*function(-A*0.4333953941292472 + B) + \
0.2692667193099963*function(+A*0.4333953941292472 + B) + \
0.2190863625159820*function(-A*0.6794095682990244 + B) + \
0.2190863625159820*function(+A*0.6794095682990244 + B) + \
0.1494513491505806*function(-A*0.8650633666889845 + B) + \
0.1494513491505806*function(+A*0.8650633666889845 + B) + \
0.0666713443086881*function(-A*0.9739065285171717 + B) + \
0.0666713443086881*function(+A*0.9739065285171717 + B)
)
|
def get_max(filename):
"""
Isolate the maximum search size from a file name.
Example
input: github_notebooks_200..203_p3.json
output: 203
"""
return int(filename.split("_")[2].split("..")[1])
|
def pwm2rpm(pwm, pwm2rpm_scale, pwm2rpm_const):
"""Computes motor squared rpm from pwm.
Args:
pwm (ndarray): Array of length 4 containing PWM.
pwm2rpm_scale (float): Scaling factor between PWM and RPMs.
pwm2rpm_const (float): Constant factor between PWM and RPMs.
Returns:
ndarray: Array of length 4 containing RPMs.
"""
rpm = pwm2rpm_scale * pwm + pwm2rpm_const
return rpm
|
def compare_fields(lhs, rhs):
"""
Comparison function for cpe fields for ordering
- * is considered least specific and any non-* value is considered greater
- if both sides are non-*, comparison defaults to python lexicographic comparison for consistency
"""
if lhs == "*":
if rhs == "*":
return 0
else:
return 1
else:
if rhs == "*":
return -1
else:
# case where both are not *, i.e. some value. pick a way to compare them, using lexicographic comparison for now
if rhs == lhs:
return 0
elif rhs > lhs:
return 1
else:
return -1
|
def progress_bar_width(p):
"""Compute progress bar width."""
p = int(p)
return 15.0 + p * 0.85
|
def calc_3d_dist(p, q):
"""
:param p: robot position list p
:param q: robot position list q
:return: the 3D Euclidean distance between p and q
"""
return sum((p - q) ** 2 for p, q in zip(p, q)) ** 0.5
|
def insert_shift_array(lst, val):
"""Takes in a list and a value and insertes the value in the center of the list"""
center = (len(lst) + 1) // 2
return lst[:center] + [val] + lst[center:]
|
def GetNiceArgs(level: int):
"""Returns the command/arguments to set the `nice` level of a new process.
Args:
level: The nice level to set (-20 <= `level` <= 19).
"""
if level < -20 or level > 19:
raise ValueError(
f"The level must be >= -20 and <= 19. The level specified is {level}.")
return ["nice", "-n", str(level)]
|
def _between_symbols(string, c1, c2):
"""Will return empty string if nothing is between c1 and c2."""
for char in [c1, c2]:
if char not in string:
raise ValueError("Couldn't find charachter {} in string {}".format(
char, string))
return string[string.index(c1)+1:string.index(c2)]
|
def solve(N, M, items):
""" Greedy version """
res = 0
shoots = [0] * (N + M)
for n, m in items:
shoots[n] += 1
shoots[N + m] += 1
while any(s != None for s in shoots):
av = min([(n, s) for n, s in enumerate(shoots) if s != None], key=lambda x: x[1])[0]
res += 1
shoots[av] = None
if av < N: # is a row
for n, m in items:
if n == av and shoots[N + m] != None:
shoots[N + m] = None
for n2, m2 in items:
if m2 == m and shoots[n2] != None:
shoots[n2] -= 1
else: # is a col
for n, m in items:
if m == av - N and shoots[n] != None:
shoots[n] = None
for n2, m2 in items:
if n2 == n and shoots[N + m2] != None:
shoots[N + m2] -= 1
return res
|
def contains_words(message, words):
"""
Checks if a message contains certain words.
:param message: Text message to check
:param words: List of words
:return: Boolean if all words are contained in the message
"""
for w in words:
if str(message).lower().find(w) < 0:
return False
return True
|
def insert_cnpj(num):
"""
Cast a string of digits to the formatted 00.000.000/0001-00 CNPJ standard.
"""
cnpj = num[:2]+'.'+num[2:5]+'.'+num[5:8]+r'/'+num[8:12]+'-'+num[12:]
return cnpj
|
def parser_shortname(parser_argument):
"""short name of the parser with dashes and no -- prefix"""
return parser_argument[2:]
|
def valid(board, val, pos):
"""Checks if value is valid to be entered in the cell or not
params : val : int
pos : tuple (cell cordinates)
returns : boolean
"""
# Check row
for i in range(len(board[0])):
if board[pos[0]][i] == val and pos[1] != i:
return False
# Check column
for i in range(len(board)):
if board[i][pos[1]] == val and pos[0] != i:
return False
# Check box
box_x = pos[1] // 3
box_y = pos[0] // 3
for i in range(box_y * 3, box_y * 3 + 3):
for j in range(box_x * 3, box_x * 3 + 3):
if board[i][j] == val and (i, j) != pos:
return False
return True
|
def is_sequence(arg):
"""
Checks to see if something is a sequence (list).
Parameters
----------
arg : str
The string to be examined.
Returns
-------
sequence : bool
Is True if `arg` is a list.
"""
sequence = (not hasattr(arg, 'strip') and hasattr(arg, '__getitem__')
or hasattr(arg, '__iter__'))
return sequence
|
def _bump_seed(seed):
"""
Helper to bump a random seed if not None.
"""
return None if seed is None else seed + 1
|
def pci_deleted(new_list, old_list):
"""Returns list of elements in old_list which are not present in new list."""
delete_list = []
for entry in old_list:
# Check whether bus addresses and interface names match in the two lists for
# each entry.
bus_addr_matches = [x for x in new_list if x['bus_address'] == entry['bus_address'] and
x.get('config_script', None)]
device_matches = [x for x in new_list if x['device'] == entry['device'] and
x.get('config_script', None)]
if not (bus_addr_matches and device_matches):
delete_list.append(entry)
return delete_list
|
def compare_dicts(cloud1, cloud2):
"""
Compare the dicts containing cloud images or flavours
"""
if len(cloud1) != len(cloud2):
return False
for item in cloud1:
if item in cloud2:
if cloud1[item] != cloud2[item]:
return False
else:
return False
return True
|
def format_version(version):
"""format server version to form X.X.X
Args:
version (string): string representing Demisto version
Returns:
string.
The formatted server version.
"""
formatted_version = version
if len(version.split('.')) == 1:
formatted_version = f'{version}.0.0'
elif len(version.split('.')) == 2:
formatted_version = f'{version}.0'
return formatted_version
|
def setup_cmd_input(multi, sequences, ordering, structure = ''):
""" Returns the command-line input string to be given to NUPACK. """
if not multi:
cmd_input = '+'.join(sequences) + '\n' + structure
else:
n_seqs = len(sequences)
if ordering == None:
seq_order = ' '.join([str(i) for i in range(1, n_seqs+1)])
else:
seq_order = ' '.join([str(i) for i in ordering])
cmd_input = str(n_seqs) + '\n' + ('\n'.join(sequences)) + '\n' + seq_order + '\n' + structure
return cmd_input.strip()
|
def _inc_average(count, average, value):
"""Computes the incremental average, `a_n = ((n - 1)a_{n-1} + v_n) / n`."""
count += 1
average = ((count - 1) * average + value) / count
return (count, average)
|
def count_steps(splitting="OVRVO"):
"""Computes the number of O, R, V steps in the splitting string"""
n_O = sum([step == "O" for step in splitting])
n_R = sum([step == "R" for step in splitting])
n_V = sum([step == "V" for step in splitting])
return n_O, n_R, n_V
|
def _describe_source(d):
"""return either '<path>' or 'line N of <path>' or 'lines M-N of <path>'.
"""
path = d.get('path') or ''
if 'num_lines' in d and 'start_line' in d:
if d['num_lines'] == 1:
return 'line %d of %s' % (d['start_line'] + 1, path)
else:
return 'lines %d-%d of %s' % (
d['start_line'] + 1, d['start_line'] + d['num_lines'], path)
else:
return path
|
def char_value(char):
"""A=10, B=11, ..., Z=35
"""
if char.isdigit():
return int(char)
else:
return 10 + ord(char) - ord('A')
|
def vault_encrypted(value):
"""Evaulate whether a variable is a single vault encrypted value
.. versionadded:: 2.10
"""
return getattr(value, '__ENCRYPTED__', False) and value.is_encrypted()
|
def _dec_to_base(num, nbits, base):
"""
Creates a binary vector of length nbits from a number.
"""
new_num = num
bin = []
for j in range(nbits):
current_bin_mark = base**(nbits-1-j)
if (new_num >= current_bin_mark):
bin.append(1)
new_num = new_num - current_bin_mark
else:
bin.append(0)
return bin
|
def v2_subscriptions_response(subscriptions_response):
"""Define a fixture that returns a V2 subscriptions response."""
subscriptions_response["subscriptions"][0]["location"]["system"]["version"] = 2
return subscriptions_response
|
def camelify(s):
"""Helper function to convert a snake_case name to camelCase."""
start_index = len(s) - len(s.lstrip("_"))
end_index = len(s.rstrip("_"))
sub_strings = s[start_index:end_index].split("_")
return (s[:start_index]
+ sub_strings[0]
+ "".join([w[0].upper() + w[1:] for w in sub_strings[1:]])
+ s[end_index:])
|
def _cut_eos(predict_batch, eos_id):
"""cut the eos in predict sentences"""
pred = []
for s in predict_batch:
s_ = []
for w in s:
if(w == eos_id): break
s_.append(w)
pred.append(s_)
return pred
|
def strip_type_hints(source_code: str) -> str:
"""This function is modified from KFP. The original source is below:
https://github.com/kubeflow/pipelines/blob/b6406b02f45cdb195c7b99e2f6d22bf85b12268b/sdk/python/kfp/components/_python_op.py#L237-L248
"""
# For wandb, do not strip type hints
# try:
# return _strip_type_hints_using_lib2to3(source_code)
# except Exception as ex:
# print('Error when stripping type annotations: ' + str(ex))
# try:
# return _strip_type_hints_using_strip_hints(source_code)
# except Exception as ex:
# print('Error when stripping type annotations: ' + str(ex))
return source_code
|
def rectified_linear(x):
"""Bounds functions with a range of [-infinity, 1] to [0, 1].
Negative values are clipped to 0.
This function is used for scorers, e.g. R^2 (regression metric), where
1 is the best possible score, 0 indicates expected value of y, and negative
numbers are worse than predicting the mean.
"""
return 0 if x < 0 else x
|
def reverse_bits(value, width):
"""Reverses bits of an integer.
Reverse bits of the given value with a specified bit width.
For example, reversing the value 6 = 0b110 with a width of 5
would result in reversing 0b00110, which becomes 0b01100 = 12.
Args:
value (int): Value to be reversed.
width (int): Number of bits to consider in reversal.
Returns:
The reversed int value of the input.
"""
binary_val = '{:0{width}b}'.format(value, width=width)
return int(binary_val[::-1], 2)
|
def jid_escape(nodeId):
"""
Unescaped Character Encoded Character
<space> \20
" \22
\ \5c
& \26
' \27
/ \2f
: \3a
< \3c
> \3e
@ \40
"""
if nodeId is None:
return
newNode = nodeId
newNode = newNode.replace("\\", '\\5c')
newNode = newNode.replace(' ', "\\20")
newNode = newNode.replace('"', '\\22')
newNode = newNode.replace("&", '\\26')
newNode = newNode.replace("'", '\\27')
newNode = newNode.replace("/", '\\2f')
newNode = newNode.replace(":", '\\3a')
newNode = newNode.replace("<", '\\3c')
newNode = newNode.replace(">", '\\3e')
newNode = newNode.replace("@", '\\40')
return newNode
|
def __analysis_list_to_dict__(data_list):
""" Given a data_list (list of sublists) it creates dictionary with key-value dictionary entries
@parameter
data_list (list)
@returns
dict_list (list)
"""
dictionary = dict()
for incident in data_list:
# index 0: timestamp, index 1: num of attacks
dictionary[incident[0]] = incident[1]
return dictionary
# -----------------------------------------------------------------------------------------------------------------#
|
def variables(data):
"""Get variables (int32_t)."""
return [
[ # multipliers for sensors
(name, value)
for name, value in data['multipliers'].items()
],
[ # other json specific variables
(name, value) if type(value) is not list else value
for name, value in data['variables'].items()
]
]
|
def round_pruning_amount(total_parameters, n_to_prune, round_to):
"""round the parameter amount after pruning to an integer multiple of `round_to`.
"""
n_remain = round_to*max(int(total_parameters - n_to_prune)//round_to, 1)
return max(total_parameters - n_remain, 0)
|
def calculate_percent(partial, total):
"""Calculate percent value."""
if total:
percent = round(partial / total * 100, 2)
else:
percent = 0
return f'{percent}%'
|
def replace_config(a, b):
"""Updates fields in a by fields in b."""
a.update(b)
return a
|
def getGlobalVariable(name):
"""Returns the value of a requested global variable, or None if does not exist.
name -- the name of the global variable whose value should be returned.
"""
if name in globals():
return globals()[name]
else:
return None
|
def str2bool(s):
""" convert string to a python boolean """
return s.lower() in ("yes", "true", "t", "1")
|
def localizePath(path):
"""
str localizePath(path)
returns the localized version path of a file if it exists, else the global.
"""
#locale='de_DE'
#locPath=os.path.join(os.path.dirname(path), locale, os.path.basename(path))
#if os.path.exists(locPath):
# return locPath
return path
|
def get_label(audio_config):
"""Returns label corresponding to which features are to be extracted
e.g:
audio_config = {'mfcc': True, 'chroma': True, 'contrast': False, 'tonnetz': False, 'mel': False}
get_label(audio_config): 'mfcc-chroma'
"""
features = ["mfcc", "chroma", "mel", "contrast", "tonnetz"]
label = ""
for feature in features:
if audio_config[feature]:
label += f"{feature}-"
return label.rstrip("-")
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.