content stringlengths 42 6.51k |
|---|
def spatial_overlap_conv_1x1_stride_2(p):
"""
This method computes the spatial overlap of 1x1 convolutional layer with stride 2 in terms of its input feature map's
spatial overal value (p).
"""
return 2 * max(p - 0.5, 0) |
def interp_to_order(interp):
"""Convert interpolation string to order."""
if isinstance(interp, int):
return interp
order_map = {None: 0, "nearest": 0, "linear": 1, "quadratic": 2, "cubic": 3}
return order_map.get(interp, None) |
def profiler_setup(config):
"""
Set up profiler based on config
"""
if not config["profile"]:
return
import cProfile
profiler = cProfile.Profile()
profiler.enable()
return profiler |
def isclose(a, b, rel_tol=1e-09, abs_tol=0.0):
"""
Notes
=====
* rel_tol is a relative tolerance, it is multiplied by the greater
of the magnitudes of the two arguments; as the values get larger,
so does the allowed difference between them while still considering them equal.
* abs_tol is an absolute tolerance that is applied as-is in all cases.
If the difference is less than either of those tolerances,
the values are considered equal.
"""
return abs(a-b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol) |
def length_gt(value, arg):
"""Returns a boolean of whether the value's length is greater than the
argument.
"""
return len(value) > int(arg) |
def unique(list1):
"""Delete duplicate elements in a list.
Parameters
----------
list1 : Input list that may contain duplicate elements
Returns
-------
unique_list : Output list with duplicate elements deleted
"""
unique_list = []
# traverse for all elements
for x in list1:
# check if exists in unique_list or not
if x not in unique_list:
unique_list.append(x)
# print list
return unique_list |
def hold(state):
"""Apply the hold action to a state to yield a new state.
Reap the 'pending' points and it becomes the other player's turn.
"""
player, me, you, pending = state
return (not player, you, me + pending, 0) |
def service_factory(prefix, base):
""" Test utility to create subclasses of the above ServiceHandler classes
based on a prefix and base. The prefix is set as the ``name`` attribute
on the resulting type.
e.g. ``service_factory("foo", ServicePoolHandler)`` returns a type
called ``FooServicePoolHandler`` that inherits from ``ServicePoolHandler``,
and ``FooServicePoolHandler.name`` is ``"foo"``.
If prefix is falsy, return the base without modification.
"""
if not prefix:
return base
name = prefix.title() + base.__name__
cls = type(name, (base,), {'name': prefix})
return cls |
def size_box(box):
"""Calculates the length and the height of a box.
Arguments:
box: boundaries of the box (left, top, right, bottom)
Return:
length_box: length of the box
height_box: height of the box
"""
length_box = box[2]-box[0]
height_box = box[3]-box[1]
return [length_box, height_box] |
def nvt_cv(e1, e2, kt, volume = 1.0):
"""Compute (specific) heat capacity in NVT ensemble.
C_V = 1/kT^2 . ( <E^2> - <E>^2 )
"""
cv = (1.0/(volume*kt**2))*(e2 - e1*e1)
return cv |
def find_largest_hotspot(centroid_list: list) -> int:
"""
Description: Find the size of the cluster with the most data points
:param centroid_list: list of centroid for each final cluster.
each centroid in form of [longitude, latitude, # location]
:return: an integer which is the length of the longest cluster
"""
largest_hotspot = 0 # set the current largest size
for a_centroid in centroid_list: # iterate through each centroid
if a_centroid[2] > largest_hotspot: # if [# location] > the current largest size
largest_hotspot = a_centroid[2] # change the largest size to the size of this centroid
return largest_hotspot |
def pop_kwargs_with_prefix(prefix, kwargs):
"""Pop all items from a dictionary that have keys beginning with a prefix.
Parameters
----------
prefix : str
kwargs : dict
Returns
-------
kwargs : dict
Items popped from the original directory, with prefix removed.
"""
keys = [key for key in kwargs if key.startswith(prefix)]
return {key[len(prefix):]: kwargs.pop(key) for key in keys} |
def detailed_event_metrics_to_list(detailed_event_results):
""" Converting detailed event metric results to a list (position of each item is fixed)
Argument:
detailed_event_results (dictionary): as provided by the 3rd item in the results of eval_events function
Returns:
list: Item order: 0. correct, 1. deletions 2. merged, 3. fragmented, 4. fragmented and merged, 5. fragmenting, 6. merging, 7. fragmenting and merging, 8. insertions, 9. total of actual events, 10. total of detected events
"""
return [
detailed_event_results["C"],
detailed_event_results["D"],
detailed_event_results["M"],
detailed_event_results["F"],
detailed_event_results["FM"],
detailed_event_results["F'"],
detailed_event_results["M'"],
detailed_event_results["FM'"],
detailed_event_results["I'"],
detailed_event_results["total_gt"],
detailed_event_results["total_det"],
] |
def get_cap(assets):
"""
Converts assets into corresponding market capitalization category.
Returns the market capitalization category based on the provided net assets
or market capitalization value.
Parameters
----------
assets : int
Net Assets of mutual funds or Exchange Traded Funds, market
capitalization of stocks.
Returns
-------
str
Formatted version of error with type and message.
"""
if assets < 0:
return "UNKNOWN"
elif assets < 2000000000:
return "small"
elif assets < 10000000000:
return "mid"
else:
return "large" |
def object_attr_string_repr(attr):
"""Returns string representation of attr."""
return str(attr) if attr is not None else '' |
def string_num(row_num):
"""
This function returns a 3-character string that contains a register row number
in a police daily report
"""
if row_num < 10:
return '00'+str(row_num)
else:
return '0'+str(row_num) |
def group_cast(value):
"""Parse a group="n" attribute."""
try:
return int(value)
except ValueError:
return value |
def remote_url(uri: str) -> str:
"""
Todo (never) :
- actually do something to resolve URLs
"""
if "https" in uri:
return uri
if "git@" in uri:
return uri.replace(":", "/").replace("git@", "https://")
return uri |
def inside(bb, v):
"""
Test if a point is inside a bounding box.
Arguments:
bb: Bounding box list [minx, maxx, miny, maxy[, minz, maxz]].
v: 3-tuple
Returns:
True if v is inside the bounding box, false otherwise.
Raises:
ValueError if the number of dimensions of the point and bounding box
don't match.
"""
rv = (bb[0] <= v[0] <= bb[1]) and (bb[2] <= v[1] <= bb[3])
if len(bb) == 6 and len(v) == 3:
return rv and (bb[4] <= v[2] <= bb[5])
elif len(bb) == 4 and len(v) == 2:
return rv
else:
raise ValueError("bbox and v must both be 2D or 3D") |
def pretty_byte_count(num):
"""Converts integer into a human friendly count of bytes, eg: 12.243 MB"""
if num == 1:
return "1 byte"
elif num < 1024:
return "%s bytes" % (num)
elif num < 1048576:
return "%.2f KB" % (num / 1024.0)
elif num < 1073741824:
return "%.3f MB" % (num / 1048576.0)
elif num < 1099511627776:
return "%.3f GB" % (num / 1073741824.0)
else:
return "%.3f TB" % (num / 1099511627776.0) |
def unique3(s):
"""Implement an algorithm to determine if a string has all unique characters. What if you
can not use additional data structures?"""
# O(nlogn) time, O(n) space
previous = None
for char in sorted(s):
if char == previous:
return False
previous = char
return True |
def cplex_varname(k, j: int) -> str:
"""Return name for quadratic program variable to meet CLPEX conventions."""
if k == 0:
name = "x" + "_" + str(j)
else:
name = "x" + str(k) + "_" + str(j)
return name |
def factorial(n):
"""return n!"""
return 1 if n < 2 else n * factorial(n-1) |
def uri_split(uri):
"""Split Pyro4 URI in name, ip and port."""
name = uri[uri.find("PYRO:") + 5:uri.find("@")]
ip = uri[uri.find("@") + 1:uri.find(":", 7)]
port = int(uri[uri.find(":", 7) + 1:])
return name, ip, port |
def add_at_idx(seq, k, val):
"""
Add (subtract) a value in the tuple at position k
"""
lst = list(seq)
lst[k] += val
return tuple(lst) |
def indent(s, depth):
# type: (str, int) -> str
"""
Indent a string of text with *depth* additional spaces on each line.
"""
spaces = " "*depth
interline_separator = "\n" + spaces
return spaces + interline_separator.join(s.split("\n")) |
def ms2knots(ms: float) -> float:
"""
Convert meters per second to knots.
:param float ms: m/s
:return: speed in knots
:rtype: float
"""
if not isinstance(ms, (float, int)):
return 0
return ms * 1.94384395 |
def _get_referenced_libs(specs):
"""
Returns all libs that are referenced in specs.apps.depends.libs
"""
active_libs = set()
for app_spec in specs['apps'].values():
for lib in app_spec['depends']['libs']:
active_libs.add(lib)
return active_libs |
def emap(func, iter_, **kwargs):
"""
Eager version of the builtin map function.
This provides the same functionality as python2 map.
Note this is inefficient and should only be used when prototyping and
debugging.
Extended functionality supports passing common kwargs to all functions
"""
return [func(arg, **kwargs) for arg in iter_]
# return list(map(func, iter_)) |
def _build_drift_insight(graph_result):
"""
Build drift insight
:type graph_result: BoltStatementResult
:param graph_result: Graph data returned by the validation_query
:return: Dictionary representing the addition data we have on the drift
"""
data = {}
for k in graph_result.keys():
data[k] = graph_result[k]
return data |
def tokenized_by_answer(context, answer_text, answer_start, tokenizer):
"""
Locate the answer token-level position after tokenizing as the original location is based on
char-level
snippet modified from: https://github.com/haichao592/squad-tf/blob/master/dataset.py
:param context: passage
:param answer_text: context/passage
:param answer_start: answer start position (char level)
:param tokenizer: tokenize function
:return: tokenized passage, answer start index, answer end index (inclusive)
"""
fore = context[:answer_start]
mid = context[answer_start: answer_start + len(answer_text)]
after = context[answer_start + len(answer_text):]
tokenized_fore = tokenizer(fore)
tokenized_mid = tokenizer(mid)
tokenized_after = tokenizer(after)
tokenized_text = tokenizer(answer_text)
for i, j in zip(tokenized_text, tokenized_mid):
if i != j:
return None
words = []
words.extend(tokenized_fore)
words.extend(tokenized_mid)
words.extend(tokenized_after)
answer_start_token, answer_end_token = len(tokenized_fore), len(tokenized_fore) + len(tokenized_mid) - 1
return words, answer_start_token, answer_end_token |
def rectangles_collide(actual_position, calculated_position):
"""
Detects if the two given boxes collide
"""
x_actual = actual_position.get("x", None)
y_actual = actual_position.get("y", None)
w_actual = actual_position.get("width", None)
h_actual = actual_position.get("height", None)
x_calculated = calculated_position.get("x", None)
y_calculated = calculated_position.get("y", None)
w_calculated = calculated_position.get("width", None)
h_calculated = calculated_position.get("height", None)
#conditions
x_a = (x_actual <= x_calculated) and (x_calculated < (x_actual + w_actual))
x_b = (x_calculated <= x_actual) and (x_actual < (x_calculated + w_calculated))
y_a = (y_actual <= y_calculated) and (y_calculated < (y_actual + w_actual))
y_b = (y_calculated <= y_actual) and (y_actual < (y_calculated + w_calculated))
if (((x_a) or (x_b)) and ((y_a) or (y_b))):
return True |
def rule_exists(rules, from_port, to_port, ip_protocol='tcp', cidr_ip='0.0.0.0/0'):
""" A convenience method to check if an authorization rule in a security
group exists.
"""
for rule in rules:
if rule.ip_protocol == ip_protocol and rule.from_port == from_port and \
rule.to_port == to_port and cidr_ip in [ip.cidr_ip for ip in rule.grants]:
return True
return False |
def match(pattern, string):
"""String matching function with wildcard characters.
"""
if not len(pattern) and not len(string):
return True
if len(pattern) > 1 and pattern[0] == '*' and len(string) == 0:
return False
if (len(pattern) > 0 and pattern[0] == '?') or \
(len(pattern) != 0 and len(string) != 0 and pattern[0] == string[0]):
return match(pattern[1:], string[1:])
if len(pattern) != 0 and pattern[0] == '*':
return match(pattern[1:], string) or match(pattern, string[1:])
return False |
def get_decks(text):
"""
>>> get_decks(EXAMPLE)
[[9, 2, 6, 3, 1], [5, 8, 4, 7, 10]]
"""
decks = [[], []]
p = 0
for line in text.strip().split("\n"):
if line.startswith("Player"):
continue
if line == "":
p += 1
continue
decks[p].append(int(line))
return decks |
def fill_gaps(l):
"""
Return l replacing empty strings with the value from the previous position.
Parameters
----------
l: list
Returns
-------
list
"""
lnew = []
for i in l:
if i == '':
lnew.append(lnew[-1])
else:
lnew.append(i)
return lnew |
def array_reverse_order_changed_distances(size, move):
"""Aid function for delta evaluation.
Works with the array_reverse_order move type.
This function returns the pairs who would have an altered evaluation
value due to the move.
Parameters
----------
size : int
The size of the array.
move : tuple of int
A tuple of 2 ints that represents a single valid move.
Returns
-------
set of tuple
this set contains a tuple with every (from,to) pair that would have
an altered evaluation value due to the move.
A pair (x, y) and a pair (y, x) are assumed to have different
evaluation values.
Examples
--------
Some simple examples to demonstrate the behaviour:
.. doctest::
>>> from lclpy.evaluation.deltaeval.delta_tsp import \\
... array_reverse_order_changed_distances as \\
... changed_distances
... # init
>>> size = 10
... # tests
... # since the order of the items in a set might be different,
... # they are compared to an equivalent set.
>>> changed = changed_distances(size, (4, 8))
>>> changed == {(3, 4), (4, 5), (5, 6), (6, 7), (7, 8), (8, 9)}
True
>>> changed = changed_distances(size, (4, 9))
>>> changed == {(3, 4), (4, 5), (5, 6),
... (6, 7), (7, 8), (8, 9), (9, 0)}
True
>>> changed = changed_distances(size, (0, 4))
>>> changed == {(9, 0), (0, 1), (1, 2), (2, 3), (3, 4), (4, 5)}
True
>>> changed = changed_distances(size, (0, 9))
>>> changed == {(0, 1), (1, 2), (2, 3), (3, 4), (4, 5),
... (5, 6), (6, 7), (7, 8), (8, 9), (9, 0)}
True
"""
changed_dist = set()
# Calculating the distances that are always changed
if (move[0] == 0):
changed_dist.add((size - 1, 0))
else:
changed_dist.add((move[0] - 1, move[0]))
if (move[1] == size - 1):
changed_dist.add((size - 1, 0))
else:
changed_dist.add((move[1], move[1] + 1))
# calculating the distances that are only changed if X -> Y causes a
# different evaluation value than Y -> X
for i in range(move[0], move[1]):
changed_dist.add((i, i + 1))
return changed_dist |
def moeda(n=0, moeda='R$'):
"""
-> Formata o valor para o tipo Moeda
:param n: Valor a ser formatado
:param moeda: Tipo da moeda
:return: O valor formato em moeda
"""
r = f'{moeda}{n:>8.2f}'.replace('.', ',')
return r |
def mean_df(objects):
"""Basic calculation of mean (average) of a list of DataFrames.
Parameters
----------
objects : list of pandas.DataFrame
the DataFrames to calculate the mean (NB: technically, these don't
have to be DataFrames. They must be closed on the `sum` operation
and over division by a float.
Returns
-------
pandas.DataFrame :
the mean of each element in the DataFrame
"""
return sum(objects) / float(len(objects)) |
def prob_of_sick_among_m(p, m):
""" returns the probability that there exists at least one sick person
among m independent people, each sick with probability p.
"""
return (1 - (1-p)**m) |
def simple_quicksort(alist):
"""
Simple implementation.
:param alist: list
:return: sorted list
"""
if len(alist) <= 1:
return alist
p_item = alist[0]
smaller_list = [a for a in alist[1:] if a <= p_item]
larger_list = [b for b in alist[1:] if b > p_item]
return simple_quicksort(smaller_list) + [p_item] + simple_quicksort(larger_list) |
def get_locations(top_container_info):
"""Gets a string representation of a location for an ArchivesSpace top container.
Args:
top_container_info (dict): json for a top container (with resolved container locations)
Returns:
string: all locations associated with the top container, separated by a comma.
"""
def make_short_location(loc_data):
return ".".join([
loc_data.get("room", "").strip().replace("Vault ", ""),
loc_data.get("coordinate_1_indicator", "").strip(),
loc_data.get("coordinate_2_indicator", "").strip()])
locations = None
if top_container_info.get("container_locations"):
locations = ",".join([make_short_location(c["_resolved"]) for c in top_container_info.get("container_locations")])
return locations |
def calculate_Xmech(Xmax):
"""Proposed Xmech value for given Xmax value.
All values in basic SI units.
"""
Xclearance = 1e-3 + (Xmax - 3e-3) / 5
return(Xmax + Xclearance) |
def rank_group(group, reverse=True):
"""
rank QA group data by score
:param group: QA group data
:param reverse: True or False
:return:
"""
group.sort(key=lambda x: x['score'], reverse=reverse)
return group |
def binary_string_to_num(bvalue):
""" convert from binary string (as list of chars)to int """
return int("".join(bvalue), 2) |
def to_uni(s):
""" str => unicode """
return s.decode("utf_8") |
def size_to_str(size):
"""
@brief Determines a string representation for a given size
"""
lookup = {1:'b', 2:'w', 4:'d', 8:'q'}
try:
return lookup[size]
except:
return '' |
def find_loop(head):
"""
Returns the node that originates a loop if a loop exists
"""
if not head:
return None
slow, fast = head, head
while fast and fast.next and fast.next.next:
fast = fast.next.next
slow = slow.next
if slow is fast:
break
if slow is fast:
slow = head
while slow is not fast:
slow = slow.next
fast = fast.next
return slow
else:
return None |
def eval_tuple(arg_return):
"""Evaluate a tuple string into a tuple."""
if arg_return[0] not in ["(", "["]:
arg_return = eval(arg_return)
else:
splitted = arg_return[1:-1].split(",")
List = []
for item in splitted:
try:
item = eval(item)
except:
pass
if item == "":
continue
List.append(item)
arg_return = tuple(List)
return arg_return |
def is_boolean(value):
"""Checks if `value` is a boolean value.
Args:
value (mixed): Value to check.
Returns:
bool: Whether `value` is a boolean.
Example:
>>> is_boolean(True)
True
>>> is_boolean(False)
True
>>> is_boolean(0)
False
See Also:
- :func:`is_boolean` (main definition)
- :func:`is_bool` (alias)
.. versionadded:: 1.0.0
.. versionchanged:: 3.0.0
Added ``is_bool`` as alias.
"""
return isinstance(value, bool) |
def calc_orbit_times(time_stamp, transitC, exposure_time, orb_p):
"""
Calculates the start, end and center of the transit from the provided times
input:
time_stamp: type: float, time
transitC: type:float, transit center - 2400000.
exposure_times: type: float, exposure time in seconds
orb_p: type: float, orbital period in days
output:
orbit_start (, orbit_end, orbit_center): times of current exposure relative to transit start, end, center in days
"""
#this allows to really think about start and end of the exposures. It might be interesting for long exposures, but I'm leaving this for later
orbit_center = (time_stamp - transitC + 2400000.)% orb_p
#orbit_start = (time_stamp-exposure_time/(2.*24.*3600.)- transitC + 2400000.) % orb_p
#orbit_end = (time_stamp+exposure_time/(2.*24.*3600.)- transitC + 2400000.) % orb_p
return orbit_center |
def kdelta(i: int, j: int) -> float: # testpragma: no cover
# coverage: ignore
"""Delta function."""
return 1.0 if i == j else 0.0 |
def tastes_like_gdal(seq):
"""Return True if `seq` matches the GDAL geotransform pattern."""
return seq[2] == seq[4] == 0.0 and seq[1] > 0 and seq[5] < 0 |
def oneline(string: str) -> str:
"""Helper method that transform multiline string to one line for grepable output"""
return " ".join(line.strip() for line in string.splitlines()) |
def row_processor(key, row, arg):
"""(row, arg) => return pred function
Avoid using lambda, generator and nested func.
row_processor should be picklable for multiprocess computation.
"""
row[key] = arg
return True |
def pluralize(count: int) -> str:
"""
Return 's' as long as count is not 1
:param count: as int
:return:
"""
return '' if count == 1 else 's' |
def removeComments(line):
"""
function : Remove Comments
input : String
output : String
"""
words = line.split("#")
if len(words) < 2:
return line
return words[0] |
def swap_bits(s,i,j):
""" Swap bits i, j in integer s.
Parameters
-----------
s: int
spin configuration stored in bit representation.
i: int
lattice site position to be swapped with the corresponding one in j.
j: int
lattice site position to be swapped with the corresponding one in i.
"""
x = ( (s>>i)^(s>>j) ) & 1
return s^( (x<<i)|(x<<j) ) |
def tol(word: str) -> int:
"""Return the tolerance (max Levenshtein distance) accepted for the specific word
based on its length.
"""
return min(3, max(len(word) // 2, 1)) |
def summation(lower, upper):
"""Returns the sum of the numbers from lower through upper"""
#base case
if lower > upper:
return 0
#recursive case
return lower + summation(lower + 1, upper) |
def GetNextHigh(temp, templist):
"""Outputs the next higher value in the list."""
templist = (int(t) for t in templist if t != '')
templist = [t for t in templist if t > int(temp)]
if templist: return min(templist)
else: return None |
def validate_value(arg):
"""Function: validate_value
Description: Test function.
Arguments:
"""
return arg == "value" |
def _availability_zone_to_region_name(zone):
"""Get the region_name from an availability zone by removing last letter
:type zone: str
:param zone: name of availability zone
:returns str -- the name of the region
"""
return zone[:-1] |
def alphabetical(lst):
""" Sorts a list of tuples in reverse alphabetical order by the first key
in the tuple.
Arguments:
lst -- the list to sort
Returns:
the sorted list
"""
return list(reversed(sorted(lst, key=lambda x: x[0]))) |
def sanitise_args(config):
"""
Sanitise command-line configuration.
:param config: Config dictionary (from docopt)
:returns: Config dictionary with all keys stripped of '<' '>' and '--'
"""
sane_conf = {}
for key, value in config.items():
if value is not None:
key = key.lstrip("-><").rstrip("><")
sane_conf[key] = value
return sane_conf |
def cut_point2(data: bytes, min_size=6, max_size=1000, shift=4) -> int:
"""Find first cut point in byte string"""
prefix = data[: min_size - 1]
max_byte = max(prefix)
max_byte2 = max_byte - shift
secondary = None
opt = int((max_size - min_size) / 4)
nbytes = len(data)
i = min_size
while i < nbytes:
cur_byte = data[i]
if cur_byte >= max_byte:
return i
if cur_byte >= max_byte2:
secondary = i
i += 1
if i >= opt and secondary:
return secondary
if i == max_size:
return i
return i |
def _visit_or_none(node, attr, visitor, parent, assign_ctx, visit='visit',
**kws):
"""If the given node has an attribute, visits the attribute, and
otherwise returns None.
"""
value = getattr(node, attr, None)
if value:
return getattr(visitor, visit)(value, parent, assign_ctx, **kws)
else:
return None |
def _get_updated_tags(update_function, *args):
"""Get an updated list of tags.
:param update_function: The function used to update tags.
:param args: (The resource :py:class:`dict` to get updated tags for., The tags :py:class:`list` to update ``resource`` with.)
:rtype: :py:class:`list`
If the tag list update function modifies the existing tag list then that new list is returned. In all other cases
None is returned.
"""
updated_tags = None
resource, tags = args[:2]
existing_tags = resource.get("tags")
if existing_tags is not None:
existing_tags_set = set(existing_tags)
tags_set = set(tags)
updated_tags_set = update_function(existing_tags_set, tags_set)
if existing_tags_set != updated_tags_set:
updated_tags = list(updated_tags_set)
return updated_tags |
def search4letters(phase: str, letters: str='aeiou') -> set:
"""Return a set of the 'letters' found in 'phase'."""
return set(letters).intersection(set(phase)) |
def check_limit(value, max_value):
"""
test if the value is lower than max_value
raise exception otherwise
"""
value = int(value)
if value > max_value:
raise ValueError("Invalid value number: {} is too big. Max is {}.".format(value, max_value))
else:
return value |
def optimal_change(change, coins={1, 5, 10, 25}):
"""
Not efficient recursive call for optimal change problem
"""
if change in coins:
return 1, [change]
counts = list()
outcomes = list()
which_coin = list()
for coin in coins:
if change > coin:
a, b = optimal_change(change-coin, coins=coins)
count = a+1
counts.append(count)
outcomes.append(b)
which_coin.append(coin)
min_count = min(counts)
min_index = counts.index(min_count)
best_outcome = outcomes[min_index]
best_coin = which_coin[min_index]
return min_count, best_outcome + [best_coin] |
def unique_with_order_preserved(items):
"""
Return a list of unique items in the list provided, preserving the order
in which they are found.
"""
new_items = []
for item in items:
if item not in new_items:
new_items.append(item)
return new_items |
def lookup(dikt, key):
"""Return a value from a dictionary or 'unknown'."""
return dikt.get(key, "unknown") |
def floaterr(string):
"""
convert any not numerical/floating point error to 0.0, a float
"""
try:
floatnum = float(string)
except:
floatnum = 0
return floatnum |
def truncate_lines(str, num_lines, EOL="\n"):
"""Truncate and remove EOL characters
:param str: String to truncate
:type str: `str`
:param num_lines: Number of lines to process
:type num_lines: `int`
:param EOL: EOL char
:type EOL: `char`
:return: Joined string after truncation
:rtype: `str`
"""
return EOL.join(str.split(EOL)[0:num_lines]) |
def check_proto(proto):
"""return proto value"""
"""proto value == -1, means all protocols"""
if str(proto) == '-1':
return 'all'
else:
return proto |
def go_to_sortkey(hits, center_id):
""" Step through the lists until the center entry is passed
The center is at the beginning of the list, or after its homonymns
(entries with the same primary sort key). Pass these.
Stop counting when the center_id is passed.
"""
n = 1
stopped = True
for hit in hits:
if center_id == hit["_id"]:
stopped = True
break
n += 1
# if the center, for some reson, is not among the hits, show all hits
n = 0 if not stopped else n
return hits[n:] |
def seat (bpass):
"""Returns the seat ID for the given boarding pass (`bpass`)."""
row = sum(2**(6-n) for n, s in enumerate(bpass[0:7]) if s == 'B')
col = sum(2**(2-n) for n, s in enumerate(bpass[7:] ) if s == 'R')
return (row * 8) + col |
def is_Prime(n):
"""
Check if a number is prime.
"""
# make sure n is a positive integer
n = abs(int(n))
# 0 and 1 are not primes
if n < 2:
return False
# 2 is the only even prime number
if n == 2:
return True
# all other even numbers are not primes
if not n & 1:
return False
# range starts with 3 and only needs to go up the squareroot of n
# for all odd numbers
for x in range(3, int(n ** 0.5) + 1, 2):
if n % x == 0:
return False
return True |
def PhiInv(x):
"""
Inverse
"""
return x**3 - 1.0 |
def add_costs(*args):
"""Add the arguments as costs.
Here when one of the operand is unity, it will be taken as a zero in the
summation.
"""
res = sum(i if abs(i) != 1 else 0 for i in args)
return res if res != 0 else 1 |
def convert_numeral(string: str) -> str:
"""
Convert a assembly numeral into a hexadecimal numeral
:param string: A string representation of a simpSim numeral
:return: Hexadecimal representation of the numeral
"""
return_num: int = 0
is_pointer: bool = string.startswith("[") and string.endswith("]")
string = string.strip("[").strip("]")
replacement_dict = {
'b': 2,
'0x': 16,
'$': 16,
'h': 16,
'-': 10,
'': 10
}
for identifier in replacement_dict:
if identifier in string:
string = string.replace(identifier, '')
return_num = int(string, base=replacement_dict[identifier])
break
if is_pointer: # If number is a pointer.
return "[" + format(return_num, "02X") + "]"
return format(return_num, "02X") |
def tz_dst2std(tzstr: str) -> str:
"""Return the standard time zone abbreviation for the given
timezone abbreviation. Needed, because we cannot use DST abbreviations
when setting the timezone via timedatectl on the tablet.
Using DST-to-STD mappings from:
https://en.wikipedia.org/wiki/List_of_tz_database_time_zones
except for GMT --> IST (Irish Std Time)
"""
mapping = {
'ACDT': 'ACST',
'ADT': 'AST',
'AEDT': 'AEST',
'AKDT': 'AKST',
'BST': 'GMT',
'CDT': 'CST',
'CEST': 'CET',
'EDT': 'EST',
'EEST': 'EET',
'HDT': 'HST',
'IDT': 'IST',
'MDT': 'MST',
'NDT': 'NST',
'NZDT': 'NZST',
'PDT': 'PST',
'WEST': 'WET'
}
if tzstr in mapping:
return mapping[tzstr]
else:
return tzstr |
def trunc(X, high, low):
"""truncates the value X to be within [high, low]"""
return min(high, max(X, low)) |
def get_object_type(object_uri):
"""Return the type of an object from its id."""
obj_parts = object_uri.split('/')
if len(obj_parts) % 2 == 0:
object_uri = '/'.join(obj_parts[:-1])
# Order matters here. More precise is tested first.
if 'records' in object_uri:
obj_type = 'record'
elif 'collections' in object_uri:
obj_type = 'collection'
elif 'groups' in object_uri:
obj_type = 'group'
elif 'buckets' in object_uri:
obj_type = 'bucket'
else:
obj_type = None
return obj_type |
def interpolate_bad_channels(raw, bad_channels=None, auto_bad_channels=None):
"""Interpolates any channels from the two lists."""
# Combine lists of bad channels
all_bad_channels = []
if bad_channels is not None and bad_channels != 'auto':
all_bad_channels += bad_channels
if auto_bad_channels is not None:
all_bad_channels += auto_bad_channels
# Interpolate bad channels
if all_bad_channels != []:
raw.info['bads'] += auto_bad_channels
raw = raw.interpolate_bads()
return raw, all_bad_channels |
def parse_author(a):
"""Parses author name in the format of `Last, First Middle` where
the middle name is sometimes there and sometimes not (and could just be an initial)
Returns: author name as `F. M. Last`
"""
a = a.split(', ')
last = a[0].strip()
fm = a[1].split(' ')
first = fm[0][0] + '.'
if len(fm) > 1:
middle = fm[1][0] + '.'
else:
middle = ''
if not middle == '':
return first + ' ' + middle + ' ' + last
else:
return first + ' ' + last |
def _upper(string):
"""Custom upper string function.
Examples:
foo_bar -> FooBar
"""
return string.title().replace("_", "") |
def same_exp(exp1, exp2):
"""Checks if 2 expressions are syntactically the same"""
perm_invariant_ops = ["union", "=f", "=", "+", "intersection", "and", "or"]
if exp1 == exp2:
return True
if type(exp1) != type(exp1) or len(exp1) != len(exp2):
return False
elif type(exp1) == type(exp2) == tuple:
if len(exp1) == 3:
if exp1[0] == exp2[0]:
if exp1[0] in perm_invariant_ops:
return (
same_exp(exp1[1], exp2[1])
and same_exp(exp1[2], exp2[2])
) or (
same_exp(exp1[1], exp2[2])
and same_exp(exp1[2], exp2[1])
)
else:
return same_exp(exp1[1], exp2[1]) and same_exp(
exp1[2], exp2[2]
)
else:
return exp1[0] == exp2[0] and same_exp(exp1[1], exp2[1])
elif type(exp1) == str:
return exp1 == exp2
else:
return False |
def oo_selector_to_string_list(user_dict):
"""Convert a dict of selectors to a key=value list of strings
Given input of {'region': 'infra', 'zone': 'primary'} returns a list
of items as ['region=infra', 'zone=primary']
"""
selectors = []
for key in user_dict:
selectors.append("{}={}".format(key, user_dict[key]))
return selectors |
def get_mysql_client_cmd(db_username, db_password, db_host, db_port, db_schema):
"""
Returns a connection string according to the given variables
"""
if db_password:
cmd = "mysql -h %s -u%s -p%s -P %s %s" % (db_host, db_username, db_password, db_port, db_schema)
else:
cmd = "mysql -h %s -u%s -p -P %s %s" % (db_host, db_username, db_port, db_schema)
return cmd |
def longMessage(message):
"""Use this to prevent the bot from trying to send messages over 2000 characters."""
if len(message) > 2000:
return "hey!! you tricked me into making a big message!! no fair :(("
else:
return message |
def _is_model(layer):
"""Returns True if layer is a model.
Args:
layer: a dict representing a Keras model configuration.
Returns:
bool: True if layer is a model.
"""
return layer.get('config').get('layers') is not None |
def get_list_from_dict(dictionary, key):
"""Get a list from dictionary, if key not present, return empty list."""
if key in dictionary:
return dictionary[key]
else:
return [] |
def success_email_subject_msid_author(identity, msid, author):
"""email subject for a success email with msid and author values"""
return u"{identity}JATS posted for article {msid:0>5}, author {author}".format(
identity=identity, msid=str(msid), author=author
) |
def word_count(i_source, i_dest):
"""
count the number of words from i_source string
which are in destination string.
i_source: source string
i_dest: destination string
return: count of words, 0 to indicate no match
"""
counter = 0
if not i_source or not i_dest:
return counter
unCharSet = {'\\': '', "'": '', '(': '', ')': '',
'.': '', ',': '', '-': ''}
for key, value in unCharSet.items():
i_source = i_source.replace(key, value)
for key, value in unCharSet.items():
i_dest = i_dest.replace(key, value)
sourceArr = i_source.split(' ')
destArr = i_dest.split(' ')
for word in sourceArr:
if word in destArr:
counter += 1
return counter |
def plastic(diffuse, specular, nonlinear, intior,extior):
"""[Plastic material dict]
Args:
diffuse ([list]): [rgb values]
specular ([list]): [rgb values]
nonlinear ([bool]): [description]
intior ([float]): [description]
extior ([list]): [description]
Returns:
[dict]: [material dict]
"""
return {
"type" : "roughplastic",
"diffuse_reflectance" : {
"type" : "rgb",
"value" : diffuse,
},
'nonlinear':False,
'int_ior':intior,
'ext_ior':extior,
'specular_reflectance':{
"type" : "rgb",
"value" : specular,
}
} |
def pound_force_to_newtons(val):
"""convert pound max_force to newtons
:param float or list val: value to convert
:returns: converted value
:rtype: float or tuple
"""
try:
return val * 4.448
except TypeError:
return [x * 4.448 for x in val] |
def _process_exp(exp):
"""Use the exp name to return the names of the t2 data, the MPRAGE data
and the bold data (in that order).
"""
if exp == "fh":
t2name = "t2"
mpragename = "mprage"
boldname = "fh"
else:
raise ValueError("exp name not understood.")
return t2name, mpragename, boldname |
def StringBool(arg: str) -> bool: # pylint: disable=C0103
"""Implementation inspiration taken from
https://github.com/python/cpython/blob/3.8/Lib/distutils/util.py#L306
"""
arg = arg.lower()
if arg in {"true", "t", "yes", "y", "1"}:
return True
return False |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.