content stringlengths 42 6.51k |
|---|
def is_valid_int_greater_zero_param(param, required=True):
"""Checks if the parameter is a valid integer value and greater than zero.
@param param: Value to be validated.
@return True if the parameter has a valid integer value, or False otherwise.
"""
if param is None and not required:
ret... |
def _pitch2m(res):
"""Convert pitch string to meters.
Something like -600- is assumed to mean "six-hundreths of an inch".
>>> _pitch2m("-600-")
4.233333333333333e-05
>>> _pitch2m("-1200-")
2.1166666666666665e-05
"""
res = int(res[1:-1])
return 0.0254 / res |
def vector_in_01(x):
"""Returns True if all elements are in [0, 1]."""
for element in x:
if element < 0.0 or element > 1.0:
return False
return True |
def handle_mask(mask, tree):
"""Expand the mask to match the tree structure.
:param mask: boolean mask
:param tree: tree structure
:return: boolean mask
"""
if isinstance(mask, bool):
return [mask] * len(tree)
return mask |
def powerlaw_u_alpha(x, p, z_ref=100):
""" p = (alpha, u_ref) """
return p[1] * (x / z_ref) ** p[0] |
def distance_pronoun_antecedent (pair) :
"""Distance is 0 if the pronoun and antecedent are in the same sentence"""
return pair[3]-pair[2] |
def time_format(seconds):
"""
Convert seconds into DATE HOUR MIN SEC format.
"""
if seconds is not None:
seconds = int(seconds)
d = seconds // (3600 * 24)
h = seconds // 3600 % 24
m = seconds % 3600 // 60
s = seconds % 3600 % 60
if d > 0:
retur... |
def comma_filter(value):
"""
Format a number with commas.
"""
return '{:,}'.format(value) |
def interval_intersect(a, b, c, d):
"""Returns whether the intervals [a,b] and [c,d] intersect."""
return (c <= b) and (a <= d) |
def compare_ltiv_data(expected, actual):
"""
Helper to test the LENGTH|TYPE|ID|VALUE data. It is packed in a dictionary like
{ID: (VALUE, TYPE)
"""
for k, val in expected.items():
actual_v = actual.pop(k)
if not (actual_v[0] == val[0] and actual_v[1] == val[1]):
return Fa... |
def get_name(header, splitchar="_", items=2):
"""use own function vs. import from match_contigs_to_probes - we don't want lowercase"""
if splitchar:
return "_".join(header.split(splitchar)[:items]).lstrip(">")
else:
return header.lstrip(">") |
def Int2AP(num):
"""string = Int2AP(num)
Return 'num' converted to bytes using characters from the set 'A'..'P'
"""
val = b''; AP = b'ABCDEFGHIJKLMNOP'
num = int(abs(num))
while num:
num, mod = divmod(num, 16)
val = AP[mod:mod+1] + val
return val |
def lca_main(root, v1, v2):
"""
I'm thinking of a method inloving recursion.
Both v1 and v2 WILL indeed exist, so it's a matter of seeing if they are on
the left or right. If it's THIS node, somehow report that correctly maybe.
Very proud of this one! Thought it up completely and it passed all t... |
def _job_id_from_worker_name(name):
""" utility to parse the job ID from the worker name
template: 'prefix--jobid--suffix'
"""
_, job_id, _ = name.split("--")
return job_id |
def summarize_mutation(mutation_name, event, inputs, outputs, isAsync=False):
"""
This function provides a standard representation of mutations to be
used when services announce themselves
"""
return dict(
name=mutation_name,
event=event,
isAsync=isAsync,
inpu... |
def define_token(token):
"""Return the mandatory definition for a token to be used within nstl
where nstl expects a valid token.
For example, in order to use an identifier as a method name in a
nstl type, the definition generated by this function must be written
for that specific identi... |
def cleanup_watch(watch):
"""Given a dictionary of a watch, return a new dictionary for output as
JSON.
This is not the standard cleanup function, because we know who the author
is."""
return str(watch["watched"]) |
def rgb_to_hex(color):
"""Convert an rgb color to hex."""
return "#%02x%02x%02x%02x" % (*color,) |
def r1_p_r2(R1, R2):
"""
Calculate the Resistance of a parallel connection
"""
return R1 * R2 / (R1 + R2) |
def _to_yaml_defs(wrapped, instance, args, kwargs):
"""
New in v17
public decorator for yaml generator
"""
return wrapped(*args, **kwargs) |
def num_configs(n: int) -> int:
"""We are given a 2 x N board. This problem is mostly about figuring out
the possible cases for laying out the shapes. Here are the possible cases:
* Place a domino vertically
* Place two dominos horizontal on top of each other
* two trominos interlocking
We can... |
def _FixInt(value: int) -> int:
"""Fix negative integer values returned by TSK."""
if value < 0:
value &= 0xFFFFFFFF
return value |
def xml_get_attrs(xml_element, attrs):
"""Returns the list of necessary attributes
Parameters:
element: xml element
attrs: tuple of attributes
Returns:
a dictionary of elements
"""
result = {}
for attr in attrs:
result[attr] = xml_element.getAtt... |
def normalize_from_minmax(v, min_v, max_v):
"""Normalize a value given their max and minimum values of the lists
:param v: value to normalize
:param max_v: maximum value of the list
:param min_v: minimum value fo the list
:return:
"""
# todo why ((10 - 1) + 1)?
if min_v == 0 and max_v =... |
def int_to_roman(num):
"""Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.
roman_integer_value = {"I":1, "V":5, "X":10, "L":50, "C":100, "D":500, "M":1000}
For example, 2 is written as II in Roman numeral, just two one's added together. 12 is written as XII,
whi... |
def is_valid_option(parser, arg, checklist):
"""
Check if a string arg is a valid option according to a checklist
Parameters
----------
parser : argparse object
arg : str
checklist
Returns
-------
arg
"""
if not arg in checklist:
parser.error("'{}' parametised m... |
def handle_input(arguments):
"""
Validates command-line arguments, and returns setting dictionary.
Manages defaults: config file if present, otherwise internal value, unless overridden from command-line.
:param args:
:return: settings dictionary
"""
settings = {}
i... |
def to_int_or_zero(value):
"""
Converts given value to an integer or returns 0 if it fails.
:param value: Arbitrary data type.
:rtype: int
.. rubric:: Example
>>> to_int_or_zero("12")
12
>>> to_int_or_zero("x")
0
"""
try:
return int(value)
except ValueError:
... |
def find_idx_nonsol(list_kappa_idx, solution_idx):
"""
Find the scalar products for nonsolutions.
Parameters:
list_kappa_idx -- list
solution_idx -- list of Decimal
Return:
nonsol_idx -- list
"""
nonsol_idx = [sublist for sublist in list_kappa_idx if (sublist[0] != solution_idx[0]) and (sublist[1] != sol... |
def interrogate_age_string(age_string):
"""
Take a string referring to an age group and find it's upper and lower limits.
Args:
age_string: The string to be analysed
Returns:
limits: List of the lower and upper limits
dict_limits: Dictionary of the lower and upper limits
"""... |
def get_component_key(out_chan: str, in_chan: str) -> str:
"""
Get key for out channel and in channel combination in the solution
Parameters
----------
out_chan : str
The output channel
in_chan : str
The input channel
Returns
-------
str
The component key
... |
def _MakeSplitDimension(value, enabled):
"""Return dict modelling a BundleConfig splitDimension entry."""
return {'value': value, 'negate': not enabled} |
def _x2n(x):
"""
converts base 26 number-char into decimal
:param x:
:return:
"""
numerals = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
b=26
n=0
for i,l in enumerate(reversed(x)):
n+=(numerals.index(l)+1)*b**(i)
return n |
def _resolve_nodata(src, band, fallback=None, override=None):
"""Figure out what value to use for nodata given a band and fallback/override
settings
:param src: Rasterio file
"""
if override is not None:
return override
band0 = band if isinstance(band, int) else band[0]
nodata = sr... |
def vari(blue, green, red):
"""
# VARI: Visible Atmospherically Resistant Index
# VARI is the Visible Atmospherically Resistant Index, it was
# designed to introduce an atmospheric self-correction
# Gitelson A.A., Kaufman Y.J., Stark R., Rundquist D., 2002.
# Novel algorithms for estimation of v... |
def is_os_tool(path_to_exe):
"""test if path_to_exe was installed as part of the OS."""
return path_to_exe.startswith('/usr/bin') |
def YEAR(expression):
"""
Returns the year portion of a date.
See https://docs.mongodb.com/manual/reference/operator/aggregation/year/
for more details
:param expression: expression or variable of a Date, a Timestamp, or an ObjectID
:return: Aggregation operator
"""
return {'$year': expr... |
def contains_static_content(content: str) -> bool:
"""check if html contains links to local images"""
return "<img alt=" in content |
def select_user(user):
"""Selects a specific mysql user and returns true if it exists."""
return "SELECT user FROM mysql.user WHERE user = '" + user + "'" |
def mclag_session_timeout_valid(session_tmout):
"""Check if the MCLAG session timeout in valid range (between 3 and 3600)
"""
if session_tmout < 3 or session_tmout > 3600:
return False, "Session timeout %s not in valid range[3-3600]" % session_tmout
return True, "" |
def CSourceForElfSymbolListMacro(variable_prefix, names, name_offsets,
base_address=0x10000, symbol_size=16,
spacing_size=16):
"""Generate C source definition for a macro listing ELF symbols.
Args:
macro_suffix: Macro name suffix.
names: Lis... |
def shorten_url(youtube_id: str) -> str:
"""Return the shortened url for YouTube video."""
return f'https://youtu.be/{youtube_id}' |
def _saferound(value, decimal_places):
"""
Rounds a float value off to the desired precision
"""
try:
f = float(value)
except ValueError:
return ''
format = '%%.%df' % decimal_places
return format % f |
def strorblank(s):
"""return '' if not already string
"""
return "" if not isinstance(s, str) else s |
def split_filename(name):
"""Splits a string containing a file name into the filename and extension"""
dot = name.rfind('.')
if (dot == -1):
return name, ''
return name[:dot], name[dot + 1:] |
def to_iso_date(value):
"""
handle incomplete iso strings, so we can specify <year> or <year-month>,
in addition to <year-month-day>
"""
hyphen_count = value.count('-')
if hyphen_count < 2:
value += '-01' * (2 - hyphen_count)
return value |
def threshold(number:int,minNumber:int=20) -> int:
"""Threshold a value to a minimum int"""
return number if abs(number) >= minNumber else 0 |
def tsym(name):
"""
Returns unicodes for common symbols.
Definition
----------
def tsym(name):
Input
-----
name Symbol name, case insensitive
Output
------
Raw unicode string
Restrictions
------------
... |
def str2bool(text, test=True):
""" Test if a string 'looks' like a boolean value.
Args:
text: Input text
test (default = True): Set which boolean value to look for
Returns:
True if the text looks like the selected boolean value
"""
if test:
return str(text).lower() ... |
def detectEmptyTFR(frame):
"""'Empty' TFRs are NOTAM-TFRs which are NOTAM-TFRs that have been
sent previously, and are active, but which every other cycle is sent
with no text-- Just with it's number, an empty text field, and an
indication that it is still active.
Args:
frame (dict): Frame ... |
def accuracy_score(actual, predicted):
"""This method predicts the accuracy percentage"""
correct = 0
for i in range(len(actual)):
if actual[i] == predicted[i]:
correct += 1
return correct / float(len(actual)) * 100.0 |
def is_valid_mojang_uuid(uuid):
"""https://minecraft-de.gamepedia.com/UUID"""
allowed_chars = '0123456789abcdef'
allowed_len = 32
uuid = uuid.lower()
if len(uuid) != 32:
return False
for char in uuid:
if char not in allowed_chars:
return False
return True |
def date_trigger_dict(ts_epoch):
"""A cron trigger as a dictionary."""
return {
'run_date': ts_epoch,
'timezone': 'utc',
} |
def normalize(value, dict_type=dict):
"""Normalize values. Recursively normalizes dict keys to be lower case,
no surrounding whitespace, underscore-delimited strings."""
if isinstance(value, dict):
normalized = dict_type()
for k, v in value.items():
key = k.strip().lower().replac... |
def normalizeAddress(address):
"""We need this because we internally store email addresses in this format
in the black- and whitelists
"""
if address.startswith("<"):
return address
else:
return "<" + address + ">" |
def get_index_name(create_index_statement, unique_constraint):
"""
Return the name of the index from the create index statement.
:param create_index_statement: The create index statement
:param unique_constraint: The unique constraint
:return: The name of the index
"""
splitted_statement = ... |
def _as_set(spec):
"""Uniform representation for args which be name or list of names."""
if spec is None:
return []
if isinstance(spec, str):
return [spec]
try:
return set(spec.values())
except AttributeError:
return set(spec) |
def create_bbox(boundries):
""" BBox serves for the plotting size figures"""
BBox = ((boundries[3], boundries[2],
boundries[1], boundries[0]))
return BBox |
def make_poly(bit_length, msb=False):
"""Make `int` "degree polynomial" in which each bit represents a degree who's coefficient is 1
:param int bit_length: The amount of bits to play with
:param bool msb: `True` make only the MSBit 1 and the rest a 0. `False` makes all bits 1.
"""
if msb:
r... |
def __ior__(self,other): # supports syntax S |= T
"""Modify this set to be the union of itself an another set."""
for e in other:
self.add(e)
return self # technical requirement of in-place operator |
def ok_for_raw_triple_quoted_string(s: str, quote: str) -> bool:
"""
Is this string representable inside a raw triple-quoted string?
Due to the fact that backslashes are always treated literally,
some strings are not representable.
>>> ok_for_raw_triple_quoted_string("blah", quote="'")
True
... |
def trim_spaces_from_args(args):
"""
Trim spaces from values of the args dict.
:param args: Dict to trim spaces from
:type args: dict
:return:
"""
for key, val in args.items():
if isinstance(val, str):
args[key] = val.strip()
return args |
def _delist(val):
"""returns single value if list len is 1"""
return val[0] if type(val) in [list, set] and len(val) == 1 else val |
def non_repeating(given_string):
"""
Go through each character in the string and map them to a dictionary
where the key is the character and the value is the time that character appear
in the string.
Because the dictionary doesn't store thing in order. Therefore, we cannot loop
... |
def remove_numbers(s):
"""Remove any number in a string
Args:
s (str): A string that need to remove number
Returns:
A formatted string with no number
"""
return ''.join([i for i in s if not i.isdigit()]) |
def rev_comp_motif( motif ):
"""
Return the reverse complement of the input motif.
"""
COMP = {"A":"T", \
"T":"A", \
"C":"G", \
"G":"C", \
"W":"S", \
"S":"W", \
"M":"K", \
"K":"M", \
"R":"Y", \
"Y... |
def _parse_id(func):
"""Supplies the module name and functon name as a 2-tuple"""
return (func.__module__.split(".")[-1], func.__name__) |
def split(ds, partition):
"""Split the dataset according to some partition.
Parameters
----------
ds :
partition :
Returns
-------
"""
n_data = len(ds)
# get the actual size of partition
partition = [int(n_data * x / sum(partition)) for x in partition]
ds_batched =... |
def cell(data, label, spec):
"""
Format the cell of a latex table
Parameters
----------
data : string
string representation of cell content
label : string
optional cell label, used for tooltips
spec : dict
options for the formatters
Returns
-------
str... |
def xgboost_problem_type(hyperparameters: dict) -> str:
""" XGboost problem type finder
The function finds the type of the problem that should be solved when using the xgboost method. The function uses
the objective variable to find out what type of problem that should be solved
:param dict hyperpara... |
def setup_permissions(bot):
"""Use this decorator to return a dictionary of required permissions."""
return {
'read_messages': "This is a dummy additional permission.",
'change_nickname': "This allows the bot to change its own nickname."
} |
def rotate_list(l):
"""
Take a nested list of (x, y) dimensions, return an (y, x) list.
:param l: a 2-nested list
"""
# Without loss of generality, presume list is row-first and we need it
# column-first
r = [[None for x in range(len(l))] for x in range(len(l[0]))]
for row_index, row in... |
def span(array):
"""
Returns the span of array: the difference between the last and
first elements, or array[array.length-1] - array[0].
"""
return array[-1] - array[0] |
def rev_word(s):
"""
Manually doing the splits on the spaces.
"""
words = []
length = len(s)
spaces = [' ']
# Index Tracker
i = 0
# While index is less than length of string
while i < length:
# If element isn't a space
if s[i] not in spaces:
# The... |
def desanitise(dic):
"""Removes underscores from dictionary"""
new_dic = dict()
for key, value in dic.items():
#omit the underscore from the key name
new_dic[key[1:]] = value
return new_dic |
def size_color_unique_id(unique_id=999999999):
""" Return an interpolated color for a given byte size.
"""
#r1 = size[-3:]
#g1 = size[-6:-3]
#b1 = size[-9:-6]
red = (unique_id >> 16) & 0xff
green = (unique_id >> 8) & 0xff
blue = unique_id & 0xff
try:
red = int( floa... |
def gini_index(groups: list, class_values: list) -> float:
"""
Calculate the Gini index for a split dataset (0 is perfect split)
:param groups: to compute the gini index (last item is class value)
:param class_values: class values present in the groups
:return: gini index
"""
gini = 0.0
... |
def transDataRow(origins, pep, protDict):
"""
Called by writeToFasta(), this function takes the trans origin data for a given peptide and formats it for writing
to the csv file.
:param origins: the data structure containing information on where a given peptide was found within the input
proteins. H... |
def apply_prot_to_nuc(aligned_prot, nuc):
"""
Use aligned protein sequence to update the corresponding nucleotide
sequence.
:param aligned_prot: str, aligned amino acid sequence
:param nuc: str, original nucleotide sequence
:return: str, nucleotide sequence with codon gaps
"""
res = ''... |
def make_pair_table(ss, base=0, chars=['.']):
"""Return a secondary struture in form of pair table.
Args:
ss (str): secondary structure in dot-bracket format
base (int, optional): choose between a pair-table with base 0 or 1
chars (list, optional): a list of characters to be are ignored, defa... |
def create_network_config_kubernetes(config):
"""Create a BIG-IP Network configuration from the Kubernetes config.
Args:
config: Kubernetes BigIP config which contains openshift-sdn defs
"""
f5_network = {}
if 'openshift-sdn' in config:
openshift_sdn = config['openshift-sdn']
... |
def get_class_labels(labels_map):
"""Returns the list of class labels from the given labels map.
The class labels are returned for indexes sequentially from
`min(1, min(labels_map))` to `max(labels_map)`. Any missing indices are
given the label "class <index>".
Args:
a dictionary mapping i... |
def layer(height: int) -> int:
"""
Max number of nodes in the lowest layer of a tree of given height.
"""
assert height > 0
return 2 ** (height - 1) |
def set_size(width, fraction=1, subplots=(1, 1)):
"""
Set figure dimensions to avoid scaling in LaTeX.
"""
golden_ratio = 1.618
height = (width / golden_ratio) * (subplots[0] / subplots[1])
return width, height |
def calc_max_quant_value(bits):
"""Calculate the maximum symmetric quantized value according to number of bits"""
return 2**(bits - 1) - 1 |
def get_cluster_label(cluster_id):
"""
It assigns a cluster label according to the cluster id that is
supplied.
It follows the criterion from below:
Cluster id | Cluster label
0 --> A
1 --> B
2 --> C
25 --> Z
26 --> AA
... |
def is_utf8(bs):
"""Check if the given bytes string is utf-8 decodable."""
try:
bs.decode('utf-8')
return True
except UnicodeDecodeError:
return False |
def get_matrix_diff_coords(indices):
"""returns coordinates for off diagonal elements"""
return [(i, j) for i in indices for j in indices if i != j] |
def public_notification(title=None, alert=None, summary=None):
"""Android L public notification payload builder.
:keyword title: Optional string. The notification title.
:keyword alert: Optional string. The notification alert.
:keyword summary: Optional string. The notification summary.
"""
pay... |
def _build_tree_string(root, curr_index, index=False, delimiter='-'):
"""
Recursively walk down the binary tree and build a pretty-print string.
Source: https://github.com/joowani/binarytree
"""
if root is None or root.leaf:
return [], 0, 0, 0
line1 = []
line2 = []
if index:
... |
def tag_to_regex(tag_name, tags):
"""Convert a decomposition rule tag into regex notation.
Parameters
----------
tag_name : str
Tag to convert to regex notation.
tags : dict
Tags to consider when converting to regex.
Returns
-------
w : str
Tag converted to ... |
def get_most_visible_camera_annotation(camera_data_dict: dict) -> dict:
"""
Get the most visibile camera's annotation.
:param camera_data_dict: Dictionary of form:
{
'CAM_BACK': {'attribute_tokens': ['cb5118da1ab342aa947717dc53544259'],
'bbox_corners': [600.8315617945755,
4... |
def maybe_coerce_with(converter, obj, **kwargs):
"""Apply converter if str, pass through otherwise."""
obj = getattr(obj, "original_object", obj)
return converter(obj, **kwargs) if isinstance(obj, str) else obj |
def getUniqueValuesFromList(inlist):
"""
Returns the unique values from the list containing no. of items""
Parameters
----------
inlist (list): List containing items to get unique values from
Returns
-------
values(list): list containing unique values sorted in order
"""
valu... |
def store_error_star(params, substep, state_history, state, policy_input):
"""
Store the error_star state, which is the error between the target and market price.
"""
error = policy_input["error_star"]
return "error_star", error |
def R13(FMzul, P, d2, DKm, mu_Gmin, mu_Kmin,
MU = 0, MKZu = 0):
"""
R13 Determining the tightening torque MA
(Sec 5.4.3)
"""
# The tightening torque may be calculated :
MA = (FMzul * (0.16 * P + 0.58 * d2 * mu_Gmin
+ mu_Kmin * (DKm / 2.0))) # (R13/1)
... |
def skip_add(n):
""" Takes a number n and returns n + n-2 + n-4 + n-6 + ... + 0.
>>> skip_add(5) # 5 + 3 + 1 + 0
9
>>> skip_add(10) # 10 + 8 + 6 + 4 + 2 + 0
30
>>> # Do not use while/for loops!
>>> from construct_check import check
>>> # ban iteration
>>> check(this_file, 'skip_add... |
def cid_with_annotation2(cid, expected_acc=None):
"""Given a cluster id, return cluster id with human readable annotation.
e.g., c0 --> c0 isoform=c0
c0/89/3888 -> c0/89/3888 isoform=c0;full_length_coverage=89;isoform_length=3888;expected_accuracy=0.99
c0/f89p190/3888 -> c0/f89p190/3888 isof... |
def cow_line_splitter(cow_line):
"""
Turn a single line from the cow data file into a list of [cow, weight].
"""
return cow_line.strip().split(",") |
def parse_version_req(version):
"""
Converts a version string to a dict with following rules:
if string starts with ':' it is a channel
if string starts with 'sha256' it is a digest
else it is a release
"""
if version is None:
version = "default"
if version[0] == ':' or... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.