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 ... |
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 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 ``FooServicePoolHandl... |
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 [leng... |
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 ... |
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 ... |
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... |
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 F... |
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 th... |
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"... |
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
... |
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
"""
... |
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():
... |
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
:par... |
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)
... |
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 =... |
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(patt... |
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].appe... |
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)
... |
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 ar... |
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... |
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_qu... |
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, separat... |
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 sl... |
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)
... |
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
... |
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... |
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)^(... |
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.... |
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
wh... |
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... |
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... |
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_... |
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
:rty... |
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 =... |
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 no... |
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.endsw... |
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_dat... |
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'
... |
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_channe... |
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 =... |
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... |
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... |
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... |
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:
... |
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... |
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.")
r... |
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.