content stringlengths 42 6.51k |
|---|
def NormalsAverage(NormalParameters):
"""Returns the "average" of the normal distributions from NormalParameters.
NormalParameters: a list of length 2 lists, whose entries are the mean and SD of each normal distribution."""
return [sum([Parameter[0] for Parameter in NormalParameters])/(len(NormalParameters)), \... |
def truncateToSplice(exons):
""" Truncates the gene to only target splice sites """
splice_sites = []
for ind in range(0, len(exons)):
splice_sites.append([exons[ind][0], exons[ind][1]-1, exons[ind][1]+1])
splice_sites.append([exons[ind][0], exons[ind][2]-1, exons[ind][2]+1])
# Remove f... |
def getminmax_linear_search(arr):
""" Linear method
Initialize values of min and max as minimum and maximum of the first two elements
respectively. Starting from 3rd, compare each element with max and min, and
change max and min accordingly
"""
if len(arr) == 0:
return None, ... |
def multiply_by_1_m(n):
"""Returns concatenated product of n with 1-m (until digits > 8)"""
conc_product = ""
i = 1
while len(conc_product) < 9:
conc_product += str(n*i)
i += 1
return int(conc_product) |
def classify_label_list(MAlist, labelset):
"""Add set of labels to an axonset or create new axonset."""
found = False
for i, MA in enumerate(MAlist):
for l in labelset:
if l in MA:
MAlist[i] = MA | labelset
found = True
break
if not fo... |
def subtract(value, entries):
"""Subtract the entry off the value and return another set of remainders"""
return {(value - entry) for entry in entries} |
def get_gcp_instance_responses(project_id, zones, compute):
"""
Return list of GCP instance response objects for a given project and list of zones
:param project_id: The project ID
:param zones: The list of zones to query for instances
:param compute: The compute resource object
:return: A list ... |
def decode_scoreboard_item(item, with_weight=False, include_key=False):
"""
:param item: tuple of ZSet (key, score)
:param with_weight: keep decimal weighting of score, or return as int
:param include_key: whether to include to raw key
:return: dict of scoreboard item
"""
key = item[0].decod... |
def lr_schedule(epoch, lr=1e-2):
"""Learning Rate Schedule
Learning rate is scheduled to be reduced after 30, 60, 90, 120 epochs.
Called automatically every epoch as part of callbacks during training.
# Arguments
epoch (int): The number of epochs
# Returns
lr (float32): learning r... |
def get_orderedTC_ordering(T: int):
"""TC swap shuffles temporal ordering,
so use this sorting indices to fix it
"""
if T % 3 == 0:
ordering = [(x*(T//3) + x//3) % T for x in range(T)]
elif T % 3 == 1:
ordering = [(x*((2*T+1)//3)) % T for x in range(T)]
else:
ordering = [... |
def findORF_all_sorted(dna_seq):
"""
Finds all the longest open reading frames in the DNA sequence.
"""
tmpseq = dna_seq.upper();
orf_all = []
for i in range(0, len(tmpseq), 3):
codon = tmpseq[i:i+3]
if codon == 'ATG':
orf = tmpseq[i:]
for j in range(0, le... |
def is_item_visible(item):
"""Returns true if the item is visible."""
for attr in ['is_deleted', 'is_archived', 'in_history', 'checked']:
if item[attr] == 1:
return False
return True |
def check_if_modem_enabled(out):
"""Given an output, checks if the modem is in the correct mode"""
for line in out:
if '12d1:1446' in line:
return 0
if '12d1:1001' in line:
return 1
return -1 |
def is_philips(dicom_input):
"""
Use this function to detect if a dicom series is a philips dataset
:param dicom_input: directory with dicom files for 1 scan of a dicom_header
"""
# read dicom header
header = dicom_input[0]
if 'Manufacturer' not in header or 'Modality' not in header:
... |
def rotate_r (sequence) :
"""Return a copy of sequence that is rotated right by one element
>>> rotate_r ([1, 2, 3])
[3, 1, 2]
>>> rotate_r ([1])
[1]
>>> rotate_r ([])
[]
"""
return sequence [-1:] + sequence [:-1] |
def lighten(color, ratio=0.5):
"""Creates a lighter version of a color given by an RGB triplet.
This is done by mixing the original color with white using the given
ratio. A ratio of 1.0 will yield a completely white color, a ratio
of 0.0 will yield the original color.
"""
red, green, blue, alp... |
def interpretStatus(status, default_status="Idle"):
"""
Transform a integer globus status to
either Wait, Idle, Running, Held, Completed or Removed
"""
if status == 5:
return "Completed"
elif status == 9:
return "Removed"
elif status == 1:
return "Running"
elif st... |
def preprocess(data):
"""
Function used to preprocess the input and output for the model.
The input gets the special [SEP] token and the output gets a space added.
"""
return {
"input": data['premise'] + '</s>' + data['hypothesis'],
"output": str(data['label']) + ' ' + data['explanat... |
def euler_problem_15(n=20):
"""
Starting in the top left corner of a 2 * 2 grid, and only being able to move to the right and down, there are exactly 6 routes to the bottom right corner.
How many such routes are there through a 20 * 20 grid?
"""
# this is classic "2n choose n".
num_routes = 1.0
... |
def WinPathToUnix(path):
"""Convert a windows path to use unix-style path separators (a/b/c)."""
return path.replace('\\', '/') |
def markdown_header(header: str, level: int = 1) -> str:
"""Return a Markdown header."""
return ("\n" if level > 1 else "") + "#" * level + f" {header}\n" |
def to_arn(region, account_id, name):
"""
returns the arn of an SSM parameter with specified, region, account_id and name. If the name
starts with a '/', it does not show up in the Arn as AWS seems to store it that way.
"""
return "arn:aws:ssm:%s:%s:parameter/%s" % (
region,
account_... |
def append_PKCS7_padding(b):
"""
Function to pad the given data to a multiple of 16-bytes by PKCS7 padding.
@param b data to be padded (bytes)
@return padded data (bytes)
"""
numpads = 16 - (len(b) % 16)
return b + numpads * bytes(chr(numpads), encoding="ascii") |
def groupIntersections(intersections: list, key: int) -> dict:
"""
Function to group horizontal or vertical intersections
Groups horizontal or vertical intersections
as a list into a dict by the given key
Parameters:
intersections (list): List of tuples representing
intersection points
key... |
def ensure_trailing_slash(url):
"""ensure a url has a trailing slash"""
return url if url.endswith("/") else url + "/" |
def insertion_sort_descending(dList):
"""
Given a unsorted list of integers other comparable types,
it rearrange the integers in natural order in place in an
descending order.
Example: Input: [8,5,3,1,7,6,0,9,4,2,5]
Output: [9,8,7,6,5,5,4,3,2,1,0]
"""
n = len(dList)
for i i... |
def method_to_permcode(method):
"""
return the django permcode for the specified method
eg. "POST" => "add"
"""
method = method.upper()
if method == "POST":
return "add"
if method == "GET":
return "view"
if method == "PUT" or method == "UPDATE":
return "change"
... |
def isfloat(value):
"""
This function checks if a string can be converted to a float.
Parameters:
-----------
value : string
Returns:
--------
boolean
"""
try:
float(value)
return True
except ValueError:
return False |
def shortText(a,b):
"""
Returns a short portion of the text that shows the first difference
@ In, a, string, the first text element
@ In, b, string, the second text element
@ Out, shortText, string, resulting shortened diff
"""
a = repr(a)
b = repr(b)
displayLen = 20
halfDisplay = displayLen... |
def is_entry_a_header(key, value, entry):
"""Returns whether the given entry in the header is a expected header."""
return (key.lower() in entry.lower() or
value.lower() in entry.lower()) |
def _preprocess_conv2d_input(x, data_format):
"""Transpose and cast the input before the conv2d.
# Arguments
x: input tensor.
data_format: string, `"channels_last"` or `"channels_first"`.
# Returns
A tensor.
"""
if data_format == 'channels_last':
# TF uses the last ... |
def b(n, k, base_case):
"""
:param n: int
:param k: int
:param base_case: list
:return: int
"""
if k == 0 or k == n:
print('base case!')
base_case[0] += 1
return 2
else:
return b(n-1, k-1, base_case) + b(n-1, k, base_case) |
def alternate(seq):
"""
Splits *seq*, placing alternating values into the returned iterables
"""
return seq[::2], seq[1::2] |
def _make_sent_csv(sentstring, fname, meta, splitter, i, skip_meta=False):
"""
Take one CONLL-U sentence and add all metadata to each row
Return: str (CSV data) and dict (sent level metadata)
"""
fixed_lines = []
raw_lines = sentstring.splitlines()
for line in raw_lines:
if not line... |
def friendly_channel_type(channel_type: str) -> str:
"""Return a human readable version of the channel type."""
if channel_type == "controlled_load":
return "Controlled Load"
if channel_type == "feed_in":
return "Feed In"
return "General" |
def compose(*values):
"""
Compose the specified 8-bit *values* into a single integer.
"""
result = 0
for i, value in enumerate(values):
result |= value << (i * 8)
return result |
def consecutive_ducks2(n):
"""
Time complexity: O(1).
Space complexity: O(1).
"""
# Edge case.
if n == 2:
return False
# Check if n is odd, then it can be expressed.
if n % 2 == 1:
return True
# Check if n is power of two, then it cannot be expressed.
if n & (n ... |
def daily_mean_t(tmin, tmax):
"""
Estimate mean daily temperature from the daily minimum and maximum
temperatures.
:param tmin: Minimum daily temperature [deg C]
:param tmax: Maximum daily temperature [deg C]
:return: Mean daily temperature [deg C]
:rtype: float
"""
return (tmax + tm... |
def thumbnail(value, size):
"""
Get the thumbnail of 'size' of the corresponding url
"""
return value.replace('.jpg', '.' + size + '.jpg') |
def swaggerFilterByOperationId(pathTypes):
"""take pathTypes and return a dictionary with operationId as key
and PathType object as value
Keyword arguments:
pathTypes -- list of types that build the model, list of yacg.model.openapi.PathType instances
"""
ret = {}
for pathType in pathTypes... |
def message(name, pval, alpha=0.01):
"""Write a message."""
if pval < alpha:
return '{0} can be rejected (pval <= {1:.2g})'.format(name, pval)
else:
return '{0} cannot be rejected (pval = {1:.2g})'.format(name, pval) |
def unsanitize(t, mappings):
"""Unsanitizes a previously sanitized token."""
final = t
for original, sanitized in mappings.items():
assert len(original) == 1
final = final.replace(sanitized, original)
return final |
def hexagonal(nth):
"""
Providing n'th hexagonal number.
:param nth: index for n'th hexagonal
:returns: n'th hexagonal number
see http://en.wikipedia.org/wiki/Hexagonal_number
>>> hexagonal(3)
15
>>> hexagonal(4)
28
"""
return nth * (2 * nth - 1) |
def add_vec3_vec3(va, vb):
"""Return the sum of given vec3 values.
>>> va = [1,5,-2]
>>> vb = [-10,4,6]
>>> add_vec3_vec3(va, vb)
[-9, 9, 4]
"""
assert type(va) == list
assert type(vb) == list
vv = [ None for _ in range(3) ]
for row in range(3):
vv[row] = va[row] + vb[... |
def format_slack_message(table_name, metric, avg_time, increase, stddev, stddev_old):
""" Formats slack message using slack emojis.
:param table_name: BigQuery table name that was analysed.
:param metric: string with metric name.
:param avg_time: calculated average time for recent data of given metric.... |
def convert_range_to_number_list(range_list):
"""
Returns list of numbers from descriptive range input list
E.g. ['12-14', '^13', '17'] is converted to [12, 14, 17]
Returns string with error message if unable to parse input
"""
# borrowed from jpalanis@redhat.com
num_list = []
exclude_nu... |
def fontInfoStyleMapStyleNameValidator(value):
"""
Version 2+.
"""
options = ["regular", "italic", "bold", "bold italic"]
return value in options |
def wallis_product(n_terms):
"""Implement the Wallis product to compute an approximation of pi.
See:
https://en.wikipedia.org/wiki/Wallis_product
Parameters
----------
n_terms : number for terms in the product. Higher is more precise.
Returns
-------
pi : approximation of pi
... |
def isPalindrome(n):
"""returns if a number is palindromic"""
s = str(n)
if s == s[::-1]:
return True
return False |
def translate_terms(yamldoc, idspace):
"""
Reads the `term_browser` field from the given YAML document, validates that it is a supported
term browser, and returns a corresponding Apache redirect statement.
"""
if 'term_browser' in yamldoc and yamldoc['term_browser'].strip().lower() == 'ontobee':
replaceme... |
def extractDidParts(did, method="dad"):
"""
Parses and returns keystr from did
raises ValueError if fails parsing
"""
try: # correct did format pre:method:keystr
pre, meth, keystr = did.split(":")
except ValueError as ex:
raise ValueError("Invalid DID value")
if pre != "di... |
def get_lines_coordinates(input_data):
"""extract end coordinates from input text
:input data (str): plain text read from txt file
:returns end_coordinates (list of list of tuples)"""
input_lines = input_data.split("\n")
end_coordinates = []
for il in input_lines:
if il != "":
... |
def to_float(val):
"""Convert string to float, but also handles None and 'null'."""
if val is None:
return None
if str(val) == "null":
return None
return float(val) |
def function_comments(f):
"""
Uses single line comments as we can't know if there are string escapes such as /* in the code
:param f:
:return:
"""
try:
return '\n'.join(["//" + line.strip() for line in f.__doc__.splitlines()])
except AttributeError:
return "// No Comment" |
def get_label_file_template(doc_name):
"""
VOTT header file version
:param doc_name: Label.json
:return: The header for the label.json file
"""
return {
"document": doc_name,
"labels": []
} |
def validate_isdigit(in_data, key):
"""Validate if a key value of a dictionary is a pure numeric string
This function will check if the the value of a dictionary's key is a string
that only includes the digits
Args:
in_data (dict): The dictionary sent py the patient side client that
in... |
def _flatten_vectors(vectors):
"""Returns the flattened array of the vectors."""
return sum(map(lambda v: [v.x, v.y, v.z], vectors), []) |
def _get_out_class(objs):
"""
From a list of input objects ``objs`` get merged output object class.
This is just taken as the deepest subclass. This doesn't handle complicated
inheritance schemes.
"""
out_class = objs[0].__class__
for obj in objs[1:]:
if issubclass(obj.__class__, ou... |
def get_replication_status(response_json):
"""
Create a dictionary of the replicated volumes on the cluster
This is used to ensure we can track volume ID to volume name from
disparate data sources that don't all contain both sets of data
"""
paired_vols = {}
for volume in response_jso... |
def getManifestSchemaVersion(manifest):
""" returns manifest schema version for manifest"""
return manifest["manifest"]["schemaVersion"] |
def SFP_update(L, R, t0, t1, u, v):
"""
Update L and R according to the link (t0,t1,u,v)
:param L:
:param R:
:param t0:
:param t1:
:param u:
:param v:
:return:
"""
su, du, au = L[u]
su = -su
new_start = min(t1, su)
new_arrival = t0
new_distance = du + 1
ne... |
def _is_wav_file(filename):
"""Is the given filename a wave file?"""
return len(filename) > 4 and filename[-4:] == '.wav' |
def on_board(position):
"""Check if position is on board."""
return (0 <= position[0] < 8) and (0 <= position[1] < 8) |
def get_unset_keys(dictionary, keys):
"""
This is a utility that takes a dictionary and a list of keys
and returns any keys with no value or missing from the dict.
"""
return [k for k in keys if k not in dictionary or not dictionary[k]] |
def create_dataset_url(base_url, identifier, is_pid):
"""Creates URL of Dataset.
Example: https://data.aussda.at/dataset.xhtml?persistentId=doi:10.11587/CCESLK
Parameters
----------
base_url : str
Base URL of Dataverse instance
identifier : str
Identifier of the dataset. Can be... |
def one_hot(src_sentences, src_dict, sort_by_len=False):
"""vector the sequences.
"""
out_src_sentences = [[src_dict.get(w, 0) for w in sent] for sent in src_sentences]
# sort sentences by english lengths
def len_argsort(seq):
return sorted(range(len(seq)), key=lambda x: len(seq[x]))
#... |
def type_exists(data, type_name):
"""Check if type exists in data pack
Keyword arguments:
data -- data structure where type might be found
struct_name -- name of the type to search for
"""
for established_type in data['types']:
if established_type['name'] == type_name:
... |
def _make_bold_stat_signif(value, sig_level=0.05):
"""Make bold the lowest or highest value(s)."""
val = "{%.1e}" % value
val = "\\textbf{%s}" % val if value <= sig_level else val
return val |
def sum_values(values, period=None):
"""Returns list of running sums.
:param values: list of values to iterate.
:param period: (optional) # of values to include in computation.
* None - includes all values in computation.
:rtype: list of summed values.
Examples:
>>> values = [34, 30, 2... |
def has_c19_tag (tags):
""" Check if the COVID-19 tag is present """
for tag in tags:
if tag.vocabulary == "99" and tag.code.upper() == "COVID-19":
return True
return False |
def is_file_like(f):
"""Check to see if ```f``` has a ```read()``` method."""
return hasattr(f, 'read') and callable(f.read) |
def round_to_decimal(value, precision: float = 0.5) -> float:
"""
Helper function to round a given value to a specific precision, for example *.5
So 5.4 will be rounded to 5.5
"""
return round(precision * round(float(value) / precision), 1) |
def axLabel(value, unit):
"""
Return axis label for given strings.
:param value: Value for axis label
:type value: int
:param unit: Unit for axis label
:type unit: str
:return: Axis label as \"<value> (<unit>)\"
:rtype: str
"""
return str(value) + " (" + str(unit) + ")" |
def deobfuscate_value(obfuscation_key, value):
"""
De-obfuscate a given value parsed from the chainstate.
:param obfuscation_key: Key used to obfuscate the given value (extracted from the chainstate).
:type obfuscation_key: str
:param value: Obfuscated value.
:type value: str
:return: The d... |
def _get_comparisons_3(idx, paraphrases, other):
"""Collect basic comparisons:
Paraphrases should be closer to their seed than any transformation which significantly
changes the meaning of the seed or modality of the seed.
"""
out = []
for p in paraphrases:
for o in other:
... |
def remove_multiple_blank_lines(instring):
"""
Takes a string and removes multiple blank lines
"""
while '\n\n' in instring:
instring = instring.replace('\n\n', '\n')
return instring.strip() |
def _get_parameter_metadata(driver, band):
"""
Helper function to derive parameter name and units
:param driver: rasterio/GDAL driver name
:param band: int of band number
:returns: dict of parameter metadata
"""
parameter = {
'id': None,
'description': None,
'unit_... |
def string_rotation(x, y):
"""
:param x: string
:param y: string
:return:
"""
if len(x) != len(y):
return False
new_str = x + x
if y in new_str:
return True
return False |
def make_dataframe_value(nrows: int, ncols: int) -> str:
"""The default value generator for
`pandas._testing.makeCustomDataframe`.
Parameter names and descriptions are based on those found in
`pandas._testing.py`.
https://github.com/pandas-dev/pandas/blob/b687cd4d9e520666a956a60849568a98dd00c67... |
def checkStatus(vL, vA, vB):
"""
Validacion de las marcas, si el pixel coincide con algun color regresa True
"""
if (vL >= 40 and vL <= 80) and (vA >= 50 and vA <= 80) and (vB >= -40 and vB <= 10):
return True
else:
return False |
def calc_delta(times):
""" create time-slices for: 22000, 18000, 14000, 10000, 6000, 2000, 1990 BP """
btime = 22000 # BP
if type(times) == list:
idx = [(t+btime)*12 for t in times]
else:
idx = times+btime*12
return idx |
def sec_from_hms(start, *times):
""" Returns a list of times based on adding each offset tuple in times
to the start time (which should be in seconds). Offset tuples can be
in any of the forms: (hours), (hours,minutes), or (hours,minutes,seconds).
"""
ret = []
for t in times:
cur = 0
... |
def zalpha(z, zmin, zrng, a_min=0):
""" return alpha based on z depth """
alpha = a_min + (1-a_min)*(z-zmin)/zrng
return alpha |
def selectNRandom(nodes, N):
"""
Selects n random nodes from a list of nodes and returns the list
"""
import random
random.shuffle(nodes)
return nodes[:N] |
def avgout(vallist):
""" entry-wise average of a list of matrices """
r = len(vallist)
A = 0
if r > 0:
for B in vallist:
A += (1.0/r) * B
return A |
def get_k_for_topk(k, size):
"""Get k of TopK for onnx exporting.
The K of TopK in TensorRT should not be a Tensor, while in ONNX Runtime
it could be a Tensor.Due to dynamic shape feature, we have to decide
whether to do TopK and what K it should be while exporting to ONNX.
If returned K is les... |
def fib(n):
"""
Returns the nth Fibonacci number.
"""
if n < 2:
return n
else:
return fib(n-2) + fib(n-1) |
def dt2str(dt):
"""
Convert a datetime object to a string for display, without microseconds
:param dt: datetime.datetime object, or None
:return: str, or None
"""
if dt is None:
return None
dt = dt.replace(microsecond=0)
return str(dt) |
def get_added_labels(l_new, l_old):
"""
Get labels that are new to this PR
:param l_new: new labels to be added
:param l_old: labels that were already in the PR
:type l_new: list
:type l_old: list
:returns: list of labels that were added
:rtype: list
"""
r... |
def percentage_as_number(percent_str):
"""
Convert a percentage string to a number.
Args:
percent_str: A percent string, for example '5%' or '1.2%'
Usage
=====
>>> percentage_as_number('8%')
0.08
>>> percentage_as_number('250%')
2.5
>>> percentage_as_number('-10%')
... |
def dict_to_cmdlist(dp):
""" Transform a dictionary into a list of command arguments.
Args:
dp Dictionary mapping parameter name (to prepend with "--") to parameter value (to convert to string)
Returns:
Associated list of command arguments
Notes:
For entries mapping to 'bool', the parameter is inclu... |
def conv_F2K(value):
"""Converts degree Fahrenheit to Kelvin.
Input parameter: scalar or array
"""
value_k = (value-32)*(5/9)+273.15
if(hasattr(value_k, 'units')):
value_k.attrs.update(units='K')
return(value_k) |
def _default_validator(value):
"""A default validator, return False when value is None or an empty string. """
if not value or not str(value).strip():
return False
return True |
def get_sub_formula(formula):
"""
"(SO3)2" -> ("(SO3)2", "(SO3)", "2")
"(SO3)" -> ("(SO3)", "(SO3)", "")
"""
import re
match = re.search('(\([a-zA-Z\d]+\))(\d*)', formula)
if not match:
return
full_sub_formula = match.group(0)
sub_formula = match.group(1)
multiplier = ... |
def cluster_hierarchically(active_sites):
"""
Cluster the given set of ActiveSite instances using a hierarchical algorithm. #
Input: a list of ActiveSite instances
Output: a list of clusterings
(each clustering is a list of li... |
def get_crop_range(maxX, maxY, size=32):
"""Define region of image to crop
"""
return maxX-size, maxX+size, maxY-size, maxY+size |
def hardlims(n):
"""
Symmetrical Hard Limit Transfer Function
:param int n:Net Input of Neuron
:return: Compute Heaviside step function
:rtype: int
"""
if n<0:
return -1
else:
return 1 |
def zeroPad(n, l):
"""Add leading 0."""
return str(n).zfill(l) |
def get_accidental(i: int) -> str:
"""Returns the accidental string from its index, e.g. 1->#."""
s: str = ""
if i > 0:
s = "x" * (i // 2) + "#" * (i % 2)
elif i < 0:
s = "b" * abs(i)
return s |
def what_type(data):
"""
Description: Identify the data type
:param data: raw data (e.g. list, dict, str..)
:return: Data type in a string format
"""
return str(type(data)).split('\'')[1] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.