content stringlengths 42 6.51k |
|---|
def get_kth_minimum(x, k=1):
""" gets the k^th minimum element of the list x
(note: k=1 is the minimum, k=2 is 2nd minimum) ...
based on the incomplete selection sort pseudocode """
n = len(x)
for i in range(n):
minIndex = i
minValue = x[i]
for j in range(i+1, n):
... |
def parse_list(list, keyword):
"""
Parses the port/or alarmlist(list). (keyword) triggers on.
Returns a list of active in list
"""
cnt = 1
ports = []
for port in list:
if port == keyword:
ports.append(cnt)
cnt += 1
return ports |
def k_const(k):
"""Returns the constant reaction rate coefficients
INPUTS
======
k: float, constant reaction rate coefficient
RETURNS
=======
constant reaction rate coefficients, which is k
EXAMPLES
========
>>> k_const(1.5)
1.5
"""
k1 = k
return k1 |
def _parse_mapping_config(config: str):
"""Parse config such as: numpy -> asnumpy, reshape, ...
Return a list of string pairs
"""
mapping = []
for line in config.splitlines():
for term in line.split(','):
term = term.strip()
if not term:
continue
... |
def find_levels(variable_names):
"""This method...
.. note: Might need the dataframe to check ints!
Returns
-------
list
Variables with the word levels in it.
"""
return [c for c in variable_names if 'level' in c] |
def escape(content):
""" Escapes a string's HTML. """
return content.replace('&', '&').replace('<', '<').replace('>', '>')\
.replace('"', '"').replace("'", ''') |
def isProperStage(stage):
"""Checks if the stage is a proper stage
Arguments:
stage(list) a 3x3 list containg a tic-tac-toe stage
Returns:
retVal(bool) True if the stage is a 3x3 list
"""
retVal = True
if type(stage) == list and len(stage) == 3:
for row in s... |
def relax_menu_text(text):
"""Remove any &, lower case, stop at first \\t"""
tmp = text.replace('&', '').lower()
tabind = tmp.find('\t')
if tabind > 0:
tmp = tmp[:tabind]
return tmp.strip() |
def _jacobi_symbol(a: int, n: int) -> int:
"""
Calculate the Jacobi symbol (a/n)
"""
if n == 1: # pragma: no cover
return 1
if a == 0:
return 0
if a == 1:
return 1
if a == 2:
if n % 8 in [3, 5]:
return -1
if n % 8 in [1, 7]:
ret... |
def build_header(item, suffix='rating'):
"""
Build the row of header for a CSV file
:param item: A test item, normally the first test item in responses of a test
:param suffix: This will be using in a test with rating bar
:return: CSV format string including double quota
"""
if item['type'] ... |
def split_html_by_tds(html):
"""get a peace of html containing tds and returns the
content of each td as a elemenent in a list"""
splited_html = html.split('</td>')
result = []
for html_chunck in splited_html:
striped_html_chunk = html_chunck.strip()
if striped_html_chunk:
... |
def decode_synchsafe_int( i ):
"""Decode SynchSafe integers from ID3v2 tags"""
i = int.from_bytes( i, 'big' )
if i & 0x80808080:
raise Exception( 'Bad sync in SynchSafe integer!' )
return ( ( i & 0xFF000000 ) >> 3 ) | ( ( i & 0x00FF0000 ) >> 2 ) | ( ( i & 0x0000FF00 ) >> 1 ) | ( i & 0x000000FF ) |
def uptime_collect(self):
"""Static collected uptime data for testing."""
return {
'response_time': 120.10,
'uptime_ratio': 99.96
} |
def trapezoid_height(base_short,base_long,area):
"""Usage: Find height of a trapezoid"""
return 2*(area/(base_short+base_long)) |
def standardize_number(phone_number):
"""
>>> standardize_number('07895462130')
'+91 78954 62130'
>>> standardize_number('919875641230')
'+91 98756 41230'
>>> standardize_number('9195969878')
'+91 91959 69878'
"""
return "+91 %s %s" % (phone_number[-10:-5], phone_number[-5:]) |
def split_list_into_chunks(list_to_split, max_entries_per_list):
"""
Takes a list and splits it up into smaller lists
"""
chunks = []
for i in range(0, len(list_to_split), max_entries_per_list):
chunk = list_to_split[i:i + max_entries_per_list]
chunks.append(chunk)
return chunk... |
def pad(name):
"""Add a space if name is a non-empty string."""
if name != '':
return ' ' + name
else:
return '' |
def check_for_files(item_json):
"""Find all files and extentions of an item, add their size together.
Arguments:
item_json -- (json) the json of the item being parsed.
Returns:
item_data -- (dictionary) a dictionary including a list of all
file jsons attached to the... |
def dict_chs_best(iterable, max_key=lambda x: len(x.eventarray)):
"""
Group an iterable of utype-ch_struct pairs into a dict, keeping only those
channels with the highest sample length for their utype.
"""
result = {}
for utype, ch_struct in iterable:
if not utype in result:
... |
def allocated_size(allocation_unit, requested_size):
"""
Round ``requested_size`` up to the nearest ``allocation_unit``.
:param int allocation_unit: The interval in ``bytes`` to which
``requested_size`` will be rounded up.
:param int requested_size: The size in ``bytes`` that is required.
:... |
def merge_dicts(x, y):
"""
Merge dictionaries
:param Mapping x: dict to merge
:param Mapping y: dict to merge
:return Mapping: merged dict
"""
z = x.copy()
z.update(y)
return z |
def nearest_color(palette, in_color):
"""returns nearest RGB color in palette"""
out_color = min(palette, key=lambda palette_entry: sum((pe - c) ** 2 for pe, c in zip(palette_entry, in_color)))
return out_color |
def rootFolder(exp=''):
"""
Get root folder path for Hansard modeling experiments
Args:
exp (str, optional): name of experiment. Defaults to ''.
Returns:
str: full path for a given experiment
"""
root_folder = '/home/azureuser/cloudfiles/code/data/processing/hansard/experiment'
... |
def underline(text: str) -> str:
"""Formats text for discord message as underlined"""
return f"__{text}__" |
def to_python_type(py_type: str) -> type:
"""Transform an OpenAPI-like type to a Python one.
https://swagger.io/docs/specification/data-models/data-types
"""
TYPES = {
"string": str,
"number": float,
"integer": int,
"boolean": bool,
"array": list,
"object"... |
def json_parsing(obj, key):
"""Recursively pull values of specified key from nested JSON."""
arr = []
def extract(obj, arr, key):
"""Return all matching values in an object."""
if isinstance(obj, dict):
for k, v in obj.items():
if isinstance(v, (dict)) or... |
def convergents(v):
"""
Returns the partial convergents of the continued
fraction v.
Input:
v -- list of integers [a0, a1, a2, ..., am]
Output:
list -- list [(p0,q0), (p1,q1), ...]
of pairs (pm,qm) such that the mth
convergent of v is pm/qm.
Exa... |
def linterp(xind, yarr, frac):
"""
Linear interpolation
"""
return yarr[xind] * (1 - frac) + yarr[xind + 1] * frac |
def eec(u, v):
""" The Extended Eculidean Algorithm
For u and v this algorithm finds (u1, u2, u3)
such that uu1 + vu2 = u3 = gcd(u, v)
We also use auxiliary vectors (v1, v2, v3) and
(tmp1, tmp2, tmp3)
"""
(u1, u2, u3) = (1, 0, u)
(v1, v2, v3) = (0, 1, v)
while (v3 !=... |
def as_bytes(string):
"""
Ensure that whatever type of string is incoming, it is returned as bytes,
encoding to utf-8 otherwise
"""
if isinstance(string, bytes):
return string
return string.encode('utf-8', errors='ignore') |
def is_fixed(state):
"""Helper to discover if fixed limits have been selected"""
return state.get("colorbar", {}).get("fixed", False) |
def check_zip(zip_code):
"""check if zip code has correct format.
Args:
zip_code as a string
Returns:
a boolean indicating if valid (True) or not (False)
"""
if len(zip_code) < 5:
return False
if not zip_code[:5].isdigit():
return False
return True |
def is_string_an_integer(string: str) -> bool:
"""
AUTHORS:
--------
:author: Alix Leroy
DESCRIPTION:
------------
Check whether a string is an integer or not
PARAMETERS:
-----------
:param string(str): The string to analyze
RETURN:
-------
:return (bool): Whet... |
def half_up_round(value, scale):
"""
Round values using the "half up" logic
See more: https://docs.python.org/3/library/decimal.html#rounding-modes
>>> half_up_round(7.5, 0)
8.0
>>> half_up_round(6.5, 0)
7.0
>>> half_up_round(-7.5, 0)
-8.0
>>> half_up_round(-6.5, 0)
-7.0
... |
def bits2MB(bits):
"""
Convert bits to MB.
:param bits: number of bits
:type bits: int
:return: MiB
:rtype: float
"""
return bits / (8 * 1000 * 1000) |
def ContiguousRanges(seq):
"""Given an integer sequence, return contiguous ranges.
This is expected to be useful for the tr-98 WLANConfig PossibleChannels
parameter.
Args:
seq: a sequence of integers, like [1,2,3,4,5]
Returns:
A string of the collapsed ranges.
Given [1,2,3,4,5] as input, will r... |
def get_attrs(obj):
"""
Utility function to return all non-function variables in an object
:param obj: The object to retrieve vars from
:return: The vars found, excluding all methods
"""
return [x for x in dir(obj) if not x.startswith('__') and not callable(getattr(obj, x))] |
def insertion_sort(list):
"""
Takes in a list and sorts the list using an insertion sort method.
Modifies the list in place, but returns it for convenience.
"""
round_number = 1
curr = round_number
while round_number < len(list):
while curr > 0:
if list[curr] < list[curr ... |
def cap(value: float, minimum: float, maximum: float) -> float:
"""Caps the value at given minumum and maximum.
Arguments:
value {float} -- The value being capped.
minimum {float} -- Smallest value.
maximum {float} -- Largest value.
Returns:
float -- The capped value or the... |
def mktext_from_rec(rec):
""" Return textual representation of rec dotfields.
"""
# Get list of dot fields in alphabetical order.
# dot fields = [all rec fields] - [base fields]
base_fields = {'_id', '_body'}
dot_fields = sorted(set(rec.keys()).difference(base_fields))
dotfield_lines = [... |
def dotify(adict):
"""
Contract a dictionary to use "dot notation".
This support both standard dict or OrderedDict, or any dict subclass.
For example::
.. code-block:: python3
adict = {
'key1': {
'key2': {
'key3': 'string1',
... |
def get_decimal_len(s):
"""used to find the length of the decimal part of lan/lon"""
t = str(s)
for c in t:
if c not in '-.0123456789':
return -1
if '.' not in t:
return 0
while '.' in t:
try:
t = t[1:]
except:
pass
return len(... |
def EmoteListToString(emoteList):
"""Convert an EmoteList to a string."""
# Use string.join to glue string of emotes in emoteList
separator = " "
return separator.join(emoteList) |
def _generateEscapeSequence(styleSequence, preNum=0):
"""
Generate Escape Sequence
Parameters:
styleSequence (list): Sequenced list of escape sequence
preNum (int): Number, that prepends before sequence count
Returns:
variables (str): Newline separat... |
def list_to_string(l: list) -> str:
"""
:param list l: A list to serialize.
:return str: The same list, as a string.
"""
return ', '.join([str(v) for v in l]) |
def twos_comp(val, bits):
"""compute 2's complement """
if val & (1 << (bits - 1)):
val = val - (1 << bits)
return val |
def degTohms(ideg):
"""
Converts degrees to hours:minutes:seconds
:param ideg: objects coordinates in degrees
:type ideg: float
:return: hours:minutes:seconds
:rtype: string
"""
ihours = ideg / 15.
hours = int(ihours) + 0.
m = 60. * (ihours - hours)
minutes = int(m) + 0.
... |
def get_request_method(environ: dict) -> str:
"""
Returns a method name of HTTP request.
:param environ: WSGI environment
:return: HTTP method name
"""
method = environ["REQUEST_METHOD"]
return method |
def prob_mass_grey_from_ndvi(ndvi, old_min=0.1, old_max=0.7):
"""
Calculates probability masses for grey from NDVI values
:param ndvi:
:param old_min:
:param old_max:
:return:
"""
# Not Green belief
if ndvi > old_max:
return 0
elif ndvi < old_min:
return 1
el... |
def is_master(config):
"""Return true we're on a master node."""
return not hasattr(config, 'workerinput') |
def clean_hotel_prefer(string):
"""
Cambie por esta condicion porque me tiraba un warning si hacia solo if hotel_preferente:
"""
if string is not None:
r = 1
else:
r = 0
return r |
def make_deps_full_name(i):
"""
Input: {
deps - dict with deps
}
Output: {
return - return code = 0, if successful
> 0, if error
(error) - error text if return > 0
full_name - full... |
def capwords(s, sep=None):
"""capwords(s [,sep]) -> string
Split the argument into words using split, capitalize each
word using capitalize, and join the capitalized words using
join. If the optional second argument sep is absent or None,
runs of whitespace characters are replaced by a singl... |
def importName(modulename, name):
""" Import a named object from a module in the context of this function,
which means you should use fully qualified module paths.
Return None on failure.
"""
try:
module = __import__(modulename, globals(), locals(), [name])
except ImportError:
... |
def schemaFile(csvFile):
"""
Rename the csv file with schema notation and change to json file
:param csvFile: input csv file name
:return: new file name
"""
return csvFile.replace('.csv', '_schema.json') |
def _append_extended_basins(basin_list):
"""Replace extended basins with components, e.g. atlExt with atl, mexico ...
Note: atlExt etc are removed from the list for error checking later on.
Parameters
----------
basin_list : list of strings
list of basin names potentially including 'atlExt'... |
def img_resize_bilinear(grid, w2, h2):
"""
From techalgorithm.com
"""
w = len(grid[0])
h = len(grid)
newgrid = []
x_ratio = (w-1)/float(w2)
y_ratio = (h-1)/float(h2)
for i in range(0, h2):
y = int(y_ratio * i)
y_diff = (y_ratio * i) - y
newrow = []
... |
def is_sorted(x):
"""
Test whether a list is sorted
"""
return all(a <= b for a,b in zip(x[0:-1], x[1:])) |
def arrayAlista(array):
""" Transforma un array de numpy en una lista """
lista = []
for elem in array:
lista.append(list(elem))
return lista |
def to_glob(pattern):
"""Given a pattern in match format, returns a glob in shell format."""
if "*" in pattern:
return pattern
return "*" + pattern + "*" |
def calculate_pizzas_dumb(participants, n_pizza_types, pizza_types):
"""Determine pizza types and number of feeded
participants.
Parameters
----------
participants : Int
Number of people to be feeded by pizza.
n_pizza_types : type
Description of parameter `n_pizza_types`.
... |
def generateDictFilename(series_abbr, host_name, series_code):
"""-------------------------------------------------------------------
Function: [generateDictFilename]
Description: Systematically generates a filename for a dictionary file
given the host name, series abbreviation and code
Input:
[series... |
def options_as_dictionary(meta):
"""
Transforms a list of tuples to a dictionary
Args:
meta (list): A list ot option tuples
Retuns:
dict: A dictionary of options key - values
"""
module_config = {}
for seltuple in meta:
module_config.update({seltuple[0]: seltuple[1]})... |
def language_pretty(input: str) -> str:
""".repo-metadata.json language field to pretty language."""
if input == "nodejs":
return "Node.js"
return input |
def UniformPrior(Parameter,Bounds):
"""
Uniform prior to limit a parameter within a bound
"""
if Parameter < Bounds[0] or Parameter > Bounds[1]:
return 0
else:
return 1 |
def _GetMassCenter(MassCoordinates):
"""
#################################################################
Get the center of mass.
INPUT: MassCoordinates is [[atommass,[x,y,z]],......].
#################################################################
"""
res1 = 0.0
res2 = 0.0
res3 ... |
def check_url(input_str):
"""Check if a string is a 'https' url.
Parameters
----------
input_str : str
An input string or path.
Returns
-------
bool
True if input_string is url, else False.
"""
return 'https' in str(input_str) |
def split_get_output(output: str):
"""'
Parse output like:
-1 0 CS{Cell{...} bits: 64..66; refs: 0..0} CS{Cell{...} bits: 66..333; refs: 0..0} C{...}
To:
[-1, 0, "CS{Cell{...} bits: 64..66; refs: 0..0}", "CS{Cell{...} bits: 66..333; refs: 0..0}", "C{...}"]
"""
data = output.split()
res... |
def should_force_step(step_name, force_steps):
"""
Check if step_name is in force_steps
We support multi-level flags, ex for step_name = "a.b.c",
we allow : "a", "a.b", "a.b.c"
If one of force_steps is a wildcard (*), it will also force the step
"""
for step in force_steps:
if step =... |
def get_all_dates(year_start, month_start, year_end, month_end):
"""get_all_dates
Get all the dates between two dates.
:param year_start: The starting year
:param month_start: The starting month
:param year_end: The ending year
:param month_end: The ending month
"""
assert (year_start < ... |
def get_size_to_pretty(the_size, in_bits=False):
"""
Get a pretty string of a number of bits or bytes
:param the_size: The Size in bits or bytes
:param in_bits: Should the pretty string show bits?
:return: A pretty string, reduced version of the_size
"""
if the_size >= 1000000:
retur... |
def expandCommaSeparatedRanges(s):
"""
's' format - comma separated ranges or values
a-b,c,..,d,e-f,a etc.
Includes the first and the last value in the range
"""
range_list = s.split(',')
values = list()
for r in range_list:
# range a-b
if '-' in r:
... |
def build_target_command(target_bin: str, config: str) -> str:
"""
Builds a command that starts a singer target connector with the
required command line arguments
Args:
target_bin: path the target python executable
config: path to config json file
Returns:
string of command... |
def _rhs(model_expression):
"""
Get only the right-hand side of a patsy model expression.
Parameters
----------
model_expression : str
Returns
-------
rhs : str
"""
if '~' not in model_expression:
return model_expression
else:
return model_expression.split(... |
def Convert2Num(text):
"""converts text to python type in order
Int, hex, Float, Complex
ValueError if can't
"""
#convert to number if possible
try:
value = int(text, 10)
return value
except ValueError as ex:
pass
try:
value = int(text, 16)
... |
def making_change(amt: int, coins: list) -> int:
"""Iterative implementation of the making change algorithm.
:param amt (int) : Amount, in cents, to be made into change.
:param coins (list) : List of coin denominations
:return (int) : Number of different combinations of change.
"""
# calc[i... |
def file_from_list_of_images(file_list, current_file, request):
"""
return filename from file_list depends of request
request: position on the list
"""
if file_list:
if request == "first":
file = file_list[0]
elif request == "previous":
position = file_list.in... |
def convert_2_BIO(label):
""" Convert inplace IOBES encoding to BIO encoding """
tag = []
i = 0
while i < len(label):
char = label[i]
i += 1
if char == 'S':
tag.append('B')
elif char == 'E':
tag.append('I')
elif char == 'I':
tag... |
def is_leap(year):
"""Return True for leap years, False for non-leap years."""
return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0) |
def find_ngrams(input_list, n, **kwargs):
"""Generates all n-gram combinations from a list of strings
Args:
input_list (list): List of string to n-gramize
n (int): The size of the n-gram
Returns:
list: A list of ngrams across all the strings in the \
input list
"""
... |
def average_(numList, printed=False):
"""Find the average/mean of a set of numbers."""
# The sum of the numbers in the numList divided by the length of the list.
if printed:
print(sum(numList)/len(numList))
else:
return sum(numList)/len(numList) |
def flatten(array):
"""
Return a flattened copy of a list of lists.
"""
return [item for row in array for item in row] |
def extract_first_three_lanes(polys):
"""
Extract the first three lanes
Input
polys: all lanes
Ouput
the first three lanes
"""
return polys[:3] |
def get_dat_id(datnum, datname):
"""Returns unique dat_id within one experiment."""
name = f'Dat{datnum}'
if datname != 'base':
name += f'[{datname}]'
return name |
def clip(min, val, max):
"""
Returns `val` clipped to `min` and `max`.
"""
return min if val < min else max if val > max else val |
def to_str(var):
"""Similar to to_list function, but for string attributes."""
try:
return str(var)
except TypeError:
raise ValueError("{} cannot be converted to string.".format(var)) |
def decbin(num):
"""
Converts a decimal number(num) to binary
Parameters
----------
num : int or string
Returns
-------
integer denoting value of decimal number in binary format.
"""
try:
return bin(int(num))[2:]
except:
raise ValueError("Expected a Numb... |
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...17K/abstract
"""
BEAMA_i = 15
BEAMA_f = 196
DYDX_0_0 = 1.96882E... |
def normalize_encoding(encoding, default):
"""Normalize the encoding name, replace ASCII w/ UTF-8."""
if encoding is None:
return default
encoding = encoding.lower().strip()
if encoding in ['', 'ascii']:
return default
return encoding |
def traverse_json_obj(obj, path=None, callback=None):
"""
Recursively loop through object and perform the function defined
in callback for every element. Only JSON data types are supported.
:param obj: object to traverse
:param path: current path
:param callback: callback executed on every eleme... |
def get_max_episode(num_h_layers, epoch_factor, penalty_every, **_):
"""Routine to calculate the total number of training episodes
(1 episode = 1 penalty epoch + *penalty_every* normal epochs"""
max_episode = (num_h_layers * epoch_factor) // penalty_every
if max_episode == 0:
raise ValueError('P... |
def pairwise_reduce(op, x):
"""
Parameters
----------
op
Operation
x
Input list
Returns
-------
"""
while len(x) > 1:
v = [op(i, j) for i, j in zip(x[::2], x[1::2])]
if len(x) > 1 and len(x) % 2 == 1:
v[-1] = op(v[-1], x[-1])
x =... |
def to_upper(ins):
""" A trivial function to test from pytest in the app file. """
return ins.upper() |
def func_poly2d(x,y,*args):
""" 2D polynomial surface"""
p = args
np = len(p)
if np==0:
a = p[0]
elif np==3:
a = p[0] + p[1]*x + p[2]*y
elif np==4:
a = p[0] + p[1]*x + p[2]*x*y + p[3]*y
elif np==6:
a = p[0] + p[1]*x + p[2]*x**2 + p[3]*x*y + p[4]*y + p[5]*y**2... |
def pig_it(string):
"""Function creates string with simple pig latin words."""
pyg = "ay"
final_output = ""
for word in string.split():
if not word.isalpha():
final_output += word + " "
break
else:
first = word[0]
new_word = word + first + ... |
def clean_kwargs(kwargs, keys=None):
"""Removes each key from kwargs dict if found
Parameters
----------
kwargs : dict
* dict of keyword args
keys : list of str, optional
* default: ['obj', 'pytan_help', 'objtype']
* list of strs of keys to remove from kwargs
Returns
... |
def msb(value: bytearray) -> int:
"""
Return the value of the highest digit of the number 'value'.
Args:
value: The number for which you want to determine the value of the
high order.
"""
return value[0] & 0x80 |
def get_pos(sequence):
"""
Get the positions of 'A', 'C',
'T', 'G' on the sequence
:param letter: the sequence
:return: the positions of 'A',
'C', 'T', 'G' on the sequence
"""
Apos = []
Cpos = []
Gpos = []
Tpos = []
length = len(sequence)
for pos in ran... |
def _even_quotient(a, b, tol=1e-6):
"""Returns a / b if it is an integer, -1 if it is not.."""
num = int(round(a / b))
if abs(a - b * num) < abs(b * tol):
return num
return -1 |
def convert_tok_str_to_sent(tok_str):
"""Returns the sentence given the subword tokens"""
res = ''
tokens = tok_str.split(' ')
for token in tokens:
if '#' in token:
token = token.replace('#', '')
res += token
else:
res = res + ' ' + token
return re... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.