content stringlengths 42 6.51k |
|---|
def map_structure(operation, *param_groups):
""" Expects a pair of list of lists of identical structure representing
two sets of parameter states. This will apply the desired operation to
each element in the two groups
:param param_groups_1: The first parameter group
:param param_groups_2: The secon... |
def get_match(match, index, default=''):
"""
Returns a value from match list for a given index. In the list is out of
bounds `default` is returned.
"""
if index >= len(match):
return default
else:
return match[index] |
def reformat_params(params):
"""Transform from pygmm input to spreadsheet input."""
if "mechanism" in params:
# Replace mechanism with flags
mech = params.pop("mechanism")
if mech == "SS":
params["flag_u"] = 0
params["flag_rv"] = 0
params["flag_nm"] = ... |
def drude(ep, eb, gamma, e):
"""dielectric function according to Drude theory"""
eps = 1 - (ep ** 2 - eb * e * 1j) / (e ** 2 + 2 * e * gamma * 1j) # Mod drude term
return eps |
def clean_names(names):
"""Removes whitespace from channel names, useful sometimes when comparing
lists of channels.
Parameters
----------
names : list
List of channel names
Returns
-------
list
Returns list of channel names without any whitespace.
"""
return [... |
def shell_sort(arr):
"""Shell Sort
Complexity: O(n^2)
:param arr: The input array, unsorted.
:return arr: The sorted array
"""
n = len(arr)
# Initialize size of the gap
gap = n // 2
while gap > 0:
y_index = gap
while y_index < len(arr):
y = arr[... |
def knapval_rep(capacity, items):
"""
Returns the maximum value achievable in 'capacity'
weight using 'items' when repeated items are allowed
"""
options = list(
item.value + knapval_rep(capacity-item.weight, items) for item in items if item.weight <= capacity)
if len(options):
r... |
def capitalize_name(name):
"""
:param name: a string containing a name
:return: the string where the first letter of every token is capitalized
"""
tokens = name.split(" ")
tokens_capitalized = [token[0].upper()+token[1:].lower() for token in tokens]
return " ".join(tokens_capitaliz... |
def format_collapse(ttype, dims):
"""
Given a type and a tuple of dimensions, return a struct of
[[[ttype, dims[-1]], dims[-2]], ...]
>>> format_collapse(int, (1, 2, 3))
[[[<class 'int'>, 3], 2], 1]
"""
if len(dims) == 1:
return [ttype, dims[0]]
else:
return format_colla... |
def decode_string(v, encoding="utf-8"):
""" Returns the given value as a Unicode string (if possible).
"""
if isinstance(encoding, str):
encoding = ((encoding,),) + (("windows-1252",), ("utf-8", "ignore"))
if isinstance(v, bytes):
for e in encoding:
try:
retur... |
def _guess_type_from_network(network):
"""
Return a best guess of the type of network (road, hiking, bus, bicycle)
from the network tag itself.
"""
if network in ['iwn', 'nwn', 'rwn', 'lwn']:
return 'hiking'
elif network in ['icn', 'ncn', 'rcn', 'lcn']:
return 'bicycle'
el... |
def read_vx(pointdata):
"""Read a variable-length index."""
if pointdata[0] != 255:
index = pointdata[0] * 256 + pointdata[1]
size = 2
else:
index = pointdata[1] * 65536 + pointdata[2] * 256 + pointdata[3]
size = 4
return index, size |
def get_volume():
"""
Example of amixer output :
Simple mixer control 'Master',0
Capabilities: pvolume pswitch pswitch-joined
Playback channels: Front Left - Front Right
Limits: Playback 0 - 65536
Mono:
Front Left: Playback 40634 [62%] [on]
Front Right: Playback 40634 [62%] [on]
"""
retu... |
def get_hosts_ram_usage_ceilo(ceilo, hosts_ram_total):
"""Get ram usage for each host from ceilometer
:param ceilo: A Ceilometer client.
:type ceilo: *
:param hosts_ram_total: A dictionary of (host, total_ram)
:type hosts_ram_total: dict(str: *)
:return: A dictionary of (host, ram_usage)
... |
def iterable(obj):
"""Return true if the argument is iterable"""
try:
iter(obj)
except TypeError:
return False
return True |
def center_y(cell_lower_left_y, cell_height, y0, word_height):
""" This function centers text along the y-axis
:param cell_lower_left_y: Lower left y-coordinate
:param cell_height: Height of cell in which text appears
:param y0: Lower bound of text (sometimes can be lower than cell_lower_left-y (i.e. l... |
def bstr_to_set(b):
"""
Convert a byte string to a set of the length-1 bytes obejcts within it.
"""
return set(bytes([c]) for c in b) |
def calc_p_ratio(hps, nhps, total_hps, total_nhps):
"""
Returns a ratio between the proportion hps/nhps to the proportion nhps/hps. The larger proportion will be the
numerator and the lower proportion will be the denominator (and thus the p-ratio>=1).
This corrects for the total_hps/total_nhps imbalance... |
def segno(x):
"""
Input: x, a number
Return: 1.0 if x>0,
-1.0 if x<0,
0.0 if x==0
"""
if x > 0.0: return 1.0
elif x < 0.0: return -1.0
elif x == 0.0: return 0.0 |
def clean_arguments(args: dict) -> dict:
"""Cleans up a dictionary from keys containing value `None`.
:param args: A dictionary of argument/value pairs generated with ArgumentParser
:return: A dictionary with argument/value pairs without `None` values
:rtype: dict
"""
rv = {}
for (key, val)... |
def is_error_yandex_response(data: dict) -> bool:
"""
:returns: Yandex response contains error or not.
"""
return ("error" in data) |
def convert_edition_to_shortform(edition):
"""Convert edition to shortform Enterprise or Community or N/E"""
if edition.lower() in ['enterprise', 'true', 'ee'] or 'enterprise' in edition.lower():
return "Enterprise"
if edition.lower() in ['community', 'false', 'ce'] or 'community' in edition.lower... |
def betterFib(n):
"""
Better implementation of nth Fibonacci number generator
Time complexity - O(n)
Space complexity - O(n)
:param n: The nth term
:return: The nth fibonnaci number
"""
fib = [None] * n
#print fib
if n == 0:
return 0
elif n == 1:
return 1
... |
def irange(start, end):
"""Inclusive range from start to end (vs. Python insanity.)
irange(1,5) -> 1, 2, 3, 4, 5"""
return range( start, end + 1 ) |
def extract_cfda(field, type):
""" Helper function representing the cfda psql functions """
extracted_values = []
if field:
entries = [entry.strip() for entry in field.split(';')]
if type == 'numbers':
extracted_values = [entry[:entry.index(' ')] for entry in entries]
els... |
def strip_article_title_word(word:str):
"""
Used when tokenizing the titles of articles
in order to index them for search
"""
return word.strip('":;?!<>\'').lower() |
def successResponse(response):
"""
Format the given object as a positive response.
"""
response = str(response)
return '+OK %s\r\n' % (response,) |
def component_src_subdir(category, type):
"""name of the subdir of component source to be generated
"""
return '%s_%s' % (category, type) |
def line(k, x):
""" line function """
return k[0]*x + k[1] |
def find_intersection(*args):
"""Find intersecting list of values between an arbitrary number of arguments.
:return: Returns list[] containing intersecting values.
"""
# Original case:
# unique_codes = list(country_codes['ped'].intersection(country_codes['gtd'].intersection(country_cod... |
def _to_hass_temperature(temperature):
"""Convert percentage to Home Assistant color temperature units."""
return int(temperature * 346) + 154 |
def _shorten_name(name):
"""Format asset name to ensure they match the backend requirements."""
if len(name) < 100:
return name
return name[:75] + '...' + name[:20] |
def camelize(src: str) -> str:
"""Convert snake_case to camelCase."""
components = src.split("_")
return components[0] + "".join(x.title() for x in components[1:]) |
def _make_filename_from_pytest_nodeid(nodeid):
"""Transforms pytest nodeid to safe file name"""
return (nodeid.lower()
.replace('/', '_')
.replace(':', '_')
.replace('.', '_')) |
def subset_of_dict(dict, chosen_keys):
"""make a new dict from key-values of chosen keys in a list"""
return {key: value for key, value in dict.items() if key in chosen_keys} |
def build_query_from_table(name):
""" Create a query given the table name
Args:
name: Table name
Returns:
query string
"""
return "SELECT * FROM {0}".format(name) |
def _GenerateQueryParameters(parameters):
"""Generates query parameters using parameters.
Reference: https://goo.gl/SyALkb.
Currently this function only supports parameters of a single value. To support
struct or array parameters, please refer to the link above.
Args:
parameters ([tuples]): A list of p... |
def is_inconsistent(results_dict, iterations):
"""Return whether or not a single test is inconsistent."""
return len(results_dict) > 1 or sum(results_dict.values()) != iterations |
def _decode_int(data):
"""
decode integer from bytearray
return int, remaining data
"""
data = data[1:]
end = data.index(b'e')
return int(data[:end],10), data[end+1:] |
def xmltag_split2(tag, namespaces, colon=False):
"""Return XML namespace prefix of element"""
try:
nsuri = tag.split('}')[0].split('{')[1]
nsprefix = [key for key, value in namespaces.items()
if value == nsuri]
value = nsprefix[0]
if colon:
return ... |
def _get_spm_arch(swift_cpu):
"""Maps the Bazel architeture value to a suitable SPM architecture value.
Args:
bzl_arch: A `string` representing the Bazel architecture value.
Returns:
A `string` representing the SPM architecture value.
"""
# No mapping at this time.
return swif... |
def crc8P1(byteData):
"""
Generate 8 bit CRC of supplied string + 1
eg as used in REVO PI30 protocol
"""
CRC = 0
for b in byteData:
CRC = CRC + b
CRC += 1
CRC &= 0xFF
return CRC |
def remove_whitespace (string):
"""
Useless function how remove all whitespaces of string
@type string: numpy str
@param string: The string with whitespaces
@rtype: str
@return: Return the saem string but whitout whitespaces
"""
if (type(string) is not str):
raise TypeError('Type of stri... |
def usage(prtflag):
"""
Do something with the usage message.
If the prtflag parameter is non-zero, we'll print and exit.
If it is zero, we'll just return the string.
"""
#
# Set up our usage string.
#
outstr = """zeek-grep [options]
where [options] are:
-filter - define a filter for search log f... |
def protobuf_get_constant_type(proto_type) :
"""About protobuf write types see :
https://developers.google.com/protocol-buffers/docs/encoding#structure
+--------------------------------------+
+ Type + Meaning + Used For +
+--------------------------------------+
+ + + i... |
def write_arbitrary_beam_section(inps, ts, branch_paths, nsm, outp_id, core=None):
"""writes the PBRSECT/PBMSECT card"""
end = ''
for key, dicts in [('INP', inps), ('T', ts), ('BRP', branch_paths), ('CORE', core)]:
if dicts is None:
continue
# dicts = {int index : int/float value... |
def complement(y, n):
"""Complement of y in [0,...,n-1]. E.g. y = (0,2), n=4, return [1,3]."""
return sorted(list(set(range(n)) - set(y))) |
def get_music(song):
"""Artists who intoned the text"""
artists = [contributor['contributor_name'] for contributor in song['contributors']]
artists = [a for a in artists if a is not None]
if len(artists) == 0 and song['song_description']:
return song['song_description']
elif len(artists) > 2... |
def bitmask(str):
"""
bitmask from character string
"""
res = []
for ci in range(0, len(str)):
c = str[ci]
for i in range(0, 8):
res.append(((ord(c) << i) & 0x80) >> 7)
return res |
def zfp_rate_opts(rate):
"""Create compression options for ZFP in fixed-rate mode
The float rate parameter is the number of compressed bits per value.
"""
zfp_mode_rate = 1
from struct import pack, unpack
rate = pack('<d', rate) # Pack as IEEE 754 double
high = unpack('<I', rate[0:4])[0] ... |
def anisotropy_from_intensity(Ipar, Iper):
"""
Calculate anisotropy from crossed intensities values.
"""
return (Ipar - Iper)/(Ipar + 2*Iper) |
def _get_positional_body(*args, **kwargs):
"""Verify args and kwargs are valid, and then return the positional body, if users passed it in."""
if len(args) > 1:
raise TypeError("There can only be one positional argument, which is the POST body of this request.")
if args and "options" in kwargs:
... |
def fib_iter(number):
"""Funkce vypocita number-te finonacciho cislo pomoci linearniho
iterativniho algoritmu.
0. fibonacciho cislo je 0, 1. je 1
"""
if number == 0:
return 0
lower = 0
higher = 1
for i in range(number - 1):
lower, higher = higher, lower + higher
retu... |
def fsplit(pred, objs):
"""Split a list into two classes according to the predicate."""
t = []
f = []
for obj in objs:
if pred(obj):
t.append(obj)
else:
f.append(obj)
return (t, f) |
def compute_anchored_length(qry_aln_beg, qry_aln_end, ref_aln_beg, ref_aln_end,
aln_len, qry_len, ref_len):
"""
Compute the maximal length of the alignable region anchored by the best hit
"""
if qry_aln_beg < qry_aln_end:
qab = qry_aln_beg
qae = qry_aln_end
... |
def transform_data(data_array):
"""Trasnform a matrix with String elements to one with integers."""
transformed_data = []
n = len(data_array)
for row in range(0, n):
temp = []
for elem in range(0, n):
temp.append(int(data_array[row][elem]))
transformed_data.append(tem... |
def NcbiNameLookup(names):
"""Returns dict mapping taxon id -> NCBI scientific name."""
result = {}
for name in names:
if name.NameClass == "scientific name":
result[name.TaxonId] = name
return result |
def overlap(start1, end1, start2, end2):
"""Does the range (start1, end1) overlap with (start2, end2)?"""
return not (end1 < start2 or end2 < start1) |
def display_list_by_prefix(names_list, starting_spaces=0):
"""Creates a help string for names_list grouped by prefix."""
cur_prefix, result_lines = None, []
space = " " * starting_spaces
for name in sorted(names_list):
split = name.split("_", 1)
prefix = split[0]
if cur_prefix !... |
def multiply_matrix_by_real(a, real):
"""
Return result of real*a
:param a: a 2 dimensional array
:param real: a real
:return: a 2 dimensional array
"""
return [[j*real for j in i] for i in a] |
def obj_id(obj):
"""Return the last four digits of id(obj), for dumps & traces."""
return str(id(obj))[-4:] |
def convert(x):
"""
function takes x which is an array in the form
x = [(station, distance), ......] // note station is an object
and returns an array in the form of
[(station.name, station.town, distance ), ......]
"""
res_arr = []
for tuple in x:
res_arr.append((tuple[0].n... |
def one_of_k_encoding_unk(x, allowable_set):
"""Maps inputs not in the allowable set to the last element."""
if x not in allowable_set:
x = allowable_set[-1]
return list(map(lambda s: x == s, allowable_set)) |
def bboxFromString(bboxStr):
""" Get bbox dictionary from comma separated string of the form
'-76.769782 39.273610 -76.717498 39.326008'
@param bboxStr String representing bounding box in WGS84 coordinates
@return Dict representing bounding box with keys: minX, minY, maxX, maxY, and srs... |
def _AddLabels(existing_labels, labels_to_add):
"""Adds labels in labels_to_add to existing_labels."""
updated_labels = existing_labels + labels_to_add
return list(set(updated_labels)) |
def which(program):
"""Returns full path to `program` if found in $PATH or else None
if the executable is not found.
SRC: http://stackoverflow.com/a/377028/983310
"""
import os
def is_exe(fpath):
return os.path.isfile(fpath) and os.access(fpath, os.X_OK)
fpath, fname = os.path.split... |
def get_magic_number(divisor, word_size):
"""
Given word size W >= 1 and divisor d, where 1 <= d < 2**W,
finds the least integer m and integer p such that
floor(mn // 2**p) == floor(n // d) for 0 <= n < 2**W
with 0 <= m < 2**(W+1) and p >= W.
Implements the algorithm described by Hacker's D... |
def solve(arr: list) -> int:
""" This function returns the difference between the count of even numbers and the count of odd numbers. """
even = []
odd = []
for item in arr:
if str(item).isdigit():
if item % 2 == 0:
even.append(item)
else:
... |
def _pylontech_quirk(dvcc, bms, charge_voltage, charge_current, feedback_allowed):
""" Quirk for Pylontech. Make a bit of room at the top. Pylontech says that
at 51.8V the battery is 95% full, and that balancing starts at 90%.
53.2V is normally considered 100% full, and 54V raises an alarm. By
running the ... |
def fib_loop(num):
"""
Finds the N-th fibonacci number using ordinary for-loop.
:param int num: The N-th fibonacci number (index).
:return: Computed number.
"""
if num < 2:
return num
first, second = 0, 1
for i in range(2, num + 1):
first, second = second, first + secon... |
def matrix_inverse(matrix):
"""Docstring"""
dimension = len(matrix)
con = 0.0
for k in range(dimension):
con = matrix[k][k]
matrix[k][k] = 1
for j in range(dimension):
matrix[k][j] = matrix[k][j]/con
for i in range(dimension):
if i != k:
... |
def diff(rankx, ranky):
""" Return the difference of valuations rankx and ranky.
Trivial, but included for consistency with other modules.
"""
return float(ranky - rankx) |
def _apply_decreasing_rate(value: float, rate: float) -> float:
"""
Apply a decreasing rate to a value
:param value: current value
:param rate: per second
:return: updated value
"""
return value - (60 * rate) |
def _check_frequency(frequency):
"""Check given frequency is valid."""
if frequency is None:
frequency = 'monthly'
if frequency not in ('daily', 'monthly'):
raise ValueError("Unsupported frequency '%r'" % frequency)
return frequency |
def can_merge(a, b):
"""
Test if two cubes may be merged into a single cube (their bounding box)
:param a: cube a, tuple of tuple ((min coords), (max coords))
:param b: cube b, tuple of tuple ((min coords), (max coords))
:return: bool, if cubes can be merged
"""
c = 0 # Count the number of ... |
def make_full_path(path, name):
""" Combine path and name to make full path"""
if path == "/":
full_path = "/" + name
else:
assert not path.endswith('/'), "non-root path ends with '/' (%s)" % path
full_path = path + "/" + name
# remove any duplicate slashes, should be unnecessary
... |
def sum_rec_goingup_idx(x, i, j):
"""
"""
if i < j:
return x[i] + sum_rec_goingup_idx(x, i + 1, j)
if i == j:
return x[i]
return 0 |
def get_regexp_pattern(regexp):
"""
Helper that returns regexp pattern from given value.
:param regexp: regular expression to stringify
:type regexp: _sre.SRE_Pattern or str
:returns: string representation of given regexp pattern
:rtype: str
"""
try:
return regexp.pattern
ex... |
def odd_desc(count):
"""
Replace ___ with a single call to range to return a list of descending odd numbers ending with 1
For e.g if count = 2, return a list of 2 odds [3,1]. See the test below if it is not clear
"""
return list(reversed(range(1,count*2,2))) |
def highlight_text(text):
"""Returns text with html highlights.
Parameters
----------
text: String
The text to be highlighted.
Returns
-------
ht: String
The text with html highlight information.
"""
return f"""<code style="background:yellow; color:black; padding-top: ... |
def sub_dir_by_split(d):
""" build out the split portion of the results directory structure.
:param dict d: A dictionary holding BIDS terms for path-building
"""
return "_".join([
'-'.join(['parby', d['parby'], ]),
'-'.join(['splby', d['splby'], ]),
'-'.join(['batch', d['batch'],... |
def convert_to_unicode(text):
"""Converts `text` to Unicode (if it's not already)."""
if isinstance(text, str):
return text
elif isinstance(text, bytes):
return text.decode('utf-8', 'ignore')
else:
raise ValueError('Unsupported string type: %s' % (type(text))) |
def factorial(n):
""" Returns the factorial of n.
"""
f = 1
while (n > 0):
f = f * n
n = n - 1
return f |
def _preprocess_and_filter_original_dataset(data):
"""Filters out badly visible or uninteresting signs."""
label_order = ("EMPTY", "50_SIGN", "70_SIGN", "80_SIGN")
filtered_data = []
for image, signs in data:
if not signs:
filtered_data.append((image, label_order.index("EMPTY")))
else:
# t... |
def sqrt(n: int) -> int:
"""Gets the integer square root of an integer rounded toward zero."""
return int(n ** 0.5) |
def kwattr(d, name, default=None):
"""Return attribute, converted to lowercase."""
v = d.get(name, default)
if v != default and v is not None:
v = v.strip().lower()
v = v or default
return v |
def _getImport(libs, val):
"""
Dynamically imports a library into memory for referencing during configuration file parsing.
Args:
libs (list): The list of libraries already imported.
val (str): The name of the new library to import.
Returns:
(str): The name of the new... |
def nested_map(fn, x, iter_type=list):
"""
A python analogue to BPL "apply_to_nested"
https://github.com/brendenlake/BPL/blob/master/stroke_util/apply_to_nested.m
"""
if isinstance(x, iter_type):
return [nested_map(fn, elt) for elt in x]
else:
return fn(x) |
def count_sixes(results):
"""
Count the number of sixes in a list of integers.
"""
return sum(1 for roll in results if roll == 6) |
def sol(arr, n, k):
"""
Store the position of the element in a hash and keep updating it
as we go forward. If the element already exists in the hash check
the distance between them and return True if it is <= k
"""
h = {}
for i in range(n):
if arr[i] in h:
pos = h[arr[i... |
def distance_xy(p1, p2):
"""Calculates 2D distance between p1 and p2. p1 and p2 are vectors of
length >= 2."""
return ((p1[0]-p2[0])**2 + (p1[1]-p2[1])**2)**0.5 |
def crop_axis(points, axis_number):
"""keeps only the axis_number most important axis"""
return [point[:axis_number] for point in points] |
def make_ping(userid):
"""Turn a user ID into a ping"""
return f"<@{userid}>" |
def __wavelength_to_rgb(wavelength, gamma=0.8):
"""Not intended for use by users, See noah.org: http://www.noah.org/wiki/Wavelength_to_RGB_in_Python .
Parameters
----------
wavelength : `float` or `int`
wavelength of light
gamma : `float`, optional
output gamma
Returns
----... |
def append_str_to(append_to: str, *args, sep=", ", **kwargs):
"""Concatenate to a string.
Args:
append_to(str): The string to append to.
args(list): list of string characters to concatenate.
sep(str): Seperator to use between concatenated strings.
kwargs(dict): Mapping of variabl... |
def is_degrading(metric_value, best_metric_value, metric):
"""Return true if metric value is degrading."""
if metric not in ['spr', 'rmse', 'pearson', 'both']:
raise Exception('Unsupported metric: {}'.format(metric))
if metric == 'both':
spr = metric_value[0]
rmse = metric_value[1]
... |
def _get_tag_value(x, i=0):
""" Get the nearest to 'i' position xml tag name.
x -- xml string
i -- position to start searching tag from
return -- (tag, value) pair.
e.g
<d>
<e>value4</e>
</d>
result is ('d', '<e>value4</e>')
"""
x = x.strip()
va... |
def validate_subnet_input(subnetCount, host_bits):
"""
Validates Subnet count input
:param subnetCount: Subnet count from user input
:param host_bits: Number of host bits of from the network object
:return: 'valid' if subnetCount is valid, Invalid reason otherwise
"""
if subnetCount.isnumeri... |
def indented_entry_to_str(entries, indent=0, sep=' '):
"""Pretty formatting."""
# Get the longest keys' width
width = max([len(t[0]) for t in entries])
output = []
for name, entry in entries:
if indent > 0:
output.append(f'{"":{indent}}{name:{width}}{sep}{entry}')
else:
... |
def intsqrt(x):
"""
Return the largest integer whose square is less than or equal to x.
"""
if x == 0:
return 0
# invariant: l^2 <= x and x < r^2
l = 1
r = x
while r-l > 1:
m = l + (r-l)//2
s = m*m
if s <= x:
l = m
else:
r =... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.