content stringlengths 42 6.51k |
|---|
def normalize(name):
"""
We normalize directory names to fix some name misalignments in vad/snr data,
unzipped data, and the original meta-data jsons. Examples:
- SNR has typical format of `.../1000things_1807_librivox_wav/1000things_00_fowler.wav`,
when the correspoding meta-data is in `1000things_1807_librivox_64kb_mp3_metadata.json`
- unzipped/converted flac is in `.../rock_me_to_sleep_1502/` while the correspoding meta-data
is in `.../rock_me_to_sleep_1502.poem_librivox_64kb_mp3_metadata.json`
The normalization is done by removing the suffixes removed/added by ffmpeg.
"""
for suffix in ['.poem_', '_librivox', '_64kb', '_wav']:
pos = name.find(suffix)
if pos != -1:
name = name[:pos]
return name
return name |
def get_data_ranges(bin_path, chunk_size):
"""Get ranges (x,y,z) for chunks to be stitched together in volume
Arguments:
bin_path {list} -- binary paths to tif files
chunk_size {list} -- 3 ints for original tif image dimensions
Returns:
x_range {list} -- x-coord int bounds for volume stitch
y_range {list} -- y-coord int bounds for volume stitch
z_range {list} -- z-coord int bounds for volume stitch
"""
x_curr, y_curr, z_curr = 0, 0, 0
tree_level = len(bin_path)
for idx, i in enumerate(bin_path):
scale_factor = 2 ** (tree_level - idx - 1)
x_curr += int(i[2]) * chunk_size[0] * scale_factor
y_curr += int(i[1]) * chunk_size[1] * scale_factor
# flip z axis so chunks go anterior to posterior
z_curr += int(i[0]) * chunk_size[2] * scale_factor
x_range = [x_curr, x_curr + chunk_size[0]]
y_range = [y_curr, y_curr + chunk_size[1]]
z_range = [z_curr, z_curr + chunk_size[2]]
return x_range, y_range, z_range |
def fix_compile(remove_flags):
"""
Monkey-patch compiler to allow for removal of default compiler flags.
"""
import distutils.ccompiler
def _fix_compile(self, sources, output_dir=None, macros=None, include_dirs=None, debug=0,
extra_preargs=None, extra_postargs=None, depends=None):
for flag in remove_flags:
if flag in self.compiler_so:
self.compiler_so.remove(flag)
macros, objects, extra_postargs, pp_opts, build = self._setup_compile(output_dir, macros,
include_dirs, sources, depends, extra_postargs)
cc_args = self._get_cc_args(pp_opts, debug, extra_preargs)
for obj in objects:
try:
src, ext = build[obj]
except KeyError:
continue
self._compile(obj, src, ext, cc_args, extra_postargs, pp_opts)
return objects
distutils.ccompiler.CCompiler.compile = _fix_compile |
def join_filters(*filters):
"""Joins multiple filters"""
return "[in]{}[out]".format("[out];[out]".join(i for i in filters if i)) |
def _handleTextNotes(s):
"""Split text::notes strings."""
ssplit = s.split('::', 1)
if len(ssplit) == 1:
return s
return u'%s<notes>%s</notes>' % (ssplit[0], ssplit[1]) |
def decode_state(state_id, vert_num, al_size):
"""Converts integer id to state.
Can also be applied to np.array with multiple state ids.
"""
return [(state_id // (al_size ** j)) % al_size for j in range(vert_num)] |
def parse_paths_as_list(arg):
"""
Allow singular path string or list of path strings
:param arg: This could be a string... or it could be a list of strings! Who knows what could happen?
:return: List of strings
"""
invalid_argument = False
if type(arg) is str:
arg = [arg]
elif type(arg) is list:
for item in arg:
if type(item) is not str:
invalid_argument = True
else:
invalid_argument = True
if invalid_argument:
exit("ERROR: invalid attachment argument. Must be string or list of strings, but found: %s" % str(arg))
return arg |
def _calculate_f1(tp, fp, fn):
"""Calculate f1."""
return tp * 2.0, (tp * 2.0 + fn + fp) |
def stripPunc(sent):
"""Strips punctuation from list of words"""
puncList = [".",";",":","!","?","/","\\",",","#","@","$","&",")","(","\""]
for punc in puncList:
sent = sent.replace(punc,'')
return sent |
def _reverse_bytes(mac):
"""Helper method to reverse bytes order.
mac -- bytes to reverse
"""
ba = bytearray(mac)
ba.reverse()
return bytes(ba) |
def walk_through_dict(
dictionary, end_fn, max_depth=None, _trace=None, _result=None, **kwargs
):
"""Runs a function at a given level in a nested dictionary.
If `max_depth` is unspecified, `end_fn()` will be run whenever
the recursion encounters an object other than a dictionary.
Parameters
----------
dictionary : foo
The dictionary to be recursively walked through.
end_fn : function
THe function to be run once recursion ends, either at
`max_depth` or when a non-dictionary is encountered.
max_depth : int, optional
How far deep the recursion is allowed to go. By default, the
recursion is allowed to go as deep as possible (i.e., until
it encounters something other than a dictionary).
_trace : tuple, optional
List of dictionary keys used internally to track nested position.
_result : dict
Used internally to pass new dictionaries and avoid changing the
input dictionary.
**kwargs : key-value pairs
Argument values that are passed to `end_fn()`.
Returns
-------
dict
A processed dictionary. The input dictionary remains unchanged.
"""
# Define default values
if max_depth is None:
max_depth = float("inf")
if _trace is None:
_trace = tuple()
if _result is None:
_result = dict()
# If the max_depth is zero, simply run `end_fn()` right away
if max_depth <= 0:
return end_fn(dictionary, **kwargs)
# Iterate over every dictionary key and run `end_fn()` if the value
# isn't a dictionary and the end depth isn't met. Otherwise, walk
# through nested dictionary recursively.
for k, v in dictionary.items():
# Track nested position
current_trace = _trace + (k,)
if isinstance(v, dict) and len(current_trace) < max_depth:
_result[k] = dict()
walk_through_dict(v, end_fn, max_depth, current_trace, _result[k], **kwargs)
else:
_result[k] = end_fn(v, **kwargs)
return _result |
def triangleType(a,b,c):
"""Categorize tree sides of a triangle into equilateral, unequal sided or isosceled.
Args:
a; int; Side a of the Triangle
b; int; Side b of the Triangle
c; int; Side c of the Triangle
Returns:
str; String of the category
"""
if a == b == c:
return "equilateral"
elif a == b and a != c:
return "isosceled"
else:
return "unequal sided" |
def merge(l1: list, l2: list):
"""Merge two sorted lists into a single sorted list."""
l = [None] * (len(l1) + len(l2))
i, j = 0, 0
while i < len(l1) and j < len(l2):
if l1[i] < l2[j]:
l[i + j] = l1[i]
i += 1
else:
l[i + j] = l2[j]
j += 1
idx, l_inp = (i, l1) if i < len(l1) else (j, l2)
for k in range(1, len(l_inp) - idx + 1):
l[-k] = l_inp[-k]
return l |
def convert_bytes(num):
"""
Converts bytes to human readable format.
"""
for x in ['bytes', 'KB', 'MB', 'GB', 'TB']:
if num < 1024.0:
return "%3.1f %s" % (num, x)
num /= 1024.0 |
def _is_list(item):
"""Check whether the type is list"""
return isinstance(item, list) |
def IS(x, lower, upper, alp):
"""Interval score.
Parameters
----------
x:
lower:
upper:
alp:
Returns
-------
ndarray
"""
return (upper - lower) + 2.0 / alp * (lower - x) * (x < lower) + 2.0 / alp * (x - upper) * (x > upper) |
def _structure_parent_category(_parent_id, _payload):
"""This function structures the portion of the payload for the parent category.
.. versionadded:: 2.5.0
:param _parent_id: The ID of the parent category (if applicable)
:type _parent_id: str, None
:param _payload: The partially constructed payload for the API request
:type _payload: dict
:returns: The API request payload with appended entries for ``parent_category``
"""
if _parent_id:
_payload['data']['parent_category'] = {
'id': _parent_id
}
return _payload |
def get_unique_id(serial_number: str, key: str) -> str:
"""Get a unique entity name."""
return f"{serial_number}-{key}" |
def clamp(val: float, minimum: float = 0.0, maximum: float = 1.0) -> float:
""" Fix value between min an max"""
if val < minimum:
return minimum
if val > maximum:
return maximum
return val |
def linear_search(arr, item):
""" Searches for an item in a given list and returns
True or False depending if the item is found
args:
arr: list,
item: any type """
for i in arr:
if i == item:
return True
return False |
def __sbiw_rd_i(op):
"""
Decode and return the 'Rd' and 'immediate' arguments of a SBIW opcode
"""
AVR_SBIW_RD_MASK = 0x0030
AVR_SBIW_CONST_MASK = 0x00CF
imm_part = op & AVR_SBIW_CONST_MASK
imm = ((imm_part >> 2) & 0x30) | (imm_part & 0xF)
# rd_part is 2 bits and indicates r24, 26, 28, or 30
rd_part = (op & AVR_SBIW_RD_MASK) >> 4
rd = (2 * rd_part) + 24
return (rd, imm) |
def fix_id(raw_data: dict) -> dict:
"""Fix known errors in station ids like superfluous spaces."""
if not raw_data:
return raw_data
for station in raw_data:
if "_id" not in station:
continue
station["_id"] = station["_id"].replace(" ", "")
for module in station.get("modules", {}):
module["_id"] = module["_id"].replace(" ", "")
return raw_data |
def find_cdr_exception(
cdr_exceptions,
orig_device_name=None,
dest_device_name=None,
orig_cause_value=None,
dest_cause_value=None,
):
"""For given list of CDRException, find & return first CDRException for given device & cause (optional), else return None.
Parameters, orig or dest required (CMRs device only):
cdr_exceptions (list of CDRException) - CDRException found so far
orig_device_name (str) - originating device name
dest_device_name (str) - destination device name
orig_cause_value (str) - originating cause code
dest_cause_value (str) - destination cause code
Returns:
cdr_exception (CDRException) - matching CDRException or None"""
# Sanity checks
assert orig_device_name is not None or dest_device_name is not None
if len(cdr_exceptions) > 0:
if cdr_exceptions[0].cdr_record_type == 1:
assert orig_cause_value is not None or dest_cause_value is not None
# Iterate through CDRExceptions to find a match
for cdr_exception in cdr_exceptions:
# CDRs
if cdr_exception.cdr_record_type == 1:
if orig_device_name is not None:
if orig_cause_value is not None:
if (
orig_cause_value == cdr_exception.orig_cause_value
and orig_device_name == cdr_exception.orig_device_name
):
return cdr_exception
elif dest_cause_value is not None:
if (
dest_cause_value == cdr_exception.dest_cause_value
and orig_device_name == cdr_exception.orig_device_name
):
return cdr_exception
if dest_device_name is not None:
if orig_cause_value is not None:
if (
orig_cause_value == cdr_exception.orig_cause_value
and dest_device_name == cdr_exception.dest_device_name
):
return cdr_exception
elif dest_cause_value is not None:
if (
dest_cause_value == cdr_exception.dest_cause_value
and dest_device_name == cdr_exception.dest_device_name
):
return cdr_exception
# CMRs
elif cdr_exception.cdr_record_type == 2:
if orig_device_name is not None:
if (
cdr_exception.orig_device_name is not None
and orig_device_name == cdr_exception.orig_device_name
):
return cdr_exception
if dest_device_name is not None:
if (
cdr_exception.dest_device_name is not None
and dest_device_name == cdr_exception.dest_device_name
):
return cdr_exception
# No match?
return None |
def check_slash(path):
""" Make sure that a slash terminates the string """
if path[-1] == "/":
return path
else:
return path + "/" |
def find_max_index(val, arr, exc=None):
"""Return index of max element in an array not larger than `val`,
excluding index `exc` if provided
>>> find_max_index(1, [1, 2, 3])
0
>>> find_max_index(2, [1, 2, 3, 4])
1
>>> find_max_index(0, [1, 2, 3, 4])
-1
>>> find_max_index(5, [1, 2, 3, 4])
3
>>> find_max_index(2, [1, 2, 3, 4], {1})
0
>>> find_max_index(3, [1, 2, 3, 4], {1})
2
>>> find_max_index(3, [2, 4, 4, 9], {0})
-1
"""
index = -1
for i, el in enumerate(arr):
if exc and i in exc:
continue
if el < val:
index = i
elif el == val:
return i
else:
return index
return index |
def drop_dupes(sequence):
"""Drop duplicate elements from a list or other sequence.
C.f. https://stackoverflow.com/a/7961390
"""
orig_type = type(sequence)
return orig_type(list(dict.fromkeys(sequence))) |
def inner_product(L1, L2):
"""
Take the inner product of the frequency maps.
"""
result = 0.
for word1, count1 in L1:
for word2, count2 in L2:
if word1 == word2:
result += count1 * count2
return result |
def rounddown_100(x):
"""
Project: 'ICOS Carbon Portal'
Created: Tue May 07 09:00:00 2019
Last Changed: Tue May 07 09:00:00 2019
Version: 1.0.0
Author(s): Karolina
Description: Function that takes a number as input and
floors it to the nearest "100".
Input parameters: Number (var_name: 'x', var_type: Integer or Float)
Output: Float
"""
#Import module:
import numbers
#Check if input parameter is numeric:
if(isinstance(x, numbers.Number)==True):
#If the number is an integral multiple of 100:
if(((x/100.0)%2==0) or (x<=0) or (x==100)):
return(int(x / 100.0) * 100) - 100
#If the input number is NOT an integral multiple of 100:
else:
return(int(x / 100.0) * 100)
#If input parameter is not numeric, prompt an error message:
else:
print("Input parameter is not numeric!") |
def link_in_path(link, node_list):
""" This function checks if the given link is in the path defined by this node list.
Works with undirected graphs so checks both link orientations.
Parameters
----------
link : tuple
a link expressed in a node pair tuple
node_list : list
a path as a list of nodes
Returns
-------
indicator : boolean
true is the link is in the path, false if not.
"""
b_link = (link[1], link[0]) # The link in reverse order
for i in range(len(node_list) - 1):
p_link = (node_list[i], node_list[i+1])
if link == p_link:
return True
if b_link == p_link:
return True
return False |
def formatTuples(tuples):
"""
Renders a list of 2-tuples into a column-aligned string format.
tuples (list of (any, any): The list of tuples to render.
Returns: A new string ready for printing.
"""
if not tuples:
return ""
tuples = [(str(x), str(y)) for (x, y) in tuples]
width = max([len(x) for (x, y) in tuples])
fmt = " {{:{}}} {{}}\n".format(width + 2)
result = ""
for (x, y) in tuples:
result += fmt.format(x, y)
return result |
def is_place_id(location):
""" Checks whether or not the city lookup can be cast to an int, representing a OWM Place ID """
try:
int(location)
return True
except (TypeError, ValueError):
return False |
def add_to_hierarchy(collection,triple):
"""Add TRIPLE to COLLECTION."""
# Comments will illustrate adding the triple
# {'a' : {'b' : ['d']}}
# to an existing collection with various possible features
top=collection.get(triple[0])
if (top):
med=top.get(triple[1])
# we see: {'a' : {'b' : ['c']}}
if (med):
# we get: {'a' : {'b' : ['c', 'd']}}
med.append(triple[2])
else:
# we see: {'a' : {'p' : ['q']}}
newb = {triple[1]:[triple[2]]}
# we get: {'a' : {'p' : ['q'], 'b' : ['c']}}
top.update(newb)
# we see: {'p' : {'q' : ['r']}}
else:
# ... build: {'b' : ['d']}
newm= {triple[1] : [triple[2]]}
# ... build: {'a' : {'b' : ['d'] }}
newt= {triple[0] : newm}
# we get: {'p' : {'q' : ['r']}, 'a' : {'b' : ['d']}}
collection.update(newt)
return collection |
def clean_street_name(name, mapping):
"""This function takes a string and a mapping dictionary and return a string of a curated street name
found in the boston_massachusetts.osm
This is a modification from
https://classroom.udacity.com/nanodegrees/nd002/parts/0021345404/modules/316820862075461/lessons/5436095827/concepts/54446302850923#"""
# delete number after street name,
if "," in name:
return name.split(",")[0]
# delete suite number after street and fixed one abbreviated street type
elif "#" in name:
if "Harvard" in name:
return "Harvard Street"
else:
name_split_pound = name.split("#")
return name_split_pound[0]
# map all street names in question to standard street names
else:
name_as_list = name.split(" ")
if name_as_list[-1] in mapping.keys():
name_as_list[-1] = mapping[name_as_list[-1]]
name = " ".join(name_as_list)
return name
else:
return name |
def daysBetweenDates(year1, month1, day1, year2, month2, day2):
"""Returns the number of days between year1/month1/day1
and year2/month2/day2. Assumes inputs are valid dates
in Gregorian calendar, and the first date is not after
the second."""
month = month2
year = year2
day = day2 - day1
if (day < 0):
day += 30
month -= 1
month = month - month1
if (month < 0):
month += 12
year -= 1
year = year - year1
return (year * 360) + month * 30 + day |
def EITCamount(basic_frac, phasein_rate, earnings, max_amount,
phaseout_start, agi, phaseout_rate):
"""
Returns EITC amount given specified parameters.
English parameter names are used in this function because the
EITC formula is not available on IRS forms or in IRS instructions;
the extensive IRS EITC look-up table does not reveal the formula.
"""
eitc = min((basic_frac * max_amount +
(1.0 - basic_frac) * phasein_rate * earnings), max_amount)
if earnings > phaseout_start or agi > phaseout_start:
eitcx = max(0., (max_amount - phaseout_rate *
max(0., max(earnings, agi) - phaseout_start)))
eitc = min(eitc, eitcx)
return eitc |
def compute_2(x, offset=1):
"""Compute by looping and checking ahead."""
y = 0
x2 = x + x[:offset] # Lists are concatenated, but they take memory
for i in range(len(x)):
if x2[i] == x2[i+offset]:
y += int(x2[i])
return y |
def version_tuple(ver):
"""Convert a version string to a tuple containing ints.
Parameters
----------
ver : str
Returns
-------
ver_tuple : tuple
Length 3 tuple representing the major, minor, and patch
version.
"""
split_ver = ver.split(".")
while len(split_ver) < 3:
split_ver.append('0')
if len(split_ver) > 3:
raise ValueError('Version strings containing more than three parts '
'cannot be parsed')
vals = []
for item in split_ver:
if item.isnumeric():
vals.append(int(item))
else:
vals.append(0)
return tuple(vals) |
def _num_to_list(num, length):
"""
258, 2 -> [1,2]
:param int num:
:param int length:
:rtype: list
"""
output = []
for l in range(length):
output = [int((num >> 8*l) & 0xff)]+output
return output |
def Keck_distortion(measured_wave, cutoff=10000.):
"""Telescope dependent distortion function for the Keck sample."""
slope1 = .0600
intercept1 = -100
slope2 = .160
intercept2 = -1500
if measured_wave < cutoff:
return measured_wave * slope1 + intercept1
else:
return measured_wave * slope2 + intercept2 |
def check_not_finished_board(board):
"""
list -> bool
Check if skyscraper board is not finished, i.e., '?' present on the game board.
Return True if finished, False otherwise.
>>> check_not_finished_board(['***21**', '4?????*', '4?????*', \
'*?????5', '*?????*', '*?????*', '*2*1***'])
False
>>> check_not_finished_board(['***21**', '412453*', '423145*', \
'*543215', '*35214*', '*41532*', '*2*1***'])
True
>>> check_not_finished_board(['***21**', '412453*', '423145*', \
'*5?3215', '*35214*', '*41532*', '*2*1***'])
False
"""
return '?' not in ''.join(board) |
def escape_html(text: str) -> str:
"""Replaces all angle brackets with HTML entities."""
return text.replace('<', '<').replace('>', '>') |
def register_actions(cls):
""" Registers all marked methods in the agent class
:param cls: Agent Subclass of Agent containing methods decorated with @action
"""
for name, method in cls.__dict__.items():
if hasattr(method, "_register_action"):
cls._actions[name] = method
return cls |
def get_file_contents(f):
"""returns contents of file as str"""
data = ""
try:
with open(f, "r") as open_file:
data = open_file.read()
except Exception as e:
print(e)
finally:
return data |
def factorial(n):
"""Compute factorial of n, n!"""
if n <= 1:
return 1
return n * factorial(n-1) |
def auto_ext_from_metadata(metadata):
"""Script extension from kernel information"""
auto_ext = metadata.get('language_info', {}).get('file_extension')
if auto_ext == '.r':
return '.R'
return auto_ext |
def is_localhost(host):
"""Verifies if the connection is local
Parameters
----------
host : str
The requesting host, in general self.request.headers['host']
Returns
-------
bool
True if local request
"""
localhost = ('localhost', '127.0.0.1')
return host.startswith(localhost) |
def import_string(path: str):
"""
Path must be module.path.ClassName
>>> cls = import_string('sentry.models.Group')
"""
if "." not in path:
return __import__(path)
module_name, class_name = path.rsplit(".", 1)
module = __import__(module_name, {}, {}, [class_name])
try:
return getattr(module, class_name)
except AttributeError as exc:
raise ImportError from exc |
def anchorfree(anchor=5, free=7, start=1, stop=100, step=1):
"""
Return a list of strings consisting of either the number,
the phrase "anchor", "free" or "WOW" when
the number is divisible by anchor, free or both.
:param anchor: return "anchor" when number is divisible by this
:param free: return "free" when the number is divisible by this
:param start: the first number
:param stop: the last number (not inclusive)
:param step: the amount to increase the number on each iteration
:return: A list of strings
"""
return ['1', 'anchor', 'free', 'anchor', '5', 'WOW', '7', 'anchor', 'free'] |
def list_neighbors(current_row, current_col, grid):
"""
Args:
current_row: Current row of the animal
current_col: Current column of the animal
grid: The grid
Returns:
List of all position tuples that are around the current position,
without including positions outside the grid
"""
# WRITE YOUR CODE FOR QUESTION 1 HERE
all_positions = []
#creates empty list to store possible positions
rows = [current_row]
cols = [current_col]
#creates lists to store possible rows and columns, already includes current row and column
for row in range(len(grid)):
if row-current_row == 1:
rows.append(row)
if row-current_row == -1:
rows.append(row)
#iterates through rows in the grid, if the row is larger or smaller than the current row by 1, the index of the row is added to the list of rows
for col in range(len(grid[0])):
if col-current_col == 1:
cols.append(col)
if col-current_col == -1:
cols.append(col)
#iterates through columns in the grid, if the column is larger or smaller than the current column by 1, the index of the row is added to the list of columns
for row in rows:
for col in cols:
all_positions.append((row,col))
#iterates through all values in both rows and cols list and appends all possible tuples to the all_positions list
all_positions.remove((current_row,current_col))
#removes the current position from the generated list
all_positions.sort()
#sorts the list of tuples by their first integer
return all_positions |
def encode_int(i):
"""Encode an integer for a bytes database."""
return bytes(str(i), "utf-8") |
def p_a2(npsyns, ninputs):
"""
Probability of selecting one input given ninputs and npsyns attempts. This
uses a binomial distribution.
@param npsyns: The number of proximal synapses.
@param ninputs: The number of inputs.
@return: The computed probability.
"""
p = 1. / ninputs
return npsyns * p * ((1 - p) ** (npsyns - 1)) |
def calculate_iou(gt, pr, form='pascal_voc') -> float:
"""Calculates the Intersection over Union.
Args:
gt: (np.ndarray[Union[int, float]]) coordinates of the ground-truth box
pr: (np.ndarray[Union[int, float]]) coordinates of the prdected box
form: (str) gt/pred coordinates format
- pascal_voc: [xmin, ymin, xmax, ymax]
- coco: [xmin, ymin, w, h]
Returns:
(float) Intersection over union (0.0 <= iou <= 1.0)
"""
if form == 'coco':
gt = gt.copy()
pr = pr.copy()
gt[2] = gt[0] + gt[2]
gt[3] = gt[1] + gt[3]
pr[2] = pr[0] + pr[2]
pr[3] = pr[1] + pr[3]
# Calculate overlap area
dx = min(gt[2], pr[2]) - max(gt[0], pr[0]) + 1
if dx < 0:
return 0.0
dy = min(gt[3], pr[3]) - max(gt[1], pr[1]) + 1
if dy < 0:
return 0.0
overlap_area = dx * dy
# Calculate union area
union_area = (
(gt[2] - gt[0] + 1) * (gt[3] - gt[1] + 1) +
(pr[2] - pr[0] + 1) * (pr[3] - pr[1] + 1) -
overlap_area
)
return overlap_area / union_area |
def return_other_zones(zones, index):
"""return all other zones not assigned to uav to make as a no fly zone"""
copy = zones
copy.pop(index)
return copy |
def should_run(config):
"""
Checks if canary tests should run.
"""
if "canaries" in config["bootstrap"] and config["bootstrap"]["canaries"] == "none":
return False
if "canaries" in config["test_control"] and config["test_control"]["canaries"] == "none":
return False
return True |
def to_bool(answer, default):
"""
Converts user answer to boolean
"""
answer = str(answer).lower()
default = str(default).lower()
if answer and answer in "yes":
return True
return False |
def health_summary(builds):
"""Summarise the health of a project based on builds.
Arguments:
builds (:py:class:`list`): List of builds.
Returns:
:py:class:`str`: The health summary.
"""
for build in builds:
if build['outcome'] in {Outcome.PASSED}:
return 'ok'
elif build['outcome'] in {Outcome.CRASHED, Outcome.FAILED}:
return 'error'
else:
continue
return 'neutral' |
def represents_int(s: str) -> bool:
"""Checks if a string s represents an int.
Args:
s: string
Returns:
boolean, whether string represents an integer value
"""
try:
int(s)
return True
except ValueError:
return False |
def points_match(par_before, par_after):
"""
Do points match?
"""
return (par_before.get("latitude", None) == par_after.get("latitude", None)
and par_before.get("longitude", None) == par_after.get("longitude", None) ) |
def indent(lines, amount, ch=' '):
"""indent the lines in a string by padding each one with proper number of pad characters"""
padding = amount * ch
return padding + ('\n'+padding).join(lines.split('\n')) |
def _flows_finished(pgen_grammar, stack):
"""
if, while, for and try might not be finished, because another part might
still be parsed.
"""
for dfa, newstate, (symbol_number, nodes) in stack:
if pgen_grammar.number2symbol[symbol_number] in ('if_stmt', 'while_stmt',
'for_stmt', 'try_stmt'):
return False
return True |
def generate_query(query_tuples):
"""
Builds a query from a list of tuples.
:param List query_tuples: Lists of tuples to build query item.
:return: SQL compatible query as a string.
"""
# prepend ID and date items
master_query = ("ID integer PRIMARY KEY ASC NOT NULL,"
"date text,")
for name in query_tuples:
master_query += '%s %s,' % (name[0], name[1])
return master_query[:-1] |
def prod_double(x, y, param_0):
"""
Product
:param x:
:param y:
:param param_0:
:return:
"""
return x * y * param_0 |
def parse_megawatt_value(val):
"""Turns values like "5,156MW" and "26MW" into 5156 and 26 respectively."""
return int(val.replace(',', '').replace('MW', '')) |
def group_split(items, group_size):
"""Split a list into groups of a given size"""
it = iter(items)
return list(zip(*[it] * group_size)) |
def endswith(value, arg):
"""Usage {% if value|endswith:"arg" %}"""
if value:
return value.endswith(arg)
return False |
def DeltaAngle(a, b):
"""
Calculates the shortest difference between
two given angles given in degrees.
Parameters
----------
a : float
Input a
b : float
Input b
"""
return abs(a - b) % 360 |
def concatenate_unique(la, lb):
"""Add all the elements of `lb` to `la` if they are not there already.
The elements added to `la` maintain ordering with respect to `lb`.
Args:
la: List of Python objects.
lb: List of Python objects.
Returns:
`la`: The list `la` with missing elements from `lb`.
"""
la_set = set(la)
for l in lb:
if l not in la_set:
la.append(l)
la_set.add(l)
return la |
def calculate(expr: str) -> int:
"""Evaluate 'expr', which contains only non-negative integers,
{+,-,*,/} operators and empty spaces."""
plusOrMinus = {'+': lambda x, y: x + y ,
'-': lambda x, y: x - y}
mulOrDiv = {'*': lambda x, y: x * y ,
'/': lambda x, y: x // y}
stack = []
operators = []
number = 0
for char in expr:
if char.strip() == '':
# Skip whitespace.
continue
if char.isdigit():
# Add digit to current number.
number = number * 10 + int(char)
continue
stack.append(number)
number = 0
if operators and operators[-1] in mulOrDiv:
# Perform multiplication or division first.
snd = stack.pop()
fst = stack.pop()
operator = operators.pop()
stack.append(mulOrDiv[operator](fst, snd))
operators.append(char)
# The last operand must be a number, so add that to the stack.
# Also perform multiplication or division if it is the last operator.
stack.append(number)
if operators and operators[-1] in mulOrDiv:
snd = stack.pop()
fst = stack.pop()
operator = operators.pop()
stack.append(mulOrDiv[operator](fst, snd))
# The remaining computations are addition or subtraction. Perform these
# in order from left to right.
result = stack[0]
for snd, operator in zip(stack[1:], operators):
result = plusOrMinus[operator](result, snd)
return result |
def convert_string(s):
"""
Converts a string to the appropriate type, either a float type or a int type
Parameters
----------
s : string
The string that should be converted
Returns
-------
float or int : The numerical representation of "s"
"""
if "." in s:
return float(s)
else:
return int(s) |
def NormalizeRegEx(regEx):
"""NormalizeRegEx(regEx) -> str
Escapes the special characters in a regular expression so it can be
compiled properly.
arguments:
parent
string of the regular expression where special characters are not
escaped
returns:
string of the regular expression where special caharacters are escaped
"""
regEx = regEx.replace("\\", "\\\\")
regEx = regEx.replace(".", "\\.")
regEx = regEx.replace("^", "\\^")
regEx = regEx.replace("$", "\\$")
regEx = regEx.replace("[", "\\[")
regEx = regEx.replace("]", "\\]")
regEx = regEx.replace("(", "\\(")
regEx = regEx.replace(")", "\\)")
return regEx |
def shorten(thelist, maxlen, shorten):
"""
If thelist has more elements than maxlen, remove elements to make it of size maxlen.
The parameter shorten is a string which can be one of left, right, both or middle
and specifies where to remove elements.
:param thelist: the list to shorten
:param maxlen: maximum length of the list
:param shorten: one of left, right, both, middle, where to remove the elements
:return: the shortened list
"""
if len(thelist) <= maxlen:
return thelist
if shorten == "right":
return thelist[0:maxlen]
elif shorten == "left":
return thelist[-maxlen-1:-1]
elif shorten == "both":
excess = len(thelist) - maxlen;
left = int(excess/2)
right = excess - left
return thelist[left:-right]
elif shorten == "middle":
excess = len(thelist) - maxlen;
left = int(excess/2)
right = excess - left
return thelist[0:left]+thelist[-right:]
else:
raise Exception("Not a valid value for the shorten setting: {}".format(shorten)) |
def rm_spaces(filename):
""" Replaces all spaces with underscores in a filename. """
return filename.replace(' ', '_') |
def _geoserver_endpoints(workspace, layer):
"""Form GeoServer WMS/WFS endpoints.
Parameters:
workspace (str): GeoServer workspace
layer (str): Layer name
Returns:
(dict) The GeoServer layer endpoints.
"""
return {
"wms": '{0}/wms?service=WMS&request=GetMap&layers={0}:{1}'.format(workspace, layer),
"wfs": '{0}/ows?service=WFS&request=GetFeature&typeName={0}:{1}'.format(workspace, layer)
} |
def _formatElement(element, count, index, lastSeparator):
"""Format an element from a sequence.
This only prepends a separator for the last element and wraps each element
with single quotes.
Parameters
----------
element : object
Current element.
count : int
Total number of items in the sequence.
index : int
Current index.
lastSeparator : str
Separator to be used for joining the last element when multiple
elements are to be joined.
Returns
-------
str
The joined object string representations.
"""
return ("%s'%s'" % (lastSeparator, element)
if count > 1 and index == count - 1
else "'%s'" % (element,)) |
def get_data_center(hostname):
"""Guess data center from Keeper server hostname
hostname(str): The hostname component of the Keeper server URL
Returns one of "EU", "US", "US GOV", or "AU"
"""
if hostname.endswith('.eu'):
data_center = 'EU'
elif hostname.endswith('.com'):
data_center = 'US'
elif hostname.endswith('govcloud.keepersecurity.us'):
data_center = 'US GOV'
elif hostname.endswith('.au'):
data_center = 'AU'
else:
# Ideally we should determine TLD which might require additional lib
data_center = hostname
return data_center |
def parse_time_cmd(s):
""" Convert timing info from `time` into float seconds.
E.g. parse_time('0m0.000s') -> 0.0
"""
s = s.strip()
mins, _, secs = s.partition('m')
mins = float(mins)
secs = float(secs.rstrip('s'))
return mins * 60.0 + secs |
def hexdump(data, offset, size):
"""Return hexdump string of given data in isobuster format."""
def ascii_print(c):
return chr(c) if 32 <= c <= 127 else "."
dump = ""
for i in range(size // 0x10):
line_offset = offset + i * 0x10
line_data = data[line_offset: line_offset + 0x10]
line_format = "{:04X} :" + " {:02X}" * 8 + " " + " {:02X}" * 8
dump += line_format.format(line_offset, *line_data)
dump += " " + "".join([ascii_print(b) for b in line_data]) + "\n"
return dump |
def contain_zh(text):
"""
Check if string contains chinese char
"""
for c in text:
if '\u4e00' <= c <= '\u9fa5':
return True
return False |
def key_pem(cert_prefix):
"""This is the key entry of a self-signed local cert"""
return cert_prefix + '/server.key' |
def format_info(variant, variant_type="snv", nr_cases=None, add_freq=False):
"""Format the info field for SNV variants
Args:
variant(dict)
variant_type(str): snv or sv
nr_cases(int)
Returns:
vcf_info(str): A VCF formated info field
"""
observations = variant.get("observations", 0)
homozygotes = variant.get("homozygote")
hemizygotes = variant.get("hemizygote")
vcf_info = f"Obs={observations}"
if homozygotes:
vcf_info += f";Hom={homozygotes}"
if hemizygotes:
vcf_info += f";Hem={hemizygotes}"
if add_freq and nr_cases and nr_cases > 0:
frequency = observations / nr_cases
vcf_info += f";Frq={frequency:.5f}"
# This is SV specific
if variant_type == "sv":
pos= int((variant["pos_left"] + variant["pos_right"]) / 2)
end = int((variant["end_left"] + variant["end_right"]) / 2)
if not variant['sv_type'] == "BND":
vcf_info += f";SVTYPE={variant['sv_type']};END={end};SVLEN={variant['length']}"
else:
vcf_info += f";SVTYPE=BND"
return vcf_info |
def _ivc_to_model_input(ivc, actual_yield, burst_height):
"""This function converts an International Visibility Code [1-9] into the numbers used in the Soviet thermal impulse model."""
if ivc == 9:
return 1
else:
groundburst = 10 - ivc
if ivc == 3 or ivc == 2:
groundburst = groundburst + 1
if burst_height == 0 or actual_yield <= 100:
return groundburst
else:
return groundburst - 1 |
def fuzz(val):
""" A fuzzer for json data """
if isinstance(val, int):
return val + 7
if isinstance(val, str):
return "FUZ" + val + "ZY"
if isinstance(val, list):
return ["Q(*.*)Q"] + [fuzz(x) for x in val] + ["P(*.*)p"]
if isinstance(val, dict):
fuzzy = {x: fuzz(y) for x, y in val.items()}
return fuzzy |
def volume(iterable):
"""
Computes the volume of an iterable.
:arg iterable: Any python iterable, including a :class:`Dims` object.
:returns: The volume of the iterable. This will return 1 for empty iterables, as a scalar has an empty shape and the volume of a tensor with empty shape is 1.
"""
vol = 1
for elem in iterable:
vol *= elem
return vol |
def GetQNNSquareLoss(labelValues, predictionValues):
""" Get the Square loss function
"""
lossValue = 0
for label, prediction in zip(labelValues, predictionValues):
lossValue = lossValue + (label - prediction) ** 2
lossValue = lossValue / len(labelValues)
return lossValue |
def _handle_string(val):
"""
Replaces Comments: and any newline found.
Input is a cell of type 'string'.
"""
return val.replace('Comments: ', '').replace('\r\n', ' ') |
def win_check(riddle):
"""
Check whether user have get the whole word.
:param riddle: str, user's guess
:return win: int, 0 = no any un-found alphabet
"""
win = 0
for i in range(len(riddle)):
# check whether any character other than alphabet exist
if str.isalpha(riddle[i]):
win += 0
else:
# for each un-found alphabet -> count one
win += 1
return win |
def str_committees_header(committees, winning=False):
"""
nicely format a header for a list of committees,
stating how many committees there are
winning: write "winning committee" instead of "committee"
"""
output = ""
if committees is None or len(committees) < 1:
if winning:
return "No winning committees (this should not happen)"
else:
return "No committees"
if winning:
commstring = "winning committee"
else:
commstring = "committee"
if len(committees) == 1:
output += "1 " + commstring + ":"
else:
output += str(len(committees)) + " " + commstring + "s:"
return output |
def _create_rest_error_output(error_message, error_code):
"""creates rest service error output"""
response = {
"success": "false",
"data": {},
"error": {
"code": error_code,
"message": error_message
}
}
return response |
def penalize_off_pulse(genotype, weight=20):
"""fitness function handling off pulse notes
Args:
genotype ((int, int)[]): list of tuples (pitch, dur) representing genotype of a chromosome
weight (int, optional): Defaults at 20. Defines penalty/reward rate
Returns:
int: aggregate fitness value based on off pulse notes
"""
total = 0
total_dur = 0
for i, (ed, dur) in enumerate(genotype):
total_dur += dur
if not total_dur % 4 == 0:
total += weight * -.25
if total_dur % 4 == 0 and total_dur % 8 != 0: # means off beat!
total += weight * .25
return total |
def is_transition_allowed(constraint_type: str,
from_tag: str,
to_tag: str):
"""
Given a constraint type and strings ``from_tag`` and ``to_tag`` that
represent the origin and destination of the transition, return whether
the transition is allowed under the given constraint type.
Parameters
----------
constraint_type : ``str``, required
Indicates which constraint to apply. Current choices are
"BIO", "IOB1", "BIOUL", and "BMES".
from_tag : ``str``, required
The tag that the transition originates from. For example, if the
label is ``I-PER``, the ``from_tag`` is ``I``.
from_entity: ``str``, required
The entity corresponding to the ``from_tag``. For example, if the
label is ``I-PER``, the ``from_entity`` is ``PER``.
to_tag : ``str``, required
The tag that the transition leads to. For example, if the
label is ``I-PER``, the ``to_tag`` is ``I``.
to_entity: ``str``, required
The entity corresponding to the ``to_tag``. For example, if the
label is ``I-PER``, the ``to_entity`` is ``PER``.
Returns
-------
``bool``
Whether the transition is allowed under the given ``constraint_type``.
"""
# pylint: disable=too-many-return-statements
if to_tag == "START" or from_tag == "END":
# Cannot transition into START or from END
return False
if constraint_type == "BIOUL":
if from_tag == "START":
return to_tag in ('O', 'B', 'U')
if to_tag == "END":
return from_tag in ('O', 'L', 'U')
return any([
# O can transition to O, B-* or U-*
# L-x can transition to O, B-*, or U-*
# U-x can transition to O, B-*, or U-*
from_tag in ('O', 'L', 'U') and to_tag in ('O', 'B', 'U'),
# B-x can only transition to I-x or L-x
# I-x can only transition to I-x or L-x
from_tag in ('B', 'I') and to_tag in ('I', 'L')
])
elif constraint_type == "BIO":
if from_tag == "START":
return to_tag in ('O', 'B')
if to_tag == "END":
return from_tag in ('O', 'B', 'I')
return any([
# Can always transition to O or B-x
to_tag in ('O', 'B'),
# Can only transition to I-x from B-x or I-x
to_tag == 'I' and from_tag in ('B', 'I')
])
elif constraint_type == "IOB1":
if from_tag == "START":
return to_tag in ('O', 'I')
if to_tag == "END":
return from_tag in ('O', 'B', 'I')
return any([
# Can always transition to O or I-x
to_tag in ('O', 'I'),
# Can only transition to B-x from B-x or I-x, where
# x is the same tag.
to_tag == 'B' and from_tag in ('B', 'I')
])
elif constraint_type == "BMES":
if from_tag == "START":
return to_tag in ('B', 'S')
if to_tag == "END":
return from_tag in ('E', 'S')
return any([
# Can only transition to B or S from E or S.
to_tag in ('B', 'S') and from_tag in ('E', 'S'),
# Can only transition to M-x from B-x, where
# x is the same tag.
to_tag == 'M' and from_tag in ('B', 'M'),
# Can only transition to E-x from B-x or M-x, where
# x is the same tag.
to_tag == 'E' and from_tag in ('B', 'M')
])
else:
raise TypeError("Unknown constraint type: {constraint_type}") |
def try_integer(s) -> int:
"""Attempts to convert some input into an integer"""
try:
return int(s)
except ValueError:
return s |
def cipher(text, shift, encrypt=True):
"""
Encrypt (decrypt) a text (ciphertext) into ciphertext (text)
:param text: The plaintext or ciphertext
:param shift: The shift that encrypts the text
:param encrypt: True for encryption, False for decryption
:return: ciphertext or plaintext
>>> plain_text = 'this is a message.'
>>> cipher_text = cipher(plain_text, 5, True)
>>> cipher_text
'ymnx nx f rjxxflj.'
>>> new_plain_text = cipher(cipher_text, 5, False)
>>> new_plain_text
'this is a message.'
"""
alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
new_text = ''
for c in text:
index = alphabet.find(c)
if index == -1:
new_text += c
else:
new_index = index + shift if encrypt == True else index - shift
new_index %= len(alphabet)
new_text += alphabet[new_index:new_index+1]
return new_text |
def add_app(INSTALLED_APPS, app, prepend=False, append=True):
""" add app to installed_apps """
if app not in INSTALLED_APPS:
if prepend:
return (app,) + INSTALLED_APPS
else:
return INSTALLED_APPS + (app,)
return INSTALLED_APPS |
def rawtext(s):
"""Compile raw text to the appropriate instruction."""
if "\n" in s:
return ("rawtextColumn", (s, len(s) - (s.rfind("\n") + 1)))
else:
return ("rawtextOffset", (s, len(s))) |
def decimal_to_any(decimal: int , base: int) -> str:
"""Convert a positive integer to another base as str."""
if not isinstance(decimal , int):
raise TypeError("You must enter integer value")
if not 2 <= base <= 32:
raise ValueError("base must be between 2 and 36")
def getChar(num: int):
"""This method produces character value of the input integer and returns it"""
if 0 <= num <= 9:
return chr(num + ord('0'))
else:
return chr(num - 10 + ord('A'))
is_negative: bool = True if decimal < 0 else False
decimal = abs(decimal)
ans: list[str] = []
while decimal > 0:
ans.insert(0 , getChar(decimal % base))
decimal //= base
if is_negative:
ans.insert(0 , '-')
return ''.join(ans) |
def sum_squared(x):
""" Return the sum of the squared elements
Parameters
----------
x (list): List of numbers
Return
------
ss (float): sum of the squared """
ss = sum(map(lambda i : i * i, x))
# ss = sum([i**2 for i in x])
return ss |
def vect3_dot(u, v):
"""
u.v, dot (scalar) product.
u, v (3-tuple): 3d vectors
return (float): dot product
"""
return u[0] * v[0] + u[1] * v[1] + u[2] * v[2] |
def K(x, y):
""" Converts K/control codes to bytes
Does not result in 8b10b data; requires explicit encoding.
See the USB3 / PCIe specifications for more information.
"""
return (y << 5) | x |
def pad_middle(seq, desired_length):
"""
Pad the middle of a sequence with gaps so that it is a desired length.
Fail assertion if it's already longer than `desired_length`.
"""
seq_len = len(seq)
assert seq_len <= desired_length
pad_start = seq_len // 2
pad_len = desired_length - seq_len
return seq[:pad_start] + '-' * pad_len + seq[pad_start:] |
def iid_divide(data, g):
"""divide list data among g groups each group has either int(len(data)/g)
or int(len(data)/g)+1 elements returns a list of groups."""
num_elems = len(data)
group_size = int(len(data) / g)
num_big_groups = num_elems - g * group_size
num_small_groups = g - num_big_groups
glist = []
for i in range(num_small_groups):
glist.append(data[group_size * i:group_size * (i + 1)])
bi = group_size * num_small_groups
group_size += 1
for i in range(num_big_groups):
glist.append(data[bi + group_size * i:bi + group_size * (i + 1)])
return glist |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.