content stringlengths 42 6.51k |
|---|
def add_tag(tag, filename):
"""
modifies a filename adding a tag in the extension:
filename.ext -> filename.tag.ext
(if the filename has no ".", an extension (.tag) is added)
:param tag: rag to be added
:param filename: original filename
"""
pos = filename.find(".")
if pos == -1:
... |
def mask_by( var, maskvar, lo=None, hi=None ):
"""masks a variable var to be missing except where maskvar>=lo and maskvar<=hi. That is,
the missing-data mask is True where maskvar<lo or maskvar>hi or where it was True on input.
For lo and hi, None means to omit the constrint, i.e. lo=-infinity or hi=infini... |
def split_tokenize(text):
"""Splits tokens based on whitespace after adding whitespace around
punctuation.
"""
return (text.lower().replace('.', ' . ').replace('. . .', '...')
.replace(',', ' , ').replace(';', ' ; ').replace(':', ' : ')
.replace('!', ' ! ').replace('?', ' ? ')
.spl... |
def ortho(subj_coord, obj_coord, subj_dim, obj_dim):
""" It returns a tuple of 3 values: new dim for combined array,
component of subj_origin in it, component of obj_origin in it. """
if subj_coord > obj_coord:
return (subj_coord + (obj_dim - obj_coord), 0,
subj_coord - obj_coord)
... |
def as_cloud_front_headers(headers):
"""Convert a series of headers to CloudFront compliant ones.
Args:
headers (Dict[str, str]): The request/response headers in
dictionary format.
"""
res = {}
for key, value in headers.items():
res[key.lower()] = [{"key": key, "value"... |
def _ispath(string):
"""Check if a string is a directory."""
if string.startswith('$') or string.startswith('/'):
return True
else:
return False |
def get_patterns_per_repository(repo):
"""
Get all unique patterns in the repository.
Keyword arguments:
repo -- object containing properties of the repo
"""
dynamic_count = 0
if 'DYNAMIC-PATTERN' in repo['uniquePatterns']:
dynamic_count += repo['uniquePatterns']['DYNAMIC-PATTERN'... |
def get_value(obj, key, default=None):
"""
Mimic JavaScript Object/Array behavior by allowing access to nonexistent
indexes.
"""
if isinstance(obj, dict):
return obj.get(key, default)
elif isinstance(obj, list):
try:
return obj[key]
except IndexError:
... |
def sorted_edges(element, argyris=True):
"""
Return the edges (as sorted (start, end) tuples) of a given element.
Required Arguments
------------------
* element : array-like container of the nodes comprising a finite element.
Assumed to be in GMSH or Argyris order.
Optional Ar... |
def mergeIf(dict1, dict2):
"""Returns the merge of dict1 and dict2 but prioritizing dict1's items"""
return {**dict2, **dict1} |
def get_seq_next_residue(seq, idx, size):
"""Get the next residue after the chunk."""
return seq[idx + size: idx + size + 1] |
def countFrequency(fname):
"""
get the frequency of each byte
"""
nodeDic = {}
if isinstance(fname, list):#work for stdin/stdout part
for e in fname:
if e in nodeDic.keys():
nodeDic[e] += 1
else:
nodeDic[e] = 1
return sorted(nod... |
def ERR_FILEERROR(sender, receipient, message):
""" Error Code 424 """
return "ERROR from <" + sender + ">: " + message |
def compare_list_of_committees(list1, list2):
"""Check whether two lists of committees are equal when the order (and multiplicities)
in these lists are ignored.
To be precise, two lists are equal if every committee in list1 is contained in list2 and
vice versa.
Committees are, as usual, sets of posi... |
def check_new(database: list, url_dict: dict) -> list:
"""
Function that filters list of all URLs to only URLs not present in current database
@param database: a list of all craigslist post ids currently in text database
@param url_dict: a dict of URLs to be checked against URLs already scraped, ge... |
def beautifyDescription(description):
""" Converts docstring of a function to a test description
by removing excess whitespace and joining the answer on one
line """
lines = (line.strip() for line in description.split('\n'))
return " ".join(filter(lambda x: x, lines)) |
def apply_eqn(eqn, x):
"""
Applies a line equation in the form returned by get_eqn().
"""
return eqn[0] * x + eqn[1] |
def link(item:dict):
"""
input: item:dict ={"content":str,"link":str}
"""
return f"[{item['content']}]({item['link']['url']})" |
def dict_filter(
kwargs,
filters,
defaults=None,
copy=False,
short=False,
keep=False,
**kwadd,
):
"""Filter out kwargs (typically extra calling keywords)
Parameters
----------
kwargs:
Dictionnary to filter.
filters:
Single or list of prefixes.
default... |
def parse_schedule_with_breaks(schedule_data):
"""Parse schedule_data.
Return list of tuples having delay in deparing to the first bus in list
and bus number. Bus number represents as welll time between bus
departures."""
return [
(delay_in_departing, int(bus))
for delay_in_departin... |
def predict_next_element(lis, base_case, reduce_function, inference_function):
"""
:param lis: the list to predict the next element of
:param base_case: each iteration would be given the current list. if it returns None we continue the recursion,
otherwise we assume that the returned value is the base ... |
def remove_duplicates_with_order(lst):
""" Remove all duplicates of a list while not reordering the list.
"""
if isinstance(lst, list):
lst = list(n for i, n in enumerate(lst) if n not in lst[:i])
if isinstance(lst, tuple):
lst = tuple(n for i, n in enumerate(lst) if n not in lst[:i])
... |
def instantiate_schema(values, rule):
"""
evaluates rule by substituting values into rule and evaluating the resulting literal.
This is currently insecure
* "For security the ast.literal_eval() method should be used."
"""
r = rule
for k in values.keys():
r = r.replace(k, values[k... |
def note_favorite(note):
"""
get the status of the note as a favorite
returns True if the note is marked as a favorite
False otherwise
"""
if 'favorite' in note:
return note['favorite']
return False |
def decode_MAC(MAC_address):
"""
Returns a long int for a MAC address
@param MAC_address : like "00:12:34:56:78:9a"
@type MAC_address : str of colon separated hexadecimal ints
@return: long int
"""
parts = MAC_address.split(':')
if len(parts) == 6:
value = 0
for i in range(6):
shift = 8... |
def _llvm_get_formatted_target_list(repository_ctx, targets):
"""Returns a list of formatted 'targets': a comma separated list of targets
ready to insert in a template.
Args:
repository_ctx: the repository_ctx object.
targets: a list of supported targets.
Returns:
A formatted... |
def hess_binary(n, oracle, fast=False, cycles=1, target=0, seq=None):
"""
HESS Algorithm is a Universal Black Box Optimizer (binary version).
:param n: The size of bit vector.
:param oracle: The oracle, this output a number and input a bit vector.
:param fast: More fast some times less accuracy.
... |
def persistence(num: int) -> int:
"""
returns the persistence of a number\
:param num: the number to check
:param num: the number to calculate the persistence of
Example:
>>> persistence(1234)
>>> 2
"""
string_num = str(num)
count: int = 0
while len(string_num) > 1:... |
def _UTMLetterDesignator(Lat):
"""This routine determines the correct UTM letter designator for the given latitude
returns 'Z' if latitude is outside the UTM limits of 84N to 80S
Written by Chuck Gantz- chuck.gantz@globalstar.com"""
if 84 >= Lat >= 72: return 'X'
elif 72 > Lat >= 64: return 'W'
elif 64 > Lat >= ... |
def _handleResponse(results, assure_address=True):
"""Process the results from a Google Maps API callself.
Heuristically (by visual inspection), approximate addresses tend to resolve
better to buildings than geographic centers. So if we are willing to relax
address constraints, then filter on that typ... |
def full_method(apple, pear, banana=9, *args, **kwargs):
""" methody docstring """
return (apple, pear, banana, args, kwargs) |
def product_and_sum(a, b):
"""Return product and sum tuple of two numbers."""
return (a * b, a + b) |
def map_cap_to_opnames(instructions):
"""Maps capabilities to instructions enabled by those capabilities
Arguments:
- instructions: a list containing a subset of SPIR-V instructions' grammar
Returns:
- A map with keys representing capabilities and values of lists of
instructions enabled by the corres... |
def php_array_search(_needle, _haystack, _strict=False):
"""
>>> array = Array({0: 'blue', 1: 'red', 2: 'green', 3: 'red'})
>>> php_array_search('green', array)
2
>>> php_array_search('red', array)
1
>>> php_array_search('purple', array)
False
"""
if not _needle in _haystack.valu... |
def expandInSubstr(t,args={}):
""" expand all occurences of a macro bounded by %item% with a value from the dict passed via args """
x = 0
while (x > -1):
x = t.find('%')
if (x > -1):
y = t[x+1:].find('%')
if (y > -1):
xx = t[x+1:x+y+1]
... |
def add_with_saturation(a:int, b:int, *, high_water_mark:int=256):
"""Addition with a maximum threshold
Parameters
----------
a:int
b:int
number to add together
high_water_mark:int[default to 256]
Maximum value returned by the addition
Returns
-------
Sum of ... |
def snake_to_camel(name: str) -> str:
"""Converts a snake case string to a camelcase string."""
return ''.join(name.title().split('_')) |
def wave_array(arr):
"""
Given an array of integers, sort the array into a wave like array and
return it, In other words, arrange the elements into a sequence such
that a[0] >= a[1] <= a[2] >= a[3] <= a[4]
"""
for i in range(0, len(arr), 2):
# if current even element is smaller than pre... |
def emd_function_value(pixel_group, base):
"""Calculate and return the f value of the given pixel group
f value is defined as a weighted sum of the pixel values
modulo a chosen base"""
f_value = 0
for i in range(len(pixel_group)):
f_value = (f_value + pixel_group[i] * (i + 1)) % base
return f_value |
def find_column_types(orig_metadata, synth_method, categorical_types):
"""
This method creates a list of categorical columns (defined by user)
and a list of numerical columns, using types included in the
.json metadata.
"""
categorical_features = []
numeric_features = []
for col in orig_... |
def stringify_datetime_types(data: dict):
"""Stringify date, and datetime, types."""
for key in ("date", "timestamp"):
if key in data:
data[key] = data[key].isoformat()
return data |
def make_a_list_from_uncommon_items(list1, list2):
"""
Make a list from uncommon items between two lists.
:param list1: list
:param list2: list
:return: list
"""
try:
if len(list1) - len(list2) >= 0:
return list(set(list1) - set(list2))
return list(set(list2) - ... |
def parse_request_parameters(filter_args):
"""Generates a dict with params received from client"""
session_args = {}
for key, value in filter_args.items():
if key != "limit" and key != "next":
session_args[key] = set(value.replace(" ", "").split(","))
return session_args |
def convert_direction_to_north_or_west(distance_moved, direction):
"""Convert East and South direction to North and East."""
if direction in ["S", "E"]:
if direction == "S":
distance_moved = distance_moved * -1
direction = "N"
elif direction == "E":
dis... |
def check(line, queries):
"""
check that at least one of
queries is in list, l
"""
line = line.strip()
spLine = line.replace('.', ' ').split()
matches = set(spLine).intersection(queries)
if len(matches) > 0:
return matches, line.split('\t')
return matches, False |
def karatsuba(x: int, y: int) -> int:
"""Multiply two numbers using the Karatsuba algorithm
Args:
x (int): the first integer to be multiplied
y (int): the second integer to be multiplied
Returns:
int: the result of the multiplication
"""
# Break the recursion written below... |
def lss(inlist):
"""
Squares each value in the passed list, adds up these squares and
returns the result.
Usage: lss(inlist)
"""
ss = 0
for item in inlist:
ss = ss + item*item
return ss |
def get_milliseconds(time_sec: float) -> int:
"""
Convertit un temps en secondes sous forme de float en millisecondes
sous forme d'un int.
Args:
time_sec: Le temps en secondes.
Returns:
Le temps en millisecondes.
"""
assert isinstance(time_sec, float)
... |
def is_ecalendar_crse(course_code):
"""Checks whether a given crse code matches the eCalendar crse format, code-900 (ccc-xxx or ccc-xxxcx)
Rules:
at least 7 char in length
two sections separated by '-'
first section is letters
second is alphanumeric, first 3 are numbers
"""
code = str(co... |
def safe_divide_list(x_list, y_list):
"""
Divides x_list by y_list. Returns list of division results, where a divide by zero results in a zero.
:param x_list: list of value's
:param y_list: list of value,s
:return: list of x value's divided by y value's. results in 0 value when y is zero.
... |
def onehot_encode(position: int, count: int) -> list:
"""One-hot encode position
Args:
position (int): Which entry to set to 1
count (int): Max number of entries.
Returns:
list: list with zeroes and 1 in <position>
"""
t = [0] * (count)
t[position - 1] = 1
return t |
def is_complete(board):
"""
Given a bingo board as a 2D array of integers,
return if it is now complete
"""
rows = board
for row in rows:
if all(cell < 0 for cell in row):
return True # We have a row which has all numbers marked
width = len(rows[0])
for i in range(w... |
def selection_sort(alist):
"""
Sorts a list using the selection sort algorithm.
alist - The unsorted list.
Examples
selection_sort([4,7,8,3,2,9,1])
# => [1,2,3,4,7,8,9]
a selection sort looks for the smallest value as it makes a pass and,
after completing the pass, places it in ... |
def get_tuple_version(hexversion):
"""Get a tuple from a compact version in hex."""
h = hexversion
return(h & 0xff0000) >> 16, (h & 0xff00) >> 8, h & 0xff |
def parse_property_string(prop_str):
"""
Generate valid property string for extended xyz files.
(ref. https://libatoms.github.io/QUIP/io.html#extendedxyz)
Args:
prop_str (str): Valid property string, or appendix of property string
Returns:
valid property string
"""
if prop_... |
def disgustingworkaroundforpossiblebug(p):
"""this is the solution for weird interleaving effects
p is procpar dictionary
returns boolean
use when sliceorder is 1 but is not actually interleaved
rearrange slices in kmake when false
"""
def _evenslices(p):
print('slices {}'.format(p... |
def total_plane_strain_R_disp(r, p, ri, ro, E, nu, dT, alpha):
"""
Constants of integration (stress) assume a linear temperature gradient
and constraint of plane strain
"""
A = ri**2 * ro**2 * -p / (ro**2 - ri**2)
C = p * ri**2 / (ro**2 - ri**2)
C_1 = -alpha*dT*(nu + 1)*(2*nu - 1)*\
(-ri**3/6 + ri*ro*... |
def get_max_temp(liveness, args):
"""Returns sum of maximum memory usage per tile of temporary variables."""
return sum(liveness["notAlwaysLive"]["maxBytesByTile"]) |
def can_embed(bin_msg: str, width: int, height: int) -> bool:
"""Determines whether the image can hold the message.
Parameters:
-----------
bin_msg:
string: A string of 1's and 0's representing the characters in the msg.
width:
int: The width of the image.
height:
int: T... |
def decompress_database(database):
"""Undo the above compression"""
for section in database["sections"]:
new_results = []
for result in section["results"]:
parameters = {}
for name, value in zip(section["parameter_names"], result[0].split(",")):
parameters... |
def remove_first(generator, default=None):
"""This function only works once for each generator
- because it pops returned items from generator"""
if generator:
for item in generator:
return item
return default |
def _addsum(arr):
"""Compute the XOR checksum value.
Parameters
----------
arr : bytes, bytearray, or list of int
Bytes to be addsum.
Returns
-------
addsum: int
the checksum byte as integer.
"""
if not isinstance(arr, (bytes, bytearray, list)):
raise TypeEr... |
def nondimensionalise(rc, qc, rho, x, nature):
"""
Nondimensionalise a parameter using the characteristic parameters.
Arguments
---------
rc : float
Characteristic radius (length)
qc : float
Characteristic flow
rho : float
Density of blood
x : float
Param... |
def patch_version(apiLevel):
"""Helper function for generate a patch for a JSON state fixture."""
return f"""{{ "device": {{ "apiLevel": {apiLevel} }} }}""" |
def translate_key(key):
"""
Function to return the correct configuration key.
If not found return the key itself.
Returns a string.
"""
mapping = {
'user': 'User',
'identityfile': 'IdentityFile',
'proxycommand': 'ProxyCommand',
'ip': 'Hostname',
... |
def prune_empty(items):
"""
Remove None items from a list.
"""
return list(filter(None, items)) |
def build_arbitration_id(msg_type, source_id, msg_id):
"""
typedef union CanId {
uint16_t raw;
struct {
uint16_t source_id : 4;
uint16_t type : 1;
uint16_t msg_id : 6;
};
} CanId;
"""
return ((source_id & ((0x1 << 4) - 1)) << (0)) | \
((msg_type ... |
def gibbs(dH,dS,temp=37):
""" Calc Gibbs Free Energy in cal/mol from enthaply, entropy, and temperature
Arguments:
dH -- enthalpy in kcal/mol
dS -- entropy in cal/(mol * Kelvin)
temp -- temperature in celcius (default 37 degrees C)
"""
return dH*1000 - (temp+273.15)*dS |
def create_vocab(docs):
"""Create a vocabulary for a given set of documents"""
words = set()
for d in docs:
for w in d:
words.add(w)
vocab = {}
for i, w in enumerate(list(words)):
vocab[w] = i
return vocab |
def _call_strace(self, *args, **kwargs):
""" Top level function call for Strace that can be run in parallel """
return self(*args, **kwargs) |
def sum_var_positional_args(a, b, *args):
"""perform math operation, variable number of positional args"""
# does not work unless decorator used functools.wrap
# print("func name inside
# {}".format(show_math_resultVarPositionalArgs.__name__))
sum = a + b
for n in args:
sum += n
r... |
def str_to_bool(string):
# type (str) -> bool
"""Converts string to boolean value.
Args:
string (str): Input string.
Returns:
bool: True if input string is "True" or "true",
False if input string is "False" or "false".
Raises:
ValueError: If input string is not... |
def add_name_combiner(combiner, name):
""" adding a node's name to each field from the combiner"""
combiner_changed = []
for comb in combiner:
if "." not in comb:
combiner_changed.append("{}.{}".format(name, comb))
else:
combiner_changed.append(comb)
return combin... |
def assert_keys_in_form_exist(form, keys):
"""
Check all the keys exist in the form.
:param form: object form
:param keys: required keys
:return: True if all the keys exist. Otherwise return false.
"""
if form is None:
return False
if type(form) is not dict:
return False... |
def _digit_to_alpha_num(digit, base=52):
"""Convert digit to base-n."""
base_values = {
26: {j: chr(j + 65) for j in range(0, 26)},
52: {j: chr(j + 65) if j < 26 else chr(j + 71) for j in range(0, 52)},
62: {j: chr(j + 55) if j < 36 else chr(j + 61) for j in range(10, 62)},
}
if... |
def has_prefix(sub_s, dic_list):
"""
:param dic_list:
:param sub_s: (str) A substring that is constructed by neighboring letters on a 4x4 square grid
:return: (bool) If there is any words with prefix stored in sub_s
"""
new_list = []
for word in dic_list:
if word.startswith(sub_s) is... |
def _parse_range_value(range_value):
"""Parses a single range value from a Range header.
Parses strings of the form "0-0", "0-", "0" and "-1" into (start, end) tuples,
respectively, (0, 0), (0, None), (0, None), (-1, None).
Args:
range_value: A str containing a single range of a Range header.
Returns:
... |
def format_hex(text: str) -> str:
"""
Formats a hexadecimal string like "0x12B3"
"""
before, after = text[:2], text[2:]
return f"{before}{after.upper()}" |
def fix_filename(urlTitle):
"""
Change the url 'urlTitle' substring used to acess the DOU article to something
that can be used as part of a filename.
"""
fixed = urlTitle.replace('//', '/')
return fixed |
def tanh_backward(dout, cache):
"""
Computes the backward pass for a layer of tanh units.
Input:
- dout: Upstream derivatives, of any shape
- cache: Values from the forward pass, of same shape as dout
Returns:
- dx: Gradient with respect to x
"""
dx, tanh_x = None, cache
######... |
def gcd(lat1, lon1, lat2, lon2, earth_radius=6367):
"""
Calculate the great circle distance between two points
on the earth (specified in decimal degrees or in radians)
All (lat, lon) coordinates must have numeric dtypes, be already converted to
radians and be of equal length.
"""
import n... |
def __getTriangleCentroid(triangle):
"""
Returns the centroid of a triangle in 3D-space
"""
# group the xs, ys, and zs
coordGroups = zip(triangle[0], triangle[1], triangle[2])
centroid = tuple([sum(coordGroup)/3.0 for coordGroup in coordGroups])
return centroid |
def cyl_inside_box(s1, v2):
"""return true if s1 is inside v2"""
b1 = s1["center"][1] + s1["radius"] < v2["p2"][1]
b2 = s1["center"][1] - s1["radius"] > v2["p1"][1]
b3 = s1["center"][0] + s1["radius"] < v2["p2"][0]
b4 = s1["center"][0] - s1["radius"] > v2["p1"][0]
return (b1 and b2 and b3 and b4... |
def map_category(category):
"""
Monarch's categories don't perfectly map onto the biolink model
https://github.com/biolink/biolink-model/issues/62
"""
return {
'variant' : 'sequence variant',
'phenotype' : 'phenotypic feature',
'sequence variant' : 'variant',
'phenoty... |
def isLiteralValue(symbol, T=[]):
"""
>>> isLiteralValue("'123'")
True
>>> isLiteralValue("'123")
False
>>> isLiteralValue("abc")
False
>>> isLiteralValue("\\'abc\\'", ["a", "b", "c"])
True
>>> isLiteralValue("\\'abc\\'", ["a", "b"])
False
>>> isLiteralValue('0')
... |
def clip_to_boundary(bbox, canvas_shape):
"""Clip bbox coordinates to canvas shape
Args:
bbox:
canvas_shape:
Returns:
"""
ymin, xmin, ymax, xmax = bbox
assert len(canvas_shape) == 2, 'canvas shape {} is not 2D!'.format(canvas_shape)
height, width = canvas_shape
# crop... |
def get_dimensions(model_dict):
"""Extract the dimensions of the model.
Args:
model_dict (dict): The model specification. See: :ref:`model_specs`
Returns:
dict: Dimensional information like n_states, n_periods, n_controls,
n_mixtures. See :ref:`dimensions`.
"""
all_n_p... |
def is_core_cs(csname):
"""
If 'csname' is a core C-state name, returns 'True'. Returns 'False' otherwise (even if
'csname' is not a valid C-state name).
"""
return csname.startswith("CC") and len(csname) > 2 |
def compute_sea_level(altitude: float, atmospheric: float) -> float:
"""
Calculates the pressure at sea level (in hPa) from the specified altitude
(in meters), and atmospheric pressure (in hPa).
# Equation taken from BMP180 datasheet (page 17):
# http://www.adafruit.com/datasheets/BST-BMP180-DS000-0... |
def get_full_link(link):
"""
Add domain to link if missing:
"""
domain = 'https://www.camara.leg.br'
if link[4] != 'http' and link[0] == '/':
return domain + link
else:
return link |
def roms_varlist(option):
"""
varlist = roms_varlist(option)
Return ROMS varlist.
"""
if option == 'physics':
varlist = (['temp', 'salt', 'u', 'v', 'ubar', 'vbar', 'zeta'])
elif option == 'physics2d':
varlist = (['ubar', 'vbar', 'zeta'])
elif option == 'physics3d':
... |
def comma_code(a_list):
"""
Turns a list into a string of elements separated by commas
:param a_list: a list of strings
:return: a string separated by commas
"""
a_list[-1] = 'and ' + a_list[-1]
stringified = ", ".join(a_list)
return stringified |
def beta_from_gamma(gamma):
"""Return exponent beta for the (integrated) propagator decay
G(lag) = lag**-beta
that compensates a sign-autocorrelation
C(lag) = lag**-gamma.
"""
return (1-gamma)/2. |
def fix_spio_issues(mcn_net):
"""Modify data structures that have been loaded using scipy.io.loadmat
The purpose of this function is to address an issue with loadmat, by which
it does not always consistently produce the same array dimensions
for objects stored in .mat files. Specifically, the level of ... |
def update_config(config,config_update):
"""Update config with new keys. This only
does key checking at a single layer of depth,
but can accommodate dictionary assignment
:config: Configuration
:config_update: Updates to configuration
:returns: config
"""
for key, value in config_updat... |
def velocity(estimate, actual, times=60):
"""Calculate velocity.
>>> velocity(2, 160, times=60)
0.75
>>> velocity(3, 160, times=60)
1.125
>>> velocity(3, 160, times=80)
1.5
"""
return (estimate*times)/(actual*1.) |
def draw_hierarchy(dict, point):
"""
Function to add the locations at the end to the list (stack).
:param dict: dictionary of points
:param point: location to add
:return: list
"""
list = []
p_l = map(str, point)
p_l = ','.join(p_l)
list.append(p_l)
# Using the dictionary t... |
def parser_ancillary_data_Descriptor(data,i,length,end):
"""\
parser_ancillary_data_Descriptor(data,i,length,end) -> dict(parsed descriptor elements).
This descriptor is not parsed at the moment. The dict returned is:
{ "type": "ancillary_data", "contents" : unparsed_descriptor_contents }
... |
def users_to_names(users):
"""Convert a list of Users to a list of user names (str).
"""
return [u.display_name if u is not None else '' for u in users] |
def scale_log2lin(value):
"""
Scale value from log10 to linear scale: 10**(value/10)
Parameters
----------
value : float or array-like
Value or array to be scaled
Returns
-------
float or array-like
Scaled value
"""
return 10**(value/10) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.