content stringlengths 42 6.51k |
|---|
def does_seq_contain_fixed_numbers(sequence: str):
"""
sequence: A string that contains a comma seperated numbers
return: True if one of the terms is an integer, False if all terms are patterns
"""
seq_terms = sequence.split(",")
for term in seq_terms:
if str(term).strip().lstrip("+-").i... |
def category_styledict(colordict, highlight_grp):
"""Generate a dictionary mapping categories to styles.
The only styling implemented at present is converting the highlighted group to a dashed line.
Args:
colordict (dict) A mapping of categories to colors
highlight_grp (string) The name of... |
def pluralize_type_designator(designator):
"""
:param designator: the XNAT type name or synonym
:return: the pluralized type designator
"""
if designator == 'analysis':
return 'analyses'
elif designator.endswith('s'):
# No examples of this (yet), but play it safe.
return ... |
def getEditDist(str1, str2):
""" return edit distance between two strings of equal length
>>> getEditDist("HIHI", "HAHA")
2
"""
assert(len(str1)==len(str2))
str1 = str1.upper()
str2 = str2.upper()
editDist = 0
for c1, c2 in zip(str1, str2):
if c1!=c2:
editDist +... |
def gcd(a: int, b: int) -> int:
""" Euclidean algorithm for calculating greatest common divisor. """
while b != 0:
(a, b) = (b, a % b)
return a |
def pluralize(item, amount):
"""Title for a count of items."""
if amount == 0:
return "No %ss yet" % item
elif amount == 1:
return "1 %s" % item
elif amount > 1:
return "%s %ss" % (amount, item)
return "<Unable to retrieve %ss. Field hidden?>" % item |
def estimate_p_value(observed_value, random_distribution):
"""Estimate the p-value for a permutation test.
The estimated p-value is simply `M / N`, where `M` is the number of
exceedances, and `M > 10`, and `N` is the number of permutations
performed to this point (rather than the total number of
pe... |
def join_url(url, *paths):
"""
Joins individual URL strings together, and returns a single string.
Usage::
>>> util.join_url("example.com", "index.html")
'example.com/index.html'
"""
result = '/'.join(chunk.strip('/') for chunk in [url] + list(paths))
if url.startswith('/'):
... |
def atleast(a,val,c):
"""
atleast(a,val,c)
Ensure that the number of occurrences of val in a is atmost c.
"""
return [sum([a[i] == val for i in range(len(a))]) >= c] |
def split_name(fullname):
"""
Split a pckg.name string into its package and name parts.
:param fullname: an entity name in the form of <package>.<name>
"""
parts = fullname.split('.')
pkg = ".".join(parts[:-1])
simpleName = parts[-1]
return pkg, simpleName |
def parse_value(val):
"""Parse value from cell.
:returns (tuple): (value, status)
"""
if val == ".":
return None, "missing or 0"
elif val == "..":
return None, "too few"
else:
return float(val.replace(",",".").replace(" ", "")), None |
def del_none(o):
"""
Delete keys with the value ``None`` in a dictionary, recursively.
This alters the input so you may wish to ``copy`` the dict first.
"""
if isinstance(o, dict):
d = o.copy()
else:
d = o.__dict__.copy()
for key, value in list(d.items()):
if value i... |
def cmp_mount_order(this, other):
"""Sort comparision function for mount-point sorting
See if ``this`` comes before ``other`` in mount-order list. In
words: if the other mount-point has us as it's parent, we come
before it (are less than it). e.g. ``/var < /var/log <
/var/log/foo``
:param thi... |
def merge_pairs (seq1, seq2, qual1, qual2, q_cutoff=10, minimum_q_delta=5):
"""
Combine paired-end reads into a single sequence by managing discordant
base calls on the basis of quality scores.
"""
mseq = ''
# force second read to be longest of the two
if len(seq1) > len(seq2):
seq1,... |
def unit_converter(value):
"""Converts the given value to MH"""
if value.endswith("M"):
return float(value[:-1])
else:
if value.endswith("K") or value.endswith("k"):
return float(value[:-1])/1000
elif value.endswith("G"):
return float(value[:-1])*1000
... |
def zstrip(chars):
"""Strip all data following the first zero in the string"""
if '\0' in chars:
return chars[:chars.index("\0")]
return chars |
def get_themes_for_design(request, design=None):
"""
Return a list of all theme available for a design with a specific slug (arg design)
"""
if not design:
return None
return "" |
def rseq(from_num, to_num, length):
"""
RSEQ from to count
outputs a list of COUNT equally spaced rational numbers
between FROM and TO, inclusive::
? show rseq 3 5 9
[3 3.25 3.5 3.75 4 4.25 4.5 4.75 5]
? show rseq 3 5 5
[3 3.5 4 4.5 5]
"""
result = [from_num + (... |
def countEnnemies(column,ennemies):
""" Return the closest enemy distance, and the total in a column """
tot_ennemies = 0
closest = 0
colx= column
for ennemy in ennemies :
if ennemy.y>0:
if (ennemy.x == colx):
tot_ennemies = tot_ennemies +1
if (e... |
def normalize_11(x, low, high):
"""
Normalize [low, high] to [-1, 1]
low and high should either be scalars or have the same dimension as the last dimension of x
"""
return 2 * (x - low) / (high - low) - 1 |
def custom_formatwarning(msg, *args, **kwargs):
"""Ignore everything except the message."""
return str(msg) + '\n' |
def check_datasets(datasets):
"""Check that datasets is a list of (X,y) pairs or a dictionary of dataset-name:(X,y) pairs."""
try:
datasets_names = [dataset_name for dataset_name, _ in datasets]
are_all_strings = all([isinstance(dataset_name, str) for dataset_name in datasets_names])
are... |
def has_votes(change):
"""Returns True if there are any votes for a given change.
Assumes that change has the keys: positive_reviews_counts and
negative_reviews_counts.
"""
return change.get("positive_reviews_counts", 0) + change.get("negative_reviews_counts", 0) > 0 |
def center_based_to_rect(cx, cy, rx, ry):
"""Returns x, y, w, h from the center and radius parameters."""
return cx - rx, cy - ry, rx * 2, ry * 2 |
def _num_epochs(tokens_per_epoch, seq_length, num_samples):
"""Based on number of samples and sequence lenght, calculate how many
epochs will be needed."""
num_epochs = 0
total_tokens = 0
while True:
num_epochs += 1
total_tokens += tokens_per_epoch
# -1 is because we need to ... |
def binary_search(arr, low, high, x):
"""
Find index of x in arr if present, else -1
Thanks to https://www.geeksforgeeks.org/python-program-for-binary-search/
:param arr: Ascending order sorted array to search
:param low: Start index (inclusive)
:param high: End index (inclusive)
:param x: E... |
def _isnamedtupleinstance(x):
"""https://stackoverflow.com/questions/2166818/how-to-check-if-an-object-is-an-instance-of-a-namedtuple"""
t = type(x)
b = t.__bases__
if len(b) != 1 or b[0] != tuple: return False
f = getattr(t, '_fields', None)
if not isinstance(f, tuple): return False
return ... |
def tupleize(obj):
"""
Converts into or wraps in a tuple.
If `obj` is an iterable object other than a `str`, converts it to a `tuple`.
>>> tupleize((1, 2, 3))
(1, 2, 3)
>>> tupleize([1, 2, 3])
(1, 2, 3)
>>> tupleize(range(1, 4))
(1, 2, 3)
Otherwise, wraps `obj` in a... |
def count_inversions(array, blank):
"""Returns the number of inversions in a list ignoring the blank value."""
count = 0
for i, tile1 in enumerate(array[:-1]):
if tile1 is not blank:
for tile2 in array[i + 1 :]:
if tile2 is not blank:
if tile1 > tile2:... |
def replace(string, repl, from_line, to_line, from_col, to_col):
"""Replace a substring in *string* with *repl*. """
if from_line < 0 and to_line < 0:
return string
lines = string.split('\n')
if from_line > len(lines) - 1 and to_line > len(lines) - 1:
return string
if from_line < ... |
def unquote(s):
"""
>>> unquote('"foo"')
'foo'
>>> unquote('"foo"bar')
'"foo"bar'
"""
for quote in ('"', "'"):
if s.startswith(quote) and s.endswith(quote):
return s[1:-1]
return s |
def clock_angle(hour, minute):
"""
Calculate Clock Angle between hour hand and minute hand
param hour: hour
type: int
param minute: number of minutes pas the hour
type: int
return: the smallest angle of the two possible angles
"""
if (hour < 0 or minute < 0 or hour > 12 or minute... |
def mid(f, a, b):
"""Midpoint Rule for function f on [a,b]"""
return 1.0*(b-a)*f((a+b)/2.0) |
def strip_file_protocol(path: str, strict: bool = True) -> str:
"""Strip (if necessary) file://host/ protocol from an local path
See:
- https://en.wikipedia.org/wiki/File_URI_scheme
- https://tools.ietf.org/html/rfc3986
Args:
file_path (str): The file path
strict (bool, opt... |
def analogy2query(analogy):
""" Decompose analogy string of n words into n-1 query words and 1 target word (last one)
zips with +-
>>> analogy2query("Athens Greece Baghdad Iraq")
('+Athens -Greece +Baghdad', 'Iraq')
"""
words = analogy.split()
terms, target = words[:-1], words[-1]
pm_ter... |
def convert_to_markdown(outline, indent = 4, curr_indent = 0):
"""Convert an outline to markdown format"""
lines = []
for i in outline:
if type(i) == str:
lines.append("%s* %s" % (curr_indent * " ", i))
else:
lines.append("%s* %s" % (curr_indent * " ", i[0]))
... |
def min_edit_distance(word1: str, word2: str) -> int:
"""
Calculates the edit distance between two words.
More specifically, the number of operations (insert, replace, remove)
needed to convert word1 into word2.
"""
word1_length = len(word1)
word2_length = len(word2)
# When any of the... |
def size_as_number_of_bytes(size):
"""Returns the minimum number of bytes needed to fit given positive
integer.
"""
if size == 0:
return 1
else:
number_of_bits = size.bit_length()
rest = (number_of_bits % 8)
if rest != 0:
number_of_bits += (8 - rest)
... |
def format_context(text, data):
"""replace custom templating by something compliant with python format function"""
# { and } need to be escaped for the format function
text = text.replace('{', '{{').replace('}', '}}')
# #!- and -!# are turned into { and }
text = text.replace('#!-', '{').rep... |
def validateNumber(n):
"""check if the input is a valid number"""
try:
n = float(n)
if n < 0:
exit()
return n
except:
print("invalid input")
exit(1) |
def transformer_tpl(data):
"""Generates Mantle transformer
Output:
/**
* Converts '{}' property from '{}' class type.
*
* @return NSValueTransformer
*/
+ (NSValueTransformer *)articleJSONTransformer
{
return [NSValueTransformer
mtl_JSONArrayTransformerWithMod... |
def find_namespaces(parsed_token):
"""
Find the namespace claims in the parsed Access Token
:param parsed_token: dictionary containing a valid Parsed Access Token
:return: list of namespace names
"""
namespaces = []
for k in parsed_token.keys():
if k.startswith('namespace-'):... |
def remove_empty(file_list):
"""
Given a file list, return only those that aren't empty string or None.
Args:
- file_list (list): a list of files to remove None or empty string from.
Returns:
(list) list of (non None or empty string) contents.
"""
return [x for x in file_list i... |
def add_previous(location, previous):
"""
Add previous location
"""
if location is None:
return previous
current, old_previous = location
return (current, add_previous(old_previous, previous)) |
def bmi(weight, height):
"""
>>> bmi(160, 67)
25.056805524615726
>>> bmi(200, 72)
27.121913580246915
>>> bmi(120, 60)
23.433333333333334
"""
return (weight * 703) / (height**2) |
def dedupe_by_keys(data, dedupe_by):
"""Helper function for deduplicating a list of dicts by a set of keys.
"""
output = {}
for d in data:
output["".join([str(v) for k, v in d.items() if k in dedupe_by])] = d
return list(output.values()) |
def find_open_and_close_braces(line_index, start, brace, lines):
"""
Take the line where we want to start and the index where we want to start
and find the first instance of matched open and close braces of the same
type as brace in file file.
@param: line (int): the index of the line we want to st... |
def isiterable(var):
"""
Check if input is iterable.
"""
return hasattr(var, "__iter__") |
def set_domain_at_host(domains_host, i):
""" Choose the right domain out of domains_host. If i < len(domains_host)
then it is the i-th element otherwise it is the last element in the list.
"""
if type(domains_host) == list:
j = i if i < len(domains_host) else len(domains_host)-1
doma... |
def _gr_text_to_no(l, offset=(0, 0)):
"""
Transform a single point from a Cornell file line to a pair of ints.
:param l: Line from Cornell grasp file (str)
:param offset: Offset to apply to point positions
:return: Point [y, x]
"""
x, y = l.split()
return [int(round(float(y))) - offset[0], int(round(flo... |
def get_tag_str(cmd, tag):
"""
Returns the string for a tag in a command, or 'None' if the tag doesn't exist.
"""
idx = 0
while len(cmd) > idx and cmd[idx] != tag:
idx += 1
if idx <= len(cmd) - 1:
return cmd[idx + 1]
return None |
def throttle_angle_to_thrust(r, theta):
""" Assumes theta in degrees and r = 0 to 100 %
returns a tuple of percentages: (left_thrust, right_thrust)"""
theta = ((theta + 180) % 360) - 180 # normalize value to [-180, 180)
r = min(max(0, r), 100) # normalize value to [0, 1... |
def tonumber(v):
"""
Convert a value to int if its an int otherwise a float.
"""
try:
v = int(v)
except ValueError as e:
v = float(v)
return v |
def reverse_str(s):
"""Returns reverse of input str (s)"""
return s[::-1] |
def make_video_path(task_path, itr):
"""
Generate a video name based on a task name and iteration number
:param task_path: the name of the task
:param itr: the iteration number
"""
return "{}_tune_iter{}.mp4".format(task_path.replace("_center", ""), itr) |
def should_reformat(value, line_length):
"""
Do we want to reformat this string.
Only bother if it's a string and longer than the current line length target
or if it currently has a break
"""
return isinstance(value, str) and ("\n" in value or len(value) > line_length) |
def HammingOrder(n):
"""Gives you the order of the Hamming gate as a function of n
Args:
n (int): lenght of the input message
Returns:
N (int): order of the Hamming gate
"""
for i in range(0,15):
N=2**i
if N-i-1>=n: return i |
def split_list(items, separator=",", last_separator=" and "):
"""Split a string listing elements into an actual list.
Parameters
----------
items: :class:`str`
A string listing elements.
separator: :class:`str`
The separator between each item. A comma by default.
last_separator:... |
def m1_m2_from_M_q(M, q):
"""Compute individual masses from total mass and mass ratio.
Choose m1 >= m2.
Arguments:
M {float} -- total mass
q {mass ratio} -- mass ratio, 0.0< q <= 1.0
Returns:
(float, float) -- (mass_1, mass_2)
"""
m1 = M / (1.0 + q)
m2 = q * m1
... |
def psa_want_symbol(name: str) -> str:
"""Return the PSA_WANT_xxx symbol associated with a PSA crypto feature."""
if name.startswith('PSA_'):
return name[:4] + 'WANT_' + name[4:]
else:
raise ValueError('Unable to determine the PSA_WANT_ symbol for ' + name) |
def readout_meminfo(line):
"""
Builds the dict for memory info from line provided by qemu
"""
split = line.split("|")
mem = {}
mem["ins"] = int(split[0], 0)
mem["size"] = int(split[1], 0)
mem["address"] = int(split[2], 0)
mem["direction"] = int(split[3], 0)
mem["counter"] = int(s... |
def is_dict_pyleecan_type(type_name):
"""Check if the type is a dict of Pyleecan type ({name})
Parameters
----------
type_name : str
Type of the property
Returns
-------
is_list : bool
True if the type is a dict of pyleecan type
"""
return type_name[0] == "{" and ty... |
def get_damage_vulnerabities(monster_data) -> str:
"""Returns a string list of damage types to which the monster is
vulnerable.
"""
return ", ".join(monster_data["damage_vulnerabilities"]) |
def wrap_headlines(dbhead, width=75):
"""
wraps lines of a restraint header to prevent too long lines in
SHELXL. wrapping is done with = at the end of a line and ' ' at
start of the next line
:param dbhead: header with restraints
:param width: wrap after width characters
>>> line = ['foo bar... |
def remove_quotation_marks(source_string):
"""
:param source_string: String from which quotation marks will be removed (but only the outermost).
:return: String without the outermost quotation marks and the outermost white characters.
"""
first = source_string.find('"')
second = source_string[fi... |
def split_component_param(string, sep='_', pos=2):
"""Split the component, e.g. lens_mass, from the parameter, e.g. center_x, from the paramter names under the Baobab convention
Parameters
----------
string : str
the Baobab parameter name (column name)
sep : str
separation character... |
def constraint(x,y):
"""
Evaluates the constraint function @ a given point $(x,y)$
@ In, self, object, RAVEN container
@ Out, g(x, y), float, constraint function after modifications
$g(x, y) = 2 - (x**2+y**2)$
because the original constraint was (x**2+y**2) <= 2
t... |
def extract_val_from_str(s):
"""Extract value from string.
Args:
s (str): A string that looks like "200*a"
Returns:
float: The float from the string.
"""
index = s.find("*")
return float(s[:index]) |
def _enum_to_int(value):
"""Convert an IntEnum member to a numeric value.
If it's not an IntEnum member return the value itself.
"""
try:
return int(value)
except (ValueError, TypeError):
return value |
def canQuit(targetList):
"""
Return true if the target list contains at least one valid target
"""
for t in targetList:
try:
valid = t['match']
if valid:
return True
except:
pass
return False |
def reorder_json(data, models, ordering_cond=None):
"""Reorders JSON (actually a list of model dicts).
This is useful if you need fixtures for one model to be loaded before
another.
:param data: the input JSON to sort
:param models: the desired order for each model type
:param ordering_cond: a... |
def is_ip_valid(ip_string: str, port: int) -> bool:
"""Receive ip address and port and return if valid.
Args:
ip_string (str): ip address to check.
port (int): port to check.
Returns:
bool: is the string a valid ip address.
"""
if not isinstance(port, int):
print('Inv... |
def hello(name):
"""say hello to name"""
return 'Hello, ' + name + '!' |
def split_xz(xz, x_dims, x_only=False, z_only=False):
"""
Split concatenated xz vector into x and z vectors.
Args:
xz (list): The XZ matrix.
x_dims ([list/tuple]) the dimensions of the X dimensions
x_only (bool): If True, returns only the x vector.
z_only (bool): If True, re... |
def lerp(x0: float, x1: float, p: float) -> float:
"""
Interplates linearly between two values such that when p=0
the interpolated value is x0 and at p=1 it's x1
"""
return (1 - p) * x0 + p * x1 |
def reverses_transpose(trans1, trans2):
"""Checks if one transpose reverses another"""
if trans1 is None or trans2 is None:
return False
for idx, val in enumerate(trans1):
if trans2[val] != idx:
return False
return True |
def format_comma(d):
"""
Format a comma separated number.
"""
return '{:,d}'.format(int(d)) |
def split_annotation_lh_rh(ann):
"""Splitting of the annotation data in left and right hand
Notebook: C8/C8S3_NMFAudioDecomp.ipynb
Args:
ann (list): Annotation data
Returns:
ann_lh (list): Annotation data for left hand
ann_rh (list): Annotation data for right hand
"""
... |
def is_mention(text):
"""
Determines whether the tweet is a mention i.e. `text` begins with <USER>
:param text: The text to analyze (str)
:return: true | false
"""
return int(text[0] == '@') |
def parse_platform_specific(cfg, is_linux):
"""Recursive function that will parse platform specific config
This will move all children of matching platform keys to its parent
I.e. if current platform is "linux" this config:
nrf5:
version: 15.3.0_59ac345
windows:
... |
def D(corpus, word, second_word=None):
"""
Function to count how many documents a word appears in. If provided a
second word, will also calculate the number of documents both words
appear in.
"""
counts = {word:0}
if second_word:
counts["both"] = 0
# Need corpus to be... |
def check_board(board):
"""
This function is to check if the board is in correct format
The length of the board must be 9 (Rows)
Each row must have 9 elements (Columns)
Each element must be between 1 - 9
"""
check_if_the_board_is_correct = True
if len(board) == 9:
... |
def enforce_cookiecutter_options(struct, opts):
"""Make sure options reflect the cookiecutter usage.
Args:
struct (dict): project representation as (possibly) nested
:obj:`dict`.
opts (dict): given options, see :obj:`create_project` for
an extensive list.
Returns:
... |
def has_next_page(json_data):
"""Check for more labels."""
page_info = json_data.get("data").get(
"repository").get("labels").get("pageInfo")
if page_info.get("hasNextPage"):
return True
return False |
def attr_fmt_vars(*attrses, **kwargs):
"""Return a dict based attrs that is suitable for use in parse_fmt()."""
fmt_vars = {}
for attrs in attrses:
if type(attrs).__name__ in ['MessageMap', 'MessageMapContainer']:
for (name, attr) in attrs.iteritems():
if attr.WhichOneof('attribute'):
... |
def _determine_case(was_upper, words, string):
"""
Determine case type of string.
Arguments:
was_upper {[type]} -- [description]
words {[type]} -- [description]
string {[type]} -- [description]
Returns:
- upper: All words are upper-case.
- lower: All words are l... |
def pythagoras(opposite, adjacent, hypotenuse):
"""
Returns length of a third side of a right angled triangle.
Passing "?" will indicate the unknown side.
"""
try:
if opposite == str("?"):
return ("Opposite = " + str(((hypotenuse**2) - (adjacent**2))**0.5))
if adjacent ==... |
def get_intent_from_transfer_to_action_event(response):
"""
On a transfer to action event, MS will return the current context of the chat - including the intent name
This method will pull that value out of the response
"""
# Variables will be stored in a dict in the response:
if 'value' in respo... |
def categorize(text_arr):
"""Get item name"""
item = ""
for i in range(2, len(text_arr)-1):
item += text_arr[i] + " "
item += text_arr[len(text_arr)-1]
return item |
def convert_tf_name(tf_name):
""" Convert certain patterns in TF layer names to Torch patterns """
tf_name_tmp = tf_name
tf_name_tmp = tf_name_tmp.replace(':0', '')
tf_name_tmp = tf_name_tmp.replace('/forward_lstm/lstm_cell_1/recurrent_kernel', '/weight_hh_l0')
tf_name_tmp = tf_name_tmp.replace('/fo... |
def spiral_matrix(matrix):
"""Navigates a 2D array and traverses the edges in a spiral-pattern.
Args:
matrix; list: a 2D list to traverse.
Returns:
A string representation of all points traveled in the matrix in the order
they were traveled to.
"""
output = list()
rows = len(matrix[0])
colum... |
def chocolate_cakes(recipes):
"""
IMPORTANT: You should NOT use loops or list comprehensions for this question.
Instead, use lambda functions, map, and/or filter.
Take a dictionary of dishes and ingredients
and return cakes that contain chocolate in them.
>>> chocolate_cakes({'rum cake... |
def make_station_list(data):
"""make station name list from given json data"""
assert type(data) == dict
station_list = []
for i in range(0, len(data.keys())):
station_list.append(data[str(i)])
return station_list |
def majority(x, y, z):
"""
Maj(x, y, z) = (x AND y) XOR (x AND z) XOR (y AND Z)
"""
return (x & y) ^ (x & z) ^ (y & z) |
def make_cannonical(title):
"""Spaces to underscore; first letter upper case only."""
# Cannot use .title(), e.g. 'Biopython small.jpg' --> 'Biopython Small.Jpg'
title = title.replace(" ", "_")
return title[0].upper() + title[1:].lower() |
def _get_extension(sep):
""" Based on delimiter to be used, get file extension. """
return {"\t": ".tsv", ",": ".csv"}[sep] |
def get_pagenation(current, total, page_size,
param_name = 'start', maxpages = 10):
"""
A helper function to make list of pagenation
current : the item number of current page
max : total number of items
page_size : item count in each page
"""
pages = []... |
def add_tuples(a, b):
"""
Add two elements as it were tuples
:return tuple:
"""
if not isinstance(a, tuple):
a = (a, )
if not isinstance(b, tuple):
b = (b, )
return a + b |
def negNDx(v, limit=0):
"""Returns negative of an nD vector,
ignoring items if they are not numeric, with
an option to limit length of the tuple to a certain
length defined by the `limit` argument"""
if limit > 0:
return [-vv for i, vv in enumerate(v)
if (isinstance(vv, (int, floa... |
def _url_prefix(url):
"""Determine url up to the terminal path component."""
# We're assuming no query parameter/fragment since these are git URLs.
# otherwise we need to parse the url and extract the path
return url[:url.rfind('/')] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.