content stringlengths 42 6.51k |
|---|
def unique(elements):
"""
Returns a list of unique elements from the `elements`.
:param elements: the input elements.
:type elements: list
:return: the list of unique elements
:rtype: list
"""
element_set = set()
unique_list = []
for element in elements:
if isinstance(el... |
def label_given_method_str(method):
"""Get method labels for bar charts and tables."""
# get label
label = ''
if method.split('_')[0] == 'True':
label += 'adaptive'
else:
assert method.split('_')[0] == 'False', method
label += 'vanilla'
if method.split('_')[1] != 'None':
... |
def clamp(value: float, minimum: int = 0, maximum: int = 255) -> float:
"""Clamps `value` between `minimum` and `maximum`."""
return max(minimum, min(value, maximum)) |
def duplicate_encode(word):
"""
Apply dict.
Time complexity: O(n).
Space complexity: O(n).
"""
from collections import defaultdict
# Convert word to lower case.
word_lower = word.lower()
# Create a dict to accumulate char numbers.
char_nums = defaultdict(int)
for c in wor... |
def _check_axis_in_range(axis, ndim):
"""Checks axes are with the bounds of ndim"""
if -ndim <= axis < ndim:
return True
raise ValueError(
f'axis {axis} is out of bounds for array of dimension {ndim}') |
def fill_zeros(number):
"""
Fills zeros before the number to make digits with length of 5
Parameters
----------
number : str
digits in string
Returns
-------
number : str
digits in string with length of 5
"""
d = 5 - len(number)
return '0' * d + number |
def getTemperature(
U_code,
helium_mass_fraction=None,
ElectronAbundance=None,
mu = None):
"""U_code = snapdict['InternalEnergy'] INTERNAL ENERGY_code = VELOCITY_code^2 = (params.txt default = (km/s)^2)
helium_mass_fraction = snapdict['Metallicity'][:,1]
ElectronAbundance= snapdict['Electron... |
def get_key(item, key_length):
"""
key + value = item
number of words of key = key_length
function returns key
"""
word = item.strip().split()
if key_length == 0: # fix
return item
elif len(word) == key_length:
return item
else:
return ' '.join(word[0:key_le... |
def isfloat(string):
"""Returns True if string is a float"""
try: float(string)
except: return False
return True |
def batch_matmul_legalize(attrs, inputs, types):
"""Legalizes batch_matmul op.
Parameters
----------
attrs : tvm.ir.Attrs
Attributes of current batch_matmul
inputs : list of tvm.relay.Expr
The args of the Relay expr to be legalized
types : list of types
List of input and... |
def package(x):
"""
Get the package in which x was first defined, or return None if that cannot be determined.
"""
return getattr(x, "__package__", None) or getattr(x, "__module__", None) |
def easeInOutCubic(currentTime, start, end, totalTime):
"""
Args:
currentTime (float): is the current time (or position) of the tween.
start (float): is the beginning value of the property.
end (float): is the change between the beginning and
destination value of the propert... |
def is_numeric(value):
"""
Test if a value is numeric.
PARAMETERS
==========
value
The value whose datatype is to be determined.
RETURNS
=======
Boolean true if the value is numeric, else boolean false.
"""
return isinstance(value, int) or isinstance(value, float) |
def cvi(b3, b4, b8):
"""
Chlorophyll Vegetation Index (Hunt et al., 2011).
.. math:: CVI = (b8/b3) * (b4/b3)
:param b3: Green.
:type b3: numpy.ndarray or float
:param b4: Red.
:type b4: numpy.ndarray or float
:param b8: NIR.
:type b8: numpy.ndarray or float
:returns CVI: Index... |
def _ewc_buffer_names(task_id, param_id, online):
"""The names of the buffers used to store EWC variables.
Args:
task_id: ID of task (only used of `online` is False).
param_id: Identifier of parameter tensor.
online: Whether the online EWC algorithm is used.
Returns:
(tuple... |
def str_to_hex(value: str) -> str:
"""Convert a string to a variable-length ASCII hex string."""
return "".join(f"{ord(x):02X}" for x in value)
# return value.encode().hex() |
def display_mal_list(value):
"""
Function that either displays the list of malicious domains or hides them
depending on the position of the toggle switch.
Args:
value: Contains the value of the toggle switch.
Returns:
A dictionary that communicates with the Dash interface whether ... |
def _get_bounds_as_str(bounds):
""" returns a string representation of bounds. """
bounds_list = [list(b) for b in bounds]
return str(bounds_list) |
def _find_clusters(mst_graph, vertices):
"""Find the cluster class for each vertex of the MST graph.
It uses the DFS-like algorithm to find clusters.
Args:
mst_graph (dict): A non-empty graph representing the MST.
vertices (list): A list of unique vertices.
Returns:
A l... |
def local_name(name):
"""Return a name with all namespace prefixes stripped."""
return name[name.rindex("::") + 2 :] if "::" in name else name |
def largest_sum(int_list):
"""Return the maximum sum of of all the possible contiguous subarrays.
Input is an array of integers. All possible summations of contiguous
subarrays are calulated and the maximum is updated whenever a sum is
greater than the current maximum.
Args:
int_list: A li... |
def make_price(price):
"""
Convert an ISK price (float) to a format acceptable by Excel
:param price: Float ISK price
:return: ISK price as Excel string
"""
return ('%s' % price).replace('.', ',') |
def nii_to_json(nii_fname):
"""
Replace Nifti extension ('.nii.gz' or '.nii') with '.json'
:param nii_fname:
:return: json_fname
"""
if '.nii.gz' in nii_fname:
json_fname = nii_fname.replace('.nii.gz', '.json')
elif 'nii' in nii_fname:
json_fname = nii_fname.replace('.nii', ... |
def argmax(seq, func):
""" Return an element with highest func(seq[i]) score; tie
goes to first one.
>>> argmax(['one', 'to', 'three'], len)
'three'
"""
return max(seq, key=func) |
def find_min(L, b):
"""(list, int) -> int
Precondition: L[b:] is not empty.
Return the index of the smallest value in L[b:].
>>> find_min([3, -1, 7, 5], 0)
1
"""
smallest = b
i = b + 1
while i != len(L):
if L[i] < L[smallest]:
smallest = i
i = i + 1
r... |
def py_non_decreasing(L):
"""test series"""
return all(x <= y for x, y in zip(L[:-1], L[1:])) |
def sanitize_path(ctx, param, value):
""" remove leading/trailing dots on a path if there are any
can be modified to do additional sanitizations
"""
return value.strip('.') |
def getProbability(value, distribution, values):
"""
Gives the probability of a value under a discrete distribution
defined by (distributions, values).
"""
total = 0.0
for prob, val in zip(distribution, values):
if val == value:
total += prob
return total |
def getPermutation(perm, numberOfQubits):
"""
Returns the permutation as a list of tuples. [(logical,physical),(log,phys),...]
"""
res = []
res.append(("log", "phy"))
for i in range(numberOfQubits):
res.append((perm[i], i))
return res |
def _excess_demand(price, D, S, a, b, gamma, p_bar):
"""Excess demand function."""
return D(price, a, b) - S(price, gamma, p_bar) |
def _try_make_number(value):
"""Convert a string into an int or float if possible, otherwise do nothing."""
try:
return int(value)
except ValueError:
try:
return float(value)
except ValueError:
return value
raise ValueError() |
def step(x):
"""
Unit Step Function
x < 0 --> y = 0
y = step(x):
x > 0 --> y = 1
:param x:
:return:
"""
if x < 0:
return 0
return 1 |
def Main(a, b, c, d):
"""
:param a:
:param b:
:param c:
:param d:
:return:
"""
m = 0
if a > b:
if c > d:
m = 3
else:
if b > c:
return 8
else:
return 10
else:
if c > d:
... |
def _matrix_from_shorthand(shorthand):
"""Convert from PDF matrix shorthand to full matrix
PDF 1.7 spec defines a shorthand for describing the entries of a matrix
since the last column is always (0, 0, 1).
"""
a, b, c, d, e, f = map(float, shorthand)
return ((a, b, 0),
(c, d, 0),
... |
def is_haploid(chromo, is_male):
"""
Is this chromosome haploid (one allele per person)
:param chromo: chromosome letter or number (X, Y, MT or 1-22)
:param is_male: boolean if male
:return:
"""
return (chromo == 'X' and is_male) or chromo == 'MT' or chromo == 'Y' |
def getBaseEntity(entity):
"""
Remove extra information from an entity dict
keeping only type and id
"""
if entity is None:
return entity
return dict([(k, v) for k, v in entity.items() if k in ['id', 'type']]) |
def check_requirements(program):
"""
Check if required programs are installed
"""
# From https://stackoverflow.com/a/34177358
from shutil import which
return which(program) is not None |
def hexdump(data):
"""Print string as hexdecimal numbers
data: string"""
s = ""
for x in data: s += "%02X " % ord(x)
return s |
def convertIDToPublication(db_id, db_name):
""" Takes a Solr ID and spits out the publication"""
if 'AGW' in db_id:
## AGW-XXX-ENG_YYYYMMDD.NNNN
r = db_id.split("_")[1]
elif 'NYT' in db_id:
r = 'NYT'
else:
r = db_id.split("_")[0]
## replace - with space
... |
def replace_num(phrase, val):
""" Add a numerical value to a string. """
if val == 1:
return phrase.replace("(^)", "one")
elif val == 2:
return phrase.replace("(^)", "two")
else:
return phrase.replace("(^)", "several") |
def load(data):
"""Load graph and costs of edges from serialized data string"""
lines = data.splitlines()
graph = {}
costs = {}
for line in lines:
source, dest, cost = map(int, line.split())
if source not in graph:
graph[source] = set()
if dest not in graph:
... |
def _xctoolrunner_path(path):
"""Prefix paths with a token.
We prefix paths with a token to indicate that certain arguments are paths,
so they can be processed accordingly. This prefix must match the prefix
used here: rules_apple/tools/xctoolrunner/xctoolrunner.py
Args:
path: A string of the... |
def toggle_navbar_collapse(n, is_open):
"""
This overall callback on the navigation bar allows to toggle the collapse on small screens.
"""
if n:
return not is_open
return is_open |
def twos_complement(hexstr,bits):
"""
twos_complement(hexstr,bits)
Converts a hex string of a two's complement number to an integer
Args:
hexstr (str): The number in hex
bits (int): The number of bits in hexstr
Returns:
int: An integer containing the number
"""
val... |
def vset(seq,idfun=None,as_list=True):
"""
order preserving
>>> vset([[11,2],1, [10,['9',1]],2, 1, [11,2],[3,3],[10,99],1,[10,['9',1]]],idfun=repr)
[[11, 2], 1, [10, ['9', 1]], 2, [3, 3], [10, 99]]
"""
def _uniq_normal(seq):
d_ = {}
for s in seq:
if s not in d_:
... |
def absolute_min(array):
"""
Returns absolute min value of a array.
:param array: the array.
:return: absolute min value
>>> absolute_min([1, -2, 5, -8, 7])
1
>>> absolute_min([1, -2, 3, -4, 5])
1
"""
return min(array, key=abs) |
def next_p2(n):
"""Returns the smallest integer, greater than n
(n positive and >= 1) which can be obtained as power of 2.
"""
if n < 1:
raise ValueError("n must be >= 1")
v = 2
while v <= n:
v = v * 2
return v |
def load_file(filename):
"""Load a file into the editor"""
if not filename:
return '', 0, 0
with open(filename, 'r') as f:
contents = f.read()
return contents, len(contents), hash(contents) |
def variable_mapping(value, from_low, from_high, to_low, to_high):
"""
maps a variables values based on old range and new range linearly
source: https://stackoverflow.com/questions/929103/convert-a-number-range-to-another-range-maintaining-ratio
:param value: the desired value to map to the range
:... |
def mpe_limits_cont_uncont_mwcm2(mhz: float) -> list:
"""Determine maximum permissible exposure limits for RF, from FCC references.
:param mhz: The radio frequency of interest (megahertz)
:return: MPE limits (mW/cm^2) for controlled & uncontrolled environments, respectively
:raises ValueError: if mhz i... |
def sort_dict(d, reverse=True):
"""Return the dictionary sorted by value."""
return {k: v for k, v in sorted(d.items(), key=lambda item: item[1], reverse=reverse)} |
def repeated_string(string: str, n: int, char: str = "a") -> int:
"""
>>> repeated_string("aba", 10)
7
>>> repeated_string("a", 1000000000000)
1000000000000
"""
string_size = len(string)
if string_size == 1:
return n if string == char else 0
whole, remainder = divmod(n, strin... |
def solution_1(A): # O(N)
"""
Write a function to find the 2nd smallest number in a list.
>>> solution_1([4, 4, -5, 3, 2, 3, 7, 7, 8, 8])
2
>>> solution_1([-1, -2, -15, -1, -2, -1, -2])
-2
>>> solution_1([1, 1, 1, 1])
"""
min_1 = None... |
def parse_data_name(line):
"""
Parses the name of a data item line, which will be used as an attribute name
"""
first = line.index("<") + 1
last = line.rindex(">")
return line[first:last] |
def get_article_info(response: dict):
"""Create a list of articles containing the:
Source name, title, description, url and author
:param response:
:return: a list of articles
"""
article_info = []
if response:
for article_number in range(response["totalResults"]):
sourc... |
def symmetric_mod(x, m):
"""
Computes the symmetric modular reduction.
:param x: the number to reduce
:param m: the modulus
:return: x reduced in the interval [-m/2, m/2]
"""
return int((x + m + m // 2) % m) - int(m // 2) |
def unique_labels(list_of_labels):
"""Extract an ordered integer array of unique labels
This implementation ignores any occurrence of NaNs.
"""
list_of_labels = [idx for idx, labels in enumerate(list_of_labels)]
return list_of_labels |
def merge_dicts(*dict_args):
"""
Given any number of dicts, shallow copy and merge into a new dict,
precedence goes to key value pairs in latter dicts.
Credit goes to Aaron Hall of stackoverflow:
https://stackoverflow.com/questions/38987/how-to-merge-two-dictionaries-in-a-single-expression
"""
... |
def is_empty(dictionary) -> bool:
"""Determine if the dictionary is empty."""
return not(bool(dictionary)) |
def claims_match(value, claimspec):
"""
Implements matching according to section 5.5.1 of
http://openid.net/specs/openid-connect-core-1_0.html
The lack of value is not checked here.
Also the text doesn't prohibit claims specification having both 'value'
and 'values'.
:param value: single va... |
def maxSubArray2(nums):
"""
:type nums: List[int]
:rtype: int
"""
if len(nums) == 0: return 0
sums = []
sums.append(nums[0])
mini = maxi = 0
for i in range(1, len(nums)):
sums.append(sums[-1] + nums[i])
mini = i if sums[mini] > sums[-1] else mini
maxi... |
def remove_all(alist,k):
"""Removes all occurrences of k from alist."""
retval = []
for x in alist:
if x != k:
retval.append(x)
return retval |
def get_sentid_from_offset(doc_start_char, doc_end_char, offset2sentid):
""" This function gets the sent index given the character offset of an entity in the document
Args:
doc_start_char: starting character offset of the entity in the document
doc_end_char: ending character offse... |
def convert_fmask_codes(flags):
"""Takes a list of arcgis dea aws satellite data
fmask flags (e.g., Water, Valid) and converts them
into their DEA AWS numeric code equivalent."""
out_flags = []
for flag in flags:
if flag == 'NoData':
out_flags.append(0)
elif flag == ... |
def conllify(sentences):
"""
return string in conll format
"""
# sentences = resentify(file)
conll = []
for sent_id, s in enumerate(sentences, 1):
for token_id, tuple in enumerate(s, 1):
token = str(tuple[0])
tag = str(tuple[1])
# add tab separated c... |
def listify(obj):
"""
Ensure that `obj` is a list.
"""
return [obj] if not isinstance(obj, list) else obj |
def file_to_class_name(f_name: str) -> str:
"""
Take the file name of a scan and return the name of it as a class: snake to camel case
"""
return "".join(word.title() for word in f_name.split('_')) |
def calc_time(since, until):
"""
simple function to calculate time passage
:param since: the start of the moment
:type since: time.struct_time
:param until: the end of the moment
:type until: time.struct_time
:return: the length of the calculated moment in seconds
:rtype: int or long
... |
def rreplace(word, old_suffix, new_suffix):
"""Helper for right-replacing suffixes"""
return new_suffix.join(word.rsplit(old_suffix, 1)) |
def truncate(text, max_len=350, end='...'):
"""Truncate the supplied text for display.
Arguments:
text (:py:class:`str`): The text to truncate.
max_len (:py:class:`int`, optional): The maximum length of the
text before truncation (defaults to 350 characters).
end (:py:class:`str`, opt... |
def compute_score_interpretability_method(features_employed_by_explainer, features_employed_black_box):
"""
Compute the score of the explanation method based on the features employed for the explanation compared to the features truely used by the black box
"""
precision = 0
recall = 0
for featur... |
def _count_nonempty(row):
"""
Returns the count of cells in row, ignoring trailing empty cells.
"""
count = 0
for i, c in enumerate(row):
if not c.empty:
count = i + 1
return count |
def get_complete_loss_dict(list_of_support_loss_dicts, query_loss_dict):
"""
Merge the dictionaries containing the losses on the support set and on the query set
Args:
list_of_support_loss_dicts (list): element of index i contains the losses of the model on the support set
after i weight upd... |
def isValidPositiveInteger(number):
"""
Check if number is valid positive integer
Parameters
----------
number : int
Returns
-------
bool
Author
------
Prabodh M
Date
------
29 Nov 2017
"""
if isinstance(number, int) and number > 0:
return Tru... |
def calc_det_dzb(theta):
"""Calculate detector vertical offset of the bottom raw
.. note:: formula taken from Table 2 on pag. 68 of CE document
vol. 3 (Olivier Proux et al.), theta in deg
"""
return -677.96 + 19.121 * theta - 0.17315 * theta ** 2 + 0.00049335 * theta ** 3 |
def get_book_url(tool_name, category):
"""Get the link to the help documentation of the tool.
Args:
tool_name (str): The name of the tool.
category (str): The category of the tool.
Returns:
str: The URL to help documentation.
"""
prefix = "https://jblindsay.github.io/wbt_bo... |
def conv(x, y):
"""
Convolution of 2 causal signals, x(t<0) = y(t<0) = 0, using discrete
summation.
x*y(t) = \int_{u=0}^t x(u) y(t-u) du = y*x(t)
where the size of x[], y[], x*y[] are P, Q, N=P+Q-1 respectively.
"""
P, Q, N = len(x), len(y), len(x)+len(y)-1
z = []
for k in range(... |
def _parse_cubehelix_args(argstr):
"""Turn stringified cubehelix params into args/kwargs."""
if argstr.startswith("ch:"):
argstr = argstr[3:]
if argstr.endswith("_r"):
reverse = True
argstr = argstr[:-2]
else:
reverse = False
if not argstr:
return [], {"rev... |
def is_whiten_dataset(dataset_name: str):
"""
Returns if the dataset specified has name "whitening". User can use any
dataset they want for whitening.
"""
if dataset_name == "whitening":
return True
return False |
def npf(number):
"""function which will return
the number of prime factors"""
i = 2
a = set()
while i < number**0.5 or number == 1:
if number % i == 0:
number = number/i
a.add(i)
i -= 1
i += 1
return (len(a)+1) |
def kernel_primitive_zhao(x, s0=0.08333, theta=0.242):
"""
Calculates the primitive of the Zhao kernel for given values.
:param x: point to evaluate
:param s0: initial reaction time
:param theta: empirically determined constant
:return: primitive evaluated at x
"""
c0 = 1.0 / s0 / (1 - ... |
def computeDerivatives(oldEntry, newEntry):
"""
Computes first-order derivatives between two corresponding sets of metrics
:param oldEntry: Dictionary of metrics at time t - 1
:param newEntry: Dictionary of metrics at time t
:return: Dictionary of first-order derivatives
"""
diff = {k: v - ... |
def UC_Q(Q_mmd, A_catch):
"""Convert discharge from units of mm/day to m3/day"""
Q_m3d = Q_mmd*1000*A_catch
return Q_m3d |
def get_cam_name(i, min_chars=7):
"""Create formatted camera name from index."""
format_str = '{:0' + str(min_chars) + 'd}'
return 'cam_' + format_str.format(i) |
def product(xs):
"""Multiplies together all the elements of a list"""
result = xs[0]
for x in xs[1:]:
result *= x
return result |
def cols(matrix):
"""
Returns the no. of columns of a matrix
"""
if type(matrix[0]) != list:
return 1
return len(matrix[0]) |
def compare_fuzz(song, best_matches, best_fuzz_ratio, fuzz_value):
"""
compare_fuzz: A helper function to compare fuzz values then add it to
the best_matches array, if needed
:param song: The song to potentially add
:param best_matches: A list of best matches
:param best_fuzz_ratio: The c... |
def pdf(kernel, x, min_x, max_x, int_k):
"""possibility distribution function
Returns:
p (array-like): probability
"""
if x < min_x or x > max_x:
return 0
else:
return kernel(x) / int_k |
def fib(n):
"""Return the n'th fibonacci number"""
a, b = 1, 1
while n:
a, b = b, a + b
n -= 1
return a |
def _valid_result(res):
"""Validate results returned by find_players"""
(HEADER, RESULTS) = [0, 1]
ok = (isinstance(res, (tuple, list)) and
len(res) == 2 and
isinstance(res[HEADER], (tuple, list)) and
isinstance(res[RESULTS], (tuple, list)))
if not ok:
return False
... |
def fac(n):
"""Returns the factorial of n"""
if n < 2:
return 1
else:
return n * fac(n - 1) |
def check_both_lists(final_sj_coordinate_dict,single_exon_reads_transcripts,transcript_coordinate_dict,transiddict,posdict,single_exon_dict):
"""Check if read is present in both lists. if it is, it is a hidden case of multimapping"""
not_single = set() #these reads are not to be outputted as they already have a map... |
def isfunction(obj, func) -> bool:
"""Checks if the given object has a function with the given name"""
if obj is None or not func:
return False
func_ref = getattr(obj, func, None)
return callable(func_ref) |
def strhash(string):
"""
Old python hash function as described in PEP 456, excluding prefix, suffix and mask.
:param string: string to hash
:return: hash
"""
if string == "":
return 0
x = ord(string[0]) << 7
for c in string[1:]:
x = ((1000003 * x) ^ ord(c)) & (1 << 32)
... |
def join(items):
"""
Shortcut to join collection of strings.
"""
return b''.join(items) |
def six_hump_camel_func(x, y):
"""
Definition of the six-hump camel
"""
x1 = x
x2 = y
term1 = (4-2.1*x1**2+(x1**4)/3) * x1**2
term2 = x1*x2
term3 = (-4+4*x2**2) * x2**2
return term1 + term2 + term3 |
def _random_big_data(bytes=65536, path="/dev/random"):
"""
Returns a random string with the number of bytes requested. Due to xar
implementation details, this should be greater than 4096 (32768 for
compressed heap testing).
"""
with open(path, "r") as f:
return f.read(bytes) |
def permute(list, index):
"""
Return index-th permutation of a list.
Keyword arguments:
list --- the list to be permuted
index --- index in range (0, factorial(len(list)))
"""
if len(list) < 2:
return list
(rest, choice) = divmod(index, len(list))
return [list[choice]] + permute(list[0:choice] +... |
def get_pydantic_error_value(data: dict, loc: tuple):
"""Get the actual value that caused the error in pydantic"""
try:
obj = data
for item in loc:
obj = obj[item]
except KeyError:
return None
else:
return obj |
def set_objective(x, a, b):
""" return the objective function """
#To-Do set the objective equation
return a*x+b |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.