content stringlengths 42 6.51k |
|---|
def cumsum(list1):
"""Return the cumulative sum of the elements at each position of list1."""
return [sum(list1[:i+1]) for i in range(len(list1))] |
def valmap(func, d, factory=dict):
""" Apply function to values of dictionary
>>> bills = {"Alice": [20, 15, 30], "Bob": [10, 35]}
>>> valmap(sum, bills) # doctest: +SKIP
{'Alice': 65, 'Bob': 45}
See Also:
keymap
itemmap
"""
rv = factory()
rv.update(zip(d.keys(), map(f... |
def get_logger(name='recibrew'):
"""
Get Logger to print something eleganlty
:param name: the logger name
:return: Logger object
"""
import logging
logger = logging.getLogger(name)
c_handler = logging.StreamHandler()
c_handler.setLevel(logging.INFO)
c_format = logging.Formatter(... |
def percent_difference(year_1_sales, year_2_sales):
""" Calculates the percentage difference in year 1 and year 2 sales.
Simple function that calculates and returns the difference in sales for 2
years.
Parameters
----------
year_1_sales : float
Total sales for year 1.
year_2_sales... |
def check_feasible(X, C):
"""Check if the current basis contains any artificial variables."""
is_feasible = True
for ind in X:
if abs(C[ind].imag) >= 1e-9:
is_feasible = False
break
return is_feasible |
def parse_units(units_str):
"""
Extract and parse the units
Extract the bounds over which the expression is assumed to apply.
Parameters
----------
units_str
Returns
-------
Examples
--------
>>> parse_units('Widgets/Month [-10,10,1]')
('Widgets/Month', (-10,10,1))
... |
def fibonacci_memory(nth_nmb: int) -> int:
"""An recursive approach to find Fibonacci sequence value, storing those already calculated."""
# Initial cache is set, hardcoded values make up the numbers for the base case
cache = {0: 0, 1: 1}
def fib_mem(_n):
if _n not in cache:
# Add... |
def is_valid_polygon(n):
"""
Returns: True if n is an int >= 3; False otherwise.
Parameter n: the value to check
Precondition: NONE (n can be any value)
"""
return (type(n) == int and 3 <= n) |
def formattext(value):
""" Filter for template. """
return value.replace('\n', '<br>') |
def nameof(sym):
"""Return the name of ``sym`` as str."""
if hasattr(sym, "name"):
return sym.name
else: # e.g. an undefined function has no name, but its *class* has a __name__.
return sym.__class__.__name__ |
def calc_tanimoto(Na, Nb):
"""Calculates the Tanimoto similarity coefficient between two sets NA and NB."""
Nab = len(set(Na).intersection((set(Nb))))
return float(Nab) / (len(Na) + len(Nb) - Nab) |
def array_pair_sum_sort(k, arr):
"""
first sort the array and then use binary search to find pairs.
complexity: O(nlogn)
"""
result = []
arr.sort()
for i in range(len(arr)):
if k - arr[i] in arr[i + 1:]:
result.append([arr[i], k - arr[i]])
return result |
def is_cdap_entity_role(role):
"""
CDAP create roles for entities by default. These roles are in the format of '.namespace', '.program' etc.
:param role: The role to judge
:return: bool: if role is a cdap entity role
"""
return role['name'].startswith(('.artifact', '.application', '.program', '.dataset', 's... |
def unset_bit(a, order):
""" Set the value of a bit at index <order> to be 0. """
return a & ~(1 << order) |
def append_subfield_from_list_to_dict(subf_list, d_dict, o_key_field_name, subfield_key_name,
subfield_name='merged_field', check=False):
# Often times, we will need to split the one data point to multiple items to be feeded into neural networks
# and after we obtain the re... |
def select_mimetype(request_headers, request_options):
"""
Returns a mimetype based on the format param or Accept header
Args:
request_headers (dict): headers from the Request object
request_options (dict): args or form fields from Request object
Returns:
... |
def mass_attenuation_coefficient(mu, rho, convert_to_um=False):
"""
Calculate the x-ray mass attenuation coefficient (mum) for a given density
(rho):
mum = mu/rho
Parameters
==========
mu: x-ray attenuation coefficient [1/um]
rho: density [g/cm3]
covnert_to_um: convert mum to g... |
def str_set_of_candidates(candset, cand_names=None):
"""
nicely format a single committee
"""
if cand_names is None:
namedset = [str(cand) for cand in candset]
else:
namedset = [cand_names[cand] for cand in candset]
return "{" + ", ".join(map(str, namedset)) + "}" |
def sorted_no_case(p_array):
"""Sort an array case insensitively, returns a sorted copy"""
p_array = list(p_array)
p_array = sorted(p_array, key=lambda x: x.upper())
return p_array |
def findCcpnDataDim(spectrum, expDim):
"""Descrn: Get the data dimension number that corresponds
to a given experimental dimension of a spectrum
Inputs: ccp.nmr.Nmr.DataSource, ccp.nmr.Nmr.ExpDim
Output: Int
"""
dataDim = None
if expDim:
dataDim = spectrum.findFirst... |
def encrypt(m,e,n):
"""
Returns decrypted message.
Parameters:
m (int): numeral message
e (int): public key
n (int): modulus
Output:
encrypted message
"""
return(pow(m,e,n)) |
def fact_imp(n: int) -> int:
""" Factorielle de n, n! = 1 * 2 * .. * n."""
f: int = 1
for i in range(2, n+1):
f = f * i # f *= i est aussi possible
return f |
def bigger(a, b):
"""This function return the largest number of two numbers."""
if a > b:
return a
else:
return b |
def loads(value):
"""Loads a base36 string and parse it into 10-based integer.
:param value: the base36 string.
:returns: the parsed integer.
"""
return int(value, 36) |
def split_file_name(d, ext):
""" Return the filename for a split-half dataframe.
:param dict d: A dictionary containing the parts of the split-half filename.
:param str ext: 'csv' for list of wellids, 'df' for dataframes
"""
if ext == 'df':
if d['norm'] == 'none':
return ... |
def distance(point1, point2):
"""
Returns the Euclidean distance of two points in the Cartesian Plane.
>>> distance([3,4],[0,0])
5.0
>>> distance([3,6],[10,6])
7.0
"""
return ((point1[0] - point2[0])**2 + (point1[1] - point2[1])**2) ** 0.5 |
def combine_two(a, b, delimiter='/'):
"""returns an n-nested array of strings a+delimiter+b
a and b (e.g. uuids and object_keys) can be a singlet,
an array, an array of arrays or an array of arrays of arrays ...
example:
>>> a = ['a','b',['c','d']]
>>> b = ['e','f',['g','h']]
>>> combine_two... |
def trace_overlap(row_candidate, row_candidates):
"""
Does any trace in `row_candidate` appear in any of `row_candidates`?
"""
# NOTE: multiple iterations over `row_candidates` - don't use generator.
for t in row_candidate:
for c in row_candidates:
if t in c:
retu... |
def _get_cqlsh_for_query(query: str):
"""
Creates a `cqlsh` command for given query that will be executed over a TLS
connection.
"""
return 'cqlsh --cqlshrc="$MESOS_SANDBOX/cqlshrc" --ssl -e "{query}"'.format(
query=query) |
def process(result_params):
"""
The main program reads the input file, processes the calculation
and writes the output file
Args:
result_params: Resulted Parameters
Returns:
final_score: Final Score
, final_result: Final Result
"""
final_score = 0
final_re... |
def to_decimal(number, base):
"""Convert a number to decimal from another base
Convert a number from any base into decimal.
Args:
number: A string representing a number in base 2 to 16.
base: The base of the number.
Returns:
An integer in base 10 of the number provided
""... |
def _parse_base_url(url: str, wkt: str, names: str):
"""Selects appropriate download request url based on WKT location string"""
# CSV allowed for single point location and single name/year
if "POINT" == wkt[:5] and len(names.split(",")) == 0:
return f"{url}.csv"
else:
return f"{url}.jso... |
def from_start(learn_from, batch_size):
"""
Select from the beginning.
Parameters
----------
learn_from : list
List of data points
batch_size : int
Number of points to select
Returns
-------
list
Selected indices.
"""
total_size = len(learn_from)
... |
def pos_byte2str(s):
"""return a list where the element value is the characther index/pos
in the string from the byte position
"""
pos_map = []
for index, c in enumerate(s):
pos_map.extend([index] * len(c.encode('utf-8')))
return pos_map |
def _canonicalize_to_list(value):
"""Canonicalize a value to a list.
If value is a list, return it. If it is None or an empty string,
return an empty list. Else, return value.
"""
if isinstance(value, list):
return value
if value == '' or value is None:
return []
return [v... |
def mean(x):
"""mean"""
return sum(x) / len(x) |
def splitargv(argv):
"""Split argv into ours and theirs. Ours ends with first non-option; e.g.,
-h --help ConfigNanny -n
splits:
-h --help ConfigNanny <<--ours theirs-->> -n
"""
which, args = 0, [[], []]
for arg in argv[1:]:
args[which].append(arg)
which = 1 if whic... |
def show_list(donor_list): # Tested
"""Convert donor key name to list."""
donor_lists = list(donor_list.keys())
donor_lists.sort()
return donor_lists |
def _value_to_numeric(value):
"""Convert a value string to a number.
Parameters
----------
value : str
Parameter value as a string.
Raises
------
ValueError
If the string cannot be converted.
Returns
-------
number
The value converted to ``int`` or ``fl... |
def parseHMS(ra_in):
""" input HHMMSS.sss '''
Decode an absolute RA value in 'funky SOSS format' (see convertToFloat()),
and return a tuple containing hours, minutes and
seconds of RA."""
# make sure that the (offset_)dec/(offset_)ra is numeric
ra_in = float(ra_in)
# then convert ... |
def format_service_listing(services, print_header=False):
"""Formats the listing of MRS services
Args:
services (list): A list of services as dicts
print_header (bool): If set to true, a header is printed
Returns:
The formated list of services
"""
if print_header:
... |
def operation_jnz(register, register_check, jump_by):
"""Jump operation. Jump if register_check is not 0."""
if register.get(register_check, register_check) != 0:
return jump_by if isinstance(jump_by, int) else register[jump_by] |
def parse_sample(sample):
"""Parse a sample. Returns List."""
return list(sample.split(",")) |
def is_iterable(value):
"""Check if value is iterable."""
try:
_ = iter(value)
return True
except TypeError:
return False |
def multi_split(s, seps):
""" Split string by multiple separators.
>>> multi_split("a,b;c:d", ",;:")
['a', 'b', 'c', 'd']
"""
if not s or not seps:
return [s]
sep = seps[0]
v = ''.join([ch if ch not in seps else sep for ch in s])
return v.split(sep) |
def b(n: int) -> int:
"""Returns the nth natural number solution for b in 2b*(b-1) = a*(a-1)."""
return (1 if n == 1 else
3 if n == 2 else
6 * b(n - 1) - b(n - 2) - 2) |
def generateId(basic, plural=None, context=None):
"""
Returns a unique message ID based on info typically stored in the code: id, plural, context
"""
result = basic
if context is not None:
result += "[C:%s]" % context
elif plural:
result += "[N:%s]" % plural
return result |
def dict_updated(dict_, entry):
"""Returns copy of dict d with updates in e"""
ret = dict_.copy()
ret.update(entry)
return ret |
def flatten(lists):
"""
Flatten a list of lists.
"""
return [item for sublist in lists for item in sublist] |
def solow_model(t, k, g, n, s, alpha, delta):
"""
Equation of motion for capital stock (per unit effective labor).
Parameters
----------
t : float
Time
k : ndarray (float, shape=(1,))
Capital stock (per unit of effective labor)
g : float
Growth rate of technology.
... |
def flatten_list(li):
"""Flatten a list by one level.
:param li: a lists of lists
"""
return [item for sublist in li for item in sublist] |
def get_printable_size(byte_size: int) -> str:
"""
A bit is the smallest unit, it's either 0 or 1
1 byte = 1 octet = 8 bits
1 kB = 1 kilobyte = 1000 bytes = 10^3 bytes
1 KiB = 1 kibibyte = 1024 bytes = 2^10 bytes
1 KB = 1 kibibyte OR kilobyte ~= 1024 bytes ~= 2^10 bytes (it usually means 1... |
def _remove_space_underscore(bitstring):
"""Removes all spaces and underscores from bitstring"""
return bitstring.replace(" ", "").replace("_", "") |
def form_command(parameters):
"""Flatten a dictionary to create a command list for use in subprocess.run()"""
command = [] if "args" not in parameters else parameters.pop("args")
for key, value in parameters.items():
if isinstance(value, list):
command.extend([key, *value])
else:... |
def sym2int(x, syms_table):
"""
convert string to int sequence
Input:
x: string
syms_table: dict
"""
x = x.strip().split()
result = []
try:
for _, i in enumerate(x):
x_int = str(syms_table[i])
result.append(x_int)
... |
def setBit(num, n):
"""
Return num with the nth bit set to 1.
"""
# Make a mask of all 0s with the nth bit set to 1.
mask = 1 << n
return num | mask |
def random(t, params):
""" Random velocity """
import random
if params == None:
b_min = 0.1
b_max = 1.0
else:
b_min = params['min']
b_max = params['max']
velocity = random.uniform(b_min, b_max)
return velocity |
def check_buzz(number: int) -> str:
"""If a integer is divisible by five function outputs buzz
Args:
number (int): integer to check if divisible by five
Returns:
str: returns buzz if divisible by five, else continues
Examples:
>>> check_buzz(3)
''
>>> check_buz... |
def len2bytes(payload: bytes) -> bytes:
"""
Generate payload length as 2 bytes, suitable for
constructing RTCM message transport.
:param bytes payload: message payload (i.e. _without_ header, length or CRC)
:return: payload length as 2 bytes padded with leading zeros
:rtype: bytes
"... |
def get_intersect(x1, y1, x2, y2, x3, y3, x4, y4):
"""
:param x1: x position of the first rect's upplerleft point
:param y1: y position of the first rect's upplerleft point
:param x2: x position of the first rect's lowerright point
:param y2: y position of the first rect's lowerright point
:para... |
def define_intent_name(scenario, intent):
"""Intent name is defined as concatenation of `scenario` and `intent`
values.
See Also:
https://github.com/xliuhw/NLU-Evaluation-Data/issues/5
"""
return f"{scenario}_{intent}" |
def labels_to_numbers(labels1, labels2):
"""
Turn labels, eg. [tfoj, tfoz]
into numbers, e.g [0, 1]
"""
uniques = list(set(labels1 + labels2))
mapping = {}
for i, label in enumerate(uniques):
mapping[label] = i
return [mapping[label] for label in labels1], [mapping[label] for lab... |
def researched_before(technology, timestamp, player):
"""Check if a technology was researched before a given time."""
for item in player['research']:
if item['technology'] == technology and item['timestamp'] < timestamp:
return True
return False |
def normalize_hue_transition(transition):
"""Return rounded transition values."""
if transition is not None:
# hue transition duration is in milliseconds and round them to 100ms
transition = int(round(transition, 1) * 1000)
return transition |
def _get_file_rows_cols(rows=None, cols=None, ann_info=None, rsc_data=None):
"""Wrapper function to find file width for different satellite types"""
if rows is not None and cols is not None:
return rows, cols
elif (not rsc_data and not ann_info) or (rsc_data and ann_info):
raise ValueError(
... |
def split_sections(diff):
"""
takes a git diff and breaks it up into sections
:param diff: a diff piped from git
:return: a list of sections
"""
sections = []
section = ''
for line in diff.splitlines():
line = line.strip()
if line.startswith('@@'):
if section... |
def str_to_bool(s: str) -> bool:
"""Helper function to parse boolean flags received from the commead line"""
if s.lower() in {'y', 'yes', 'true'}:
return True
if s.lower() in {'n', 'no', 'false'}:
return False
raise ValueError(f"Argument value {s} is neither 'true' or 'false'") |
def is_BST_recurse(root, low, high):
"""Returns True iff the tree is a BST and fits between low and high."""
if not root:
return True
return low < root.data < high and \
is_BST_recurse(root.left, low, root.data) and \
is_BST_recurse(root.right, root.data, high) |
def to_pass(line):
"""
Replace a line of code with a pass statement, with
the correct number of leading spaces
Arguments
----------
line : str, line of code
Returns
----------
passed : str, line of code with same leading spaces
but code replaced with pass statemen... |
def fuzzy_equal(x, y, z):
""" Fuzzy equal
Args:
x (ndarray): input a
y (ndarray): input b
z (ndarray): uncertainty of input a
Returns:
ndarray : bool array
"""
return (y < (x + z)) & (y > (x - z)) |
def split_labels(lst):
"""
Takes a list of tuples of the form (input, label)
Returns 2 lists, one of inputs and one of labels
"""
return tuple(zip(*lst)) |
def saffir_simpson_scale(spd):
"""Static method that returns the equivalent saffir-simpson scale rating,
based on wind-speed in knots.
This is the most-common index used to generalize tropical cyclone
intensity.
Example: saffir_simpson(100) --> 3 (implying category 3).
"""
if 34 <= spd < 6... |
def satlins(n):
"""
Symmetric Saturating Linear
"""
if n < -1:
return -1
elif n > 1:
return 1
else:
return n |
def threshold_check(errors, threshold, length):
"""Check that returns an error if the PPM threshold is surpassed."""
if length > 0:
errcount = len(errors)
ppm = (errcount / length) * 1e6
if ppm >= threshold and errcount >= 1:
return [errors[0]]
return [] |
def removeFeedbackReport(report, noFeedback=False, isChecker=False):
"""Remove the feedback from an execution report, if the test has hidden
results."""
if not noFeedback:
return report
report.update({
'noFeedback': True,
'commandLine': '',
'files': []
})
re... |
def draw_point(r, g, b, m, n, grid):
"""Draws a point on the ppm grid
Arguments
---------
r, g, b -- RGB values for the point
m, n -- row, column
grid -- ppm grid being edited
"""
grid[m][n][0], grid[m][n][1], grid[m][n][2] = r, g, b
return grid |
def _to_unicode(s):
"""
decode a string as ascii or utf8 if possible (as required by the sftp
protocol). if neither works, just return a byte string because the server
probably doesn't know the filename's encoding.
"""
try:
return s.encode('ascii')
except (UnicodeError, AttributeErr... |
def mapValue(value, in_min, in_max, out_min, out_max):
"""
Returns a new value mapped in a desired range.
Parameters:
value: value to be mapped
in_min - in_max: limits of the range where the value is
out_min - out_max: limits of the range where the value will be mapped
"""
... |
def add_to_pvi(pvi, ctupre, label, value):
"""Adds the pvi to the data dict"""
if pvi != 1000:
try:
pvi[ctupre] = dict(pvi[ctupre].items() + {label: value}.items())
except KeyError:
pvi[ctupre] = {label: value}
return pvi |
def formatBytes(value, multiplier=None, asBits=False):
"""Special data-type for byte values"""
KILOBYTES = 1024.0
MEGABYTES = KILOBYTES * 1024
GIGABYTES = MEGABYTES * 1024
TERABYTES = GIGABYTES * 1024
displayNames = [
(TERABYTES, 'TB'),
(GIGABYTES, 'GB'),
(MEGABYTES, 'MB... |
def calculate_percentile_rank(array, score):
"""Get a school score's percentile rank from an array of cohort scores."""
true_false_array = [value <= score for value in array]
if len(true_false_array) == 0:
return
raw_rank = float(sum(true_false_array)) / len(true_false_array)
return int(roun... |
def _format_result(counts, cl_reg_index, cl_reg_nbits):
"""Format the result bit string.
This formats the result bit strings such that spaces are inserted
at register divisions.
Args:
counts (dict): dictionary of counts e.g. {'1111': 1000, '0000':5}
cl_reg_index (list): starting bit in... |
def _split_into_blocks_generic(sample_values, epoch_size_samples):
"""
Split an array into blocks of the specified size, the last block may be smaller.
"""
num_windows = (len(sample_values) + epoch_size_samples - 1) // epoch_size_samples
epochs = [None] * num_windows
for index in range(len(epoch... |
def FilterName(namefilter, safechar='P', reserved_names=None):
"""Get a safe program or variable name that can be used for robot programming"""
# remove non accepted characters
for c in r' -[]/\;,><&*:%=+@!#^|?^':
namefilter = namefilter.replace(c, '')
# remove non english characters
... |
def _world2region(world_point, region_origin):
"""
Given `world_point` (x,y,z) in world coordinate (i.e. full gmapping map coordinate),
and the origin of the rectangular region, also in world coordinate,
returns the world point in region's coordinate frame. The region's
points will have the same res... |
def noneToValue(value, newValue):
"""Convert ``None`` to a different value.
Args:
value: The value to convert. This can be anything.
newValue: The resultant value. This can be anything.
Returns:
newValue
"""
if value is None:
return newValue
else:
retur... |
def get_idxpairs(cc_pair: dict, w2idx: list) -> list:
"""
The generate_center_context_pair gives a dictionary like:
{'center word 1': ['contextword1', 'contextword2', '...']
'centerword2': ['contextword1', 'contextword2', '...']}
But the code from the blog needs cc_pair like:
[['centerword1', '... |
def tunegaussmf(mean, sigma, param1, param2):
"""
Tunes the mean and standard deviation of a Gaussian MF
----------------------
:param mean: The mean of the MF
:param sigma: The S.D. of the MF
:param param1: parameter 1 for tuning mean
:param param2: parameter 2 for tuning sigma
:return... |
def get_positive_or_none(value):
""" Get positive value or None (used to parse simulation step parameters)
:param value: Numerical value or None
:return: If the value is positive, return this value. Otherwise, return None.
"""
if value is None:
return None
else:
return value if v... |
def slope(first_point, second_point):
"""
Returns the slope between 2 points
:param first_point: first point (x,y)
:param second_point: second point (x,y)
:return: the slope
"""
return 0. if first_point[0] == second_point[0] else\
((float(first_point[1]) - float(second_point[1])) / ... |
def decode(encoded: list) -> str:
"""
>>> decode([13, 25, 14, 1, 13, 5])
'myname'
"""
return "".join(chr(elem + 96) for elem in encoded) |
def same(left, right):
"""
Used for testing that thing link system names are the same (they
can be supplied in different cases - upper or lower).
returns True if they should be treated as the same
"""
return str(left).upper() == str(right).upper() |
def publish_devices(path_list, *_, **__):
"""
Returns paths as "--device" or "--mount" arguments.
Fall back to "--privileged" if no devices found.
Args:
path_list (str): List of devices paths, one path per line.
Returns:
str: arguments
"""
return ' '.join(
f'--devi... |
def offset2line(offset, linestarts):
"""linestarts is expected to be a *list) of (offset, line number)
where both offset and line number are in increasing order.
Return the closes line number at or below the offset.
If offset is less than the first line number given in linestarts,
return line number... |
def has_valid_extension(filename, extensions):
"""Checks if a file is an allowed extension.
Args:
filename (string): path to a file
extensions (tuple of strings): extensions to consider (lowercase)
Returns:
bool: True if the filename ends with one of given extensions
"""
re... |
def flatten2list(object) -> list:
"""Flatten to list nested objects of type list, tuple, sets."""
gather = []
for item in object:
if isinstance(item, (list, tuple, set)):
gather.extend(flatten2list(item))
else:
gather.append(item)
return gather |
def intersection(list1, list2):
"""Combines two lists into a set (i.e. no duplicates) composed of those
elements common to both lists"""
return list(set(list1).intersection(set(list2))) |
def cz_alphadot(cm_i, ep_alpha):
"""This calculates the coefficient of force in the z direction with
respect to the rate of change of the alpha of attack of the aircraft
Assumptions:
None
Source:
J.H. Blakelock, "Automatic Control of Aircraft and Missiles"
Wiley & Sons, Inc. New ... |
def _fragment_score_label_similarity(left_fragment, right_fragment):
"""Given two fragments return their similarity.
:param left_fragment:
:param right_fragment:
:return:
"""
# Topology must be the same.
if not left_fragment["value"] == right_fragment["value"]:
return 0
similari... |
def is_binary_palindrome(num):
"""Return True if num is binary palindromic."""
num = bin(num)
num = num[2:]
return num == num[::-1] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.