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 ... |
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
"""
... |
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:
... |
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... |
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
... |
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:
... |
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 asc... |
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... |
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
# otherwis... |
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
----------
... |
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.
heig... |
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)
... |
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 =... |
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
el... |
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,
**resp... |
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 = {
... |
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
ste... |
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 ... |
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
... |
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():
... |
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]
# ... |
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 waveleng... |
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_selecti... |
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: ]
... |
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... |
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] == "#"... |
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['pers... |
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 va... |
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 ... |
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:
n... |
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 == "*"... |
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... |
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.in... |
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... |
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:
... |
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 F... |
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, '__geti... |
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_lis... |
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:
ret... |
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'... |
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,... |
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 ... |
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 - curren... |
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:... |
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
# ... |
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 predict... |
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. ... |
def jid_escape(nodeId):
"""
Unescaped Character Encoded Character
<space> \20
" \22
\ \5c
& \26
' \27
/ \2f
: \3a
< ... |
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:
... |
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
... |
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", ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.