content stringlengths 42 6.51k |
|---|
def term256color(r, g, b, a):
"""Get the xterm-color palette entry for given color"""
def f(v):
if v < 0:
return 0
elif v > 5:
return 5
else:
return round(v)
term = a / 256 / 256 * 6
r = f(r * term)
g = f(g * term)
b = f(b * term)
r... |
def dict_depth(dictionary):
"""Get depth of nested dict
"""
if isinstance(dictionary, dict):
return 1 + (max(map(dict_depth, dictionary.values())) if dictionary else 0)
return 0 |
def _desempaquetar_segmento(x):
"""
Extrae de la cadena las centenas, decenas y unidades por separado.
Tener en cuenta que puede que la cadena tenga una longitud inferior 3.
:param x: str de como mucho 3 caracteres.
:return tuple: tupla de 3 enteros que representan a centenas, decena... |
def split_str(seq, length):
"""Separate a string seq into length-sized pieces.
Parameters
----------
seq : str
String containing sequence of smaller strings of constant length.
length : int
Length of individual sequences.
Returns
-------
list of str
List of stri... |
def percent2float(percent):
"""
Converts a string with a percentage to a float.
"""
percent = percent.replace(" ", "")
percent = percent.strip("%")
return float(percent) / 100 |
def get_arg_list_value(arg_values, key):
"""
Check and return an argument value by key.
Arguments:
arg_values : list
key : str
Returns:
str
"""
for item in arg_values:
if item and item.startswith("{0}=".format(key)):
return item[(len(key) + 1) :]
... |
def find(s, *args):
"""find(s, sub [,start [,end]]) -> in
Return the lowest index in s where substring sub is found,
such that sub is contained within s[start,end]. Optional
arguments start and end are interpreted as in slice notation.
Return -1 on failure.
"""
return s.find(*args) |
def produced_by(entry):
"""
Modify source activity names to clarify data meaning
:param entry: str, original source name
:return: str, modified activity name
"""
if "ArtsEntRec" in entry:
return "Arts Entertainment Recreation"
if "DurableWholesaleTrucking" in entry:
return "D... |
def flatten(l):
"""
Flatten irregular nested list
:param l:
:return:
"""
if isinstance(l, (list, tuple)):
return [a for i in l for a in flatten(i)]
else:
return [l] |
def minOperations(n):
"""
Method that calculates the fewest number of operations needed to result in
exactly n H characters in the file.
Args:
n: integer (number of characters to reach)
Returns:
An integer (the minimum number of operations to reach n)
"""
if type(n) != int ... |
def flatten_config_dict(x, prefix=""):
"""Flattens config dict into single layer dict
Example:
flatten_config_dict({
MODEL: {
FBNET_V2: {
ARCH_DEF: "val0"
}
}
})
=> {"MODEL.FBNET_V2.ARCH_DEF": "val0"}
"""
... |
def resolve(json_path, obj):
"""Extract the subtree within `obj` addressed by `json_path`."""
for part in json_path:
obj = obj[part]
return obj |
def insertion(sortlist):
"""starts from index 1, sorts everything behind and moves forward."""
for i in range(1,len(sortlist)):
element = sortlist[i]
j = i
while j > 0 and sortlist[j-1] > element:
sortlist[j] = sortlist[j-1]
j = j - 1
sortlist[j] = elemen... |
def transform_gender(value):
"""
Transform any gender value into a normalized value.
"""
if value.lower() in ("male", "m"):
return "male"
elif value.lower() in ("female", "f"):
return "female"
elif value.lower() in ("other", "o"):
return "other"
elif value.lower() in ... |
def color_RGB_and_brightness_to_RGB(brightness: int, rgb=(0, 0, 0)):
"""Combine RGB and brightness"""
rgb = [int((x / 255.0) * brightness) for x in rgb]
return tuple(rgb) |
def urlify(s):
"""
Turn plot title into filename for saving
"""
import re
s = s.lower()
s = re.sub(r"[^\w\s-]", '', s)
s = re.sub(r"\s+", '-', s)
s = re.sub(r"-(textbf|emph|textsc|textit)", '-', s)
return s |
def reformat_params(params):
"""Translate to spreadsheet values."""
params['mechanism'] = 1 + ['NS', 'RS', 'SS'].index(params['mechanism'])
return params |
def get_quantmap(features, acc_col, quantfields):
"""Runs through proteins that are in a quanted protein table, extracts
and maps their information based on the quantfields list input.
Map is a dict with protein_accessions as keys."""
qmap = {}
for feature in features:
feat_acc = feature.pop... |
def entity_merge(entities):
"""Merge entities."""
entity_index = {}
for obj in entities:
entity = obj['entity']
data = obj['data']
if entity not in entity_index:
entity_index[entity] = {'entity': entity, 'data': []}
entity_index[entity]['data'] += data
if ... |
def disabled_due_to_debug(opbeat_config, debug):
"""
Compares module and app configs to determine whether to log to Opbeat
:param opbeat_config: Dictionary containing module config
:param debug: Boolean denoting app DEBUG state
:return: Boolean True if logging is disabled
"""
return debug an... |
def unique_key(key,
current_keys,
update_keys = False):
"""Returns a unique key given a list of current keys.
If the key exists in current_keys then a new key with _1, _2, ..., etc
appended will be returned, otherwise the key will be returned as passed.
Args:
key: desired key... |
def lsp_create_json(src, dst, name_of_lsp , pcc, debug):
""" build a json structure to create LSPs """
lsp_dict = {}
lsp_dict.update({"input":{}})
lsp_dict["input"].update({"node":pcc,
"name": name_of_lsp,
"network-topology-ref":'/network-topolog... |
def get_style(count, passed):
""" Determine if this directory is good based on the number of clean
files vs the number of files in total. """
if passed == count:
return ":good:"
if passed != 0:
return ":part:"
return ":none:" |
def destabilize(tensor, log_register):
"""
Incorporate log register rescaling into input tensor
"""
return tensor * 2.0**log_register |
def get_site(coord, L):
"""Get the site index from the 2-vector of coordinates."""
# 2D hardcoded
return coord[0] * L[1] + coord[1] |
def cvtBitLstToInt(bLst, base=10):
"""
bLst: int-list or str-list: [bm, bm-1, ..., b0] representing number
(bm bm-1 ... b0)base
NOTE: May use np.array to handle int/str differences
See:
https://docs.scipy.org/doc/numpy/reference/generated/numpy.fromstring.html
"""
result = 0
for ... |
def vector_op(lst, func):
"""
IMPORTANT: You should ONLY use one-line list comprehension.
Make a function that applies given function to the given list.
>>> lst = [1,2,3]
>>> vector_op(lst, square)
[1, 4, 9]
>>> lst = [1,2,3,5]
>>> vector_op(lst, lambda x: -x)
[-1, -2, -3, -5]
... |
def convert_rankine_to_kelvin(temp):
"""Convert the temperature from Rankine to Kelvin scale.
:param float temp: The temperature in degrees Rankine.
:returns: The temperature in degrees Kelvin.
:rtype: float
"""
return (temp * 5) / 9 |
def _format_warning(message, category, filename, lineno, line=None): # noqa: U100, E501
"""
Simple format for warnings issued by ProPlot. See the
`internal warning call signature \
<https://docs.python.org/3/library/warnings.html#warnings.showwarning>`__
and the `default warning source code \
<https://... |
def compare_dicts(file, src_test_dict, infer_dict):
"""
Check if a particular file
exists in the source/test dict and infer dict
If file exists, decrement the counter in
both dictionaries
Args:
file: file potentially not analyzed by infer
src_test_dict: dictionary contain... |
def stringify(plaintext):
"""
Used to convert hex integers into a string when decrypting.
:param plaintext: a hex integer number.
:return: a ascii string.
"""
if len(plaintext) % 2 == 1:
plaintext = '0' + plaintext
lst = []
end = len(plaintext) // 2
for i in range(end):
... |
def total_cost(J_content, J_style, alpha = 10, beta = 40):
"""
Computes the total cost function
Arguments:
J_content -- content cost coded above
J_style -- style cost coded above
alpha -- hyperparameter weighting the importance of the content cost
beta -- hyperparameter weighting th... |
def flatten(iter_of_iters):
"""
Flatten an iterator of iterators into a single, long iterator, exhausting
each subiterator in turn.
>>> flatten([[1, 2], [3, 4]])
[1, 2, 3, 4]
"""
retval = []
for val in iter_of_iters:
retval.extend(val)
return retval |
def getFeatures(geoJson):
"""
Return a list of all features dict
params:
geoJson -> quick-search dict response
"""
return geoJson["features"] |
def argmin(pairs):
"""
Given an iterable of pairs (key, value), return the key corresponding to the smallest value.
Raises `ValueError` on empty sequence.
>>> argmin(zip(range(20), range(20, 0, -1)))
19
"""
return min(pairs, key=lambda x: x[1])[0] |
def noam_decay(step, warmup_steps, model_size):
"""Learning rate schedule described in
https://arxiv.org/pdf/1706.03762.pdf.
"""
return (
model_size ** (-0.5) *
min(step ** (-0.5), step * warmup_steps**(-1.5))) |
def _search_entity_by_annotation(entity, key, value):
"""Helper function to that recursivly looks at subentities
Returns a serialized entity that matches the annoation key & value given or None"""
if 'annotations' in entity:
if key in entity['annotations']:
my_value = entity['annotations... |
def clean_doi(doi):
"""
Cleans doi to match expected string format.
Removes leading 'https://' and 'doi.org/' from the string
Parameters
----------
doi : str
A string containing a DOI
Returns
-------
DOI string with extraneous characters removed
"""
if doi.star... |
def get_scale_factors(bbox1:tuple, bbox2:tuple):
"""Get x and y scaling factors between 2 bounding boxes.
Args:
bbox1 (tuple): xmin1, ymin1, xmax1, ymax1
bbox2 (tuple): xmin2, ymin2, xmax2, ymax2
Returns:
tuple: (x,y) scale factor.
"""
xmin1, ymin1, xmax1, ymax1 = bbox1
... |
def conv2d_output_shape(height, width, filter_height, filter_width, out_channels, stride):
"""Calculates the output shape of Conv2d
Args:
height (int): Height of the input.
width (int): Width of the input.
filter_height (int): Height of the filter.
filter_width (int): Width ... |
def ceilpow2(n):
"""
# from pyCBC this one works... mine didnt work.
convenience function to determine a power-of-2 upper frequency limit"""
from math import frexp
signif,exponent = frexp(n)
if (signif < 0):
return 1
if (signif == 0.5):
exponent -= 1
return (1) << exponen... |
def transform_list_to_dict(thelist, thedefaults, key_to_index_map):
"""
Transform thelist into a dict with keys according to key_map and defaults
from thedefaults.
"""
return {
key: thelist[key_to_index_map[key]]
if key_to_index_map[key] is not None else thedefaults[key]
for ... |
def distro_short(distro_fname):
"""Map Long Linux Distribution Name to short name."""
if "Red Hat Enterprise Linux Server" == distro_fname:
return "rhel"
elif "CentOS" == distro_fname:
return "centos"
elif "SUSE Linux Enterprise Server" == distro_fname:
return "suse" |
def _is_mmf_footer(line):
"""Returns whether a line is a valid MMF footer."""
return line == '-----' or line == 'MMMMM' |
def first_cap(string: str):
""" """
return string[0].upper() + string[1:] |
def _adjust_error(error: str) -> str:
"""Strips the message name from errors to make them more readable."""
fields = error.split(':')
location = '.'.join(fields[0].strip().split('.')[1:])
message = ':'.join(fields[1:])
if location:
return f'{location}: {message.strip()}'
return message.s... |
def collate_fun(batch):
"""Generate a batch in list format"""
token_ids = [item[0] for item in batch]
attention_mask = [item[1] for item in batch]
token_type_ids = [item[2] for item in batch]
label_ids = [item[3] for item in batch]
split_ids = [item[4] for item in batch]
return [token_ids,... |
def R_from_r(r):
"""
Calculate reflected power R, starting with reflection amplitude r.
"""
return abs(r)**2 |
def string_to_points(s):
"""
Convert a PAGE-XML valid string to a list of (x,y) values. Valid means e.g. "0,0 1,2 3,4" for the points (0, 0),
(1, 2) and (3,4).
:param s: The points given as a string in the format as defined in PAGE-XML.
:type s: str
:return: List of points as (x,y) coordinates.... |
def maybe_copy(obj, inplace=False, **kwargs):
"""Copy an object if `inplace` flag is set to `False`. Otherwise return the object unchanged."""
return obj if inplace else obj.copy(**kwargs) |
def description(name):
"""Descriptive comment of a counter, motor or EPICS record
name: string, name of EPICS process variable or name of Python variable
"""
from os.path import splitext
desc = ""
if desc == "":
try: desc = eval(name).name
except: pass
if desc == "":
... |
def get_full_cls_name(cls):
"""With a class, get its full module and class name."""
return ".".join([cls.__module__,
cls.__name__]) |
def num_knots_curve_lsq(k, num_internal_knots):
"""
Returns the number of total knots created by curve_lsq_fixed_knots.
"""
return (k+1)*2+num_internal_knots |
def message_optional_files_in_reports(calibration_file, cross_talk_file, head_pos_file, destination):
"""Create messages regarding the presence of the optional files, which will be
later added in html reports of Apps.
Parameters
----------
calibration_file: str or None
Path to the '.dat' f... |
def sha256_to_str(obj):
"""Convert a bytearray to its lowercase hexadecimal string representation.
Args
----
obj (bytearray): bytearray representation of the string.
Returns
-------
(str): Lowercase hexadecimal string.
"""
return None if obj is None else obj.hex() |
def title(text):
"""Returns a text fragment (tuple) that will be used as a title or heading."""
return ('title', text) |
def dice_coefficient(string1, string2):
""" Returns the similarity between string1 and string1 as a number between 0.0 and 1.0,
based on the number of shared bigrams, e.g., "night" and "nacht" have one common bigram "ht".
"""
def bigrams(s):
return set(s[i:i+2] for i in range(len(s)-1))
... |
def is_math_exp(str):
"""
Check if a string is a math exprssion
"""
charset = set("0123456789abcdefx+-*/%^")
opers = set("+-*/%^")
exp = set(str.lower())
return (exp & opers != set()) and (exp - charset == set()) |
def gassmann(K0, Kin, Kfin, Kfout, phi):
"""
Use Gassmann's equation to perform fluid substitution. Use the bulk modulus
of a rock saturated with one fluid (or dry frame, Kfin=0) to preduct the
bulk modulus of a rock second with a second fluid.
:param K0: Frame mineral modulus (Gpa)
:param Kin:... |
def is_pred(pred):
""" Checks if tuple represents predicate.
Args:
pred: column and associated value
Returns:
true iff predicate represents condition
"""
return not pred[0].startswith("'") |
def get_item(dictionary, key):
"""Get a diction item value by a dict key."""
return dictionary.get(key) |
def get_subtask(cmd_action, file_dep=None):
"""Return a dictionary defining a substack for string 'cmd_action'."""
if cmd_action.startswith("poetry run "):
name = cmd_action.split(" ")[2]
else:
name = cmd_action.split(" ")[0]
task = {"name": name, "actions": [cmd_action], "task_dep": ["i... |
def drop_systematics(blocks, systematics):
"""Drop a systematic from a set of blocks.
Parameters
----------
blocks : list(str)
All TRExFitter blocks.
systematics : list(str)
Name of the systematic to drop.
Returns
-------
list(str)
Blocks without desired systema... |
def is_square(mtx):
"""
Check is matrix square
"""
for line in mtx:
if len(line) != len(mtx):
return False
return True |
def int2coord(index, size=3):
"""
Converts a scalar value back to coordinate pairs
:param index:
:param size: the width/height of a perfect square
:return:
"""
x = index // size
y = index - x*size
return dict(x=x, y=y) |
def hsl(hue, saturation, lightness):
"""
Return the string HTML representation of the color
in 'hsl(hue, lightness, saturation)' format.
:param hue: float or int
:param saturation: 0 <= float or int <= 100
:param lightness: 0 <= float or int <= 100
:return: str
"""
assert isinstanc... |
def convert_char_to_num(char):
"""Convert one-digit alphabet character to number.
:param char:
:return:
"""
base = 26 # 26 letters from A to Z
digit = 0
pos = 0
for c in reversed(char):
val = ord(c) - ord('A') + 1
pos += pow(base, digit) * val
digit += 1
ret... |
def parse_id(text):
""" Parse and return the <job>:<id> string.
Args:
text String to parse
Returns:
This node's job name, this node's id
"""
sep = text.rfind(":")
if sep < -1:
raise ValueError("Invalid ID format")
nid = int(text[sep + 1:])
if nid < 0:
raise ValueError("Expected non-negat... |
def convert_im_type(im_type: str):
"""Converts the IM type to the standard format,
will be redundant in the future"""
if im_type.startswith("SA"):
return "p" + im_type.replace("p", ".")
return im_type |
def flag_vqsr(vqsr_filter, var_type):
"""For cap and wxs, is vqsr passed?"""
if var_type == 'SNV':
return str('None' == vqsr_filter)
else:
return str(vqsr_filter in ('VQSRTrancheINDEL99.90to100.00',
'None')) |
def PNT2Tidal_Pv12(XA):
""" TaylorT2 1PN Quadrupolar Tidal Coefficient, v^12 Phasing Term.
XA = mass fraction of object """
XATo2nd = XA*XA
XATo3rd = XATo2nd*XA
return (15895)/(56)-(4595*XA)/(56) - (5715*XATo2nd)/(28)+(325*XATo3rd)/(14) |
def get_forecaster_index(pressure_coeff, ptrend_coeff, wind_dir_coeff):
"""
Forecast next n hours based on pressure, trend and wind quadrant
:param int pressure_coeff:
:param int ptrend_coeff:
:param int wind_dir_coeff:
:return: str Forecast ID on my Powerpoint
"""
forecast_index = ((pr... |
def format_cpnet_query(text: str) -> str:
"""
@param text: entity to look up
@return: remove whitespace, format
"""
return text.replace(' ', '_') |
def _nearest_bigger_power_of_two(x: int) -> int:
"""Computes the nearest power of two greater than x for padding."""
y = 2
while y < x:
y *= 2
return y |
def type_or_none(typerefs, value):
"""
Provides a helper function to check that a value is of the types passed or
None.
"""
return isinstance(value, typerefs) or value is None |
def merge(lst):
""" concatenate the lists back in order for the next step """
new_list = []
for sublist in lst:
new_list.extend(sublist)
return new_list |
def solve_system(matrix):
"""Solves system of linear equations for upper triangular matrix."""
coefficients = []
matrix.reverse() # for easy access
coefficients.append(matrix[0][-1] / matrix[0][-2]) # first is solved
for i in range(1, len(matrix)):
# sub all already known coefficients...
... |
def clamp(val, min_value, max_value):
"""clamps a value between min and max"""
n = (val - min_value) / (max_value - min_value)
return n |
def get_offset(x:int):
"""Returns an int, otherwise defaults to zero."""
return int(x) if x else 0 |
def get_instance_id_to_name_map(instance_info):
"""generate instance_id to instance_name map. If an instance has no name it will have value 'unknown'."""
instance_id_to_name = {}
for instance_id in instance_info:
instance = instance_info[instance_id]
instance_name = "unnamed"
if ... |
def check_min_sample_periods_dict(count_dict, min_sample_periods):
"""
Check if all periods listed in the dictionary contain at
least min_sample_periods examples.
"""
for key in count_dict.keys():
if count_dict[key] < min_sample_periods:
return False
return True |
def jaccard_similarity(list1, list2) -> float:
"""
For comparing how much overlap there is between two sets.
Returns a normalised 0-1 similarity score, where higher = more similar.
USAGE:
a = ['hello', 'foo', 'foo', 'tux']
b = ['blah', 'hello', 'foo']
jaccard_similarity(a, b)
... |
def map_char_to_num(char):
"""
Map an uppercase alphabet letter to an integer, e.g. A -> 1
"""
return ord(char) - 64 |
def reformat_large_tick_values(tick_val, pos):
"""
Turns large tick values (in the billions, millions and thousands) such as 4500 into 4.5K and also appropriately turns 4000 into 4K (no zero after the decimal).
"""
if tick_val >= 1000000000:
val = round(tick_val/1000000000, 1)
new_tick_f... |
def _check_histories(history1, history2):
"""Check if two histories are the same."""
if (history1.replace('\n', '').replace(' ', '') == history2.replace('\n', '').replace(' ', '')):
return True
else:
return False |
def relative_url(url_a: str, url_b: str) -> str:
"""
Compute the relative path from URL A to URL B.
Arguments:
url_a: URL A.
url_b: URL B.
Returns:
The relative URL to go from A to B.
"""
directory_url = False
if url_a[-1] == "/":
url_a = url_a.rstrip("/")
... |
def delete_middle_node(node):
"""
Implement an algorithm to delete a node in the middle (i.e., any
node but the first and last node not necessarily the exact middle) of
a singly linked list, given only access to that node.
"""
if not node:
return None
next_node = node.get_next_node()... |
def d_phi_dxy(x, y):
"""
second derivative of the orientation angle in dxdy
:param x:
:param y:
:return:
"""
return (-x**2 + y**2) / (x ** 2 + y ** 2) ** 2 |
def get_default_nncf_compression_config(h, w):
"""
This function returns the default NNCF config for this repository.
The config makes NNCF int8 quantization.
"""
nncf_config_data = {
'input_info': {
'sample_size': [1, 3, h, w]
},
'compression': [
{
... |
def traceit(frame, event, arg):
"""Print a trace line for each Python line executed or call.
This function is intended to be the callback of sys.settrace.
"""
import linecache
# if event != "line":
# return traceit
try:
lineno = frame.f_lineno
filename = frame.f_globals["... |
def clamp(val, lo=-1, hi=1):
"""Shorthand for `max(lo, min(val, hi))`. """
return max(lo, min(val, hi)) |
def filter(s):
""" Filters a plain text and makes it acceptable for docbook """
if s == None:
return ""
s = s.replace(">", ">")
s = s.replace("<", "<")
return s |
def chunks2str(chunks):
"""Takes a list of chunks: (i,j) pairs, and makes a string"""
s = ''
lastj = 0
for i, j in chunks:
if i > lastj:
s += ' '
s += '-'*(j-i)
s += '|'
lastj = j
return s |
def normalize_path(path):
"""
Return a normalized path from a `path` string.
"""
return "/" + path.strip("/") |
def QuadraticLimbDarkening(Impact, limb1, limb2):
"""Quadratic limb darkening. Kopal 1950, Harvard Col. Obs. Circ., 454, 1"""
return 1 - limb1 * (1 - Impact) - limb2 * (1 - Impact) ** 2 |
def hex_list(items):
"""
Return a string of a python-like list string, with hex numbers.
[0, 5420, 1942512] --> '[0x0, 0x152C, 0x1DA30]'
"""
return '[{}]'.format(', '.join('0x%X' % x for x in items)) |
def bell_number(n):
"""
Returns the n'th bell number
Parameters
----------
n : int
denotes the number for which bell number needs to be calculated
"""
if(n<0):
raise NotImplementedError(
"Invalid Input"
)
bell = [[0 for i in range(n+1)] for j in ... |
def ntw(n):
"""Numbers to Words (ntw)
-------------------------
Convert integers less than 100 from numeric
type to spelled-out words, as strings.
Examples
--------
>>> ntw(44)
>>> "XLIV"
Parameters
----------
n : int
1 <= int(x) <= 99
Returns
-... |
def has_divider_smaller_than(n, i):
"""
Get True if n has a divided smaller than i
:param n: number
:param i: number
:return: boolean
"""
print(n, i)
if i <= 1:
return False
else:
if n % i == 0:
return True
else:
return has_divider_smal... |
def _cal_cutoff_position(length, thickness, keyIdx):
"""Returns cutoff indices of keyIdx-centred truncated list
Args:
length: `int`, length of a list
thickness: `int`, cutoff thickness - number of slices
keyIdx: `int`, index of the key slice
Returns:
a tuple of two `int`
"""
left_block = (th... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.