content stringlengths 42 6.51k |
|---|
def get_confidence(value):
"""Get the confidence from a sound localization data event
Arguments:
value -- Sound localization data
Return:
Sound localization confidence or 0.0
"""
try:
sound_position = value[1]
return sound_position[2]
except IndexError:
r... |
def _override_opts_in_shared(table, overrides):
"""
Override all shared dicts.
Looks recursively for ``opt`` dictionaries within shared dict and overrides any key-
value pairs with pairs from the overrides dict.
"""
if 'opt' in table:
# change values if an 'opt' dict is available
... |
def init(i):
"""
Input: {}
Output: {
return - return code = 0, if successful
> 0, if error
(error) - error text if return > 0
}
"""
return {'return':0} |
def replace_item_in_list(l: list, item_old: str, item_new: str):
"""
Replace a specific item into a list.
"""
for i in range(len(l)):
if l[i] == item_old:
l[i] = item_new
return l |
def marker_xml(marker, marker_words, w_ids, attrib, value):
"""Returns marker xml given words and word ids.
For headers, this function returns a byte string like:
<header level="1" text="Some Arabic text">
<ref id="145795"/>
<ref id="145796"/>
<ref id="145797"/>
<ref id="145798"/>
... |
def decrypt(s: str, n: int = 13) -> str:
"""
>>> msg = "keadaan pantai aman"
>>> decrypt(msg)
'xrnqnna cnagnv nzna'
"""
out = ""
for c in s:
if "A" <= c <= "Z":
out += chr(ord("A") + (ord(c) - ord("A") + n) % 26)
elif "a" <= c <= "z":
out += chr(ord("a... |
def my_sqrt(x):
"""Computes the square root of x, using the Newton-Raphson method"""
approx = None
guess = x / 2
while approx != guess:
approx = guess
guess = (approx + x / approx) / 2
return approx |
def validate_channel_config(channel_config):
"""
Validates a channel config
Args:
channel_config (dict):
the channel config object
Returns:
list of str:
list of errors or an empty list if no errors
"""
errors = []
if not channel_config:
erro... |
def parse_arn(arn):
"""
Parse an ARN into a dictionary comprising the component parts of the ARN
"""
elements = arn.split(":", 5)
result = {
"arn": elements[0],
"partition": elements[1],
"service": elements[2],
"region": elements[3],
"account": elements[4],
... |
def mean_with_default(l, default_val):
"""Returns the mean of the list l.
If l is empty, returns default_val instead
Args: l (iterable[float | int]) default_val
"""
if len(l) == 0:
return default_val
else:
return float(sum(l)) / len(l) |
def sort_priority2(values, group):
"""
sort_priority2
:param values:
:param group:
:return:
"""
found = False
def helper(x):
if x in group:
found = True
return (0, x)
return (1, x)
values.sort(key=helper)
return found |
def count_ending_spaces(line) -> int:
"""Counts the ending spaces of a line (string)"""
spaces = 0
for i in reversed(line):
if i == " ":
spaces += 1
else:
break
return spaces |
def dump_datetime(value):
"""Deserialize datetime object into string form for JSON processing"""
if value is None:
return None
return [value.strftime("%Y-%m-%d")] |
def make_normal_action(atype, label, i18n_labels=None):
"""
Create camera, camera roll, location action.
reference
- https://developers.worksmobile.com/jp/document/1005050?lang=en
:param atype: action's type
:return: None
"""
if i18n_labels is not None:
return {"type": ... |
def list_append_all_newline(list_item: list) -> list:
"""
Appends a newline character '\n' to every list_item in list object.
:param list_item: A list object to append newlines to.
:return list: A list object with newlines appended.
"""
return list(map(lambda x: f'{x}\n', list_item)) |
def _format_ipv6(a):
"""
Format IPv6 address (from tuple of 16 bytes) compressing sequence of
zero bytes to '::'. Ideally we would use the ipaddress module in
Python3.3 but can't rely on having this.
>>> _format_ipv6([0]*16)
'::'
>>> _format_ipv6(_parse_ipv6("::0012:5678"))
'::12:5678'
... |
def create_schema(levels):
"""Helper function to create empty array to inject quotes into"""
dtype = []
dtype.append(('time', 'uint64'))
column_datetype = [
('bid_time', 'uint64'),
('bid_px', 'float64'),
('bid_size', 'float64'),
('bid_provider', 'S1'),
('ask_time'... |
def has(l , key, value):
"""Check if list has dict with matching key-value pair
Parameters
----------
l : List[Dict[str, Any]]
List to check for matches
key : str
Key to find in list's dictionaries
value : Any
Value to be compared with value in suitable key-value pair in... |
def main(event: dict, context: dict) -> dict:
"""
Simple lambda handler to echo back responses
:param event: A JSON-formatted document that contains data for a Lambda function to process.
:param context: Provides methods and properties that provide information about the invocation,
function, and ru... |
def f_accel_decel(t, old_d, new_d, abruptness=1, soonness=1.0):
"""
abruptness
negative abruptness (>-1): speed up down up
zero abruptness : no effect
positive abruptness: speed down up down
soonness
for positive abruptness, determines how soon the
speedup occurs (0<soon... |
def parse_float(svalue):
"""floats a value"""
try:
val = float(svalue)
except TypeError:
val = 0.0
return val |
def ensure_quotes(s):
"""Quote a string that isn't solely alphanumeric.
:type s: str
:rtype: str
"""
return '"{}"'.format(s) if not s.isalnum() else s |
def is_iter(obj):
"""Return True if the argument is list-like."""
return hasattr(obj, "__iter__") |
def __fetch_infos(bp):
"""Gathers important information of blueprint"""
def safe_max(a, b):
"""Returns max(a,b) or the one which is not None or None if both are None."""
if a is None:
return b
if b is None:
return a
return max(a, b)
infos = ... |
def force_immutable(item):
"""
Forces mutable items to be immutable
"""
try:
hash(item)
return item
except Exception:
return tuple(item) |
def isint(s):
"""Does this object represent an integer?"""
try:
int(s)
return True
except (ValueError, TypeError):
return False |
def isnoterror(valor):
"""
Validate if the input value can convert to float format.
:param valor: The parameter that can are a string with fraction format or a number
:return: Boolean, True if the input value can convert to float format, False if the input value can not
convert to float format
... |
def identifyL23(addition):
"""Check if it is L2 or L3 delta request."""
return 'L3' if 'routes' in list(addition.keys()) else 'L2' |
def get_char_vocab(dataset):
"""Build char vocabulary from an iterable of datasets objects
Args:
dataset: a iterator yielding tuples (sentence, tags)
Returns:
a set of all the characters in the dataset
"""
vocab_char = set()
for sents, _ in dataset:
for sent in sents:
... |
def subject(headers):
"""
Searches for the key 'Subject' in email headers
then returns the value of this key (the email
subject title).
"""
for header in headers:
if header['name'] == 'Subject':
return header['value'] |
def degree_max_repetition(recpat_bag:list):
"""
Computes the degree of maximal repetition from a bag of
recurring patterns -- a list of ngram tuples.
"""
return max([len(recpat) for recpat in recpat_bag]) |
def using_split2(line, _len=len):
"""
Credits to https://stackoverflow.com/users/1235039/aquavitae
:param line: sentence
:return: a list of words and their indexes in a string.
"""
words = line.split(' ')
index = line.index
offsets = []
append = offsets.append
running_offset = 0... |
def get_bin(value, bins):
""" Returns the smallest index i of bins so that
bin[i][0] <= value < bin[i][1], where
bins is a list of tuples, like [(0,20), (20, 40), (40, 60)]
"""
for i in range(0, len(bins)):
if bins[i][0] <= value < bins[i][1]:
return i
return -1 |
def is_nonstr_iter(v):
""" from pyramid.compat """
if isinstance(v, str):
return False
return hasattr(v, '__iter__') |
def fib_term(n):
"""
a function that returns the nth term of Fibonaaci Series
Inputs:
1.n: integer
Output: An Integer
"""
if n==1:
return 1
elif n==2: # elif stands for "else if"
return 1
else:
# using recursion
return fib_term(n-1)+fib_term(n-... |
def make_readable_list_of_strings(input_list):
"""Return the string "'a', 'b' and 'c'" for the input ['a', 'b', 'c']."""
out = "'" + input_list[0] + "'"
list_length = len(input_list)
if list_length > 1:
for i in range(1, list_length):
s = input_list[i]
if i == list_length... |
def trace(X_ref, Y_ref):
"""
Calculates the slope and intercept for the trace, given the position of the direct image in physical pixels.
These coefficients are for the WFC3 G141 grism.
See also: https://ui.adsabs.harvard.edu/abs/2009wfc..rept...18K/abstract
"""
BEAMA_i = 41
BEAMA_f = 248
DYDX_0_0 = -3.5501... |
def numba_leastsqr(x, y):
""" Computes the least-squares solution to a linear matrix equation.
from https://stackoverflow.com/questions/23550483/numba-and-cython-arent-improving-the-performance-compared-to-cpython-significan"""
len_x = len(x)
x_avg = sum(x)/len_x
y_avg = sum(y)/len(y)
var_x... |
def reduceTypes(a, b):
"""Reduces column types among rows to find common denominator"""
type_order = {'string': 0, 'date': 1, 'double': 2, 'int': 3, 'none': 4}
reduce_map = {'int': {0: 'string', 1: 'string', 2: 'double'},
'double': {0: 'string', 1: 'string'},
'date': {0: ... |
def _int_to_json(value):
"""Coerce 'value' to an JSON-compatible representation."""
if isinstance(value, int):
value = str(value)
return value |
def remove_start(s: str) -> str:
"""
Clear string from start '-' symbol
:param s:
:return:
"""
return s[1:] if s.startswith('-') else s |
def compose_table(table_prefix, table_root):
"""Compose real source table name.
Arguments
---------
table_prefix : str
Prefix of a table.
table_root : str
Specific part of a table name.
Returns
-------
str
Real table name.
"""
table_name = table_prefix ... |
def get_overview(whole_article):
"""
:param str whole_article: article
:rtype: str
"""
try:
end_index = whole_article.index('</p>', 200) + 4
return whole_article[0:end_index]
except ValueError:
return whole_article |
def parse_package_string(path):
"""
Parse the effect package string.
Can contain the package python path or path to effect class in an effect package.
Examples::
# Path to effect pacakge
examples.cubes
# Path to effect class
examples.cubes.Cubes
Args:
path... |
def equalContents(arr1, arr2):
"""Checks if the set of unique elements of arr1 and arr2 are equivalent.
"""
return frozenset(arr1) == frozenset(arr2) |
def check_special_value(expected, value):
"""Check if value equals to Null, Not null, empty or expected value."""
if expected == "NULL":
return value is None
elif expected == "NOT_NULL":
return value is not None
elif expected == "EMPTY":
return value == ""
elif expected == "N... |
def fold(dots: set, folding: tuple) -> set:
"""Return set of dots after folding."""
axis, line = folding
folded = set()
for x, y in dots:
# update x/y coordinate if right of/below the folding line
if axis == 'x':
folded.add( (x if x < line else 2*line-x, y))
else:
... |
def calc_z_dropoff(theta, t_min, t_max):
"""
Calculates and returns the dropoff coefficient for a z rotation (used in both VR body and Fetch VR).
The dropoff is 1 if theta > t_max, falls of quadratically between t_max and t_min and is then clamped to 0 thereafter.
"""
z_mult = 1.0
if t_min < the... |
def followed_by(user1, user2):
"""
Returns whether user1 is followed by user2 or not.
"""
if not user1 or not user2 or user1.is_anonymous() or user2.is_anonymous():
return False
return user1.followed_by(user2) |
def is_open_sea(row, column, fleet):
"""
This method checks if the square given by row and column neither contains nor is adjacent
(horizontally, vertically, or diagonally) to some ship in fleet.
:param row: int
:param column: int
:param fleet: list
:returns result: bool - True if so ... |
def calc_formation_energy(prod, react):
"""
Calculate formation energy of 'A' in a.u. from 2 lists of energies.
Formation energy = sum(product energy) - sum(reactant energy)
Keyword arguments:
prod (list) - list of product energies
react (list) - list of reactant energies
Returns:... |
def collectKwargs(label, inKwargs):
"""
Collect kwargs of the type label_* and return them as a dict.
Parameters
----------
label: str
inKwargs: dict
Returns
-------
Dict with the collected kwargs.
"""
outKwargs = dict()
for key, value in inKwargs.items():
if la... |
def sexp_dis(x):
"""https://www.itl.nist.gov/div898/handbook/eda/section3/eda3667.htm
"""
x = round(x, 14)
res = round(2.718281**(-x), 14)
return res |
def get_ips_from_vnfr(vnfr):
"""Returns info on the ip addresses in a vnfr, per vdu.
:returns: A tuple. [0] is a bool with the result. [1] is a dictionary
with a key for each VDU. The value is a list of dictionaries.
Each dictionary has a type key, indicating which type of id,
... |
def dot(v,w):
"""Calculate the Dot Product function.
Parameters
----------
v : list
First 3-element list.
w : list
Second 3-element list.
Returns
-------
int or float
The quotient of the dot product of vectors v and w.
Examples
--------
>>> impo... |
def float_to_str(value: float) -> str:
"""Converts double number to string using {.12g} formatter."""
return format(value, ".12g") |
def remove_uppercase(input_words):
"""
Remove the uppercase of the beginning of sentences in a list of words.
Input:
-input_words list of strings
Ouput:
-output_words list of strings
"""
output_words = [input_words[0]]
for i in range(len(input_words[:-1])):
if input_... |
def make_holes(hole_dict, fill_in):
"""Inserts holes at given places in the template for fill in the blanks
:param hole_dict: dictionary of the holes to replace.
:param fill_in: the template.
:return: dictionary with fill in the blanks template with holes and which holes were replaced.
"""
hole... |
def merge_dict(src, dest):
"""Recursive merge dictionary"""
for key, value in src.items():
if isinstance(value, dict):
# get node or create one
node = dest.setdefault(key, {})
merge_dict(value, node)
else:
dest[key] = value
return dest |
def split_string(joined, split_char="_"):
"""Split joined string and substitute back the null characters with an underscore if necessary.
Inverse function of `join_strings(strings)`.
Args:
joined: str, the joined representation of the substrings.
split_char: str, the character to split by.... |
def lower(value):
""" Functor to return a lower-case string.
"""
return value.lower() |
def list_prettyprint(old_list: list):
"""
Prepares a list for easier viewing on Discord.
Example:
list_prettyprint([foo, bar])
Returns:
`foo, bar`
"""
return f'`{", ".join(old_list)}`' |
def hsv_to_rgb(h, s, v):
"""
:param h: 0 <= h < 360
:param s: 0 <= s <= 1
:param v: 0 <= v <= 1
:return: (r, g, b) as floats
"""
C = v * s
X = C * (1 - abs((h / 60) % 2 - 1))
m = v - C
if h < 60:
rgb_prime = (C, X, 0)
elif h < 120:
rgb_prime = (X, C, 0)
e... |
def str_to_regex(string):
"""Convert a string to a regex pattern with special treatment of an empty string."""
if string:
return string
return "a^" # This pattern should never match |
def quartic_centrifugal_dist_consts(qcd_consts_str):
""" write the quartic centrifugal distortion constant
labels and values (cm^-1) to a string (cm^-1)
"""
qcd_consts_lines = qcd_consts_str.splitlines()
qcd_consts = []
for line in qcd_consts_lines:
const = line.strip().split()
... |
def license_not_found(remove_header, license_info, src_file_content, src_filepath):
"""
Executed when license is not found. It either adds license if remove_header is False,
does nothing if remove_header is True.
:param remove_header: whether header should be removed if found
:param license_info... |
def strip_dollars(text):
"""
Remove all dollar symbols from text
Parameters
----------
text : str
Text to remove dollars from
"""
return text.strip('$') |
def continue_mdp_cost(success_cost, failure_cost, p):
"""
Cost for MDP where failures move to the intended state
failure_cost should be much larger than success_cost
"""
return p * success_cost + failure_cost * (1 - p) |
def transform(obj):
"""
Transforms an object to its NEURON representation, if the __neuron__ magic
method is present.
"""
if hasattr(obj, "__neuron__"):
return obj.__neuron__()
return obj |
def apply(m, f):
"""
Apply operation in-place
:param m:
:param f:
:return:
"""
for r in m:
for idx, v in enumerate(r):
r[idx] = f(v)
return m |
def parse_path(path):
"""
Python only works with '/', not '\\'or '\'
WARNING:
in windows use r'path' because of escape literals , e.g: "."
os.path.realpath(path).replace('\\', '/') #BUG os.path.realpath removes the last '\\' and if your sending a folder it is a problem
"""
parsed_p... |
def prepare_bid_identifier(bid):
""" Make list with keys
key = {identifier_id}_{identifier_scheme}_{lot_id}
"""
all_keys = set()
for tenderer in bid["tenderers"]:
key = u"{id}_{scheme}".format(id=tenderer["identifier"]["id"], scheme=tenderer["identifier"]["scheme"])
if bid.get("l... |
def _is_bytes(thing):
"""Check that **thing** is bytes.
:param thing: The thing to check if it's bytes.
:rtype: bool
:returns: ``True`` if **thing** is bytes or a bytearray.
"""
if isinstance(thing, (bytes, bytearray)):
return True
return False |
def search_codetree_minfreq(word,codetree,minfreq=1,minlen=1,fullwords=False):
""" Finds in codetree (symbol per node) longest possible left substring of word,
at least of len=minlen and at least of freq=minfreq;
returns frequency and substring length or None if not found
"""
ret = None
... |
def json_set_check(obj):
"""
json.dump(X,default=json_set_check)
https://stackoverflow.com/questions/22281059/set-object-is-not-json-serializable
"""
if isinstance(obj, set):
return list(obj)
raise TypeError |
def _parse_address(key):
"""Extract address from key"""
return key.split('/')[-2] |
def check_consecutive(mylist):
"""
Description:
This function checks a list of numbers and returns how many items are consecutive.
input:
my_list - A list of integers
return:
Number of items consecutive in the list - [False, 2, 3,..]
"""
my_list = list(map(int, mylist))
... |
def get_filt_raref_suffix(p_filt_threshs: str, raref: bool) -> str:
"""Create a suffix based on passed config to denote
whether the run is for filtered and/or rarefied data.
Parameters
----------
p_filt_threshs : str
Minimum sample read abundance to be kept in the sample
raref : bool
... |
def parse_raw_intervals(str_list):
"""Decode serialized CCDS exons.
Accepts a formatted string of interval coordinates from the CCDS
row and turns it into a more manageable list of lists with
(start, end) coordinates for each interval (exon).
.. code-block:: python
>>> parse_raw_intervals('[11-18, 25-3... |
def parse_gcc_style_error_message(message, filename, has_column=True):
"""Parse GCC-style error message.
Return (line_number, message). Raise ValueError if message cannot be
parsed.
"""
colons = 2 if has_column else 1
prefix = filename + ':'
if not message.startswith(prefix):
raise... |
def quotient(left_object, right_object):
"""Return quotient of the two and round towards 0."""
return int(float(left_object)/right_object) |
def clamp(n, low, high):
"""ensure that a number n is constrained in a range"""
return min(high, max(low, n)) |
def code_counter(data_list):
""" Counts each code in each element of a list of lists. Assumes elements are 0, 1, 2. Returns list of counts"""
count_list = [0, 0, 0]
for item in data_list:
for i in item:
if i == 0:
count_list[0] += 1
elif i == 1:
... |
def process(path, handler, success, failure):
"""Generic processing of path yields a,ended COHDA protocol."""
valid, message = handler(path)
if valid:
return True, message, success + 1, failure
return False, message, success, failure + 1 |
def clean_tweet_text(original_tweet_text):
"""
Remove all URL and hashtag entities in the tweet_text
param original_tweet_text: the original tweet_text field
return: new tweet_text field with out any URL and hashtag
"""
tweet_text_words = original_tweet_text.split()
filtered_tweet_... |
def search_string_in_file(file_name, string_to_search):
"""Search for the given string in file and return lines containing that string,
along with line numbers"""
line_number = 0
list_of_results = []
# Open the file in read only mode
with open(file_name, 'r') as read_obj:
# Read all line... |
def isQSPIN(filename):
"""
Checks whether a file is GSM19 format.
"""
try:
temp = open(filename, 'rt') #, encoding='utf-8', errors='ignore'
except:
return False
try:
li = temp.readline()
except:
return False
if not li.startswith('*Start Header*'):
... |
def get_worker_id_from_tf_config(tf_config_json: dict) -> str:
"""Valid roles in a cluster is "chief", "worker", "ps" and "evaluator"."""
task = tf_config_json["task"]
worker_type = task["type"]
worker_index = task["index"]
return f"{worker_type}_{worker_index}" |
def get_ref_alt_allele(ref, alt, pos):
"""
Description:
Helper function to index REF and ALT alleles with genomic positions.
Arguments:
ref list: REF alleles.
alt list: ALT alleles.
pos list: Genomic positions.
Returns:
ref_allele dict: REF alleles.
alt_... |
def dict_from_two_lists(keys: list, values: list):
"""Creates a dictionary from a list of keys and a list of values.
Examples:
>>> keys = ('bztar', 'gztar', 'tar', 'xztar', 'zip')\n
>>> values = ('.tbz2', '.tgz', '.tar', '.txz', '.zip')\n
>>> newdict = dict_from_two_lists(keys, values)\... |
def create_send_to_property_inspector_payload(context: str, action: str, payload: dict):
"""Create and return "sendToPropertyInspector" dictionary to send to the Plugin Manager.
Args:
context (str): An opaque value identifying the instance's action you want to modify.
action (str): Action name.... |
def merge_values(src, new):
"""Update a value list with a list of new or updated values."""
l_min, l_max = (src, new) if len(src) < len(new) else (new, src)
l_min.extend(None for i in range(len(l_min), len(l_max)))
for i, val in enumerate(new):
new[i] = val if val else src[i]
return new |
def shaped_policy(p_action, p_good, denominator):
"""
Returns the probability of an action given a state for the policy as a result of policy shaping
:param denominator: The sum over all p_action and p_good for every action in a given state.
"""
if denominator <= .00001:
denominator ... |
def conv_connected_inputs(input_shape, kernel_shape, output_position, strides,
padding):
"""Return locations of the input connected to an output position.
Assume a convolution with given parameters is applied to an input having N
spatial dimensions with `input_shape = (d_in1, ..., d_inN... |
def rgb2lab(red, green, blue):
"""
Convert RGB (``red``, ``green``, ``blue``) to `CIELAB <https://en.wikipedia.org/wiki/CIELAB_color_space>`_
"""
# XYZ -> Standard-RGB
# https://www.easyrgb.com/en/math.php
var_R = red / 255
var_G = green / 255
var_B = blue / 255
if var_R > 0.04045:... |
def map(fn, seq):
"""Applies fn onto each element in seq and returns a list.
>>> map(lambda x: x*x, [1, 2, 3])
[1, 4, 9]
"""
return [fn(x) for x in seq] |
def _get_first_endpoint(endpoints, region):
"""Find the first suitable endpoint in endpoints.
If there is only one endpoint, return it. If there is more than
one endpoint, return the first one with the given region. If there
are no endpoints, or there is more than one endpoint but none of
them matc... |
def get_number_of_parents(trace_json):
"""Returns the number of parents. The number of parents is the number of
events on the first level.
Args:
trace_json (json): Json representing a trace
Returns:
Number of parents for the trace.
"""
return len(trace_json.get('children')) |
def isPrime(num):
"""
Tell whether the given number is a prime number
"""
if num < 1:
return False
if num == 1:
return True
for i in range(2, int(num / 2) + 1):
if num % i == 0:
return False
return True |
def range_to_work_ids(range_ids):
"""Convert list of work id ranges to full list
This function takes a list of ranges and converts it to the full list
of work ids. Returns the original list if conversion is not possible.
Both ends of each range is included in the final list.
Args:
range_i... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.