content stringlengths 42 6.51k |
|---|
def merge_dicts(*dict_args):
"""
Given any number of dicts, shallow copy and merge into a new dict,
precedence goes to key value pairs in latter dicts.
"""
# source:
# http://stackoverflow.com/questions/38987/how-to-merge-two-python-dictionaries-in-a-single-expression
result = {}
for dictionary in dict_args:
result.update(dictionary)
return result |
def make_divisors(n, reversed=False):
"""create list of divisors O(root(N))
Args:
number (int): number from which list of divisors is created
reversed (bool, optional): ascending order if False. Defaults to False.
Returns:
list: list of divisors
"""
divisors = set()
for i in range(1, int(n**0.5) + 1):
if n % i == 0:
divisors.add(i)
divisors.add(n // i)
return sorted(list(divisors), reverse=reversed) |
def _min(*args):
"""Returns the minimum value."""
return min(*args) |
def f1x_p(x, p):
"""
General 1/x function: :math:`a + b/x`
Parameters
----------
x : float or array_like of floats
independent variable
p : iterable of floats
parameters (`len(p)=2`)
- `p[0]` = a
- `p[1]` = b
Returns
-------
float
function value(s)
"""
return p[0]+p[1]/x |
def color_based_on_operation(data, matching_criteria, matching_color, not_matching_color):
"""
:param data:
:param matching_criteria:
:param matching_color:
:param not_matching_color:
:return:
"""
color_associated = list(map(lambda x: matching_color if matching_criteria(x) else not_matching_color, data))
return color_associated |
def decint2binstr(n):
"""Convert decimal integer to binary string.
"""
if n < 0:
return '-' + decint2binstr(-n)
s = ''
while n != 0:
s = str(n % 2) + s
n >>= 1
return s or '0' |
def map_to_parent(t_class, parents_info_level):
"""
parents_info_level: {<classid>: [parent]}, only contains classid that has a super-relationship
"""
if t_class in parents_info_level:
assert len(parents_info_level[t_class]) < 2, f"{t_class} has two or more parents {parents_info_level[t_class]}"
parent = parents_info_level[t_class][0]
else:
parent = t_class
return parent |
def _parse_constraint(expr_string):
""" Parses the constraint expression string and returns the lhs string,
the rhs string, and comparator
"""
for comparator in ['==', '>=', '<=', '>', '<', '=']:
parts = expr_string.split(comparator)
if len(parts) == 2:
# check for == because otherwise they get a cryptic error msg
if comparator == '==':
break
return (parts[0].strip(), comparator, parts[1].strip())
elif len(parts) == 3:
return (parts[1].strip(), comparator,
(parts[0].strip(), parts[2].strip()))
msg = "Constraints require an explicit comparator (=, <, >, <=, or >=)"
raise ValueError(msg) |
def GetHotkey(text):
"""Return the position and character of the hotkey"""
# find the last & character that is not followed
# by & or by the end of the string
curEnd = len(text) + 1
text = text.replace("&&", "__")
while True:
pos = text.rfind("&", 0, curEnd)
# One found was at the end of the text or
# no (more) & were found
# so return the None value
if pos in [-1, len(text)]:
return (-1, '')
# One found but was prededed by non valid hotkey character
# so continue, as that can't be a shortcut
if text[pos - 1] == '&':
curEnd = pos - 2
continue
# 2 ampersands in a row - so skip
# the 1st one and continue
return (pos, text[pos+1]) |
def returnYear(date):
"""
Return the year
"""
y = str(date)[:4]
x = int(y)
return x |
def merge_args_and_kwargs(param_names, args, kwargs):
"""Merges args and kwargs for a given list of parameter names into a single
dictionary."""
merged = dict(zip(param_names, args))
merged.update(kwargs)
return merged |
def run(result):
"""Function to test empty dict return"""
ret = {}
return ret |
def divide(x, y):
"""Divide function"""
if y == 0:
raise ValueError("Cannot divide by 0")
return x / y |
def sqrt(number):
"""
Calculate the floored square root of a number
Args:
number(int): Number to find the floored squared root
Returns:
int: Floored Square Root
"""
if number is None or number < 0:
return None
if number * number == number or number == 1:
return number
lo = 0
hi = number
while lo < hi:
mid = (lo + hi) >> 1
if mid * mid == number:
return mid
elif mid * mid < number:
lo = mid + 1
else:
hi = mid
return lo - 1 |
def lsearch(l,pattern):
""" Search for items in list l that have substring match to pattern. """
rvals = []
for v in l:
if not v.find(pattern) == -1:
rvals.append(v)
return rvals |
def parse_config_sections(conf, section_defs):
"""Parse the sections of the configuration file
Args:
conf (dict): Loaded configuration file information
section_defs (dict): Mapping of configuration file values and defaults
Returns:
(dict): Final configuration to use with the script execution
"""
config = {}
for section, value in section_defs.items():
if section not in conf:
continue
for k, v in value.items():
conf_section = conf[section]
conf_value = None
if isinstance(v, str):
conf_value = conf_section.get(k)
elif isinstance(v, list):
conf_value = conf_section.get(k).split(',')
elif isinstance(v, bool):
conf_value = conf_section.getboolean(k)
elif isinstance(v, dict):
raise NotImplementedError("Unable to parse dictionary objects from config file mapping")
config[k] = conf_value
return config |
def fail(string: str) -> str:
"""Add fail colour codes to string
Args:
string (str): Input string
Returns:
str: Fail string
"""
return "\033[91m" + string + "\033[0m" |
def is_user_defined_new_style_class(obj):
"""Returns whether or not the specified instance is a user-defined type."""
return type(obj).__module__ != '__builtin__' |
def isotopeMaxBD(isotope):
"""Setting the theoretical max BD shift of an isotope
(if 100% incorporation).
Parameters
----------
isotope : str
name of isotope
Returns
-------
float : max BD value
"""
psblIsotopes = {'13C' : 0.036,
'15N' : 0.016}
try:
return psblIsotopes[isotope.upper()]
except KeyError:
raise KeyError('Isotope "{}" not supported.'.format(isotope)) |
def _calculate_slope(x_data):
"""Calculate the trend slope of the data
:param x_data: A list of the result percentages, e.g. [98, 54, 97, 99]
:type x_data: list
:rtype float:
"""
if all(x == 100 for x in x_data):
return 100
y_data = list(range(len(x_data)))
x_avg = sum(x_data) / len(x_data)
y_avg = sum(y_data) / len(y_data)
try:
slope = sum([(x - x_avg) * (y - y_avg) for x, y in zip(x_data, y_data)]) / sum(
[(x - x_avg) ** 2 for x in x_data]
)
except ZeroDivisionError:
slope = 0
return slope |
def defaults(obj, *sources):
"""
Assigns properties of source object(s) to the destination object for all destination properties
that resolve to undefined.
Args:
obj (dict): Destination object whose properties will be modified.
sources (dict): Source objects to assign to `obj`.
Returns:
dict: Modified `obj`.
Warning:
`obj` is modified in place.
Example:
>>> obj = {'a': 1}
>>> obj2 = defaults(obj, {'b': 2}, {'c': 3}, {'a': 4})
>>> obj is obj2
True
>>> obj == {'a': 1, 'b': 2, 'c': 3}
True
.. versionadded:: 1.0.0
"""
for source in sources:
for key, value in source.items():
obj.setdefault(key, value)
return obj |
def clean_material_name(material_name):
"""Make sure the material name is consistent."""
return material_name.lower().replace('\\', '/') |
def expand_grid(grid):
"""Expand grid by one in every direction."""
new_length = len(grid) + 2
row = [0 for _ in range(new_length)]
new_grid = [[0] + row + [0] for row in grid]
return [row[:]] + new_grid + [row[:]] |
def _atomic_symbol(anum):
""" convert atomic number to atomic symbol
"""
anum2asymb = ['X', 'H', 'HE', 'LI', 'BE', 'B', 'C', 'N', 'O', 'F', 'NE',
'NA', 'MG', 'AL', 'SI', 'P', 'S', 'CL', 'AR', 'K', 'CA',
'SC', 'TI', 'V', 'CR', 'MN', 'FE', 'CO', 'NI', 'CU', 'ZN',
'GA', 'GE', 'AS', 'SE', 'BR', 'KR', 'RB', 'SR', 'Y', 'ZR',
'NB', 'MO', 'TC', 'RU', 'RH', 'PD', 'AG', 'CD', 'IN', 'SN',
'SB', 'TE', 'I', 'XE', 'CS', 'BA', 'LA', 'CE', 'PR', 'ND',
'PM', 'SM', 'EU', 'GD', 'TB', 'DY', 'HO', 'ER', 'TM', 'YB',
'LU', 'HF', 'TA', 'W', 'RE', 'OS', 'IR', 'PT', 'AU', 'HG',
'TL', 'PB', 'BI', 'PO', 'AT', 'RN', 'FR', 'RA', 'AC', 'TH',
'PA', 'U', 'NP', 'PU', 'AM', 'CM', 'BK', 'CF', 'ES', 'FM',
'MD', 'NO', 'LR', 'RF', 'DB', 'SG', 'BH', 'HS', 'MT', 'DS',
'RG', 'UUB', 'UUT', 'UUQ', 'UUP', 'UUH', 'UUS', 'UUO']
return anum2asymb[anum] |
def dict_difference(one, two):
""" Return new dictionary, with pairs if key from one is not in two,
or if value of key in one is another then value of key in two.
"""
class NotFound:
pass
rv = dict()
for key, val in one.items():
if val != two.get(key, NotFound()):
rv[key] = val
return rv |
def tup_to_vs(tup):
"""tuple to version string"""
return '.'.join(tup) |
def make_grid_row(length):
"""Create a row of length with each element set to value."""
row = []
for _ in range(0, length):
row.append(False)
return row |
def uniq_list(in_list):
"""
Takes a list of elements and removes duplicates and returns this list
:param in_list: Input list
:return: List containing unique items.
"""
seen = set()
result = []
for item in in_list:
if item in seen:
continue
seen.add(item)
result.append(item)
return result |
def mean_and_median(values):
"""Gets the mean and median of a list of `values`
Args:
values (iterable of float): A list of numbers
Returns:
tuple (float, float): The mean and median
"""
mean = sum(values) / len(values)
midpoint = int(len(values) / 2)
if len(values) % 2 == 0:
median = (values[midpoint - 1] + values[midpoint]) / 2
else:
median = values[midpoint]
return mean, median |
def strip_space(tokens):
"""
strip spaces
"""
return [t.strip() for t in tokens] |
def is_sorted(l):
"""Checks if the list is sorted """
return all(l[i] <= l[i+1] for i in range(len(l)-1)) |
def implode(exploded):
"""Convert a list of lists representing a
screen display into a string."""
return '\n'.join([''.join(row) for row in exploded]) |
def slope_to_pos_interp(l: list) -> list:
"""Convert positions of (x-value, slope) pairs to critical pairs.
Intended
for internal use. Inverse function of `pos_to_slope_interp`.
Result
------
list
[(xi, yi)]_i for i in len(function in landscape)
"""
output = [[l[0][0], 0]]
# for sequential pairs in [(xi,mi)]_i
for [[x0, m], [x1, _]] in zip(l, l[1:]):
# uncover y0 and y1 from slope formula
y0 = output[-1][1]
y1 = y0 + (x1 - x0) * m
output.append([x1, y1])
return output |
def _local(tag):
"""Extract the local tag from a namespaced tag name (PRIVATE)."""
if tag[0] == '{':
return tag[tag.index('}') + 1:]
return tag |
def compute_padding(J_pad, T):
"""
Computes the padding to be added on the left and on the right
of the signal.
It should hold that 2**J_pad >= T
Parameters
----------
J_pad : int
2**J_pad is the support of the padded signal
T : int
original signal support size
Returns
-------
pad_left: amount to pad on the left ("beginning" of the support)
pad_right: amount to pad on the right ("end" of the support)
"""
T_pad = 2**J_pad
if T_pad < T:
raise ValueError('Padding support should be larger than the original' +
'signal size!')
to_add = 2**J_pad - T
pad_left = to_add // 2
pad_right = to_add - pad_left
if max(pad_left, pad_right) >= T:
raise ValueError('Too large padding value, will lead to NaN errors')
return pad_left, pad_right |
def flttn(lst):
"""Just a quick way to flatten lists of lists"""
lst = [l for sl in lst for l in sl]
return lst |
def isTerminated( lines ):
"""Given .cpp/.h source lines as text, determine if assert is terminated."""
x = " ".join(lines)
return ';' in x \
or x.count('(') - x.count(')') <= 0 |
def parse_slate(slate):
"""Parses slate document
Args:
slate (dict): slate document
Returns:
dict
"""
wanted = ['_id', 'slateTypeName', 'siteSlateId', 'gameCount', 'start', 'end', 'sport']
return {k: slate[k] for k in wanted} |
def main( argv ):
"""
Script execution entry point
@param argv Arguments passed to the script
@return Exit code (0 = success)
"""
# return success
return 0 |
def piecewise_attractor_function(x, max_positive=1.0, max_negative=0.5):
""" This shunts the input to one value or the other depending on if its greater or less than 0.5.
:param x: x-value
:return: y-value
"""
if x < 0.5:
return max_positive
else:
return -max_negative |
def validate_inferred_freq(freq, inferred_freq, freq_infer):
"""
If the user passes a freq and another freq is inferred from passed data,
require that they match.
Parameters
----------
freq : DateOffset or None
inferred_freq : DateOffset or None
freq_infer : bool
Returns
-------
freq : DateOffset or None
freq_infer : bool
Notes
-----
We assume at this point that `maybe_infer_freq` has been called, so
`freq` is either a DateOffset object or None.
"""
if inferred_freq is not None:
if freq is not None and freq != inferred_freq:
raise ValueError(
f"Inferred frequency {inferred_freq} from passed "
"values does not conform to passed frequency "
f"{freq.freqstr}"
)
elif freq is None:
freq = inferred_freq
freq_infer = False
return freq, freq_infer |
def squared(x):
"""
Input:
x, float or int
Base value
Output:
float, base to the power 2.
"""
return float(x) * float(x) |
def update_h_w_curr(h_rem, w_rem):
"""Helper function to downsample h and w by 2 if currently greater than 2"""
h_curr, w_curr = min(h_rem, 2), min(w_rem, 2)
h_rem = h_rem // 2 if h_rem > 1 else 1
w_rem = w_rem // 2 if w_rem > 1 else 1
return h_rem, w_rem, h_curr, w_curr |
def fileExtension(filename):
"""Returns file extension if exists
Arguments:
filename (str): file name
Returns:
str: file extension or None
"""
if not isinstance(filename, str):
return None
fext = filename.split('.')
if len(fext) < 2:
return None
else:
return fext[-1] |
def create_fixed_income_regex(input_symbol: str) -> str:
"""Creates a regular expression pattern to match the fixed income symbology.
To create the regular expression patter, the function uses the fact that within the
ICE consolidated feed, all the fixed income instruments are identified by the root
symbol ( a unique mnemonic based on the exchange ticker or the ISIN, where no exchange
ticker is available), prefixed with the type and the optional session indicator. In
addition to this minimal symbology setup, fixed income symbols can present optional
elements such as the "dirty bond" marker and the sub-market indicator.
The function only requires the root symbol, prefixed with the type and the optional
session indicator, to generate a regular expression pattern, and takes care to
autonomously extend the pattern to match as well all the optional components of the
symbol.
Parameters
----------
input_symbol: str
A fixed income symbol consisting of the root symbol prefixed with the type
identifier (B) and optional session indicator.
Returns
-------
str
The regular expression pattern that matches the input symbol as well as all the
optional components.
"""
return rf"\b{input_symbol}\b\\{{0,1}}D{{0,1}}@{{0,1}}[a-zA-Z0-9]{{1,10}}" |
def normalize_alef_maksura_bw(s):
"""Normalize all occurences of Alef Maksura characters to a Yeh character
in a Buckwalter encoded string.
Args:
s (:obj:`str`): The string to be normalized.
Returns:
:obj:`str`: The normalized string.
"""
return s.replace(u'Y', u'y') |
def calc_horizontal_depth_part2(lines):
"""
Calculate horizontal depth with aim
:param lines:List of tuples of lines from file
:returns: Horizontal position multiplied by final depth
"""
horizontal, depth, aim = 0, 0, 0
for command in lines:
# command = ('forward', '5')
units = int(command[1])
if command[0] == "forward":
# increases horizontal position by X units
horizontal += units
# increases depth by "aim * X" units
depth += aim * units
elif command[0] == "down":
# increases aim by X units
aim += units
elif command[0] == "up":
# decreases aim by X units
aim -= units
# final horizontal position multiplied by final depth
return horizontal * depth |
def empty_list(number_of_items=0, default_item=None):
"""
Convenience fn to make a list with a pre-determined number of items.
Its more readable than:
var = [None] * number_of_items
:param number_of_items: (int)
how many items in the list
:param default_item:
the list will come pre filled with that this in every item
example:
default_item = "foo"
return = ["foo", "foo", "foo"...]
:return:
(list)
"""
list_ = [default_item] * number_of_items
return list_ |
def to_consistent_data_structure(obj):
"""obj could be set, dictionary, list, tuple or nested of them.
This function will convert all dictionaries inside the obj to be list of tuples (sorted by key),
will convert all set inside the obj to be list (sorted by to_consistent_data_structure(value))
>>> to_consistent_data_structure([
{"a" : 3, "b": 4},
( {"e" : 5}, (6, 7)
),
set([10, ]),
11
])
Out[2]: [[('a', 3), ('b', 4)], ([('e', 5)], (6, 7)), [10], 11]
"""
if isinstance(obj, dict):
return [(k, to_consistent_data_structure(v)) for k, v in sorted(list(obj.items()), key=lambda x: x[0])]
elif isinstance(obj, set):
return sorted([to_consistent_data_structure(v) for v in obj])
elif isinstance(obj, list):
return [to_consistent_data_structure(v) for v in obj]
elif isinstance(obj, tuple):
return tuple([to_consistent_data_structure(v) for v in obj])
return obj |
def process_schema_name(name):
""" Extract the name out of a schema composite name by remove unnecessary strings
:param name: a schema name
:return: a string representing the processed schema
"""
new_raw_name = name.replace("_schema.json", '').replace('.json', '')
name_array = new_raw_name.split('_')
output_name = ""
for name_part in name_array:
output_name += name_part.capitalize()
return output_name |
def backend_anything(backends_mapping):
"""
:return: Anything backend
"""
return list(backends_mapping.values())[1] |
def parse_bint(bdata):
""" Convert bencoded data to int """
end_pos = bdata.index(ord("e"))
num_str = bdata[1:end_pos]
bdata = bdata[end_pos + 1 :]
return int(num_str), bdata |
def unindent_text(text, pad):
"""
Removes padding at the beginning of each text's line
@type text: str
@type pad: str
"""
lines = text.splitlines()
for i,line in enumerate(lines):
if line.startswith(pad):
lines[i] = line[len(pad):]
return '\n'.join(lines) |
def action_list_to_string(action_list):
"""Util function for turning an action list into pretty string"""
action_list_string = ""
for idx, action in enumerate(action_list):
action_list_string += "{} ({})".format(action["name"], action["action"]["class_name"])
if idx == len(action_list) - 1:
continue
action_list_string += " => "
return action_list_string |
def jekyllpath(path):
""" Take the filepath of an image output by the ExportOutputProcessor
and convert it into a URL we can use with Jekyll. This is passed to the exporter
as a filter to the exporter.
Note that this will be directly taken from the Jekyll _config.yml file
"""
return path.replace("./", "{{site.url}}{{site.baseurl}}/") |
def parseBoardIdentifier(lsusbpattern):
"""
Parse the lsusb identifier assigned to the board. Note that some
boards such as the PyBoard won't be enumerated by lsusb unless they
are in DFU programming mode. Array values are as follows:
key: lsusb identifier
0: name of the device
1: Is the board supported by Kubos?
2: the configuration file for use by the flasher, if any
3: the command or argument specific to the board (mostly for openocd)
"""
# FIXME
# But note that the STLINK-V2 could be connected to many different boards.
# Also: there's a v2 and a v2-1 config file for the STLINK programmer
patterns = {
'0483:3748': ['STMicro ST-LINK/V2 (old type)',
True, 'stm32f407vg.cfg', 'stm32f4_flash'],
'0483:374b': ['STMicro ST-LINK/V2-1 (new type)',
True, 'stm32f407g-disc1.cfg', 'stm32f4_flash'],
'0483:df11': ['STM32F405 PyBoard',
True, 'USE dfu-util!', '***'],
'0451:2046': ['TI MSP430F5529 Launchpad',
True, 'USE mspdebug!', '***'],
'0451:f432': ['TI MSP430G2553 Launchpad',
False, 'NOT SUPPORTED', '/usr/bin/sleep 1']
}
if lsusbpattern in patterns:
return patterns[lsusbpattern]
return None |
def convertRegionDisplayNameToRegionNameWithoutDot(regionDisplayName):
"""Converts given region display name to region name without dot. For ex; 'East US' to 'eastus'"""
return str(regionDisplayName).lower().replace(" ", "") |
def find_subclass(cls, subname):
"""Find a subclass by name.
"""
l = [cls]
while l:
l2 = []
for c in l:
if c.__name__ == subname:
return c
l2 += c.__subclasses__()
l = l2
return None |
def mag2flux(mags, mag_zeropoint=0):
"""
Magnitude to flux convertion (arbitrary array shapes)
"""
return 10 ** (-0.4 * (mags + mag_zeropoint)) |
def check_selfLink_equal(url1, url2):
"""
'https://googleapi/project/project_id/...' == '/project/project_id/...'
"""
traced_url1 = url1.split('project')[1]
traced_url2 = url2.split('project')[1]
return traced_url1 == traced_url2 |
def rev_c(seq):
"""
simple function that reverse complements a given sequence
"""
tab = str.maketrans("ACTGN", "TGACN")
# first reverse the sequence
seq = seq[::-1]
# and then complement
seq = seq.translate(tab)
return seq |
def get_all_files(target_dir):
"""Recurse the all subdirs and list os abs paths
:param str target_dir: Indicates whether the target is a file
:rtype: List[str]
"""
import os
res = []
for root, d_names, f_names in os.walk(target_dir):
for f in f_names:
res.append(os.path.join(root, f))
return res |
def soft_mask(sequence, left, right):
"""Lowercase the first left bases and last right bases of sequence
>>> soft_mask('ACCGATCGATCGTAG', 2, 1)
'acCGATCGATCGTAg'
>>> soft_mask('ACCGATCGATCGTAG', 0, 2)
'ACCGATCGATCGTag'
>>> soft_mask('ACCGATCGATCGTAG', 2, 0)
'acCGATCGATCGTAG'
>>> soft_mask('ACCGATCGATCGTAG', 0, 0)
'ACCGATCGATCGTAG'
"""
if left == 0 and right == 0:
return sequence
if left == 0 and right > 0:
return sequence[:-right] + sequence[-right:].lower()
if left > 0 and right == 0:
return sequence[:left].lower() + sequence[left:]
return sequence[:left].lower() + sequence[left:-right] + sequence[-right:].lower() |
def convert_bytes(n):
"""
Convert a size number to 'K', 'M', .etc
"""
symbols = ('K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y')
prefix = {}
for i, s in enumerate(symbols):
prefix[s] = 1 << (i + 1) * 10
for s in reversed(symbols):
if n >= prefix[s]:
value = float(n) / prefix[s]
return '%.1f%s' % (value, s)
return "%sB" % n |
def transformed_name(key: str) -> str:
"""Generate the name of the transformed feature from original name."""
return key + '_xf' |
def deg2tenths_of_arcminute(deg):
"""
Return *deg* converted to tenths of arcminutes (i.e., arcminutes *
10).
"""
return 10 * deg * 60 |
def can_slice(input_shape, output_shape):
"""Check if the input_shape can be sliced down to match the output_shape."""
if len(input_shape) != len(output_shape):
print("Slice dimensions differ:", input_shape, output_shape)
return False
for in_size, out_size in zip(input_shape, output_shape):
if in_size < out_size:
print("Input too small to slice:", input_shape, output_shape)
return False
return True |
def dumps(name, namelist):
"""
Writes a namelist to a string.
Parameters
----------
name : str
The name of the namelist
namelist : dict
Members of the namelist
Returns
-------
str
String representation of the namelist
"""
# start with the opening marker
result = " ${0}\n".format(name)
# write each key-value pair on a new line
for key, value in namelist.items():
# string values need to be exported in quotes
if isinstance(value, str):
value = "'{0}'".format(value)
# boolean values need to be replace by T or F
elif isinstance(value, bool):
value = "T" if value else 'F'
result += " {0} = {1},\n".format(key, value)
# finish with the closing marker
result += " $END\n"
return result |
def is_gt_seq_non_empty(annotations, empty_category_id):
"""
True if there are animals etc, False if empty.
"""
category_on_images = set()
for a in annotations:
category_on_images.add(a['category_id'])
if len(category_on_images) > 1:
return True
elif len(category_on_images) == 1:
only_cat = list(category_on_images)[0]
if only_cat == empty_category_id:
return False
else:
return True
else:
raise Exception('No category information in annotation entry.') |
def file_is_pdf(filename: str) -> bool:
"""
Check if `filename` has the .pdf extension.
Args:
filename (str): Any filename, including its path.
Returns:
True if `filename` ends with .pdf, false otherwise.
"""
return filename.endswith(".pdf") |
def merge(*args, **kwargs):
"""Merges any dictionaries passed as args with kwargs"""
base = args[0]
for arg in args[1:]:
base.update(arg)
base.update(kwargs)
return base |
def to_x_bytes(bytes):
"""
Take a number in bytes and return a human-readable string.
:param bytes: number in bytes
:type bytes: int
:returns: a human-readable string
"""
x_bytes = bytes
power = 0
while x_bytes >= 1000:
x_bytes = x_bytes * 0.001
power = power + 3
if power == 0:
return '%.0f bytes' % x_bytes
if power == 3:
return '%.0f kB' % x_bytes
if power == 6:
return '%.0f MB' % x_bytes
if power == 9:
return '%.0f GB' % x_bytes
if power == 12:
return '%.0f TB' % x_bytes |
def mean_precision(j1, j2):
"""
Calculate the Precision Index among judges for a given set of evaluations.
In particular, the function takes in input two sets of evaluations (one for each judges)
referring to a single score for a given systems.
For *each* judge, the function computes $P(ji) = P(j1 \cap j2) / P(ji)$, namely the precision
of evaluations of considered judge $ji$.
The two values, $P(j1)$ and P(j2), are then combined by an Harmonic Mean, that is
finally returned by the function.
Parameters:
-----------
j1: set of evaluations of the first judge, corresponding to a **single** score for a **single**
system (e.g., "Method-Comment Aggreement" in Project "X")
j2: set of evaluations of the second judge (see above for further details)
Returns:
--------
pj1: Precision associated to the first judge
pj2: Precision associated to the second judge
F: Armonic Mean between pj1 and pj2
"""
pj1 = 0.0 if not len(j1) else len(j1.intersection(j2))/len(j1)
pj2 = 0.0 if not len(j2) else len(j2.intersection(j1))/len(j2)
if (pj1 == pj2 == 0.0):
return 0.0, 0.0, 0.0
f = 2 * ((pj1 * pj2) / (pj1 + pj2))
return pj1, pj2, f |
def addr_to_address(addr: int) -> str:
"""
Converts a MAC address integer (48 bit) into a string (lowercase hexidecimal
with colons).
"""
out = "{0:012x}".format(addr)
return ":".join(out[2 * i : 2 * i + 2] for i in range(6)) |
def validate_int(s):
"""convert s to int or raise"""
try:
return int(s)
except ValueError:
raise ValueError('Could not convert "%s" to int' % s) |
def dict_sum(A, B):
"""
Sum the elements of A with the elements of B
"""
if isinstance(A, dict) and isinstance(B, dict):
return {key:dict_sum(value, B[key]) for key, value in A.items()}
else:
return A+B |
def format_num(number):
"""add commas"""
return "{:,d}".format(round(number)) |
def validate_ous(requested_ous, existing_ous):
"""
Confirms that the specified organizational unit IDs exist. Also converts
an asterisk to all known OUs. Raises an error on an unknown OU.
"""
if not requested_ous:
raise ValueError("No organizational units specified")
requested = set(requested_ous)
existing = set(existing_ous)
if "*" in requested:
return sorted(list(existing))
missing_ous = requested - existing
if missing_ous:
raise ValueError(f"Unknown OUs: {missing_ous}")
return sorted(list(requested)) |
def generate_net_file_paths(experiment_path_prefix, net_count):
""" Given an 'experiment_path_prefix', return an array of net-file paths. """
assert net_count > 0, f"'net_count' needs to be greater than zero, but was {net_count}."
return [f"{experiment_path_prefix}-net{n}.pth" for n in range(net_count)] |
def listrange2dict(L):
"""
Input: a list
Output: a dictionary that, for i = 0, 1, 2, . . . , len(L), maps i to L[i]
You can use list2dict or write this from scratch
"""
return { i:L[i] for i in range(len(L))} |
def sort_labels(labels):
""" Deal with higher up elements first. """
sorted_labels = sorted(labels, key=len)
# The length of a Subpart label doesn't indicate it's level in the tree
subparts = [l for l in sorted_labels if 'Subpart' in l]
non_subparts = [l for l in sorted_labels if 'Subpart' not in l]
return subparts + non_subparts |
def capitalLettersCipher(ciphertext):
"""
Returns the capital letters in the ciphertext
Parameters:
ciphertext (str): The encrypted text
Returns:
plaintext (str): The decrypted text
Example:
Cipher Text: dogs are cuter than HorsEs in a LooP.
Decoded Text: HELP """
plaintext = "".join([i for i in ciphertext if i.isupper()])
return plaintext |
def convert_bytes(num):
"""
this function will convert bytes to MB.... GB... etc
"""
for x in ['bytes', 'KB', 'MB', 'GB', 'TB']:
if num < 1024.0:
return "%3.1f %s" % (num, x)
num /= 1024.0 |
def progessbar(new, tot):
"""Builds progressbar
Args:
new: current progress
tot: total length of the download
Returns:
progressbar as a string of length 20
"""
length = 20
progress = int(round(length * new / float(tot)))
percent = round(new/float(tot) * 100.0, 1)
bar = '=' * progress + '-' * (length - progress)
return '[%s] %s %s\r' % (bar, percent, '%') |
def split_lambda(some_list, some_function, as_list=False):
""" Splits a list into a dict such that all elements 'x' in 'some_list' that get one value from 'some_function(x)'
end up in the same list.
Example:
split_lambda([1,2,3,4,5,6,7], lambda x: x%2) -> {0: [2, 4, 6], 1: [1, 3, 5, 7]}
if as_list is True, then you would instead get [[2,4,6], [1,3,5,7]] in the above example (although order is not guaranteed)
"""
lists = dict()
for x in some_list:
y = some_function(x)
if y in lists:
lists[y].append(x)
else:
lists[y] = [x]
if as_list:
return list(lists.values())
else:
return lists |
def _is_regex(q):
"""Check if q is a regular expression.
Parameters
----------
q : str
Query string.
Returns
-------
bool
True if q starts with "/" and ends with "/".
"""
return q.startswith("/") and q.endswith("/") |
def output_args(kwargs):
"""
:param kwargs: input parameters
:return: args: dictionary of arguments related to output format
:return: kwargs: dictionary of remaining arguments relating to query
"""
args = {'opendap': kwargs.pop("opendap"), 'ncss': kwargs.pop("ncss"), 'variable': kwargs.pop("variable"),
'output_kind': kwargs.pop("output_kind"), 'download': kwargs.pop("download"),
'download_path': kwargs.pop("download_path")}
return args, kwargs |
def flip_transpose(arr):
"""
Flip a 2D-list (i.e. transpose).
"""
m = len(arr)
n = len(arr[0])
res = [[-1 for _ in range(n)] for _ in range(m)]
for i in range(m):
for j in range(n):
res[i][j] = arr[j][i]
return res |
def pascal(n, i):
"""Get the element value at the nth level and the ith
index for Pascal's triangle. Levels are 0 at top, and
increasing number descending; e.g. indexes
Level 0 0
Level 1 0 1
Level 2 0 1 2
Level 3 0 1 2 3
etc
to return values;
Level 0 1
Level 1 1 1
Level 2 1 2 1
Level 3 1 3 3 1
etc
"""
if i > n:
return 0
if i in [0, n]:
return 1
else:
sum = (pascal(n - 1, i - 1) + pascal(n - 1, i))
return sum |
def insertion_sort(arr):
"""
Choose any element in original list and insert in order in newly partitioned list.
"""
# Iterate over list once
for i in range(len(arr)):
j = i
# Iteratively check current and left element and swap if current is smaller
while (j != 0 and arr[j] < arr[j-1]):
tmp = arr[j-1]
arr[j-1] = arr[j]
arr[j] = tmp
j-=1
return arr |
def get_fully_qualified_name(obj):
"""
Fully qualifies an object name. For example, would return
"usaspending_api.common.helpers.endpoint_documentation.get_fully_qualified_name"
for this function.
"""
return "{}.{}".format(obj.__module__, obj.__qualname__) |
def _add_suffix(name, suffix):
"""Add a suffix to a name, do nothing if suffix is None."""
suffix = "" if suffix is None else "_" + suffix
new_name = name + suffix
return new_name |
def test_sequence(value):
"""Return true if the variable is a sequence. Sequences are variables
that are iterable.
"""
try:
len(value)
value.__getitem__
except:
return False
return True |
def firstEmail(m, d):
"""
Engage stores emails and phone numbers in the 'contacts' section
of a supporter record. This function finds the first email. If
there's not an email record, then we'll return a None.
Parameters:
m dict supporter record
d string default value if an email is not equipped
Returns:
string containing an email address, or
None if no email is configured
"""
if 'contacts' not in m:
return d
for c in m['contacts']:
if c['type'] == 'EMAIL':
return c['value']
return d |
def multi_byte_xor(byte_array, key_bytes):
"""XOR the 'byte_array' with 'key_bytes'"""
result = bytearray()
for i in range(0, len(byte_array)):
result.append(byte_array[i] ^ key_bytes[i % len(key_bytes)])
return result |
def runSafely(funct, fmsg, default, *args, **kwds):
"""Run the function 'funct' with arguments args and
kwds, catching every exception; fmsg is printed out (along
with the exception message) in case of trouble; the return
value of the function is returned (or 'default')."""
try:
return funct(*args, **kwds)
except Exception as e:
print('WARNING: %s: %s' % (fmsg, e))
return default |
def cross_data(clusters, flist):
"""
Matches names in flist to the numbers in clusters.
"""
named_clusters = []
for cl in clusters:
ncl = [flist[s] for s in cl]
named_clusters.append(ncl)
return named_clusters |
def broadcast_rule(shape_a, shape_b):
"""Return output shape of broadcast shape_a, shape_b.
e.g. broadcast_rule((3,2), (4,3,2))
returns output_shape = (4,3,2)
Check out explanations and more examples at
https://docs.scipy.org/doc/numpy-1.10.0/user/basics.broadcasting.html
http://eli.thegreenplace.net/2015/broadcasting-arrays-in-numpy/
"""
assert (isinstance(shape_a, tuple))
assert (isinstance(shape_b, tuple))
if len(shape_a) > len(shape_b):
longer_shape, shorter_shape = shape_a, shape_b
else:
longer_shape, shorter_shape = shape_b, shape_a
len_diff = len(longer_shape) - len(shorter_shape)
for i in range(len_diff):
# pad with leading 1s
shorter_shape = (1,) + shorter_shape
assert len(shorter_shape) == len(longer_shape)
output_shape = list(longer_shape)
for i in range(len(output_shape)):
assert (shorter_shape[i] == longer_shape[i]) \
or (shorter_shape[i] == 1) \
or (longer_shape[i] == 1)
output_shape[i] = max(shorter_shape[i], longer_shape[i])
return tuple(output_shape) |
def C2F(degC):
"""degC -> degF"""
return 1.8*degC+32. |
def bool_xor(a, b):
"""Python's ^ operator is a bitwise xor, so we need to make a boolean equivalent function."""
return (a and not b) or (not a and b) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.