content stringlengths 42 6.51k |
|---|
def _clean_annotated_text(text):
"""Cleans text from the format that it was presented to annotators in the
S.M.A.R.T data annotation tool. Splits the title from the abstract text
and strips any trailing whitespace.
Returns:
title (str): The project title
text (str): The project abstra... |
def populate_item_object_ref_paths(set_items, obj_selector):
"""
Called when include_set_item_ref_paths is set.
Add a field ref_path to each item in set
"""
for set_item in set_items:
set_item["ref_path"] = obj_selector['ref'] + ';' + set_item['ref']
return set_items |
def solution(n):
"""Returns the sum of all fibonacci sequence even elements that are lower
or equals to n.
>>> solution(10)
[2, 8]
>>> solution(15)
[2, 8]
>>> solution(2)
[2]
>>> solution(1)
[]
>>> solution(34)
[2, 8, 34]
"""
ls = []
a, b = 0, 1
while b <... |
def repeat(s, exclaim):
"""
Repeat the String 's' three times,
If the exclaim is true, it will add ! at the end
"""
result = s * 3 #append s back to back three times.
if exclaim:
result = result + '!!!'
return result |
def dtd_correction(params):
"""
When normalizing DTDs to 1 sometimes a correction factor is needed,
caused by the uncertainty in the value of the integral of the DTD for the whole mass range
"""
if "dtd_correction_factor" in params:
return params["dtd_correction_factor"]
return 1.0 |
def fib_dp(n):
"""
An optimized dynamic programming solution to find a single number of the
Fibonacci sequence. It runs in O(n) time with O(1) space complexity.
"""
if not isinstance(n, int):
raise TypeError("n must be an int")
if n < 0:
raise ValueError("n must be non-negative")... |
def file_contents(filename):
"""Return the contents of filename."""
f = open(filename, 'r')
contents = f.read()
f.close()
return contents |
def bitCount(int_type):
""" Count bits set in integer """
count = 0
while(int_type):
int_type &= int_type - 1
count += 1
return(count) |
def encode_boolean(value):
"""
Returns 1 or 0 if the value is True or False.
None gets interpreted as False.
Otherwise, the original value is returned.
"""
if value is True:
return 1
if value is False or value is None:
return 0
return value |
def get_full_class_name(object_instance):
"""
Returns full class name
:param object_instance: object instance
"""
return object_instance.__module__ + "." + object_instance.__name__ |
def derivative_nk(nkb_average, nkt):
"""Gera d_nk"""
return (nkb_average - nkt) / nkt |
def is_256_bit_imm(n):
"""Is n a 256-bit number?"""
return type(n) == int and n >= 0 and 1 << 256 > n |
def _set_loc_key(d, k, value):
"""Set key ``k`` in ``d`` to ``value```."""
if not value:
return None
if k in d:
try:
d[k].union(value.copy())
except KeyError as e:
raise KeyError('Problem at location {}: {}'.format(k, str(e)))
else:
d[k] = value.co... |
def strip_comments(s):
"""Strips comment lines and docstring from Python source string."""
o = ''
in_docstring = False
for l in s.split('\n'):
if l.strip().startswith(('#', '"', "'")) or in_docstring:
in_docstring = l.strip().startswith(('"""', "'''")) + in_docstring == 1
... |
def data_to_rows(data):
"""Unzip column-wise data from doc._.data into rows"""
col_data = [data[key] for key in data.keys()]
row_data = list(zip(*col_data))
return row_data |
def get_unique_mask_name(task_type: str, mask_name: str) -> str:
"""Prepends the task name to the mask name to ensure uniqueness.
Args:
task_type: Name of the task for which the masks are being modified.
mask_name: Name of the mask e.g. base_eval.
Returns:
A mask name that has the task name prepende... |
def ok(message, data=None, http_status_code=200, **kwargs):
"""
used when no error
:param message: some message
:param data: data for return
:param http_status_code: http status code
:param kwargs: other data for return
:return:
"""
return {"message": message, "data": data, ... |
def average_above_zero (items):
"""
Compute the average of an given array only for positive values.
@type items: list
@param items: List of positive values
@rtype: float
@return: Return the average of the list
"""
# Don't compute if items isn't an List (array)
if type(items) is not list:
... |
def date_weekday_excel(x) :
"""function date_weekday_excel
Args:
x:
Returns:
"""
import datetime
date = datetime.datetime.strptime(x,"%Y%m%d")
wday = date.weekday()
if wday != 7 : return wday+1
else : return 1 |
def _ds(s):
"""Decode a bytestring for printing"""
return s.decode("utf-8", "backslashreplace") |
def return_repeating_word(values):
"""A helper function for read_line().
Address issues where word has repeating chargers, return them as a single word.
:param values: values, a line of embedding text data
:return: A string of repeating characters.
"""
word = []
first_char = values[0]
... |
def is_label_or_synonym(labels, provided_label):
"""Determine if a user-provided ontology label is a valid label or synonymn
:param labels: cached ontology label/synonyms from retriever.retrieve_ontology_term_label_and_synonyms
:param provided_label: user-provided label from metadata file
:return: True/... |
def _get_persons(event):
"""Get string of persons from event"""
persons = []
for person in event['persons']:
persons.append(person['public_name'])
return ', '.join(persons) |
def trim_data(data, xy, p = 0.1):
"""
RIGHT FROM iREP
remove data from ends of sorted list
"""
if xy is False:
length = len(data)
num = int(length * (p/2))
return data[num:length - num]
X, Y = data
length = len(X)
num = int(length * (p/2))
return X[num:length... |
def randSeed(val):
""" validates the range of random seed"""
if type(val) == int and 0 <= val < 2**32:
return val
else:
raise ValueError("0 <= random seed < 2^32 is the correct range") |
def is_valid_hour(seconds):
"""Check if the provided seconds is a
valid hour.
:seconds: provided seconds value
"""
if seconds % 3600 == 0:
return True
return False |
def map_llc_result_to_dictionary_list(land_charge_result):
"""Produce a list of jsonable dictionaries of an alchemy result set
"""
if not isinstance(land_charge_result, list):
return list(map(lambda land_charge: land_charge.to_dict(),
[land_charge_result]))
else:
... |
def bboxArea(a):
"""
box area
:param a:
:return:
"""
return (a[2] - a[0]) * (a[3] - a[1]) |
def tf_idf_vector(term_frequency, idf):
"""Calculates tf/idf vector"""
try:
return term_frequency * idf
except ZeroDivisionError:
return 0 |
def format_variable_name(name):
"""
Format Python variable name to LaTeX variable name
Remove underscores and case the first letter of each word.
"""
return name.replace("_", " ").title().replace(" ", "") |
def error(*_):
"""
System method
:return: dict
"""
return {'type': 'error', 'data': 'Bad request'} |
def folder( path ):
"""Extracts the resource folder."""
return path[:1+path.rfind('/')] |
def mock_valid_dropbox_config():
"""Mock valid Dropbox config."""
return {"access_token": "XXXXXXX", "upload_directory": "/home/dropbox_user/Documents/"} |
def wuyts_line_Av(Acont):
"""
Wuyts prescription for extra extinction towards nebular emission
"""
return Acont + 0.9*Acont - 0.15*Acont**2 |
def _as_list(list_str, delimiter=','):
"""Return a list of items from a delimited string (after stripping whitespace).
:param list_str: string to turn into a list
:type list_str: str
:param delimiter: split the string on this
:type delimiter: str
:return: string converted to a list
:rtype... |
def _word_to_bool(word):
"""convert a string to boolean according the first 2 characters."""
_accepted_bool_prefixes = ("T", ".T")
return word.upper().startswith(_accepted_bool_prefixes) |
def all_same(L):
"""Check if all elements in list are equal.
Parameters
----------
L : array-like, shape (n,)
List of objects of any type.
Returns
-------
y : bool
True if all elements are equal.
"""
y = len(L) == 0 or all(x == L[0] for x in L)
return y |
def dt_dosage(value, member_id=None):
"""
Format Dosage Complex data type
:param value:
:return: f_value
"""
f_value = ""
for v in value:
if isinstance(v, int) or isinstance(v, float):
if v == 0:
pass
else:
f_value += str(v) + "... |
def prime_check(n):
"""Return True if n is a prime number
Else return False.
##-------------------------------------------------------------------
"""
if n <= 1:
return False
if n == 2 or n == 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
j = 5
while j... |
def rem(x, a):
"""
Parameters
----------
x : a non-negative integer argument
a : a positive integer argument
Returns
-------
integer, the remainder when x is divided by a
"""
if x == a:
return 0
elif x < a:
return x
else:
return rem(x-a, a) |
def shake_shake_eval(xa, xb):
"""Shake-shake regularization: evaluation.
Args:
xa: input, branch A
xb: input, branch B
Returns:
Mix of input branches
"""
# Blend between inputs A and B 50%-50%.
return (xa + xb) * 0.5 |
def expand_year(year):
"""Convert 2-digit year to 4-digit year."""
if year < 80:
return 2000 + year
else:
return 1900 + year |
def __get_pod_service_list(pod_items):
"""
Returns a set of pod service_account names from the pod_list parameter
:param pod_items: the list of pod_items from which to extract the name
:return: set of pod names
"""
out_names = set()
for pod_item in pod_items:
if pod_item.spec.service... |
def insert_at(alist, i, x):
"""This function returns a new list, with x inserted
at location i
"""
# CHANGE OR REMOVE THE LINE BELOW
return alist[:i] + [x] + alist[(i+1):] |
def shift_list(array, s):
"""Shifts the elements of a list to the left or right."""
s %= len(array)
s *= -1
shifted_array = array[s:] + array[:s]
return shifted_array |
def arg01_to_bool(args, argName):
"""
This function takes {request.args} and check if the argName is 1 or 0.\n
If argName is "1", it returns True.\n
If argname is "0", it returns False.\n
And if it is anything else, or if it does not exist, it returns False aswell.
"""
if str... |
def _check_dof(dof):
"""Check the user provided 'dofs'.
Parameters
----------
dofs : array-like, shape (n_components,)
The degrees-of-freedom of each mixture.
n_components : int
Number of components.
Returns
-------
weights : array, shape (n_components,)
"""
# ... |
def checkForTextHavingOnlyGivenChars(text, ws=None):
"""Checks whether text contains only whitespace (or other chars).
Does the given text contain anything other than the ws characters?
Return true if text is only ws characters.
"""
if ws is None:
return text.isspace()
else:
for... |
def getElevations(trackSegments):
"""returns array of elevations in metres from trackSegments"""
elevations = []
for seg in trackSegments:
elevations.append([float(item.get("ele")) for item in seg])
return elevations |
def latex_format_e(num, pre=2):
"""Format a number for nice latex presentation, the number will *not* be enclosed in $"""
s = ("{:." + "{:d}".format(pre) + "e}").format(num)
fp, xp = s.split("e+")
return "{} \\times 10^{{{}}}".format(fp, int(xp)) |
def replace_prefix(text, find, replace):
"""Replace all leading instances of a string with another string.
Args:
text (str): Text to screw with
find (str): Characters to replace
replace (str): Characters to replace with
Returns:
str: `text` with all leading instances of `fi... |
def is_freq(*args):
"""Determine if input args require FreqPart"""
is_freq = False
if len(args) == 1 and type(args[0]) == tuple:
args = args[0] # if called from another script with *args
for arg in args:
if "freqs" in arg or "wavenumber" in arg:
is_freq = True
br... |
def isnumber(x):
"""Returns True, if x is a number (i.e. can be converted to float)."""
if x is None: return False
try:
float(x)
return True
except ValueError:
return False |
def one_list_to_val(val, convert_tuple=False):
"""
Convert a single list element to val
:param val:
:return:
"""
if isinstance(val, (list, tuple) if convert_tuple else (list,)) and len(val) == 1:
result = val[0]
else:
result = val
return result |
def urlify(string, length):
""" Replace single spaces with %20 and remove trailing spaces
Time complexity: O(N)
Space complexity: O(1): in-place
"""
new_index = len(string) # This is the actual length including trailing spaces to hold the additional character
for i in reversed(range(length)): ... |
def to_int(rating_count):
""" Return rating count as an int """
rating_count = rating_count.split()[0]
if ',' in rating_count:
return int(rating_count.replace(',', ''))
return int(rating_count) |
def space_separated_elements(array):
"""Converts the question_tags array to a space delimited string."""
string = ""
for element in array:
string = string + element + " "
return string |
def dot_product(vector1, vector2):
"""
Computes the dot product.
param list vector1, vector2: input vectors
"""
result = sum([x*y for x, y in zip(vector1, vector2)])
return result |
def wind_vref_5vave(vave, factor=5):
"""
It calculates the 50 year return expected maximum wind speed as 5 times the
long term average wind speed.
It uses 10-minute wind speeds to obtain the 50-year return period extreme
wind speed.
**Parameters**
vave : float or int
Long term mea... |
def xyz_to_XYZ(v):
"""
convert xyz to XYZ
"""
V = [(1.0/v[1])*v[0], 1.0,(1.0/v[1])*v[2]]
#print "XYZ val:",V
return V |
def solution(power):
"""Returns the sum of the digits of the number 2^power.
>>> solution(1000)
1366
>>> solution(50)
76
>>> solution(20)
31
>>> solution(15)
26
"""
n = 2 ** power
r = 0
while n:
r, n = r + n % 10, n // 10
return r |
def check_all_rows(A):
"""
Check if all rows in 2-dimensional matrix don't have more than one queen
"""
for row_inx in range(len(A)):
# compute sum of row row_inx
if sum(A[row_inx]) > 1:
return False
return True |
def add_to_sparse_tuple(tpl, index, new_value):
"""
Return a new tuple based on tpl with new_value added at the given index.
The tuple is either expanded with ``None`` values to match the new size
required or the value is replaced. ::
>>> t = add_to_sparse_tuple(('a', 'b'), 5, 'f')
>>> ... |
def _allocation_type(action) -> tuple:
"""Get details of child policy"""
allocation = '---'
action_type = '---'
if action.get("action-type",{}) == 'shape':
if 'bit-rate' in action.get('shape',{}).get('average',{}):
allocation = str(round(int(action.get("shape",{}).get("average",{})... |
def validate_input(cents: int, exceptions_on: bool=True):
"""Validates user input cents.
Checks to make sure input is an integer and is a valid cents value.
If it is, the value is returned. If it isn't, an exception is
raised and None is returned.
Parameters:
cents (int): The cents input to validate.
excep... |
def get_boolean(value):
""" Return a bool from value.
Args:
value: A string or bool representing a boolean.
Returns:
If value is a bool, value is returned without modification.
If value is a string this will convert 'true' and 'false'
(ignoring case) to their associated values.
Raises:
V... |
def transliterate(trans, item):
"""Transliterates string, list of strings and list of list of strings"""
if isinstance(item, str):
return trans.get(item, item)
if isinstance(item, list) and len(item) > 0:
if isinstance(item[0], str):
return [trans.get(i, i) for i in item]
... |
def parse_filename(filename):
"""Returns the separate directory, basename, and file suffix for the given
filename.
Parameters
----------
filename : str
Name of a file.
Returns
-------
directory : str
Directory containing the file.
basename : str
Name of file... |
def _set_cache_value(key, value):
""" Sets or updates the value for a cache key """
with open(key, 'w') as f:
f.seek(0)
f.write(str(value))
return value |
def prime_out(num):
"""prime_out: A user-friendly tool to evaluate whether or not a number is prime.
Args:
num (int): Number to be evaluated as prime
Returns:
Prints whether or not the number is prime and how long it took to evaluate.
"""
import time
t1_start = time.perf_counter()
... |
def capStrLen(string, length):
"""
Truncates a string to a certain length.
Adds '...' if it's too long.
Parameters
----------
string : str
The string to cap at length l.
length : int
The maximum length of the string s.
"""
if length <= 2:
raise Exception("l ... |
def fill(array, value, start=0, end=None):
"""Fills elements of array with value from start up to, but not including, end.
Args:
array (list): List to fill.
value (mixed): Value to fill with.
start (int, optional): Index to start filling. Defaults to ``0``.
end (int, optional): ... |
def is_legal_filename(name):
"""
Function that returns true if the given name can be used as a
filename
"""
if name == "":
return False
if " " in name:
return False
if "/" in name:
return False
if "\\" in name:
return False
return True |
def apply_basic_padding(text, blocksize=16):
"""just fill with null bytes at the end"""
_p = len(text)%blocksize # padding length
return text + (_p > 0 and bytes(blocksize - _p) or b'\0')
# =
# return text + (bytes(blocksize - _p) if _p > 0 else b'') |
def _num_two_factors(x):
"""return number of times x is divideable for 2"""
if x <= 0:
return 0
num_twos = 0
while x % 2 == 0:
num_twos += 1
x //= 2
return num_twos |
def dollarify(value):
"""Filter to convert int to dollar value"""
return '${:,.2f}'.format(value) |
def encode_int(i, nbytes, encoding='little'):
""" encode integer i into nbytes bytes using a given byte ordering """
return i.to_bytes(nbytes, encoding) |
def _swapxy(data):
"""Helper function to swap x and y coordinates"""
return [(y, x) for (x, y) in data] |
def __parse_cookies(headers):
"""
@type headers dict
@return dict
Parses cookies from response headers.
"""
cookies = {}
if 'Set-Cookie' in headers:
raw_cookies = headers['Set-Cookie'].split(';')
for cookie in raw_cookies:
... |
def obscure_mpinstaller_deployment_test_failure(text):
"""
Returns 'Apex Test Failure' as the error text if the text contains a test failure
message.
"""
if "Apex Test Failure: " in text:
return "Apex Test Failure"
return text |
def ispalindrome(no)->bool:
"""
If number is palindrome function return true else false.
"""
if type(no)==list:
if no==no[::-1]:
return True
else:
return False
else:
no=str(no)
rev=no[::-1]
if no==rev:
return True
else:
return False |
def remove_empty_lines(text):
"""remove empty lines"""
assert(len(text)>0)
assert(isinstance(text, list))
text = [t.strip() for t in text]
if "" in text:
text.remove("")
return text |
def isn(parameter, value):
"""
usage: k = isn(k, 'default')
alternative: if k is not None: k = 'default'
:param parameter:
:param value:
:return:
"""
# if parameter is None:
# return value
# else:
# return parameter
return parameter or value |
def get_call_uri(ad, call_id):
"""Get call's uri field.
Get Uri for call_id in ad.
Args:
ad: android device object.
call_id: the call id to get Uri from.
Returns:
call's Uri if call is active and have uri field. None otherwise.
"""
try:
call_detail = ad.droid.t... |
def as_seq(x, seq_type=None):
"""
If x is not a sequence, returns it as one. The seq_type argument allows the
output type to be specified (defaults to list). If x is a sequence and
seq_type is provided, then x is converted to seq_type.
Arguments
---------
x : seq or object
seq_type : o... |
def ppm_to_dalton(mass:float, prec_tol:int)->float:
"""Function to convert ppm tolerances to Dalton.
Args:
mass (float): Base mass.
prec_tol (int): Tolerance.
Returns:
float: Tolerance in Dalton.
"""
return mass / 1e6 * prec_tol |
def rtsip_to_tag(rel_type, rel_sense, rel_id, rel_part):
"""Convert relation type, sense, id, and part to tag."""
rel_tag = ":".join([rel_type, rel_sense, str(rel_id), rel_part])
return rel_tag |
def missing_param(param):
"""Sets param to 'dummy_data'"""
out = {param: 'dummy_data'}
return out |
def partitionCtr(nums):
"""Compute sumCounter for partition"""
sumCount = [0, 0]
for num in nums:
sumCount[0] += num
sumCount[1] += 1
return [sumCount] |
def to_string(nodes):
"""
Serialise a forest of DOM nodes to text,
using the data fields of text nodes.
:param nodes: the forest of DOM nodes
:return: a concatenation of string representations.
"""
result = []
for node in nodes:
if node.nodeType == node.TEXT_NODE:
res... |
def search_key_for_scene(scene):
"""Generate a string search key for a scene"""
elements = []
elements.append(scene['sceneName']) # name of scene
return u' '.join(elements) |
def time_diff(t0, t1):
"""
Args:
:t0: start time in seconds
:t1: end time in seconds
Returns: string with time difference (i.e. t1-t0)
"""
minutes, seconds = divmod(t1 - t0, 60)
hours, minutes = divmod(minutes, 60)
return "%d hours, %d minutes, %d seconds" % (hours, minutes, ... |
def list_profiles(profilejson):
""" expecting big json chunk containing all profiles applied to the virtual server.
returns a string listing profile names
"""
listofprofiles = ''
for nextprofile in profilejson['items']:
if listofprofiles == '' :
listofprofiles = nextprofile['name']
else:
l... |
def point_in_polygon(point, polygon):
"""
Checks if a point is inside a polygon.
:param point: point
:param polygon: polygon
:return: point is inside polygon
"""
px, py = point
size = len(polygon)
for i in range(size):
p1x, p1y = polygon[i]
p2x, p2y = polygon[(i + 1... |
def get_auth_token_url(host: str) -> str:
"""
Generate URL that creates an authentication token for the user.
:return: URL to generate the token.
"""
return f"{host}/api/token-auth/" |
def Hk(X, k):
"""
Calculate Hk for Sk(x)
Parameters
----------
X : list
list of x values
k : int
index from X
Returns
-------
float
Hk from cubic spline
"""
return X[k] - X[k - 1] |
def config_from_onnx_model(model, granularity='model', default_precision='ap_fixed<16,6>', default_reuse_factor=1):
"""Generate configuration dictionary from an ONNX model.
Parameters
----------
model : ONNX model object.
Model to be converted to hls model object.
granularity : string, ... |
def generate_placeholder(length, width):
"""
Generate "(%s, %s, %s, ...), ..." for placing parameters.
"""
return ','.join('(' + ','.join(['%s'] * width) + ')' for _ in range(length)) |
def camel_to_underscore(string):
"""Translates amazon Camelcased strings to
lowercased underscored strings"""
res = []
for index, char in enumerate(string):
if index != 0 and char.isupper():
res.extend(['_', char.lower()])
else:
res.extend([char.lower()])
re... |
def cauchy(wvl, A, *args):
"""Cauchy's equation for the (real) index of refraction of transparent materials.
Parameters
----------
wvl : `number`
wavelength of light, microns
A : `number`
the first term in Cauchy's equation
args : `number`
B, C, ... terms in Cauchy's equ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.