content stringlengths 42 6.51k |
|---|
def move_axis(ndim, i1, i2):
"""Transpose axes to move axis i1 to i2
Args:
ndim(num):
i1(num):
i2(num):
Returns:
list
"""
if i1 == i2:
return None
axes = list(range(ndim))
axes.insert(i2, axes.pop(i1))
return axes |
def hash_iterable(it):
"""Perform a O(1) memory hash of an iterable of arbitrary length.
hash(tuple(it)) creates a temporary tuple containing all values from it
which could be a problem if it is large.
See discussion at:
https://groups.google.com/forum/#!msg/python-ideas/XcuC01a8SYs/e-doB9TbDwAJ
"""
hash_value... |
def get_line(line):
"""Returns line with EOL."""
return line if line.endswith("\n") else line + '\n' |
def escape_markdown_v2(text):
"""Escapes all characters that need to be escaped in markdownV2 entites"""
text = text.replace('_', '\\_')
text = text.replace('*', '\\*')
text = text.replace('[', '\\[')
text = text.replace(']', '\\]')
text = text.replace('(', '\\(')
text = text.replace(')', '\... |
def len_min(value, other):
"""Minimum length"""
return len(value) >= other |
def merge(left, right):
"""Merges an integer list that has two sorted sublists."""
result = []
i, j = 0, 0
while i < len(left) and j < len(right):
# Left and right sublists are ordered, move indices for sublists depending on
# which sublist holds next smallest element.
if left[i]... |
def binary_search(target, source, left):
"""Recursive binary search
Args:
target (int): target value to search for
source (list of int): ordered list of integer values
left: start position in source, usually 0 at beginning
Returns:
index (int): index of target in source, othe... |
def darken(col, by=75):
"""
Darken a colour by specified amount
"""
assert col[0] == '#'
r, g, b = int(col[1:3], 16), int(col[3:5], 16), int(col[5:7], 16)
def dark(x, by=by):
new = max(x - by, 0)
return str(hex(new))[2:]
return '#{:0>2}{:0>2}{:0>2}'.format(dark(r), dark(g),... |
def matrix_jacobian(x1, x2):
"""Docstring"""
matrix = [[0.0,0.0],[0.0,0.0]]
matrix[0][0] = x2
matrix[0][1] = x1
matrix[1][0] = 2*x1
matrix[1][1] = 2*x2
return matrix |
def coalesce(*args):
"""Given a list of values, returns the first one that is not None"""
for v in args:
if v is not None:
return v
return None |
def is_list(value):
"""
Check if an object is a list
:param value:
:return:
"""
return isinstance(value, list) |
def convex_hull(points):
"""Computes the convex hull of a set of 2D points.
Input: an iterable sequence of (x, y) pairs representing the points.
Output: a list of vertices of the convex hull in counter-clockwise order,
starting from the vertex with the lexicographically smallest coordinates.
Impl... |
def declination_sexegesimal_to_decimal(
dec
):
"""
*declination_sexegesimal_to_decimal*
**Key Arguments:**
- ``dec`` -- declination in sexegesimal
**Return:**
- ``decimalDegrees``
.. todo::
@review: when complete, clean worker function and add comments
@review... |
def parse_urn(urn):
"""
Parses a URN, returning a pair that contains a list of URN namespace parts, followed by the
URN's unique ID.
"""
if not urn.startswith("urn:"):
return None
parts = urn[len("urn:") :].split(":")
return (parts[0 : len(parts) - 1], parts[len(parts) - 1]) |
def is_component_type(component_type):
"""Returns True if 'component_type' is a plausible component type, e.g.
something of the form "<xxxComponent>", otherwise False"""
return (isinstance(component_type, str) and len(component_type) >= 13 and
component_type[0] == "<" and component_type[-10:] == "Co... |
def IsWordToRemove(word):
"""
Test if word is in capital
"""
boo = True
if len(word)>2 or word=='MR':
for letter in word[:-1]:
if letter.isupper():
pass
else:
boo = False
else:
boo = False
return boo |
def decimal_to_any(num: int, base: int) -> str:
"""
Convert a positive integer to another base as str.
>>> decimal_to_any(0, 2)
'0'
>>> decimal_to_any(5, 4)
'11'
>>> decimal_to_any(20, 3)
'202'
>>> decimal_to_any(58, 16)
'3A'
>>> decim... |
def matlib_convert(path):
"""
Convert tuples of x-, y-, z-coordinates to x-, y-, z-coordinate lists for visualisation via matplotlib
Input:
path; list containing tuples of x-, y-, z-coordinates.
Return:
Tuple of x-, y-, z-coordinate lists.
"""
x_list = []
y_list = []
z_lis... |
def reindent(program):
"""Reindent the program.
This makes it a little more natural for writing the
program in a string.
Args:
program: A program which is indented too much.
Returns:
The program, reindented.
"""
# Find the first non-space character in a line.
def _non... |
def _parse_endpoint(endpoint, key, value):
"""
Returns the endpoint with values parameters replaced with their values
"""
return endpoint.replace(key, str(value)) |
def obtain_reverse_codes(mapped, dst):
"""
Given the list of desired dst codes and an extensive map src -> dst,
obtain the list of src codes
:param mapped: Correspondence between src codes and dst codes
:param dst: List of dst codes
:return: List of src codes
"""
src = set()
fo... |
def filter_results(results, filters, exact_match):
"""
Returns a list of results that match the given filter criteria.
When exact_match = true, we only include results that exactly match
the filters (ie. the filters are an exact subset of the result).
When exact-match = false,
we run a case-ins... |
def geologic_time_str(years):
"""Returns a string representing a geological time for a large int representing number of years before present."""
assert isinstance(years, int)
years = abs(years) # positive and negative values are both interpreted as the same: years before present
if years < 10000000 an... |
def random_morphing_thetas(n_thetas, priors):
"""
Utility function to be used as input to various SampleAugmenter functions, specifying random parameter points
sampled from a prior in a morphing setup.
Parameters
----------
n_thetas : int
Number of parameter points to be sampled
pr... |
def get_amount_and_variables(settings):
"""Read amount and species from settings file"""
# species for which results are expected as amounts
amount_species = settings['amount'] \
.replace(' ', '') \
.replace('\n', '') \
.split(',')
# IDs of all variables for which results are e... |
def _depset_to_list(x):
"""Helper function to convert depset to list."""
iter_list = x.to_list() if type(x) == "depset" else x
return iter_list |
def get_user_ids_from_results(results):
"""
Get all users based on the ids provided in the results
"""
user_ids = set([])
for groupId, users in results.items():
for userId, results in users.items():
user_ids.add(userId)
return user_ids |
def _equivalence_partition(iterable, relation):
"""Partitions a set of objects into equivalence classes
canned function taken from https://stackoverflow.com/a/38924631
Args:
iterable: collection of objects to be partitioned
relation: equivalence relation. I.e. relation(o1,o2) evaluates to ... |
def snp_url(snpid):
"""Create url SNP ID."""
if snpid.startswith('rs'):
url = 'http://www.ncbi.nlm.nih.gov/snp/?term={}'.format(snpid)
pass
elif snpid.startswith('COSM'):
url = 'http://cancer.sanger.ac.uk/cosmic/mutation/overview?genome=37\&id={}'.format(snpid.lstrip('COSM'))
eli... |
def _make_sentence(txt):
"""Make a sentence from a piece of text."""
#Make sure first letter is capitalized
txt = txt.strip(' ')
txt = txt[0].upper() + txt[1:] + '.'
return txt |
def ignore_trips(response):
"""
At runtime, we cannot determine the 'true' start time of any trip. As a result, all of these trips should be ignored and never written to the sqlite3 database.
"""
ignored_trips = []
for mode in response['mode']:
for route in mode['route']:
... |
def get_price_rules_total(order_items):
"""Calculate the total number of grams."""
JOINT = 0.4
# Todo: add correct order line for 0.5 and 2.5
prices = {"0,5 gram": 0.5, "1 gram": 1, "2,5 gram": 2.5, "5 gram": 5, "joint": JOINT}
total = 0
for item in order_items:
if item.description in p... |
def find_order_item(order_items, item_id):
""" Find order item with the item_id """
for order_item in order_items:
if order_item.item_id == item_id:
return order_item
return None |
def slice_vis(step, uvw, v=None):
""" Slice visibilities into a number of chunks.
:param step: Maximum chunk size
:param uvw: uvw coordinates
:param src: visibility source
:param v: Visibility values (optional)
:returns: List of visibility chunk (pairs)
"""
nv = len(uvw)
ii = range(... |
def product_of_3( numbers ):
"""
From the given list of numbers, find the group of 3 numbers that sum up to 2020.
This function returns the product of those 3 numbers.
"""
numbers = [ int( item ) for item in numbers ]
for i in range( len(numbers) ):
for j in range( i+1, len(numbers) ):
... |
def date_remove_dashes(std_date):
"""STD_DATE is a date in string form with dashes. Removes dashes for storage in JSON."""
return std_date[0:4] + std_date[5:7] + std_date[8:] |
def decode_utf8(text: bytes) -> str:
"""Decode `text` as UTF-8 string
Arguments:
bytes {text} -- ascii-encoded bytes
Returns:
str -- decoded text
"""
return text.decode('utf-8') |
def convert_keys_to_string_from_unicode(dictionary):
"""Recursively converts dictionary keys to strings."""
if not isinstance(dictionary, dict):
return dictionary
return dict((str(k), convert_keys_to_string_from_unicode(v))
for k, v in dictionary.items()) |
def scaled_color(temp):
"""Scale the color value based on whats passed in"""
temp = int(round(float(temp)))
if temp > 110 or temp < 0:
raise Exception('Temp out of bounds')
r = g = b = 0
if temp < 37:
b = 255
g = round((temp / 36) * 255)
elif temp < 74:
g = 255
... |
def yenc_name_fixer(p):
""" Return Unicode name of 8bit ASCII string, first try utf-8, then cp1252 """
try:
return p.decode('utf-8')
except:
return p.decode('cp1252', errors='replace').replace('?', '!') |
def _is_num(x):
"""Returns: True if x is an int or float; False otherwise.
Parameter x: The value to test
Precondition: NONE"""
return type(x) in [int,float] |
def leftmost(left, right):
"""Returns keys from right to left for keys that exist only in left."""
return set(left.keys()) - set(right.keys()) |
def get_fully_qualified_classname(cls=None, obj=None):
"""
Returns `fully-qualified-name` of the class represented by **cls** or **obj**
:param cls:
:param obj:
:return:
"""
if obj:
module = obj.__class__.__module__
if module is None or module == str.__class__.__module__:
... |
def qcollide(Aleft, Aright, Bleft, Bright):
"""
optimised for speed.
"""
# quickest rejections first;
if Aright < Bleft:
return(False)
if Aleft > Bright:
return(False)
if Aleft <= Bright and Aright >= Bright:
return(True) # Bright point is within A, collision
if... |
def launch_label(cfg):
"""Returns a label based on how far the piepline has progressed"""
order = ["Initial", "Classify", "Post", "Upload", "Debase", "RM", "RVM_initial", "RVM_final", "Finish"]
counter = sum(cfg["completed"].values()) # Number of True statements
return order[counter] |
def uord(c):
"""Get Unicode ordinal."""
if len(c) == 2:
high, low = [ord(p) for p in c]
ordinal = (high - 0xD800) * 0x400 + low - 0xDC00 + 0x10000
else:
ordinal = ord(c)
return ordinal |
def route_not_found(error):
"""404 error handler"""
return "This route is not found", 404 |
def get_led_status(shadow):
"""Return current reported state for attribute led"""
# Default state if attribute not found in reported state
led_state = "off"
if "reported" in shadow["state"]:
if "led" in shadow["state"]["reported"]:
led_state = shadow["state"]["reported"]["led"]
... |
def overbar(string):
"""
Returns string preceeded by an overbar of the same length:
>>> print(overbar('blee'))
____
blee
"""
return "%s\n%s" % ('_' * len(string), string) |
def human_bytes(B):
""" Return the given bytes as a human friendly KB, MB, GB, or TB string """
# https://stackoverflow.com/questions/12523586/python-format-size-application-converting-b-to-kb-mb-gb-tb/63839503
B = float(B)
KB = float(1024)
MB = float(KB ** 2) # 1,048,576
GB = float(KB ** 3) #... |
def is_real(val):
"""
Returns True if value is a Real number, False otherwise
"""
try:
float(val)
return True
except (TypeError, ValueError):
return False |
def get_args_from_parameter(parameter, param_value_dict):
"""
given a comma seprated parameter string, function returns an argument tuple
:param parameter:
:param param_value_dict:
:return:
"""
parameter = parameter.split(",")
parameter = [x.strip() for x in parameter] # remove unwante... |
def trunc_pow(x, n, theta0, I_theta0=1):
""" Truncated power law for single element, I = I_theta0 at theta0 """
a = I_theta0 / (theta0)**(-n)
y = a * x**(-n) if x > theta0 else I_theta0
return y |
def stations_by_river(stations):
"""For a list of monitoring station objects, return a dictionary that maps river names
to stations """
river_dict = {}
for station in stations:
if station.river not in river_dict:
river_dict[station.river] = station.name
elif type(river_dic... |
def raw_formatter(subtitles):
"""
Serialize a list of subtitles as a newline-delimited string.
"""
return ' '.join(text for (_rng, text) in subtitles) |
def refined(s): # 26,682 total ratings
"""Normalize numeric data to the unified-format without any commas"""
ra = s.split(' ')[0] # 26,682
return ra.replace(',', '') |
def as_bytes(s):
"""Return byte-string.
"""
if not isinstance(s, bytes):
return s.encode("utf8")
return s |
def bool2yn(b):
"""Converts a boolean to yes or no with the mapping: y = True, n = False."""
return 'y' if b else 'n' |
def find_stop_codon(sequence):
"""
finds the nucleotide position of the first stop codon
Note: the search is done in the 1st fram of the sequence
Args:
sequence (str): dna sequence 4 letter code
Returns:
int: nucleotide position of stop codon
None: sequence does not contain s... |
def find_in_dict(obj, key):
"""
Recursively find an entry in a dictionary
Parameters
----------
obj : dict
The dictionary to search
key : str
The key to find in the dictionary
Returns
-------
item : obj
The value from the dictionary
"""
if key... |
def bounding_box(locus):
"""
Compute the bounding box of a locus.
Parameters
----------
locus : list[tuple[float]]
A list of point or any iterable with the same structure.
Returns
-------
tuple[float]
Bounding box as (y_min, x_max, y_max, x_min).
"""
y_min = flo... |
def intersect_intervals(l0, s0, l1, s1):
"""
Compute the intersection of intervals (l0, l0+s0) and (l1, l1+s1).
"""
l = max(l0, l1)
r = min(l0+s0, l1+s1)
if l > r:
return None
return (l, r-l) |
def csstext(text: str, cls: str, span: bool=False, header: bool=False) -> str:
"""
Custom build HTML text element.
"""
if span:
tag = 'span'
elif header:
tag = 'h1'
else:
tag = 'p'
return f'<{tag} class="{cls}">{str(text)}</{tag}>' |
def get_obj_attr(object, item, missing_value=None, join_with=None, transform=None):
"""
Returns the value of an object's attribute, checking if it exists. It can provide a predefined default value,
in case it's an array can be joined with supplied char, and can be even transformed with supplied lambda funct... |
def to_bottom_right(grid_size=3, off_limits=()):
"""Return path to bottom right of grid
:param grid_size Height and width of the grid
:return Path to origin
"""
def to_bottom_right_helper(m, n, moves):
"""Helper function to return path to bottom right of grid
:param m ... |
def cron_str2int(str):
""" Convert day name to digit. """
days = [ "sun", "mon", "tue", "wed", "thu", "fri", "sat" ]
try:
pos = days.index(str)
if pos != ValueError:
return pos
except:
try:
value = int(str)
return value
except:
... |
def example_function_with_shape_of_return_pre_defined(a, b):
"""
Example function for unit checks
"""
result = a * b
return result |
def find_usable_exits(room):
"""
Given a room, and the player's stuff, find a list of exits that they can use right now.
That means the exits must not be hidden, and if they require a key, the player has it.
RETURNS
- a list of exits that are visible (not hidden) and don't require a key!
"""
... |
def list_to_group_count(input_list):
"""
List to item occurrences count dictionary
"""
group_count = {}
for input_item in input_list:
if input_item in group_count:
group_count[input_item] = group_count[input_item] + 1
else:
group_count[input_item] = 1
ret... |
def display(string):
"""Given a location or object or action string, get the display name"""
return " ".join([x.capitalize() for x in string.split('_')]) |
def _parse_name(name):
"""Returns a pair namespace, name
parsing string like namespace/name.
Namespace could be None if there is not backslash in the name.
"""
if '/' in name:
return name.split('/', 1)
return None, name |
def is_new_cmd(cli):
"""
Checks if the cli command contains 'new' in it.
"""
if 'new' in cli:
return True
return False |
def hex_to_rgb(hex_string):
"""Converts HEX values to RGB values
"""
h = hex_string.lstrip("#")
return tuple(int(h[i : i + 2], 16) for i in (0, 2, 4)) |
def remove_eol_characters(text) -> str:
"""
Remove end of line (\n) char.
Parameters
----------
text : str
Returns
-------
str
"""
text = text.replace("\n", " ")
return text |
def mr(a, p, q):
"""
in:
a: sorted 1d array
p: low end
q: high end
ou:
r: list of range tuples
"""
r = []
s = p
a = sorted(a)
if a == []:
return [(p, q)]
for i in a:
if s == i:
# bypassing the cut
s += 1
... |
def is_git_sha(xs: str) -> bool:
"""Returns whether the given string looks like a valid git commit SHA."""
return len(xs) > 6 and len(xs) <= 40 and all(
x.isdigit() or 'a' <= x.lower() <= 'f' for x in xs) |
def iter_as_dict(itr):
"""Given an iterable, return a comprehension with the dict version of each element"""
from operator import attrgetter
ag = attrgetter('dict')
return [ ag(e) for e in itr if hasattr(e, 'dict') ] |
def additionner(a, b):
"""Fonction qui renvoie la somme de deux nombres."""
if not isinstance(a, int) or not isinstance(b, int):
raise TypeError
return a + b |
def frequency_p(tol_str, tar_str):
"""Generate the frequency of tar_str in tol_str.
:param tol_str: mother string.
:param tar_str: substring.
"""
i, j, tar_count, tar1_count, tar2_count, tar3_count = 0, 0, 0, 0, 0, 0
tar_list = []
len_tol_str = len(tol_str)
len_tar_str = len(tar_str)
... |
def reduce_right(function, iterable, initial=None):
"""op, xs, x -> op(x, op(xs[0], op(xs[1], ...)))"""
iterator = reversed(iterable)
if initial is None:
try:
value = next(iterator)
except StopIteration:
value = initial
else:
value = initial
for elem... |
def get_covariates(header, code='#Dx'):
""" Get covariates from header files """
covariate = list()
for l in header.split('\n'):
if l.startswith(code):
try:
entries = l.split(': ')[1].split(',')
for entry in entries:
covariate.append(en... |
def getDatabaseTreeAsList(database, entries):
"""
Return a list of entries in a given database, sorted by the order they
appear in the tree (as determined via a depth-first search).
"""
tree = []
for entry in entries:
# Write current node
tree.append(entry)
# Recursively ... |
def experience(from_date=None, to_date=None, position_title=None, institution_name=None):
"""
:param from_date: start date
:param to_date: end date
:param position_title: position description
:param institution_name: name of the institution
:return: string consisting of start date end date... |
def _search_index(items_list, item):
"""
Give the index of an item in a list or return -1 if this item is not in the list
:param items_list: list with one item or more
:type items_list: list
:param item: an item
:type item: booleen, float, int, list, numpy.ndarray
:return: the index of th... |
def _decayed_value_in_linear(x, max_value, padding_center, decay_rate):
"""
decay from max value to min value with static linear decay rate.
"""
x_value = max_value - abs(padding_center - x) * decay_rate
if x_value < 0:
x_value = 1
return x_value |
def first(iterable, default=None):
"""
returns the first element of `iterable`
"""
return next(iter(iterable), default) |
def _get_cell_range(sheet, start_row, start_col, end_row, end_col):
"""Returns the values from a range
https://stackoverflow.com/a/33938163
"""
return [sheet.row_slice(row, start_colx=start_col, end_colx=end_col+1) for row in range(start_row, end_row+1)] |
def normalize_slice(slice_obj, length):
"""
Given a slice object, return appropriate values for use in the range function
:param slice_obj: The slice object or integer provided in the `[]` notation
:param length: For negative indexing we need to know the max length of the object.
"""
if isinsta... |
def round_float_to_arbitrary_resolution(value, resolution):
"""
Examples
--------
Examples ::
round_float_to_resolution(10.021, 0.025)
round_float_to_resolution(3.141592653589793, 0.001)
"""
return round(value / resolution) * resolution |
def _listminus(list1, list2):
"""
"""
return [a for a in list1 if a not in list2] |
def flexible_params(*values):
"""Parse flexible parameters."""
if len(values) == 1 and isinstance(values[0], (list, tuple,)):
return values[0]
return values |
def ip_to_int(ip):
"""
>>> ip_to_int(None)
0
>>> ip_to_int('0.0.0.0')
0
>>> ip_to_int('1.2.3.4')
16909060
"""
if ip is None:
return 0
result = 0
for part in ip.split('.'):
result = (result << 8) + int(part)
return result |
def human_2_bytes(s):
"""
>>> human2bytes('1M')
1048576
>>> human2bytes('1G')
1073741824
"""
symbols = ('B', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y')
letter = s[-1:].strip().upper()
num = s[:-1]
assert letter in symbols
num = float(num)
prefix = {symbols[0]:1}
for i, s... |
def is_reverse(i, j):
"""
Convert 2-digit numbers to strings and check if they are palindromic.
If one of the numbers has less then 2 digits, fill with zeros.
"""
str_i = str(i)
str_j = str(j)
if len(str_i) < 2:
str_i = str_i.zfill(2)
if len(str_j) < 2:
str_j = str_j.zfil... |
def merge(line):
"""
Helper function that merges a single row or column in 2048
"""
# remove all zeros in original line and output into a new list
newlist = []
output = []
for item in line:
if item != 0:
newlist.append(item)
# merge the numbers
for ... |
def netdna_js( path ):
"""
Returns a link to the named NetDNA-hosted JavaScript resource.
"""
return '//netdna.bootstrapcdn.com/%s' % path |
def any(iterable):
"""Return True if at least one element is set to True.
This function does not support predicates explicitely,
but this behaviour can be simulated easily using
list comprehension.
>>> any( [False, False, False] )
False
>>> any( [False, True, False] )
... |
def rotate_phasor(r, r1, r2):
"""Affine transformation mapping the biexponential segment to the real [0,1] segment.
r, r1, r2: array-like
Phasors, where r1 and r2 correspond to fractions 1. and 0. respectively.
"""
return (r - r2) / (r1 - r2) |
def check_test_arch(test_arch):
""" Bool amd64, arm64 if test_arch equal to given arch """
if not test_arch:
return False, False
if test_arch == "amd64":
return True, False
elif test_arch == "arm64":
return False, True
else:
return False, False |
def get_init_block_args(init_num_feature_maps, init_conv_stride, init_kernel_size,
init_maxpool_stride, init_maxpool_size, num_in_channels,
separable_convolution=False):
"""
Wrap the args for init block into a dict.
Check Config classes for arg doc string
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.