content stringlengths 42 6.51k |
|---|
def get_value_using_path(obj, path):
"""Get the attribute value using the XMLpath-like path specification.
Return any attribute stored in the nested object and list hierarchy using
the 'path' where path consists of:
keys (selectors)
indexes (in case of arrays)
separated by slash, ie. "k... |
def decodeProjectionMapID(RGBAquadlet):
""" Given the RGBA quadlet from a pixel which is encoded as an ID using an "_ids" shader."""
r = RGBAquadlet[0] << 24 # Red
g = RGBAquadlet[1] << 16 # Green
b = RGBAquadlet[2] << 8 # Blue
a = RGBAquadlet[3] # Alpha
idOut = r | g | b | a
return(idOut) |
def call_or_get(func_or_str, *args):
"""
"""
if hasattr(func_or_str, '__call__'):
return func_or_str(*args)
elif isinstance(func_or_str, str):
return func_or_str
else:
raise Exception('Positional argument 1 must be a function or a str') |
def onset_to_seconds(onset, upbeat_onset, bpm):
"""Converts the given onset to its respective time in seconds.
Parameters
----------
onset : float
Given onset to be converted.
upbeat_onset : float
Number of upbeat onsets (time offset to be added).
bpm : float
Beats per m... |
def convert2numeral(item, cls=int, default=None):
"""
Convert an argument to a new type unless it is `None`.
"""
try:
num = cls(item)
except (ValueError, TypeError):
num = default
return num |
def unionIntervals(intervals):
"""
unionIntervals(intervals)
Return a list of union interval(s) of the input intervals, e.g.,
given [[1,2], [4,6], [5,8]] will result in [[1,2], [4,8]].
PARAMETERS
intervals: list or sequence-like
list of lists/tuples defining the intervals, e.g., [[0,1], [5,... |
def win_path_dirname(path: str) -> str:
"""Retrieve only the directory part of a Windows file path"""
dirname = '\\'.join(path.rstrip('\\').split('\\')[:-1])
return 'c:\\' if dirname == 'c:' else dirname |
def time_to_min(t):
"""t: string in %H:%M:%S"""
h, m, s = tuple(map(int, t.split(":")))
minutes = h * 60 + m
return minutes |
def convert_to(value: str, cls):
"""
Attempt to convert a value to a specified type
:param value: string to convert from
:param cls: class to convert to
:return: converted value or ``None``
"""
try:
return cls(value)
except (ValueError, TypeError):
return None |
def get_centroid(moments):
"""
Computer centroid given the image/blob moments
"""
if moments['m00'] > 0:
centroid_x = moments['m10']/moments['m00']
centroid_y = moments['m01']/moments['m00']
else:
centroid_x = 0.0
centroid_y = 0.0
return centroid_x, centroid_y |
def add(value, arg):
"""Add the arg to the value."""
try:
return int(value) + int(arg)
except (ValueError, TypeError):
try:
return value + arg
except Exception: # noqa
return '' |
def eq_5_dimensionless_hrr(
Q_dot_kW: float,
rho_0: float,
c_p_0_kJ_kg_K: float,
T_0: float,
g: float,
D: float,
) -> float:
"""Equation 5 in Section 8.3.2.2 PD 7974-1:2019 calculates dimensionless for rectangular fire source.
:param Q_dot_kW: in kW, fire heat re... |
def velocity_from_doppler_shift(c, f1, f2):
"""
Calculate velocity based on measured frequency shifts due to Doppler shift.
The assumption is made that the velocity is constant between the observation times.
.. math:: v = c \cdot \\left( \\frac{f_2 - f_1}{f_2 + f_1} \\right)
:param c:... |
def int2(c):
""" Parse a string as a binary number """
return int(c, 2) |
def combine_as_max(vector1, vector2):
"""
Combine two vectors and return a vector that has the maximum values from each vector compared pairwise.
:param vector1: First list to compare
:param vector2: Second list to compare
:return: a list containing the max of each element of vector1 and vector2 co... |
def hash_equal(a, b):
"""
Returns `True` if a and b represent the same commit hash.
"""
min_len = min(len(a), len(b))
return a.lower()[:min_len] == b.lower()[:min_len] |
def minhash_containment(s, t):
"""
Calculate the MinHash estimate of the Jaccard Containment.
Parameters
----------
s, t : iterable of int
Set signatures, as returned by `signature`.
n : int
The length of signature.
Returns
-------
float
"""
return len(s & t... |
def load_parallel_state_dict(state_dict):
"""Remove the module.xxx in the keys for models trained
using data_parallel.
Returns:
new_state_dict
"""
from collections import OrderedDict
new_state_dict = OrderedDict()
for k, v in state_dict.items():
name = k[7:]
new_... |
def apply_structure(structure, fn, max_depth=2, current_depth=0):
"""Apply fn onto a structure and return the transformed structure
Args:
structure: list, dict, singleton
fn: a transformation function
"""
# don't do anything beyond certain level
if current_depth == max_depth:
... |
def _fixup_packet(entry):
"""Change PACKET to refer to the message type instead"""
if entry['record_type'] == 'PACKET':
entry['record_type'] = entry['c']
return entry |
def sort_nodes(nodes):
"""Calling sorted(nodes) will fail because nodes may contain
numbers, and we can't compre ints to strings. So always use
this method instead of calling sorted(nodes)."""
return sorted(nodes, key=lambda n: str(n)) |
def eda_attribut_string(attribut_bin):
# pylint: disable=W0105
""" Converts binary attribute field to a padded number """
""" Note: This field is not well defined.
The field only supports
bit 0 == 1, hidden
bit 0 == 0, visible
"""
return str(int(str(attr... |
def get_original_constructor_name(object_name: str) -> str:
"""Generate name for original constructor
For each custom constructor, we move the original constructor to a consistent location relative to
the original constructor so that each custom constructor automatically knows where to find the original
... |
def joint_stracks(t_list_a, t_list_b):
"""
join two track lists
:param t_list_a:
:param t_list_b:
:return:
"""
exists = {}
res = []
for t in t_list_a:
exists[t.track_id] = 1
res.append(t)
for t in t_list_b:
tid = t.track_id
if not exists.get(tid, 0... |
def setitem(index, thing, value):
"""
SETITEM index array value
command. Replaces the ``index``th member of ``array`` with the new
``value``. Ensures that the resulting array is not circular, i.e.,
``value`` may not be a list or array that contains ``array``.
"""
if isinstance(thing, dict... |
def camel(s):
"""Convert string to CamelCase."""
return ''.join(x[0].upper() + x[1:].lower() for x in s.split()) |
def convert_to_unicode(text):
"""
Converts `text` to Unicode (if it's not already), assuming utf-8 input.
Args:
text (str|bytes): Text to be converted to unicode.
Returns:
str: converted text.
"""
if isinstance(text, str):
return text
elif isinstance(text, bytes):
... |
def fib(n):
"""Compute the nth Fibonacci number"""
pred, curr = 0, 1
k = 1
while k < n:
pred, curr = curr, curr + pred
k += 1
return curr |
def nan2zero(data):
""" Replace NaNs and negative values by zeros
"""
return [val if val>0 else 0 for val in data] |
def model_name_to_rest(name):
"""Gets a name of a :mod:`atomx.models` and transforms it in the
resource name for the atomx api.
E.g.::
>>> assert model_name_to_rest('ConversionPixels') == 'conversion-pixels'
>>> assert model_name_to_rest('OperatingSystem') == 'operating-system'
>>> ... |
def keep_selected_labels(img_files, labels, occ_coords, conf):
"""Filters image files and labels to only retain those that are selected. Useful when one doesn't
want all objects to be used for synthesis
Args:
img_files(list): List of images in the root directory
labels(list): List of lab... |
def which(program):
"""Given an executable file name, search for in in the PATH and
return the location of the executable.
:param program: name of the executable to search for
"""
import os
def is_exe(f_path):
return os.path.isfile(f_path) and os.access(f_path, os.X_OK)
fpath, fna... |
def escape_attr(s):
"""Escape attributes ':' and '.' since it's not supported by jQuery
"""
return s.replace(':', '\\:').replace('.', '\\.') |
def _check_startyear(cfgs):
"""
Check to see that at most one startyear is defined in the config
Returns
-------
int
startyear
Raises
------
ValueError
if more that one startyear is defined
"""
first_startyear = cfgs[0].pop("startyear", 1750)
if len(cfgs) > 1... |
def _swap_ending(s, ending, delim="_"):
"""
Replace the ending of a string, delimited into an arbitrary
number of chunks by `delim`, with the ending provided
Parameters
----------
s : string
string to replace endings
ending : string
string used to ... |
def is_mobile_number(number):
"""
Mobile numbers have no parentheses, but have a space in the middle
of the number to help readability. The prefix of a mobile number
is its first four digits, and they always start with 7, 8 or 9.
"""
return number[0] in ['7', '8', '9'] |
def code_gen(blocks):
"""
From a list of L{CodeBlock} instances, returns a string
that executes them all in sequence.
Eg for C{(decl1, task1,
cleanup1)} and C{(decl2, task2, cleanup2)} the returned string
will be of the form:
decl1
decl2
{
task1
{
... |
def update(checklist):
"""[summary]
prevent users from excluding both adults and children
Parameters
----------
checklist : list
takes the input "include-checklist" from the callback
Returns
-------
"Include in UBI" checklist with correct options
"""
if "adults" not in c... |
def validation_file_name(test_name):
"""Std name for a result snapshot."""
return test_name + '.snapshot~' |
def process_health(health: int) -> str:
"""Process health index and return string for display."""
if health == 0:
return "Healthy"
if health == 1:
return "Fine"
if health == 2:
return "Fair"
if health == 3:
return "Poor"
return "Unhealthy" |
def Q(x, i, s):
"""
:param list x: A random list of positive and negative integers.
:param int i: A given index.
:param int s: The chosen S value, oftentimes zero.
:return bool: Given a list X, returns a boolean value if there is a nonempty subset of X_1,...,X_i which sums to S.
"""
if i == ... |
def _split_key(key):
"""Helper: Splits CSS key into selector and list of available pseudo-classes."""
pair = key.split(':')
if len(pair) == 1:
return (pair[0], [])
return tuple(pair) |
def function(a,b):
"""This function is use to make average of two numbers"""
c = (a+b)/2 # to make new function use def
return c |
def is_integer(variable, ignore_empty_case=False):
"""
Validates if variable is an integer.
:param variable: some input
:param ignore_empty_case:
:rtype: boolean
"""
if variable is None:
return False
if ignore_empty_case and len(str(variable)) == 0:
return True
try:
... |
def find_input(binary_input: list,features):
"""
This functions converts binary inputs to features for eval function
Attributes
----------
binary_input :list
length for the mask
Returns
-------
:list
return gray mask
... |
def pruneScope(target_scope, our_scope):
"""pruneScope(list A, list B) -> list
Given two lists of strings (scoped names), return a copy of list A
with any prefix it shares with B removed.
e.g. pruneScope(['A', 'B', 'C', 'D'], ['A', 'B', 'D']) -> ['C', 'D']"""
if not our_scope:
return target_scope
... |
def page_not_found(e):
"""Return a custom 404 error."""
return 'Sorry, nothing exists at this URL.', 404 |
def get_source_location_by_offset(source, offset):
"""Retrieve the Solidity source code location based on the source map offset.
:param source: The Solidity source to analyze
:param offset: The source map's offset
:return: The line number
"""
return source.encode("utf-8")[0:offset].count("\n".... |
def atmost(a,val,c):
"""
atmost(a,val,c)
Ensure that the number of occurrences of val in a is atmost c.
"""
return [sum([a[i] == val for i in range(len(a))]) <= c] |
def my_add(argument1, argument2):
"""
Describe here what this function does,
its input parameters, and what it returns.
In this example the function adds the two input
arguments.
"""
result = argument1 + argument2
return result |
def parse_song_title(song_title, artist_name=None):
"""Split a song title to retrieve the artist name and song name.
Additional argument can be added to better retrieve these names.
Args:
song_title (string): song header (or title for the ``<a>`` element)
artist_name (string, optional): nam... |
def names_in_dict_like_options(dopts):
"""
Return variable names in `dopts`.
>>> names_in_dict_like_options([('a[k]', 'b'), ('c[k]', 'd')])
['a', 'c']
"""
return [k.split('[', 1)[0] for (k, v) in dopts] |
def flatten(l, ltypes=(list, tuple)):
"""
Flatten list of lists
Parameters
----------
l: list to flatten
ltypes: tuple of types
Returns
-------
flattened list
"""
ltype = type(l)
l = list(l)
i = 0
while i < len(l):
while isinstance(l[i], ltypes):
... |
def clean_and_format(text):
"""
Strips punctuation and makes sure all text is presented in
unicode form, with no newlines or multiple spaces
:param text: the original text, in ascii or unicode
:return: unicode formatted text
"""
# ensure no '\n' s in text
lines = text.splitlines()
t... |
def jump(_word_list):
"""
Jumping action stub - causes no change to game state
Args:
_word_list (list): variable-length list of string arguments
Returns:
str: output for REPL confirming player jumped
"""
response = 'You have jumped, just not sure why.'
return response |
def is_etree_document(obj: object) -> bool:
"""A checker for valid ElementTree objects."""
return hasattr(obj, 'getroot') and hasattr(obj, 'parse') and hasattr(obj, 'iter') |
def __read_csv_2(csvdata):
"""Load data from CSV file without headers, that the first column is for PV, like:
PV,machine=xxx,elemIndex=xxx,elemPosition=xxx,elemName=xxx,elemHandle=xxx,elemField=xxx,elemType=xxx, tag1,tag2,tag3
the last one are all tags.
Parameters
----------
csvdata : list
... |
def starts_or_ends_with(s, w):
"""Returns ``True`` if string `s` starts or ends with string `w`, case
insensitively."""
lower = s.split('/')[-1].lower()
return lower.startswith(w) or lower.endswith(w) |
def capitalise(input_string: str) -> str:
"""Convert the first character of the string to uppercase."""
return input_string[0].upper() + input_string[1:] |
def make_ticks_int(tick_list):
"""
Converts axis ticks to integers.
:param tick_list: Iterable of the axis ticks to be converted. Should be sortend in the order they shall be put on \
the axis.
:return:
"""
return [int(tick) for tick in tick_list] |
def convert_to_unicode(text):
"""Converts `text` to Unicode (if it's not already), assuming utf-8 input. From https://github.com/google-research/bert"""
if isinstance(text, str):
return text
# elif isinstance(text, bytes):
# return text.decode("utf-8", "ignore")
else:
raise ValueError(... |
def timeline_postprocessing(timeline):
""" Eliminates Nones in timeline so other software don't error.
Extra lists are built for the vars with nones, each list with one point
for each None in the form (wall_time, prev_value).
"""
current_time_nones = []
audio_time_nones = []
old_curr... |
def epc_developer_profit_discount(hybrid_plant_size_MW, technology_size_MW):
"""
profit is 5% of total cost (before management cost) at 100 MW. And 8 % of TIC at 5
MW.
https://www.nrel.gov/docs/fy19osti/72399.pdf
"""
if technology_size_MW == 0:
profit_discount_multiplier = 0
else:
... |
def extract_keywords(lst_dict, kw):
"""Extract the value associated to a specific keyword in a list of dictionaries. Returns the list of values extracted from the keywords.
Parameters
----------
lst_dict : python list of dictionaries
list to extract keywords from
kw : string
... |
def detect_label_column(column_names):
""" Detect the label column - which we display as the label for a joined column.
If a table has two columns, one of which is ID, then label_column is the other one.
"""
if (column_names and len(column_names) == 2 and "id" in column_names):
return [c fo... |
def pretty_num(n):
"""Converts a number to a nicely formatted string.
>>> pretty_num(6874)
'6,874'
>>> pretty_num(-6874)
'-6,874'
"""
return "{:,}".format(n) |
def check_troposphere(altitude: float=0.0) -> bool:
""" This function checks if the input altitude is in the Troposphere."""
if -610.0 <= altitude <= 11000.0:
return True
else:
return False |
def find_event_producer(tenant, producer_id=None, producer_name=None):
"""
searches the given tenant for a producer matching either the id or name
"""
if producer_id:
producer_id = int(producer_id)
for producer in tenant.event_producers:
if producer_id == producer.get_id():
... |
def xor_cipher_genkey(key, length=None):
"""Generates a byte array for use in XOR cipher encrypt and decrypt
routines. In Python 2 either a byte string or Unicode string can be
provided for the key. In Python 3, it must be a Unicode string. In
either case, characters in the string must be within the ASC... |
def resolveDottedAttribute(obj, attr, allowDotted):
"""
Resolves a dotted attribute name to an object. Raises
an AttributeError if any attribute in the chain starts with a '``_``'.
If the optional allowDotted argument is false, dots are not
supported and this function operates similar to ``getattr(... |
def reflect(num, width):
"""Reverts bit order of the given number
Args:
num (int): Number that should be reflected
width (int): Size of the number in bits
"""
reflected = 0
for i in range(width):
if (num >> i) & 1 != 0:
reflected |= 1 << (width - 1 - i)
ret... |
def caesar(c, x):
"""
:type c: str
:type x: int
:rtype: str
"""
ic = ord(c)
if not 97 <= ic <= 122 and not 65 <= ic <= 90:
return c
if 97 <= ic <= 122 and 97 <= ic + x % 26 <= 122:
return chr(ic + x % 26)
elif 65 <= ic <= 122 and 65 <= ic + x % 26 <= 90:
ret... |
def unitSpacing2MM(unit):
""" Converts KLE unit spacing into wxPoint spacing. Used in placing KiCAD components """
unitSpacing = 19.050000
wxConversionFactor = 1000000
return unit*unitSpacing |
def getListAsStr(lst, sep=',', fmt='%s'):
"""Returns a list of values as a string using the given separator and formatter"""
return sep.join([fmt % (x,) for x in lst]) |
def extract_tail_partial_sequence(partial_sequence_string, tail_length):
"""Extracts the tail of a partial sequence.
If the specified tail length is larger than the partial sequence length, get
the entire partial sequence. For example, when partial_sequence_string is
'1_6' and tail_length is 4, it should give ... |
def stringify_stoichiometry(stoichiometry, inihibitors = None):
"""
Stoichiometry looks like [-2, -1, 3]
This is not nice as a suffix for a class name
We transform it to _m2_m1_3
:param stoichiometry:
:type stoichiometry: list(float)
:return: suffix
"""
suffix = '_'.join([str(x) for... |
def not_in_range(val, limits):
"""False if val is outside of limits."""
return val < limits[0] or val > limits[1] |
def ix_to_char(chars):
"""
Make a dictionary that maps an index to a character
Arguments:
chars -- list of character set
Returns:
dictionary that maps an index to a character
"""
return {i: ch for i, ch in enumerate(chars)} |
def empty_text(_str):
"""Returns true if null string"""
return not _str.strip() |
def find_range(index, window, max):
""" find the left and right endpoints of a window in an array
:param index: index window is to be centered at
:param window: the length of the window
:param max: the size of the array
:return: left and right endpoints of the window
"""
half_window = int(w... |
def update_show_clade_defining(switches_value):
"""Update ``show_clade_defining`` variable in dcc.Store.
This should be set to True when the clade defining mutations switch
is switched on, and False when it is turned off. It is None at
application launch.
:param switches_value: ``[1]`` if the clad... |
def validate_and_clean_float(param, value, valmin=None, valmax=None):
"""
Validates that a clinical parameter are within an allowed value range
:param param: Clinical parameter
:param value: value of the parameter
:param valmin: lowest allowed value of this parameter
:par... |
def extract_ecp_nwchem(data):
"""Extract the effective core potential basis data from a text region
passed in as data.
@param data: text region containing ECP data
@type data : str
@return: per-element effective core potential chunks
@rtype : list
"""
ecp_begin_mark = "ECP\n"
ecp_e... |
def get_x_ii(y):
"""
returns x -4y = 8 solved x
i.e. x = 8 + 4y
"""
return 8 + 4*y |
def get_account_username_split(username):
"""
Accepts the username for an unlinked InstitutionAccount
and return a tuple containing the following:
0: Account Type (e.g. 'cas')
1: Institution Slug
2: User ID for the institution
"""
username_split = username.split("-")
if len(use... |
def rating(pages):
"""Net rating."""
return sum(p.rating for p in pages) |
def format_value(value, binary=False, div=None, factor=None, prec=2, unit=True, to_str=False):
"""Return formatted value."""
if value is None:
return None
if not hasattr(value, '__truediv__'):
return value
units = ['', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y']
div = (1024. if binary el... |
def add_break_line(settings = {'symbol':'=', 'len':64}):
"""create a line used in comments
Parameters
----------
settings: dict
Returns
-------
string
"""
return '#' + settings['symbol'] * settings['len'] + '\n' |
def pluralize(count, singular, plural='%ss'):
"""Pluralizes a number.
>>> pluralize(22, 'goose', 'geese')
'22 geese'
If a list or set is given its length is used for the count.
Notice the plural is not needed in the simple append-an-s case.
>>> pluralize([1,2,3], 'bird')
'3 birds'
If... |
def CrossProduct3D(a,b):
"""Forms the 3 dimentional vector cross product of sequences a and b
a is crossed onto b
cartesian coordinates
returns a 3 tuple
"""
cx = a[1] * b[2] - b[1] * a[2]
cy = a[2] * b[0] - b[2] * a[0]
cz = a[0] * b[1] - b[0] * a[1]
return (cx,cy,cz) |
def loadPickle(filename):
"""Load and return data contained in a pickle file or json file, possibly bz2 compressed"""
try:
if filename.endswith('.bz2'):
f=BZ2File(filename,mode='r')
else:
f = open(filename,'r')
if filename.find('json')>=0:
data... |
def reliability_calc(RACC, ACC):
"""
Calculate reliability.
:param RACC: random accuracy
:type RACC : float
:param ACC: accuracy
:type ACC : float
:return: reliability as float
"""
try:
result = (ACC - RACC) / (1 - RACC)
return result
except Exception:
re... |
def new_scores(dim):
"""
Generates a new scores board
"""
scores = []
row = 0
while (row < dim):
temp = []
col = 0
while (col < dim):
temp.append(0)
col += 1
scores.append(temp)
row += 1
return scores |
def order_metadata(metadata: list) -> list:
"""Orders 2-element metadata according to measurementDate."""
key = "measurementDate"
if len(metadata) == 2 and metadata[0][key] > metadata[1][key]:
metadata.reverse()
return metadata |
def _map_outputs(predictions):
"""
Map model outputs to classes.
:param predictions: model ouptut batch
:return:
"""
labels = [
"admiration",
"amusement",
"anger",
"annoyance",
"approval",
"caring",
"confusion",
"curiosity",
... |
def nsamp_init(nsamp_par, ntaudof):
""" determine nsamp for given species"""
if nsamp_par[0]:
nsamp = min(nsamp_par[1] + nsamp_par[2] * nsamp_par[3]**ntaudof,
nsamp_par[4])
# print('Setting nsamp using formula: min(A+B*C**n')
else:
nsamp = nsamp_par[5]
return ... |
def generate_system_redaction_list_entry(newValue):
"""Create an entry for the redaction list for a redaction performed by the system."""
return {
'value': newValue,
'reason': 'System Redacted',
} |
def _is_variable(expr: str) -> bool:
"""
>>> _is_variable("foo")
False
>>> _is_variable("@foo")
True
>>> _is_variable("@foo bar")
True
>>> _is_variable("@foo bar.foo.bar")
True
"""
return expr.startswith("@") |
def box(text: str, lang=""):
"""Return text in a markdown block"""
return f"```{lang}\n{text}```" |
def group_by_lines(units):
"""Return a dictionary of lists of units grouped by line."""
groups = {i.line: [] for i in units}
for i in units: groups[i.line].append(i)
return groups |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.