content stringlengths 42 6.51k |
|---|
def user_stat_request_feedback(percentile_standing, karma=None):
"""
Sends the statistics message to the user about his karma
:param karma: The karma rating of the user.
:param percentile_standing: The percentile standing of the user.
:return:
"""
if percentile_standing is None:
sta... |
def get_pollen_message(bars):
"""
bars: {'City1': [...], 'Nederland': [...]}
groen: "geen last", geel: "weinig last", oranje: "redelijk veel last", rood: "veel last", en paars: "extreem veel last"
"""
severity = {
1: "geen last",
2: "weinig last",
3: "redelijk veel last",
... |
def removeInvertedPaths(mpDict) :
"""
Find the number of paths of this type joining
the nodes in the sample
:param mpDict: {str: [int, bool]} dict,
key, str - name of the metapath
value, [int, bool] - which matrix file to use, and
whether to use the transpose (inverse path)
:return: mpList, str list: order... |
def list_extract(lst, max_num):
""" Function used to pop a number of elements from a list equal or less than max_num """
ret_lst = []
if len(lst) >= max_num:
for i in range(max_num):
ret_lst.append(lst.pop())
else: # less elements than max_num
for i in reversed(range(len(l... |
def decode_subwords(subwords: str) -> str:
"""Decodes a given subword string into regular text.
Args:
subwords: The subword string to be decoded into regular text.
Returns:
The decoded text string.
"""
return subwords.replace(" ", "").replace("_", " ").strip() |
def extended_gcd(p, q):
"""
Find the greatest common divisor and returns them.
:param a: An integer.
:param b: An integer.
:rtype: A tuple representing the greatest common divisor.
"""
(a, b) = (p, q)
if a < 0:
a = -1 * a
if b < 0:
b = -1 * b
x0 = 0
y1 = 0... |
def _create_if_p2os(overlay, pkg, distro, preserve_existing, collector):
"""Don't if the package is p2os"""
collector.append(pkg)
if 'p2os' in pkg:
return True, False
return True, True |
def PredicateSplit(func, iterable):
"""Splits an iterable into two groups based on a predicate return value.
Args:
func: A functor that takes an item as its argument and returns a boolean
value indicating which group the item belongs.
iterable: The collection to split.
Returns:
A tuple contain... |
def perlStyleToPattern(pattern):
"""Convert 's/abc/i'-style regexes to 'abc' patterns.
Used during extraction of regexes from InternetSource.
"""
if pattern.count('/') is 2:
l = pattern.index('/')
r = pattern.rindex('/')
if 0 <= l and l < r:
pattern = pattern[l+1 : r]
return pattern |
def removeLines(svgfile, clues):
"""
Removes blank lines from text file
"""
toRemove = []
for i in range(0, len(svgfile)):
for cl in range(0, len(clues)):
found = svgfile[i].find(clues[cl])
if found != (-1):
toRemove.append(i)
return toRemove |
def extract_camera_key_from_filename(filename: str) -> str:
"""
Extract the camera name from the filename.
:param filename: the name of the file where the samples image is stored.
Ex: 'samples/CAM_BACK/n015-2018-10-02-10-50-40+0800__CAM_BACK__1538448750037525.jpg',
:return: The camera na... |
def get_start_of_album_index(text: str) -> int:
"""
Get the index of the opening parenthesis which denotes where the album name starts.
This is trickier than it first seems, and using RegEx would be difficult due to the potentially infinitely nested
parentheses caused by parentheses appearing in the al... |
def day_4(part, data):
"""
"""
lower = int(data[0].split('-')[0])
upper = int(data[0].split('-')[1])
counter = 0
for i in range(lower, upper):
num = str(i)
flag = False
pair = False
for j in range(1, 6):
# Check for non decreasing number
... |
def is_sorted(seq):
"""
Takes a list of integers and checks if the list is in sorted order.
:param seq: A list of integers
:rtype: Boolean
"""
return all(seq[i - 1] <= seq[i] for i in range(1, len(seq))) |
def is_valid_cell(ships: dict, field: list, cell: list, direction: str) -> bool:
"""
Validates if single cell result is valid
(valid submarine or single ship cell)
:param ships: collection of valid ships (dict)
:param field: board game "Battleship" (list)
:param cell: candidate for single ship/submarine
:param ... |
def _(ls):
"""
prettify
:param ls:
:return:
"""
response = []
for dictionary in ls:
response_per_dictionary = []
for key in dictionary:
response_per_dictionary.append(
'{}\t {}\n'.format(key, dictionary[key]))
response.append(' '.join(respo... |
def get_named_function(module):
"""Get function members in given module."""
from inspect import isfunction
return {k: v for k, v in module.__dict__.items() if isfunction(v) and not k.startswith("_")} |
def replace_grid_symbols(grid, old_to_new_map):
"""Replaces symbols in the grid.
If mapping is not defined the symbol is not updated.
Args:
grid: Represented as a list of strings.
old_to_new_map: Mapping between symbols.
Returns:
Updated grid.
"""
def symbol_map(x):
if x in old_to_new_map... |
def _cross(v1,v2,v3):
"""performs vector cross product"""
v30 = v1[1] * v2[2] - v1[2] * v2[1]
v31 = v1[2] * v2[0] - v1[0] * v2[2]
v32 = v1[0] * v2[1] - v1[1] * v2[0]
v3[0] = v30
v3[1] = v31
v3[2] = v32
return v3 |
def format_data(account):
"""
Format account into printable format: name, description and country
"""
name = account["name"]
description = account["description"]
country = account["country"]
return f"{name}, a {description}, from {country} " |
def quote_copy(s):
"""Quoting for copy command. None is converted to \\N.
Python implementation.
"""
if s is None:
return "\\N"
s = str(s)
s = s.replace("\\", "\\\\")
s = s.replace("\t", "\\t")
s = s.replace("\n", "\\n")
s = s.replace("\r", "\\r")
return s |
def _fetch_id(get_method, name, required=True):
"""Use `get_method` to fetch an OpenStack SDK resource by `name` and
return its ID. If `required`, ensure the fetch is successful.
Returns: the ID, or None if not found and not `required`
Raises: openstack's ResourceNotFound when `required` but not found... |
def wfi_levenshtein(string_1, string_2):
"""
Calculates the Levenshtein distance between two strings.
This version uses an iterative version of the Wagner-Fischer algorithm.
Usage::
>>> wfi_levenshtein('kitten', 'sitting')
3
>>> wfi_levenshtein('kitten', 'kitten')
0
... |
def get_uid(json_data, start=None, end=None):
"""
Give a unique id using document, paragraph and sentence number.
"""
if 'did' in json_data:
did = json_data['did']
else:
did = json_data['fileid']
pid = json_data.get('pid', '')
if 'sid' in json_data:
sid = json_data['... |
def Celsius_F(Fahrenheit):
"""Usage: Convert to Celsius from Fahrenheit
Celsius_F(Fahrenheit)"""
return (Fahrenheit-32)*5/9 |
def write_correct_link_to_cds(raw_link):
"""
Get full link to specific NCBI CDS from gemonic file
Gives the full link to the CDS from genimc data. This is the type
of input needed for calculating the codon frequencies used by codon
harmionizer.
This function is usefull mostly if the raw_lin... |
def parse_float(float_str, default=None):
"""Parse float."""
float_str = float_str.replace(',', '')
float_str = float_str.replace('-', '0')
try:
return (float)(float_str)
except ValueError:
return default |
def convert_ktoe_twh(data_ktoe):
"""Conversion of ktoe to TWh
Parameters
----------
data_ktoe : float
Energy demand in ktoe
Returns
-------
data_gwh : float
Energy demand in TWh
Notes
-----
https://www.iea.org/statistics/resources/unitconverter/
"""
dat... |
def sort_vertices(*args, **kwargs):
"""Call wrapped sorting function.
A wrapper of sorting function
Using buitin sorted() for now
Args:
same as the wrapped function
Returns
same as the wrapped function
Raises:
same as the wrapped fucntion
"""
return sorted(*a... |
def _has_methods(obj, *methods):
"""
For ducktype testers.
Tests for methods to exist on objects.
:param obj:
:param methods: (variadic)
:return:
"""
for method in methods:
if not hasattr(obj, method) or not callable(getattr(obj, method)):
return False
return True |
def format_phone(value):
"""
>>> format_phone('20108484') # 8
'2010-8484'
>>> format_phone('920108484') # 9
'92010-8484'
>>> format_phone('8420108484') # 10
'(84) 2010-8484'
>>> format_phone('84920108484') # 11
'(84) 92010-8484'
"""
if len(value) == 11:
return ... |
def _agent_has_email_address(agent_obj):
"""Check if agent has email.
Arguments:
agent_obj (list/dict): The specified field from the research dataset. If publisher then dict else list
Returns:
bool: True if has emails, False if not.
"""
if agent_obj:
if isinstance(agent_ob... |
def printer_enabled_p(printer):
"""Internal utility to see if printer (or subprinter) is enabled."""
if hasattr(printer, "enabled"):
return printer.enabled
else:
return True |
def replace_single_quotes(quoted_string):
"""Replace single quote to double quote in string.
Args:
quoted_string: The single quoted string to replace.
Returns:
The double quoted string.
"""
return quoted_string.replace("'", '"') |
def mean_of_list(list_in):
"""Returns the mean of a list
Parameters
----------
list_in : list
data for analysis
Returns
-------
mean : float
result of calculation
"""
mean = sum(list_in) / len(list_in)
return(mean) |
def arn_has_colons(arn):
"""Given an ARN, determine if the ARN has colons in it. Just useful for the hacky methods for
parsing ARN namespaces. See
http://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html for more details on ARN namespacing."""
if arn.count(":") > 0:
return True
... |
def get_value(json, attr):
"""Get the value from the json."""
if attr in json:
return json[attr][0]
return "" |
def zero_padding(sequences):
"""
Pad sequences in input array with 0's such that every sequence is of the same length
of max(len(sequences)).
Parameters
----------
sequences : np.ndarray / list
array or list of encoded protein sequences.
Returns
-------
sequences: np.ndarra... |
def parse_norm(norm):
"""
Expected format: norm = 10E15
"""
try:
base, exp = norm.split('E')
except ValueError:
base, exp = norm.split('e')
if float(base) == 1.0:
norm = '10'
else:
norm = base
norm += '^{%s}' % exp
return norm |
def transpose(lists):
""" Transpose a list of lists. """
if not lists: return []
return map(lambda *row: list(row), *lists) |
def get_div_by_ref(divs, ref):
"""
Returns the div with the id ref.
"""
refdiv = None
parent_id = None
for div in divs:
if div['id'] == ref:
refdiv = div
break
if div.get('subdivs', None):
subdiv, _ = get_div_by_ref(div['subdivs'], ref)
... |
def convert_dict_into_tuple_by_order(py_dict, py_order):
"""
Convert dictionary object to tuple by the order
of the elements specificed in the py_order.
"""
if not isinstance(py_dict, dict):
return
if not isinstance(py_order, list):
return
py_tuple = tuple(py_dict[x] for x in py_order)
return py_tuple |
def format_date(date):
"""Transforms a date from YYYY/MM/DD format to DD-MM-YYYY"""
if '/' in date:
date = date.split('/')
date = f'{date[2]}-{date[1]}-{date[0]}'
return date |
def test_pbm(h, f):
"""PBM (portable bitmap)"""
if len(h) >= 3 and \
h[0] == ord(b'P') and h[1] in b'14' and h[2] in b' \t\n\r':
return 'pbm' |
def get_primer_seqs( primers ):
"""
Extract the primer seqs from the primer dict
input: primer dict
output: list of lists containing primer name and sequence
Kim Brugger (19 Aug 2016)
"""
primer_seqs = []
for primer_id in sorted(primers):
if 'PRIMER_ID' in primer... |
def fixed_point_frac_part(fixed_point_val: int, precision: int) -> int:
"""
Extracts the fractional part from the given fixed point value.
"""
if (precision >= 0):
mask = (1 << precision) - 1
return fixed_point_val & mask
return 0 |
def add_new_tile_at_position(grid, position, value):
"""
Puts a tile in the game grid, given the coordinates (x,y) of the tile.
:param grid: The game grid
:param position: (x, y) tuple with the position
:param value: The value of the tile (its symbol, for instance)
:return: Game grid with a new... |
def prettyPrintResults(evaluationResults):
"""prettyPrintResults returns a string formatting the results of a simulation evaluation result"""
output = ""
for er in evaluationResults:
message = (
f"Evaluated Action Name: {er['EvalActionName']}\n"
f"\tEvaluated Resource name: {... |
def legendre(n, p):
"""Compute the Legendre Symbol
>>> legendre(27, 7)
-1
>>> legendre(28, 7)
0
>>> legendre(29, 7)
1
"""
return {0: 0, p - 1: -1}.get(pow(n, (p - 1) // 2, p), 1) |
def is_contained(target, keys):
"""Check is the target json object contained specified keys
:param target: target json object
:param keys: keys
:return: True if all of keys contained or False if anyone is not contained
Invalid parameters is always return False.
"""
if not target or not key... |
def first_word(str):
"""
returns the first word in a given text.
"""
text=str.split()
return text[0] |
def names(lst):
"""
Return a list of the .name attribute of the objects in the list
"""
return [obj.name for obj in lst] |
def is_palindrome(n):
"""
Checks whether n is a palindrome by converting it to a string
and and comparing it to the reversed string.
"""
return str(n) == str(n)[::-1] |
def calculate_trip_severity(firewall, cost_function, offset=0):
""" Example for depth 3
0 0
1 1
2 2
3 1
4 0
5 1
6 2
7 1
8 0
"""
severity = 0
for layer, depth in firewall.items():
if (layer + offset) % (2 * (depth - 1)) == 0:
sever... |
def shift_left(k: str, shift: int) -> str:
"""Shift a string k by shift units to the left. This is used while generating round keys in DES."""
s = k[shift:] + k[:shift]
return s |
def flatten(iterable):
"""
Flaten out a list of lists. For example
[['a','b'], ['c']] -> ['a', 'b', 'c']
"""
return [item for subiterable in iterable for item in subiterable] |
def total_orbits(orbits):
"""
>>> total_orbits([["COM", "B"], ["B", "C"], ["C", "D"], ["D", "E"], ["E", "F"], ["B", "G"], ["G", "H"], ["D", "I"], ["E", "J"], ["J", "K"], ["K", "L"]])
42
"""
orbit_dict = {orbits[i][1]: orbits[i][0] for i in range(len(orbits))}
total = 0
for orbit in orbit_dic... |
def check_is_right(name):
"""
Checks if the name belongs to a 'right' sequence (/2). Returns True or
False.
Handles both Casava formats: seq/2 and 'seq::... 2::...'
"""
if ' ' in name: # handle '@name 2:rst'
name, rest = name.split(' ', 1)
if rest.startsw... |
def type_name(instance:object) -> str:
"""
Object class name
"""
return type(instance).__name__ |
def get_padding_same(kernel_size, dilation_rate):
"""
SAME padding implementation given kernel_size and dilation_rate.
The calculation formula as following:
(F-(k+(k -1)*(r-1))+2*p)/s + 1 = F_new
where F: a feature map
k: kernel size, r: dilation rate, p: padding value, s: stri... |
def secs_to_human(elapsed):
"""
Format `elapsed` into a human-readable string with hours, minutes and seconds
:param elapsed: Milliseconds
:return: Human readable time string
"""
hours, rem = divmod(elapsed, 60 * 60)
minutes, seconds = divmod(rem, 60)
secs_plural = 's' if seconds != 1.0 ... |
def get_sequence_keys(directory):
"""Recursively get all key sequences of a dict.
:param dictionary: dict object for which key sequences will be extracted
:return: list containing all key sequences.
"""
keys_paths = []
def get_files(directory, prefix=[]):
if type(directory) is dict:
... |
def aminoacidSMILES(amino):
"""
Obtain the SMILES representation of a particular amino acid
Arguments:
amino -- One-letter code of the amino acid
Return:
smiles -- 1D Chemical representation of the amino acid
"""
# Dictionary with the SMILES per amino acid
aminoacids ... |
def scale_poly(poly, scale):
"""Converts polygons and lists of polygons by scaling their
coordinates. Works recursively on lists of polygons."""
if type(poly) != list: return poly*scale
return list(scale_poly(p, scale) for p in poly) |
def is_integer(num):
"""
>>> is_integer(0)
True
>>> is_integer(1)
True
>>> is_integer(-1)
True
>>> is_integer(1.0)
True
>>> is_integer(1.1)
False
"""
if num % 1 == 0:
return True
else:
return False |
def _normalize(color_tuple, alpha):
"""Normalize the range of values."""
is_floats = [0 <= elem <= 1 for elem in color_tuple]
if all(is_floats):
color_tuple = tuple(map(lambda elem: int(elem * 255), color_tuple))
if 1 < alpha:
alpha = alpha / 255
return color_tuple, alpha |
def playbook_check(playbook, diastema_token):
"""
A set of rules.
Returns True is Playbook is ok.
Or False if there is a problem in the playbook.
"""
if playbook is None:
print("[ERROR] No Diastema playbook given!")
return (False, "No Diastema playbook given!")
... |
def _convert_strip_time(arg_list):
"""
Handler for the "strip_time" meta-function.
@param IN arg_list List of arguments
@return DB function call string
"""
nb_args = len(arg_list)
if nb_args != 1:
raise Exception("The 'strip_time' meta-function should take exactly 1 argument "
... |
def _slugify(string):
"""Converts text to a slug with _ instead of spaces"""
return string.lower().replace(" ", "_") |
def is_singleton(atoms):
"""
returns whether all the input atoms are the same or not
Inputs
------
atoms: List[.logic.Atom]
[a_1, a_2, ..., a_n]
Returns
-------
flag : bool
a_1 == a_2 == ... == a_n
"""
result = True
for i in range(len(atoms)-1):
res... |
def isBlinking(history, maxFrames):
""" @history: A string containing the history of eyes status
where a '1' means that the eyes were closed and '0' open.
@maxFrames: The maximal number of successive frames where an eye is closed """
for i in range(maxFrames):
pattern = '1' + '0' * (i ... |
def test_path(path):
"""
Takes a path and checks if it resolves to "/"
/ -> True
/./ -> True
/<dir>/../ -> True
/<anything> -> False
"""
length = len(path)
# Handle single slash
if length == 1 and path == "/":
return True
# Strip trailing slash
... |
def is_odd(n):
""" True if the integer `n` is odd. """
return n % 2 != 0 |
def check_chrom_name(chrom_name):
"""Check validity of the input chrom_name."""
expected_chroms = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11',
'12', '13', '14', '15', '16', '17', '18', '19', '20',
'21', '22', 'X', 'Y', 'MT']
if chrom_name in expec... |
def split_warnings_errors(output: str):
"""
Function which splits the given string into warning messages and error using W or E in the beginning of string
For error messages that do not start with E , they will be returned as other.
The output of a certain pack can both include:
... |
def check_square(square):
"""
Takes a list of values from a 3 x 3 square on the puzzle as parameter
Checks if all values in the square are distinct
Returns True if they pass
Returns False if otherwise
"""
for n in square:
if square.count(n) > 1:
return False
return Tr... |
def combine_guests(guests1, guests2):
"""
Combine both dictionaries into one, with each key listed
only once, and the value from guests1 taking precedence
"""
guests = guests2
guests.update(guests1)
return guests |
def get_camera_type_int(camera_type):
"""Returns an int based on the camera type."""
if camera_type == 'fisheye':
return 0
elif camera_type == 'perspective':
return 1
else:
return 2 |
def cross(A, B):
"""Cross product of elements in A and elements in B """
return [x+y for x in A for y in B] |
def byte_from(_bytes, _index):
""" :return byte from index """
return bytes([_bytes[_index]]) |
def easy_unpack(elements):
"""
returns a tuple with 3 elements - first, third and second to the last
"""
return (elements[0], elements[2], elements[-2]) |
def dict_from_json(dictionary):
"""Takes a dictionary and recursively int's every key where possible."""
new_dict = {}
for key, value in dictionary.items():
try:
new_key = int(key)
except ValueError:
new_key = key
if isinstance(value, dict):
value ... |
def is_deprecated_annotation_version(version: str):
"""Validates that a given version string is of format X.Y, where X and Y are
integers, X>0, and Y>=0.
Args:
version: a minor version deprecation annotation value (see api/envoy/annotations/deprecation.proto)
Returns:
True iff the given st... |
def is_garbage(raw_text, precision):
""" Check if a tweet consists primarly of hashtags, mentions or urls
Args:
tweet_obj (dict): Tweet to preprocess.
"""
word_list = raw_text.split()
garbage_check = [
token for token in word_list if not token.startswith(("#", "@", "http"))]
g... |
def mvmult(mm, vv):
"""
a matrix by a vector
"""
result = []
for ii in range(4):
result.append(sum([a * b for a, b in zip(mm[ii], vv)]))
return result |
def find_star_info(line, column):
""" For a given .STAR file line entry, extract the data at the given column index.
If the column does not exist (e.g. for a header line read in), return 'False'
"""
# break an input line into a list data type for column-by-column indexing
line_to_list = line.spl... |
def get_message_id(timestamp, topic):
"""Unify the way to get a unique identifier for the given message"""
return '{}{}'.format(timestamp, topic.replace('/', '_')) |
def _get_upper_bounds(all_age_breaks):
"""
return the list of upper bounds associated with a given age stratification
:param all_age_breaks: all lower bounds
:return: list of integers. Final value assumed to be 100.
"""
return [int(all_age_breaks[i + 1]) for i in range(len(all_age_breaks) - 1)] ... |
def is_number (s) :
""" Checks to see if the string is a number. """
if '.' in s :
try :
n = float(s)
except :
return False
else :
try :
n = int(s)
except :
return False
return True |
def checkIfInAltBounds(msg, high, low):
"""If the message has geometry and an ``"altitudes"`` field
(not including NOTAM-D SUA messages), return ``True`` if
the altitude range is within the high and low values.
Messages that don't contain any geometry, or those that
contain geometry, but don;t have... |
def matches_answer_completed(line: str, ind: int):
"""
checks if coq-serapi responses matches "Answer Completed"
"""
return line.strip() == f'(Answer {ind} Completed)' |
def product_consumption_rate(total_items, total_orders):
"""Returns the average number of units per order.
Args:
total_items (int): Total number of items of a SKU sold during a period.
total_orders (int): Total number of orders during a period.
Returns:
Average number of units per ... |
def add_suffix(filenames, suffix):
"""This function adds the suffix to every name
in the set filenames and returns a set with the
new file names
inputs:
filenames - a set with all the filenames
suffix - the suffix to be removed from the filenames
output
new_filena... |
def isPrime(number):
"""
input: positive integer 'number'
returns true if 'number' is prime otherwise false.
"""
import math # for function sqrt
# precondition
assert isinstance(number,int) and (number >= 0) , \
"'number' must been an int and positive"
status = True... |
def validate_port(ports):
"""Validate a port string supplied by the user
Parameters
----------
ports : str
Must be: the string all
A numeric port number
A comma separated list of numbers
converted to a list for blacklist code use
Returns
-------
tuple
... |
def _module_descriptor_file(module_dir):
"""Returns the name of the file containing descriptor for the 'module_dir'."""
return "{}.descriptor.txt".format(module_dir) |
def group_data_list(data: list, by_key, ignore_case: bool = False):
"""Parameter 'data':
- A dict with entity ids as keys and entity info as values. """
if data:
result = {}
for entry in data:
entry_value = entry[by_key]
if ignore_case:
entry_value ... |
def validate_options(ctx, param, value):
"""
Calidate quality parameters
Args:
Default click.option callback parameters
Return:
value (str): value of validated option
"""
print(f'value: {value}')
return value |
def linearOutput_backward(dA, cache):
# Because dg=1, codes below are disabled to speed up
"""
Z=cache
dg=1
dZ=dA*dg
"""
dZ=dA
return dZ |
def to_decimal__xy(x, y):
"""
To float with 2 decimal places.
:param x:
:param y:
:return:
"""
return '{0:2.2f}'.format(x / y) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.