content stringlengths 42 6.51k |
|---|
def enums2html(enums):
"""
Given a list of enumerated value / name pairs, create an HTML output
to represent legal combinations
"""
s = "\n"
#s += "<br><u>Legal Settings</u><br>\n<table>\n"
s += '<table class="enum">\n'
s += " <thead><tr><th>Value</th><th>Definition</th></tr></thead>\n"... |
def gradient(x, x_min, x_max):
"""
Gradient scaling function. The gradient is computed
to result in +/-1 scales at x_max and x_min correspondingly.
Parameters
----------
x: ndarray
An input array, for which to compute the scalings.
x_min: float
A point, that corresponds to -... |
def to_id_str(name: str) -> str:
"""Converts a full-name to its corresponding id string.
:param name: The name to convert.
:type name: str
:return: The corresponding id string.
:rtype: str
"""
return "".join(char for char in name if char.isalnum()).lower() |
def check_frame(buff):
"""
returns False if the buffer doesn't starts with a valid frame
returns the size of the frame in success
"""
if len(buff) < 2:
return False
min_size = 2
masked = False
payload_length = 0
if buff[1] & 128:
min_size += 4
masked = True
... |
def extract_country(questionnaire_response):
"""Extracts country information from a QuestionnaireResponse resource.
Example resource:
{
...
"item": [
{
"answer": [{"valueString": "countryA"}],
"linkId": "1"
},
{
"item": [
{
"answer": [{"val... |
def rk_four(f, x, u, T):
"""
Perform fourth-order Runge-Kutta numerical integration.
The function to integrate is f(x, u, params), where the state varables are
collected in the variable x, we assume a constant input vector u over time
interval T > 0, and params is an array of the system's parameter... |
def common(expected_payload, data):
"""
The expected payload is the expected data and we compare it
to the json data
"""
for key in data.keys():
if key not in expected_payload:
msg = 'The field {} is not required'.format(key)
return {"Status":400, "Message":msg}... |
def get_tcon(v, index):
"""Gets the list indices in L of the tensors that have index as their
leg.
"""
tcon = []
for i, inds in enumerate(v):
if index in inds:
tcon.append(i)
l = len(tcon)
# If check_indices is called and it does its work properly then these
# checks ... |
def float_chk(list1):
""" In python 2 versions, at least one of the lists will need to be in floats (not ints)
to ensure correct calculation.
"""
for i, j in enumerate(list1):
list1[i] = float(j)
return list1 |
def pyflakes_filter(line):
"""
Standard filter for pyflakes.
"""
ignore = [
'from rasmus.timer import *',
'from timer import *',
'from rasmus.vector import *',
'from vector import *',
'from rasmus.plotting import *',
'from plotting import *',
]
for... |
def axial_to_cube(h):
"""
Converts a axial coord to an cube coord.
:param h: An axial coord q, r.
:return: A cube coord x, z, y.
"""
q, r = h
return q, -q - r, r |
def dict_to_kv_list(data):
"""
Take a dict and return a list of k=v pairs
Input data:
{'a': 1, 'b': 2}
Return data:
['a=1', 'b=2']
"""
return ['='.join(str(e) for e in x) for x in data.items()] |
def get_difficulty(level=1, mod=0):
"""finds the target number using Numenera Rules"""
return (level-mod)*3 |
def is_int(int_string: str):
"""
Checks if string is convertible to int.
"""
try:
int(int_string)
return True
except ValueError:
return False |
def get_most_freq_genotype(maf, no_none=False):
"""
Get highest frequent genotype.
:param maf:
:param bool no_none: do not return none
:return:
"""
freq = maf['maf']
allele = maf['maf_allele']
if freq and allele:
freq = float(freq)
if allele == 'ref':
ref... |
def decode_outputs_from_signals(signals_and_outputs) -> int:
"""
Use signals to decode seven segment wiring and calculate puzzle output
Args:
signals_and_outputs (list): input signals and outputs of seven segment displays
Returns:
sum of all decoded output numbers
"""
numbers =... |
def mul(X, varX, Y, varY):
"""Multiplication with error propagation"""
# Direct algorithm:
Z = X * Y
varZ = Y**2 * varX + X**2 * varY
# Indirect algorithm won't ensure floating point results
# varZ = Y**2
# varZ *= varX
# Z = X**2 # Using Z to hold the temporary
# Z *= varY... |
def island_perimeter(grid):
"""returns the perimeter of the island"""
patches = 0
borders = 0
for row in range(len(grid)):
for col in range(len(grid[row])):
if grid[row][col] == 1:
patches += 1
if row != len(grid) - 1:
if grid[row +... |
def get_ips_in_range(ipFrom, ipTo):
"""
Get List of IPs in a validated IP range
"""
ip_addr_lst = []
ip1 = ipFrom.split('.')
ip2 = ipTo.split('.')
idx = - (len(ip1[3]))
subnet = str(ipFrom[:idx])
for x in range(int(ip1[3]), int(ip2[3])+1):
ip_addr_lst.append(subnet + str(x))... |
def _invert_permutation(perm):
"""Calculate invert permutation."""
out = [0] * len(perm)
for i, value in enumerate(perm):
out[value] = i
return tuple(out) |
def coerce_tuple(obj):
"""Coerce an object to a tuple.
Since strings are sequences, iterating over an object that can be a string
or a sequence can be difficult. This solves the problem by ensuring scalars
are converted to sequences. """
if obj is None:
return tuple()
elif isinstance(obj... |
def getPathArch(path, arch, rcvar='PETSC_ARCH', rcfile='petsc.cfg'):
"""
Undocumented.
"""
import os, warnings
# path
if not path:
path = '.'
elif os.path.isfile(path):
path = os.path.dirname(path)
elif not os.path.isdir(path):
raise ValueError("invalid path: '%s'... |
def lists_equal (l, r) :
"""True if set of elements of `l` and `r` is equal.
>>> l = list (range (3))
>>> r = l[::-1]
>>> l,r
([0, 1, 2], [2, 1, 0])
>>> lists_equal (l, r)
True
"""
return set (l) == set (r) |
def rect(tl,br):
""" Turns a pair of top/left, bottom/right coordinates into a rect (which is left,right,top,bottom). """
return (tl[0],br[0],tl[1],br[1]) |
def a_or_an(s):
"""
Return `a` or `an` depending on the first voewl sound of s. Dumb heuristic
"""
if s[0].lower() in 'aeiou':
return 'an'
return 'a' |
def is_requirement(line):
"""
Return True if the requirement line is a package requirement;
that is, it is not blank, a comment, or editable.
"""
# Remove whitespace at the start/end of the line
line = line.strip()
# Skip blank lines, comments, and editable installs
return not (
... |
def getDigitCount(number):
"""How many digits will have the highest numbered file? e.g. if there will be 25
resulting bags the result is 2, for 300 bags the result is 3, for 8 bags it is 1"""
return len(str(number)) |
def v6_tail(iterable, n):
"""Return the last n items of given iterable.
We could fix this by doing something different in our loop whenever n is 1.
This might look a little silly/repetitive but it works.
"""
items = []
if n <= 0:
return []
for item in iterable:
if n == 1:
... |
def zero_fill(number, digits=2):
"""Make a number string zero filled to the left."""
return str(number).zfill(digits) |
def seidel(matrix_a: list, vector_b: list, vector_x: list) -> list:
"""
Seidel algorithm part
:param matrix_a: start matrix
:param vector_b: start vector
:param vector_x: solution vector
:return:
"""
x_ = vector_x.copy()
n = len(matrix_a)
for j in range(0, n):
d = vector_... |
def summarise_dict(table, field):
"""
Take an input dict (table) and reduce it to the list of unique values in field
"""
unique_values = []
for row in table:
if field in row:
if row[field] not in unique_values:
unique_values.append(row[field])
return unique_values |
def reaction_class_from_data(class_typ, class_spin,
class_radrad, class_isc):
""" Build a full-class description including the following useful
descriptors of the reaction class:
typ: type of reaction (e.g., abstraction, addition, migration)
spin: whethe... |
def _unescape_specification(specification):
# type: (str) -> str
"""
Unescapes the interface string: replaces '%2F' by slashes '/'
:param specification: Specification name
:return: The unescaped name
"""
return specification.replace("%2F", "/") |
def prepare_batch_sequences(input_sequences, target_sequences, batch_size):
""" Split cascade sequences into batches based on batch_size. """
# Split based on batch_size
assert (len(input_sequences) == len(target_sequences))
num_batch = len(input_sequences) // batch_size
if len(input_sequences) % ba... |
def number(bus_stops):
"""
There is a bus moving in the city, and it takes and drop some people in each bus stop.
You are provided with a list (or array) of integer pairs.
Elements of each pair represent number of people get into bus (The first item)
and number of people get off the bus (The second ... |
def fintlist(alist):
"""List of integers from string or list of strings/integers"""
outlist = []
if isinstance(alist, str):
# we have a string (comma-separated integers)
alist = alist.strip().strip("[] ").split(",")
for it in alist:
if it:
outlist.append(int(float(it)... |
def calculate_aim_multiply_final(course: list) -> int:
"""
Read the course of commands and calculate horizontal, depth and aim
positions. Multiply this value and return.
:param course: List of commands
:return: Multiple of horizontal and depth
:rtype: int
"""
horizontal = 0
depth = ... |
def get_user_attributes(obj, exclude_methods=True):
"""Returns a list of non-system attributes for an object.
:param obj: object or class to inspect
:param exclude_methods: [optional] do not include callable methods in the
returned list, defaults to True
:returns: list of non-system attrib... |
def acknowledgements(name, tag):
"""Returns acknowledgements for space weather dataset
Parameters
----------
name : string
Name of space weather index, eg, dst, f107, kp
tag : string
Tag of the space weather index
"""
ackn = {'dst':
{'noaa': 'Dst is maintained ... |
def coverage_shortest(seq_query, seq_target, seq_len):
"""
Return coverage of the shortest sequence in the alignment.
>>> coverage_shortest("AAAA----", "AAAAAAAA", 8)
50.0
"""
res_query = len(seq_query.replace('-', ''))
res_target = len(seq_target.replace('-', ''))
return 100.0 * min(re... |
def generate_page(title, body):
""" Scaffolding for a basic html page """
return "<html><head><title>{0}\
</title></head>\
<body>{0}{1}</body></html>".format(title, body) |
def field_to_attr(field_name):
"""Convert a field name to an attribute name
Make the field all lowercase and replace ' ' with '_'
(replace space with underscore)
"""
result = field_name.lower()
if result[0:1].isdigit():
result = "n_" + result
result = result.replace(' ', '_')
... |
def func_xy_args_kwargs(x, y, *args, **kwargs):
"""func.
Parameters
----------
x, y: float
args: tuple
kwargs: dict
Returns
-------
x, y: float
args: tuple
kwargs: dict
"""
return x, y, None, None, args, None, None, kwargs |
def get_jaccard_sim(str1, str2):
"""
Jaccard similarity:
Also called intersection over union is defined as size of intersection
divided by size of union of two sets.
"""
a = set(str1.split())
b = set(str2.split())
c = a.intersection(b)
return float(len(c)) / (len(a) + len(b) - len(c)... |
def _chr_cmp(keys):
""" Allow numeric sorting of chromosomes by chromosome number
If numeric interpretation fails, position that record at -1 """
key = keys[0].lower().replace("_", "")
chr_num = key[3:] if key.startswith("chr") else key
if chr_num == 'x':
chr_num = 98
elif chr_num ==... |
def sanitize(header_tuple):
"""Sanitize request headers.
Remove Spark authentication token.
"""
header, value = header_tuple
if (header.lower().strip() == "Authorization".lower().strip()
and "Bearer".lower().strip() in value.lower().strip()):
return header, "Bearer <redacted>"... |
def evaluate(formula, operators, numbers):
""" Evaluate a formula represented as a tree into a single integer result
If the formula involves a non-integer division, NaN will be returned
"""
calc = float("NaN")
left = formula[0]
op = operators[formula[1]]
right = formula[2]
if isinstance(left, list):
left = e... |
def is_even_faster(number: int) -> bool:
"""
Test if a number is a even number using bit operator.
:param number: the number to be checked.
:return: True if the number is even, otherwise False.
>>> is_even_faster(-1)
False
>>> is_even_faster(-2)
True
>>> is_even_faster(0)
True
... |
def get_args_validator_name(layer: int):
"""Return the specified layer's validator name"""
return "__layer{layer}_validator".format(layer=layer) |
def find_seatings(names, table):
"""Find all seating combinations for names."""
if not names:
return [table]
seatings = []
for name in names:
cur_names = names - {name}
seatings.extend(find_seatings(cur_names,
table + [name]))
return seat... |
def serial_to_endcap(x: int) -> int:
"""Convert serialized chamber id to endcap."""
return (x >> 10) + 1 |
def _incs_list_to_string(incs):
"""Convert incs list to string.
Example:
['thirdparty', 'include'] -> "-I thirdparty -I include"
"""
return ' '.join(['-I ' + path for path in incs]) |
def _convert_flag(elems, value):
"""
Checks the value is in elems and returns it.
"""
if value in elems:
return value
else:
raise ValueError(
"Expect {!r} to be one of {}".format(value, ", ".join(map(repr, elems)))
) |
def value_folded_from_limit_max(value, maximum):
"""
Testdata: (-6, -1, 2, 5, 10) or (0, 5, 8, 11, 16) # FIXME COPY
yield 2 * 2 - (-1) = 5 or 2 * 8 - 5 = 11 # FIXME COPY
"""
return 2.0 * maximum - value |
def nxz(PAxz,PBxz,Npulse,P_times_Dj):
"""
Calculates the number of events in the X or Z sifted basis per pulse
intensity per time slot.
nx[j,t] or nz[j,t]; j = {1:3}, t = {1:Nt}
Parameters
----------
PAxz : float
Probability of Alice preparing a state in the X/Z basis.
PBxz... |
def check_required_fields(req_fields, input_list):
"""Check if the required fields are present or not in a given list.
Keyword arguments:
req_fields -- The list of fields required
input_list -- The input list to check for
Returns:
Boolean
"""
if all(field in req_fields for field i... |
def class_name(class_instance):
"""Removes all values of arg from the given string"""
if class_instance:
return class_instance.__class__.__name__
return "" |
def autocomplete_service_env(actions, objects):
"""
Returns current service_env for object. Used as a callback for
`default_value`.
Args:
actions: Transition action list
objects: Django models objects
Returns:
service_env id
"""
service_envs = [obj.service_env_id fo... |
def next_power_2(x: int) -> int:
"""Return the smallest power of 2 greater than or equal to x"""
return 1 << (x-1).bit_length() |
def split_paragraphs(lines, keepends=False):
"""Split the lines into paragraphs"""
paras = list()
para = list()
for line in lines:
if line.strip():
para.append(line)
else:
if keepends:
para.append(line)
if para or keepends:
... |
def _read_xml_element(element, xml_ns, tag_name, default=""):
""" Helper method to read text from an element. """
try:
return element.find(xml_ns + tag_name).text
except AttributeError:
return default |
def tf_to_10(x):
"""
Maps true/false to 1/0
"""
if x == True:
return 1
elif x == False:
return 0
return x |
def success(message=None, data=None):
"""
Get a web response with success, message and data
"""
response = {"success": True}
if message:
response["message"] = message
if data:
response["data"] = data
return response |
def LJ(v,epsilon, sigma):
""" Lennard-Jones potential """
return (4*epsilon*(pow(sigma/v,12) - pow(sigma/v,6))) |
def insertion_sort(arr):
"""
It's insertion sort alright!
"""
for j in range(1, len(arr)):
current_val = arr[j]
i = j-1
while i >= 0 and arr[i] > current_val:
arr[i+1] = arr[i]
i = i-1
arr[i+1] = current_val
return arr |
def toBool(value):
"""Convert any type of value to a boolean.
The function uses the following heuristic:
1. If the value can be converted to an integer, the integer is then
converted to a boolean.
2. If the value is a string, return True if it is equal to 'true'. False otherwise.
Note that t... |
def binary_search(num_list, num, not_found="none"):
"""Performs a binary search on a sorted list of numbers, returns index.
Only works properly if the list is sorted, but does not check whether it is
or not, this is up to the caller.
Arguments:
num_list: a sorted list of numbers.
num: ... |
def sepdate(dt):
"""sepdate('%m/%d/%y %H:%M:%S') -> '%Y-%m-%d'
Return ISO-format yyyy-mm-dd date from Access-formatted Date/Time."""
dt = "%s" % dt
if dt.find(" ") != -1:
datepart, timepart = dt.split(" ")
else:
return None
month, day, year = dat... |
def n_palavras_unicas(lista_palavras):
"""
Essa funcao recebe uma lista de palavras e devolve o numero de palavras
que aparecem uma unica vez.
"""
freq = dict()
unicas = 0
for palavra in lista_palavras:
p = palavra.lower()
if p in freq:
if freq[p] == 1:
... |
def motion_h(input_line, cur, count):
"""Go `count` characters to the left and return position.
See Also:
`motion_base()`.
"""
return max(0, cur - max(count, 1)), False, False |
def _extract_version(version):
"""Extracts the major and minor versions from an OpenGL version string.
Can handle driver's appending their specific driver version to the string.
"""
import re
# version is guaranteed to be 'MAJOR.MINOR<XXX>'
# there can be a 3rd version
# split full stops an... |
def each(h_a):
"""See https://perldoc.perl.org/functions/each"""
key = str(id(h_a)) # Unique memory address of object
if not hasattr(each, key):
setattr(each, key, iter(h_a))
it = getattr(each, key)
try:
v = next(it)
except StopIteration:
setattr(each, key,... |
def handler_result(results):
"""
Iterates over the answers, checks if the answer is of type Exception, then replaces it with "".
"""
result_no_exception = []
for result in results:
if isinstance(result, Exception):
result_no_exception.append('')
else:
result_n... |
def utility(board, pieces, player):
"""
logic for calculating utility value of a board, using jit compilation
"""
player_num = 1 if player else -1
other_num = -player_num
pieces_player, pieces_opp = 0, 0
for y, x in pieces:
piece = board[y][x]
if piece == player_num:
... |
def make_unique_title(title, title_dict):
"""Appends number to title for duplicates"""
num = 1
base_title = title
while title_dict.get(title):
num += 1
title = f"{base_title} ({num})"
return title |
def compute_hamming_weight(n: int) -> int:
"""Computes the Hamming weight of an unsigned integer
Note that in some languages, such as Java, there is no unsigned integer
type.
In this case, the input will be given as a signed integer type.
It should not affect your implementation,
as the integer... |
def safe_hasattr(obj, attr):
"""In recent versions of Python, hasattr() only catches AttributeError.
This catches all errors.
"""
try:
getattr(obj, attr)
return True
except Exception: # pylint:disable=bare-except
return False |
def find(nda, obj):
"""returns the index of the obj in the given nda(ndarray, list, or tuple)"""
for i in range(0, len(nda)):
if(nda[i] == obj):
return i;
return -1; |
def to_k_parallel_reduced(x, x0, w_px, w):
""" Transform pixel to momentum and correct to the reduced brillouin scheme"""
kx = (x - x0) * w / w_px
return kx - (kx + w / 2) // w |
def change_to_similar_character_if_needed(predicted_letter: str,
first_character_of_word: bool,
is_word_letters: bool) -> str:
"""
Alter the predicted character to a character that looks similar, from
numbers to letters. In ... |
def memory_formatter(mem):
"""
Takes a numeric value \p mem and returns a string using the standard prefixes K,
M, G. The printed string has one decimal digit for GB, otherwise is integral.
"""
if mem is None: return None
if mem < 1000:
return str(mem)
if mem < 1000000:
retur... |
def _get_embedding_layer_name_from_var(var):
"""Get name for ElasticDL embedding layer from variable."""
# Assumes that for ElasticDL embedding layer, variable will be a
# string representing its layer name
if isinstance(var, str):
return var
return None |
def get_seconds_from_input(input_time_str: str):
"""Thanks to CorpNewt for helping out with this function"""
accepted_chars = {
"w": 604_800,
"d": 86_400,
"h": 3_600,
"m": 60,
"s": 1
}
time_seconds = 0
last_number = ""
for char in input_time_str:
i... |
def build_dd_entry(definition_entry):
"""Builds Data Dictionary entry from given dictionary entry. Given entry
itself is added as value for "definition" key.
{
"name": "",
"tags": "",
"data_type": "",
"description": "",
"entry_schema": "",
"updatedBy": "",
... |
def get_point_relative_to_another_point(endpoint, midpoint):
"""
:param endpoint: coordinates of the start point of a line in 2D Space ([x, y] or (x, y))
:type endpoint: list - [] or tuple - ()
:param midpoint: coordinates of the midpoint of a line in 2D Space ([x, y] or (x, y))
:type midpoint: list... |
def is_1d(X):
"""Returns True if X is a 1d array."""
try:
return X.ndim == 1
except:
return False |
def floatStr(decimal, decimalPlaces=2):
"""Format the decimal number into a string to be printed
Args:
decimal (float): Real number to be formatted
decimalPlaces (int)(optional): Amount of decimal places
Returns:
String: The number formatted as string
"""
return... |
def largest(a,findLoc=False):
""" Return the largest element of a sequence a. Error Checks
"""
try:
maxVal = a[0]
maxLoc = 0
for i in range(1,len(a)):
if a[i] > maxVal:
maxVal = a[i]
maxLoc = i
if findLoc == True:
retu... |
def _summarize_accessible_fields(field_descriptions, width=40,
section_title='Accessible fields'):
"""
Create a summary string for the accessible fields in a model. Unlike
`_toolkit_repr_print`, this function does not look up the values of the
fields, it just formats the... |
def surfaceColorFormatToTextureFormat(fmt, swizzled):
"""Convert nv2a draw format to the equivalent Texture format."""
if fmt == 0x3: # ARGB1555
return 0x3 if swizzled else 0x1C
elif fmt == 0x5: # RGB565
return 0x5 if swizzled else 0x11
elif fmt == 0x7 or fmt == 0x8: # XRGB8888
return 0x7 if swizzle... |
def arr_to_num(array):
"""Convert array of numbers to the number"""
num = 0
for (index, digit) in enumerate(array):
num += digit * pow(10, index)
return num |
def strtobool(val):
"""Convert a string representation of truth to true (1) or false (0).
True values are 'y', 'yes', 't', 'true', 'on', and '1'; false values
are 'n', 'no', 'f', 'false', 'off', and '0'. Raises ValueError if
'val' is anything else.
"""
val = val.lower()
if val in ('y', 'ye... |
def is_true(param):
"""Determine if the parameter passed as argument is true or false
Args:
param: the parameter we need to determine if it is True or False. Can be any type.
Returns:
bool: True if the the string representation of param is "true"
"""
return str(param).lower() == "... |
def _namespace_key(key: str, namespace: str or None) -> str:
"""
"""
if namespace is not None:
return '/'.join([namespace, key])
else:
return key |
def web_to_api(url) -> str:
"""
converts web url to api url
:param url: api url
:return: web api
"""
if '/api/v1' in url:
return url
return url.replace('.com', '.com/api/v1') |
def extract_provider_location(provider_location, key):
"""Extracts value of the specified field from provider_location string.
:param provider_location: provider_location string
:param key: field name of the value that to be extracted
:return: value of the specified field if it exists, otherwise,
... |
def _in_delta(value, target_value, delta) -> bool:
"""
Check if value is equal to target value within delta
"""
return abs(value - target_value) < delta |
def __calculate_waterfootprint(wf_ing, quantity):
"""
Calculate the right water footprint of a ingredient from its
(l/kg) water footprint and the quantity provided (in gr).
:param wf_ing: the water footprint of the ingredient.
:param quantity: the quantity of the ingredient.
:return: the water ... |
def tour_valid(tour, edges):
"""checks if the given tour only uses edges in the given graph"""
for edge in tour:
#print(edge)
if edge not in edges:
return False
return True |
def build_snmp_host_body(current_dict):
"""
Builds snmp host body
:param current_dict: current put body for snmp host
:return: snmp host dict
"""
if current_dict['trap_level'] == "all":
level = "STL_ALL"
elif current_dict['trap_level'] == "critical":
level = "STL_CRITICAL"
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.