content stringlengths 42 6.51k |
|---|
def selection_sort(arr):
"""
sort list arr by selection sort
:param arr: unsorted list
:return: sorted list arr
"""
for i in range(len(arr) - 1):
for j in range(i + 1, len(arr)):
if arr[i] > arr[j]:
arr[i], arr[j] = arr[j], arr[i]
return arr |
def opt_bool(opt):
""" Convert bool ini strings to actual boolean values
"""
return opt.lower() in ['yes', 'y', 'true', '1'] |
def find_kmers(in_fasta, k):
"""function to find k mers of given length from string"""
n= len(in_fasta)-k+1
kmers=[]
for i in range(0, n):
kmers.append(in_fasta[i:i+k])
return(kmers) |
def update_interns(n, atoms, measure ,angles):
"""
Converts internal coordinate information from x2z to the form for
a Z-Matrix required to run EStokTP
"""
if len(atoms) == 0:
return atoms, measure, angles
for index,atom in enumerate(atoms):
if n == 2:
atoms[index][0]... |
def make_round(x, base=5):
"""
Rounds the time in interval of 5 min.
"""
return int(base * round(float(x)/base)) |
def remove_blanks(d):
"""
Returns d with empty ('' or None) values stripped
"""
empty_keys = []
for key in d:
if d[key]=='' or d[key]==None:
# del d[key] raises runtime exception, using a workaround
empty_keys.append(key)
for key in empty_keys:
del d[key]
return d |
def _within_interval(x, interval):
"""Utility function returns boolean if in interval (inclusive, both sides)."""
if len(interval) == 2:
return interval[0] <= x and x <= interval[1]
else:
raise ValueError("Invalid interval parameter '{0}'. Expected to be tuple "
"or list of l... |
def resolve_value(val):
""" if given a callable, call it; otherwise, return it """
if callable(val):
return val()
return val |
def relate_parent(data, basename, url_kwargs):
"""
Add parent as related entity if created entity is nested.
"""
if list(url_kwargs.keys())[-1] != "version":
parent = list(url_kwargs.keys())[-1]
if parent == "Locations_pk":
data['Locations'] = [{"@iot.id": url_kwargs[parent]}... |
def two_digit_string(_value):
"""Convert an int value to a fixed 2-digit string
:param _value: (int) integer value to convert to string
:return: (str) 2-digit string
"""
return "0{}".format(_value) if _value < 10 else str(_value) |
def get_key_in_parse_from_config_key(config_key):
"""
Example:
Arguments:
config_key: "a-b-c"
Returns:
"c"
"""
return config_key.split("-")[-1] |
def replace_none_with_empty_iter(iterator):
""" If it is "None", return an empty iterator; otherwise, return iterator.
The purpose of this function is to make iterating over results from
functions which return either an iterator or None cleaner.
Parameters
----------
it: None or some object
... |
def can_haz(user, component):
""" Checks if the given user has the necessary roles for the component. """
if hasattr(user, 'roles'):
user_roles = set([role['name'].lower() for role in user.roles])
else:
user_roles = set([])
if set(getattr(component, 'roles', [])) <= user_roles:
r... |
def filter_dict(data, keys):
"""Filter dict :data by given :keys"""
result = {}
for key in keys:
if key in data:
result[key] = data[key]
return result |
def _find(xs, predicate):
"""Locate an item in a list based on a predicate function.
Args:
xs (list) : List of data
predicate (function) : Function taking a data item and returning bool
Returns:
(object|None) : The first list item that predicate returns True for or None
"""
... |
def uniq(lst):
""" Take a sorted list and return a list with
duplicates removed. Also return the length of
the contracted list:
>>> uniq([1,3,7,7,8,9,9,9,10])
([1, 3, 7, 8, 9, 10], 6)
>>> uniq([1,1,1,1,1,1,1,1])
([1], 1)
>>> uniq([1,1,1,2,2,3,3,3])
([1, 2, 3], 3)
>>> uniq([1,3,7... |
def prepare_email(appointments):
"""This function loops through and inserts values into a string.
Args:
appointment(list): List of tuples.
Returns:
message(list): List with formatted strings of referenced values.
Example:
>>> prepare_email([('Jen', '2015'), ('Max', 'March 3')]... |
def elevation_gain(altitudes, distance, threshold):
"""Elevation gain per km """
eg = 0.0
last_valid_i = 0
for i in range(1, len(altitudes)):
ediff = altitudes[i] - altitudes[last_valid_i]
if abs(ediff) >= threshold:
last_valid_i = i
if ediff > 0.0:
... |
def stomp_unsubscribe(topic):
""" Return a javascript callback that unsubscribes to a given topic,
or a list of topics.
"""
sub = "stomp.unsubscribe('%s');"
if isinstance(topic, list):
sub = ''.join([sub % t for t in topic])
else:
sub = sub % topic
return sub |
def remove(string, cx):
"""
Removes the character from the string.
Params
======
string: str
cx: int
The index of the character to remove
Returns
=======
_: str
"""
return "".join([string[:cx], string[cx + 1:]]) |
def strip_scheme(url):
"""
Examples:
>>> strip_scheme("https://www.conda.io")
'www.conda.io'
>>> strip_scheme("s3://some.bucket/plus/a/path.ext")
'some.bucket/plus/a/path.ext'
"""
return url.split('://', 1)[-1] |
def combine_statements(*args, group: bool = False, split: str = "\n") -> str:
"""Join *args
Args:
group: return enclosed by {...}
split: join *args by this
Example:
>>> import os
>>> where_list = ['?mrid rdf:type cim:ACLineSegment', '?mrid cim:ACLineSegment.r ?r']
>>> co... |
def lookup(dic, key, *keys):
"""A generic dictionary access helper.
This helps simplify code that uses heavily nested dictionaries. It will
return None if any of the keys in *keys do not exist.
::
>>> lookup({'this': {'is': 'nested'}}, 'this', 'is')
nested
>>> lookup({}, 'thi... |
def args(*args, **kwargs):
"""Get function arguments as a dictionary."""
if 'instance' in kwargs:
instance = kwargs['instance']
del kwargs['instance']
return dict(instance=instance, args=args, kwargs=kwargs)
else:
return dict(args=args, kwargs=kwargs) |
def replace_draft_version_by_asterix(ll, debug_level):
"""
Replace the draft version by an asterix
:param ll: list of all files
:param debug_level: debug level
:return: a list of all the lines in the file, with the draft version replaced by *
"""
newll = []
for l in ll:
head, sep... |
def is_bool(value):
"""Check if value is a bool."""
return isinstance(value, bool) |
def plusminus(n):
"""Get a number of +s or -s corresponding to n's value.
If n == 0, returns "".
Arg:
n: An int
Returns:
A str, possibly empty.
"""
return ("-", "+")[n > 0] * abs(n) |
def _makeBool(value):
""" Helper to make boolean out of a .ini value """
if value is None or value.lower() in ('off', 'false', '0'):
return False
return True |
def detections_transform(detection):
"""detections_transform transforms coordinates into [bX1, bY1, bX2, bY2].
Args:
detections: [bX, bY, bWidth, bHeight, visible]
Returns:
transformed_detections: [bX1, bY1, bX2, bY2]
"""
if len(detection) < 4:
return detection
x1 = detection[0]
y1 = detecti... |
def get_loop_vars(variants):
"""For purposes of naming/identifying, provide a way of identifying which variables contribute
to the matrix dimensionality"""
special_keys = ('pin_run_as_build', 'zip_keys', 'ignore_version')
loop_vars = [k for k in variants[0] if k not in special_keys and
any(v... |
def split_str(seq, length):
"""Separate a string seq into length-sized pieces.
Parameters
----------
seq : str
String containing sequence of smaller strings of constant length.
length : int
Length of individual sequences.
Returns
-------
list of str
List... |
def score_giver(secret, guessed_code):
"""Scores a guess against the secret and returns a tuple of (bulls, cows)
Parameters:
secret (str): Chosen secret for scoring
guessed_code (str): The guess to be scored against the secret
Returns:
tuple(int):Returni... |
def check_tor(target_ip, tor_exit_nodes):
"""Check target IP address against provided list of Known TOR Exit Nodes"""
results = {}
# Compare IP to list of known TOR Exit nodes and classify accordingly
if target_ip in tor_exit_nodes:
results = {"source_ip": target_ip, "is_TOR": True}
else:
... |
def parse_date_range(date_string):
"""
:param str date_string:
:return list:
"""
return date_string.split(' - ') |
def flatten(lst):
"""flatten([["a","btr"],"b", [],["c",["d",["e"], []]]]) will return ['a', 'btr', 'b', 'c', 'd', 'e']"""
def flatten_aux(item, accumulated):
if type(item) != list:
accumulated.append(item)
else:
for l in item:
flatten_aux(l, accumulated)
... |
def indicesToRingPos(i, j):
"""
Convert spatialLocator indices to ring/position.
One benefit it has is that it never has negative numbers.
Notes
-----
Ring, pos index system goes in counterclockwise hex rings.
"""
if i > 0 and j >= 0:
edge = 0
ring = i + j + 1
o... |
def flatten(seqs):
"""flatten(seqs)
Flattens objects in
"""
return sum(seqs, []) |
def verify_token(token: str) -> str:
"""
Mock google and fb auth.
:param token: email
:return: email
"""
return token.strip() |
def yintercept(x, y, slope):
"""Get the y intercept of a line segment"""
if slope is not None:
return y - slope * x
else:
return None |
def is_within_range(num, lower_bound: int, upper_bound: int) -> bool:
"""
check if a number is within a range bounded by upper and lower bound
:param num: target number needs to be checked against
:param lower_bound: exclusive lower bound
:param upper_bound: exclusive upper bound
:return: True ... |
def _is_prefix(lhs, rhs):
""" return True if the first list is a prefix of the second """
rhs = list(rhs)
while rhs:
if lhs == rhs: return True
rhs.pop()
return False |
def multinomial_coefficients(K: list) -> int:
"""
Returns the multinomial coefficients
- `K` - A list of [$k_1, k_2...$]
"""
# Memoization method
# A direct implementation of the binomial representation
# Better for smaller numbers
# m = 1
# for i in range(1, len(K)+1):
# m ... |
def common_parameters(cart_id: str, item_name: str):
"""
Function to deal with common parameters for endpoints.
:param str cart_id: cart id
:param str item_name: item name
:return: dict with cart id and item name
:rtype: dict
"""
return {"cart_id": cart_id, "item_name": item_name} |
def uniquify(values):
"""
Return unique values, order preserved
"""
unique = []
[unique.append(i) for i in values if i not in unique]
return unique |
def generate_blank_characters(number):
"""
This function generates blank characters.
@param number: The number of blank characters.
"""
chars = ''
for i in range(0, number):
chars += ' '
return chars |
def get_complex_info_list(complex_info_file, column_labels_simple):
"""Take complex info file path and column labels (query title) list, and
return a list of lists of complex names as the first item followed by all
the components (query titles) that go in that complex.
"""
complex_info_list = []
... |
def get_most_frequent_letter(message):
"""Return the most frequent letter in the given message dictionary"""
most_freq_value = 0
most_freq_index = None
for letter in message:
if message[letter] >= most_freq_value:
most_freq_value = message[letter]
most_freq_index = letter... |
def guess_type(filename):
"""
Guess the particle type from the filename
Parameters
----------
filename: str
Returns
-------
str: 'gamma', 'proton', 'electron' or 'unknown'
"""
particles = ['gamma', 'proton', 'electron']
for p in particles:
if p in filename:
... |
def std_from_welford(count, mean, magic):
"""Included for rerefence. The data view must implement this."""
variance = magic / count # population variance
# variance = magic / (count - 1) # sample variance
return variance ** 0.5 |
def is_valid_chunk(signature: bytes) -> bool:
"""Check if the first four bytes of a chunk are valid Usm chunks.
Returns true if valid, and false if invalid or the given input is less
than four bytes.
"""
if len(signature) < 4:
return False
valid_signatures = [
bytes("CRID", "UTF... |
def multi_map(mapping):
"""Meta-function to allow multiple strings to be mapped to one value.
The input `mapping` will be expanded like this:
>>> multi_map({"a": "1", ("b", "c", "d"): "2"})
{"a": "1", "b": "2", "c": "2", "d": "2"}
(Note we use a tuple as the key because dictionary keys must be ha... |
def count_trees_hit(grid, slope):
""" Counts the trees that were hit on the way down
:param grid: the map
:param slope: [n_rows, n_columns] determines the next position after each iteration
:return: int
"""
# [row, column]
coords = [0, 0]
counter = 0
# repeat until bottom is reache... |
def test(r, v, source_body):
"""This function does something.
:param name: The name to use.
:type name: str.
:param state: Current state to be in.
:type state: bool.
:returns: int -- the return code.
:raises: AttributeError, KeyError
"""
print('meet me')
return None |
def pow_mod(a, b, r):
""" Returns a**b (mod r) """
""" Complexity: O( log(B) * log^2(r) ) """
ans, buff = 1, a
while(b):
if b & 1:
ans = (ans * buff) % r
buff = (buff * buff) % r
b >>= 1
return ans |
def ensure_sequence(obj):
"""If `obj` isn't a tuple or list, return a tuple containing `obj`."""
if isinstance(obj, (tuple, list)):
return obj
else:
return (obj,) |
def starts_inside(current_stream, next_stream):
"""
return True if next stream starts in current stream
"""
if next_stream[0] <= current_stream[1]:
return True
else:
return False |
def to_str(bytes_or_str):
"""
to_str(python2, python3)
:param bytes_or_str:
:return:
"""
if isinstance(bytes_or_str, bytes):
value = bytes_or_str.decode('utf-8')
else:
value = bytes_or_str
return value |
def readonly(label, value):
"""Return HTML markup for a readonly display like a form input."""
return {"label": label, "value": value} |
def norm_method_normalizer(name: str):
"""Normalize the name of a normalization method."""
return name.lower().replace('_', '').replace('embeddingnormalizer', '') |
def to_byte_array(string: str) -> bytearray:
"""
convert a string into a byte list. Skip all characters that are not in the range
of ISO/IEC 8859-1 character set to avoid undefined behavior
According to PEP3333, "Native" strings (which are always implemented using the type named str)
that are used ... |
def get_latt_vecs_from_latt_consts(a, b, c, alpha=90, beta=90, gamma=90):
"""Convert lattice constants to lattice vectors in right-hand system
Currently support orthormrhobic lattice only!!!
Args:
a, b, c (float): length of lattice vectors
alpha, beta, gamma (float): angles between lattice... |
def dict_equals(d1: dict, d2: dict) -> bool:
"""
Commparing if two dictionaries are equal
:param d1:
:param d2:
:return:
"""
dict_equal = False
# converting the dictionary keys to a set
d1_keys = set(d1.keys())
d2_keys = set(d2.keys())
# building a set of keys for which a... |
def evaluateFun(a, b, x):
"""wylicza wartosc funkcji f(x) = a * x + b"""
return a * x + b |
def clip_line(line, size):
"""
:param line: (xmin, ymin, xmax, ymax)
:param size: (height, width)
:return: (xmin, ymin, xmax, ymax)
"""
xmin, ymin, xmax, ymax = line
if xmin < 0:
xmin = 0
if xmax > size[1] - 1:
xmax = size[1] - 1
if ymin < 0:
ymin = 0
if ... |
def merge_filters(filters1, filters2):
"""Merge two filter lists into one.
Duplicate filters are removed. Since filter order is important, the order
of the arguments to this function also matter. Duplicates are always
removed from the second filter set if they exist in the first.
The result will a... |
def check_kwargs(input_kwargs, allowed_kwargs, raise_error=True):
"""Tests if the input `**kwargs` are allowed.
Parameters
----------
input_kwargs : `dict`, `list`
Dictionary or list with the input values.
allowed_kwargs : `list`
List with the allowed keys.
raise_error : `bool... |
def C2F(celsius):
"""Convert celsius to fahrenheit."""
return celsius * 9 / 5 + 32 |
def zero_if_less_than(x, eps):
"""Return 0 if x<eps, otherwise return x"""
if x < eps:
return 0
else:
return x |
def format_name(first_name, last_name):
# docstrings
""" Takes first and last name as arguments and returns
formatted version in title case.
"""
if first_name == '' or last_name == '':
return "Please enter first name or last name."
return f"{first_name} {last_name}".title() |
def _is_chinese_char(cp):
"""Checks whether CP is the codepoint of a CJK character."""
# This defines a "chinese character" as anything in the CJK Unicode block:
# https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_(Unicode_block)
#
# Note that the CJK Unicode block is NOT all Japanese and Korean characters,
... |
def combinations(l,ln, partial=[]):
""" Generate all permutations of length ln using elements from l. """
if len(partial) == ln:
return [partial]
results = []
for x in l:
np = partial[:]
np.append(x)
results.extend(combinations(l,ln,np))
return results |
def _set_data(object_query, data):
"""Helper function for setting basic data in object_query"""
object_query["count"] = len(data)
object_query["total"] = len(data)
object_query["last_modified"] = None
object_query["values"] = data
return object_query |
def getDaySuffix(day):
"""Return st, nd, rd, or th for supplied day."""
if 4 <= day <= 20 or 24 <= day <= 30:
return 'th'
return ['st', 'nd', 'rd'][day % 10 - 1] |
def tags_to_new_gone(tags):
"""Split a list of tags into a new_set and a gone_set."""
new_tags = set()
gone_tags = set()
for tag in tags:
if tag[0] == '-':
gone_tags.add(tag[1:])
else:
new_tags.add(tag)
return new_tags, gone_tags |
def scaleYAxis(scl):
""" Calculates Y-axis scaling factor for internal data correction
:returns:
A float, Y-axis scaling correction for data
"""
if scl== 0:
return 1
elif scl == 1:
return 1/3
elif scl == 2:
return 1/9 |
def get_position_from_periods(iteration, cumulative_period):
"""Get the position from a period list.
It will return the index of the right-closest number in the period list.
For example, the cumulative_period = [100, 200, 300, 400],
if iteration == 50, return 0;
if iteration == 210, return 2;... |
def difference_sum_of_squares_square_of_sums(min, max):
"""Find the difference between (i) the sum of the squares of the
numbers in a range and (ii) the square of the sum of the numbers in
the same range. The `min` and `max` parameters define the minimum
and maximum integers that make up the range in qu... |
def getclosest(mins):
"""
Given a dict of thumbnail matches for a video, return overall closest match(es)
"""
return [k for k,v in mins.items() if v == min(mins.values())] |
def check_arg_bool(value: bool) -> bool:
"""Return True of the value is indeed a boolean, raise a TypeError otherwise.
:param value: the argument to test
"""
if not isinstance(value, bool):
raise TypeError(f"Error! Expected a boolean but got {type(value)} instead ({value}).")
return True |
def _quote_filter_value(s):
"""Put a string in double quotes, escaping double quote characters"""
return '"%s"' % s.replace('"', r'\"') |
def assign_dict_recursively(dict_ref, dict_to_update):
"""
Assign values to non existing dictionary keys recursively.
Parameters
----------
dict_ref : dict
Reference dictionary, contains all possible keys with default values.
dict_to_update : dict
Dictionary to be updated.
... |
def parse_is_forfeit(d):
""" Used to parse whether or not one of the teams forfeited the match.
"""
return bool("FOR" in d.get("uitslag", "")) |
def one_zero_boolean_to_string(value: str) -> str:
"""Helper function to convert arguments with 1/0 string values to true or false"""
return 'true' if value == '1' else 'false' |
def make_alias_csv(aliases):
"""Creates a csv string suitable for importing to Excel.
CAM created this to make a spreadsheet we could share with schools.
Included here just for reference.
"""
names = []
for a in aliases:
first = a[0][:1].upper() + a[0][1:]
last = a[1][:1].upper(... |
def testXMLValue(val, attrib=False):
"""
Test that the XML value exists, return val.text, else return None
Parameters
----------
- val: the value to be tested
"""
if val is not None:
if attrib:
return val.strip()
elif val.text:
return val.text.str... |
def retry_get(value):
"""Return True if value is None"""
x1, x2 = value
return x1 == 'retry' |
def generic(status_code, body, headers=None, **kwargs):
"""Generic JSON response"""
base_resp = {
'statusCode': status_code,
'headers': {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': 'Content-Type,Authorization,Accept,X-Amz-Date,X-Api-Key,X-Amz-Sec... |
def _FindLastCharOutsideOfBrackets(name, target_char, prev_idx=None):
"""Returns the last index of |target_char| that is not within ()s nor <>s."""
paren_balance_count = 0
template_balance_count = 0
while True:
idx = name.rfind(target_char, 0, prev_idx)
if idx == -1:
return -1
# It is much fas... |
def convert_p(element, text):
"""
Adds 2 newlines to the end of text
"""
depth = -1
while element:
if (not element.name == '[document]' and
not element.parent.get('id') == '__RESTRUCTIFY_WRAPPER__'):
depth += 1
element = element.parent
if text:
... |
def auto_type_convert(value):
"""Try to convert 'value' to a int, float, or bool. Otherwise leave
as a string. This is done recursively with complex values."""
if value is None:
return None
if isinstance(value, list):
return [auto_type_convert(item) for item in value]
elif isinstan... |
def check_bounds(position, limit, buffer):
"""Check whether a co-ordinate is within a limit (including a buffer).
One dimensional, and assumes the lower limit is 0 (less the buffer)."""
if position < 0 - buffer:
return limit + buffer
elif position > limit + buffer:
return -buffer
e... |
def _get_string_from_json(data, key):
"""Attempt to load a key from a JSON-decoded response object."""
try:
val = data[key]
assert hasattr(val, 'encode') # Must be unicode
except (TypeError, KeyError, AssertionError):
raise Exception('GitHub response was missing "{0}"'.format(key))
... |
def repeat(x, n):
"""
Returns a list of a given value repeated a given number of times
Args:
* `x` (any): The value to repeat
* `n` (`int`): The number of repetitions
Returns:
* `list`. List of repeated values `x`
"""
return [x for _ in range(n)] |
def join_path(a, *p):
"""Join path tokens together similar to os.path.join, but always use
'/' instead of possibly '\' on windows."""
path = a
for b in p:
if b.startswith('/'):
path += b[1:]
elif path == '' or path.endswith('/'):
path += b
else:
path += '/' + b
return path |
def issubclass_safe(cls, bases) -> bool:
""" like issubclass, but return False if cls is not a class, instead of
raising an error:
>>> issubclass_safe(Exception, BaseException)
True
>>> issubclass_safe(Exception, ValueError)
False
>>> issubclass_safe(123, BaseException)
False
"""
... |
def test_passed(correct, output):
"""Automate some of manual testing."""
if correct == output:
return True
elif type(output) is not bool and correct in output:
return True
raise ValueError('Failed test > E: {} vs. A: {}'.format(correct, output)) |
def get_tokenized_imdb(data):
"""Get the tokenized IMDB data set for sentiment analysis."""
def tokenizer(text):
return [tok.lower() for tok in text.split(' ')]
return [tokenizer(review) for review, _ in data] |
def epoch2checkpoint(_epoch: int) -> str:
"""
Args:
_epoch: e.g. 2
Returns:
_checkpoint_name: e.g. 'epoch=2.ckpt'
"""
return f"epoch={_epoch}.ckpt" |
def respond_raw(request, template, context=None, args=None, headers=None):
"""
"""
return {
'request': request,
'template': template,
'context': context,
'args': args,
'headers': headers,
} |
def _real_1d_func(x, func):
"""Return real part of a 1d function."""
return func(x).real |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.