content stringlengths 42 6.51k |
|---|
def piglatinify(st):
"""
Takes in a string, and returns the pig-latin translation of
that string.
Note: You may assume there will be no punctuation for now
HINT: You may not end up using regular expressions for this one...
"hello, connor" -> "ello-hay, onnor-cay
"""
VOWELS = [letter for... |
def response_with_headers(headers=None, status_code=200):
"""
Content-Type: text/html
Set-Cookie: user=username
"""
# header = 'HTTP/1.x {} WEB\r\n'.format(code)
header = 'HTTP/1.1 {} WEB\r\nContent-Type: text/html\r\n'
header = header.format(status_code)
if headers is not None:
... |
def graphToParenStringRecursive(node, dag):
"""subroutine to converts a graph to a parenthesized string
used in graphToParenString"""
if not node or dag.nodes[node]["type"] == "register":
return ""
# lexographically sorted children
lex = sorted(
[
child
for ... |
def systemctl_status_cmd(cmd, shell="bash"):
""" Returns the output that systemctl status <service> would return
This is a stub function. The output corresponds to a running service.
The expected usage of this function is to replace a Node object which
is able to run CLI commands.
This function ig... |
def combine_anchor2url(possible_anchor: str, main_url: str) -> str:
"""Attached anchor to the main_url"""
return (
possible_anchor
if (not possible_anchor) or (not possible_anchor.startswith("#"))
else main_url + possible_anchor
) |
def some_func(arg1, arg2):
"""Perform (sum of arg1 and arg 2).
Arguments:
arg1 - Integer
arg2 - Integer
"""
return sum([arg1, arg2]) |
def left_child(n: int) -> int:
"""Return the left child of a node with non-negative index n."""
return 2 * n + 1 |
def pad4(seq):
"""
Pad each string in seq with zeros up to four places. Note that there
is no reason to actually write this function; Python already
does this sort of thing much better. It's just an example!
"""
return_value = []
for thing in seq:
return_value.append("0" * (4 - len(... |
def filter_timeline_actions(timds, filters):
"""Puts a timeline through a filter to use for calculations.
timds are the timds that data is calculated from.
filters are the specifications that certain data points inside the
timeline must fit to be included in the returned timeline. The value
in the ... |
def get_latex_safe_string(s):
""" This function replaces various special characters in the provided
string to ensure that it renders correctly in latex.
Current changes:
"_" becomes "-"
"""
s = s.replace("_", "-")
return s |
def get_compare_value(version, index):
"""Get an integer value from a list of strings and an index.
Args:
version: A list of one or more strings.
index: An integer representing the list index to retrieve.
Returns:
An integer value from the list index or -1 if the index doesn't exis... |
def does_type_match(main_type, sub_type, main_item, sub_item):
# type: (str, str, str, str) -> bool
"""Return True iff mime type matches item type.
For example:
>>> does_type_match("*", "any", "any", "any")
True
>>> does_type_match("main", "*", "main", "any")
True
>>> does_type_match("... |
def get_settings(bot):
"""Returns settings for this bot.
This function should be fast and mostly (preferably) constant.
"""
# Here is the default values. Keep in sync with the default values in
# ../bot_code/bot_main.py.
return {
# Free partition (disk) space to keep and to self-quarantine on.
... |
def pad(sequences, max_length=None):
"""
ARGUMENTS:
sequences : list of sequences (list of word ids)
RETURNS:
padded_sequences : list with padded sequences
"""
# if max length is not defined, set length to the longest sequence,
# then return the padded sequences
if max_length is None:
length = max([len(seq... |
def set_auth_header(auth_token: str) -> dict:
"""
Creates the auth header for requests
:param auth_token
:return: dict
"""
headers = {
"Content-Type": "application/json",
"Authorization": "Bearer " + auth_token,
}
return headers |
def bool_list_item_spec(bool_item_spec):
"""A specification for a list of boolean items."""
return {
'my_bools': {
'required': True,
'items': bool_item_spec
}
} |
def _Refractive(rho, T, l=0.5893):
"""Equation for the refractive index
>>> "%.8f" % _Refractive(997.047435, 298.15, 0.2265)
'1.39277824'
>>> "%.8f" % _Refractive(30.4758534, 773.15, 0.5893)
'1.00949307'
"""
Lir = 5.432937
Luv = 0.229202
d = rho/1000.
Tr = T/273.15
L = l/0.5... |
def remove_end_of_line(string):
"""
remove "\n" at end of a string
"""
if len(string) > 0:
return str(string[:len(string)-int(string[-1] == "\n")])
else:
return "" |
def nom_ID(nom):
"""Convertis un nom en ID discord """
if len(nom) == 21:
ID = int(nom[2:20])
elif len(nom) == 22:
ID = int(nom[3:21])
elif len(nom) == 18:
ID = int(nom)
else:
print("DB >> mauvais nom")
ID = -1
return(ID) |
def sequences_info(sequences_list, normalization_coefficients):
"""
Give a list with the name, and some information on each sequence.
:param sequences_list: a dictionary with all sequences extract by the sliding window:
- keys: name of sequence
- values: the normalized sequence as numpy arr... |
def _num_bars_2_figsize(n):
""" uses linear regression model to infer adequate figsize
from the number of bars in a bar plot
Data used for training:
x = [7,9,10,12,22,23,26]
y = [[8,4],[9,5],[9,5],[7,5],[10,10],[10,9],[10,11]]
Returns
-------
(w,h) : tuple
the width a... |
def privacy_info_handle(info, anonymous, name=False):
"""hide user info from api if anonymous
:param str info: info which suppose to return
:param bool anonymous: anonymous or not
:param bool name: if the info is a name,
:return str: the handled info should be passed through api
"""
if ano... |
def getCurrencySymbolFromString(s) -> str:
"""
Firstly deletes digits and strips with space, dot, colon and dash characters.
"""
symbol = ''.join([i for i in s if not i.isdigit()])
symbol = symbol.strip(".,- ")
return symbol |
def top_files(query, files, idfs, n):
"""
Given a `query` (a set of words), `files` (a dictionary mapping names of
files to a list of their words), and `idfs` (a dictionary mapping words
to their IDF values), return a list of the filenames of the the `n` top
files that match the query, ranked accord... |
def is_gRNA_valid(cas9_cut_position,target_mutation,strand,user_target_mutation_pos,diff):
# cas9_cut_position=[chr,pos], pos is 1-based position, same as in vcf file
# target_mutation=[chr,pos], pos is 1-based position, same as in vcf file
"""
PBS sequence can't be on the same side to the target site in terms ... |
def __get_average_nut_count__(qars: list, commune):
"""
Get the average of nut_count in the commune passed as parameter in the benin republic area
"""
_all = list(filter(lambda c: c.commune == commune, qars))
total = 0
count = len(_all)
if count == 0:
count = 1
for i, x in enu... |
def _display_tag(tag_tuple):
"""Pretty-print tag tuple"""
tagkey, category, data = tag_tuple
out = ("Tag: '{tagkey}' (category: {category}{dat})".format(
tagkey=tagkey, category=category, dat=", data: {}".format(data) if data else ""))
return out |
def get_formatted_percentage_two_dp(x, tot):
"""
Return a percentage to two decimal places
"""
return "{0:.2f}".format((float(x) / tot * 100)) if tot else '0' |
def _is_this_combined_denovo_bsj_positive(parts):
""" junction orig_circOrLinear orig_decoyOrAnom orig_unmapped orig_pval swapped_circOrLinear swapped_decoyOrAnom swapped_unmapped swapped_pval total_reads
"""
if not parts:
return False
pv_threshold = 0.9
reads_rate_threshold = 0.1
orig_... |
def d2_theta(t, alpha):
"""
theta''(t) = alpha / (alpha + |t|)^2
Also called phi'' or psi''.
Nikolova et al 2013, table 1, f3.
"""
assert alpha > 0
denom = alpha + abs(t)
return alpha / (denom*denom) |
def _pixel_bounds_convert(x):
"""Convert a single 0-4096 coordinate to a pixel coordinate"""
(i, b) = x
# input bounds are in the range 0-4096 by default: https://github.com/tilezen/mapbox-vector-tile
# we want them to match our fixed imagery size of 256
pixel = round(b * 255. / 4096) # convert to t... |
def parse_ranges(ranges):
"""Helper function to parse coverage data ranges."""
total_length = 0
for single_range in ranges:
(start, end) = single_range.values()
length = end - start
total_length = total_length + length
return total_length |
def get_column_counts(workbook_dict):
"""
This expects workbook dictionaries that have been cleaned i.e. have
consistent sheet names throughout. It returns a mapping from file ids to
the number of columns in its workbook.
"""
temp_column_name_map = {}
for name, workbook in workbook_dict.item... |
def domain_in_domain(subdomain, domain):
"""Returns try if subdomain is a sub-domain of domain.
subdomain
A *reversed* list of strings returned by :func:`split_domain`
domain
A *reversed* list of strings as returned by :func:`split_domain`
For example::
>>> domain_in_domain([... |
def to_list(value, separator=','):
"""Parse a list from a delimited string value."""
return [s.strip() for s in value.split(separator) if s] |
def org_add_payload(org_default_payload):
"""Provide an organization payload for adding a member."""
add_payload = org_default_payload
add_payload["action"] = "member_added"
return add_payload |
def target_video_frame_image_to_bytes(document_asl_consultant_target_video_index_schemad_pcoll_row_tpl):
"""
document_asl_consultant_target_video_index_schemad_pcoll_row_tpl:
((<corpus doc id>, <asl consultant id>, <camera perspective>), (<target video filename>, <target video frame seq id>, <target video frame... |
def common_feats(feats_lists):
"""
return a list with the common features of a list of
feature lists, e.g.
common_feats([['F', 'PL'], ['F', 'SG'], ['M', 'PL'], ['M', 'SG']])
[]
"""
set_list=[set(feats) for feats in feats_lists]
for s in set_list[1:]:
set_list[0].inters... |
def mocked_action(*args, **kwargs):
"""
Mark action as runned.
"""
mocked_action.runned = True
return None |
def check_win(row_dict, col_dict):
"""
Check if a board has won
"""
row_win = any(x == 5 for x in row_dict.values())
col_win = any(v == 5 for v in col_dict.values())
return row_win or col_win |
def _create_atom_type_list(first_chars, second_chars):
""" Create all possible two character atom types """
# NMH: Could make this into a list comprehension probably.
types = []
for first_char in first_chars:
for second_char in second_chars:
types.append(first_char + second_char)
... |
def allowed_image(filename):
"""
Check each uploaded image to ensure a permissible filetype and filename
Takes full filename as input, returns boolean if filename passes the check
"""
allowed_img_ext = ["JPEG", "JPG", "HEIC"]
# Ensure file has a . in the name
if not "." in filename:
... |
def connect_model(input_node, operations, training=False):
"""Create graph connections for operations on default graph"""
nodes = [input_node]
for op in operations:
nodes.append(op.connect(nodes[-1], training))
return nodes |
def _colon_split(value):
""" If `value` contains colons, return a list split at colons,
return value otherwise. """
value_list = value.split(":")
if len(value_list) > 1:
return value_list
return value |
def simpleMatch(st:str, pattern:str, star:str='*') -> bool:
""" Simple string match function.
This class supports the following expression operators:
- '?' : any single character
- '*' _ zero or more characters
- '+' _ one or more characters
- '\\' - Escape an expression operator
Examples:
"hello"... |
def _encode_selected_predictions_csv(predictions, ordered_keys_list):
"""Encode predictions in csv format.
For each prediction, the order of the content is determined by 'ordered_keys_list'.
:param predictions: output of serve_utils.get_selected_predictions(...) (list of dict)
:param ordered_keys_list... |
def parse_violated_policy_rule(raw_violated_policy_rule_list: list) -> list:
"""
Parses a list of rules to context paths
:param raw_violated_policy_rule_list: the raw rules list
:return: the parsed rules list
"""
violated_policy_rule_list: list = []
for raw_violated_policy_rule in raw_violat... |
def determineSelectionType(selection):
"""
This function figures out if the current selection is single or multiple.
It then returns a string SINGLE or MULTI.
"""
if selection is None:
exit()
if "ScCellObj" in str(selection):
return('SINGLE')
if "ScCellRangeObj" in str(sel... |
def triplet_sum(l, target):
"""
Checks if the sum of a given triplet is equal to the target sum
:param l: List containing 3 integers
:param target: The target sum
:returns: 'True' if the sum of 'l' is equal to the target sum
"""
if l[0] + l[1] + l[2] == target:
return True
else... |
def clamp(x, minn, maxx):
"""Restrict the float x to the range minn-maxx."""
return max(minn, min(maxx, x)) |
def generate_session(public, private, modulus):
"""Calculates the session key given the received public key, the receiver's
private key, and the modulus"""
return pow(public, private, modulus) |
def support(pauli: str):
"""Returns indices where the Pauli string is non-identity."""
has_support = lambda c: c != "I"
inds = []
for (i, p) in enumerate(pauli):
if has_support(p):
inds.append(i)
return inds |
def get_single_tag_keys(parsed_label_config, control_type, object_type):
"""
Gets parsed label config, and returns data keys related to the single control tag and the single object tag schema
(e.g. one "Choices" with one "Text")
:param parsed_label_config: parsed label config returned by "label_studio.m... |
def align_up(v, unit_size=2):
"""Align the input variable with unit of sizes. The aligned data will always
be larger than the inputs.
Args:
v: the variable to be aligned.
unit_size: the block size of the aligned data.
Return:
aligned variable.
"""
return (v + unit_size ... |
def from_rgb(rgb):
"""translates an rgb tuple of int to a tkinter friendly color code
"""
r, g, b = rgb
return f'#{r:02x}{g:02x}{b:02x}' |
def unfold_azimuths(dataset):
"""Returns a [[azimuths], [azimuths]...] list, where the outer list is per election.
This is useful for processing, which doesn't have to worry about iterating the dict right."""
print("Unfolding azimuths")
azimuths = []
for a, e in sorted(dataset.items()):
azs... |
def minmax(t, u):
"""
Compute all local minima and maxima of the function u(t),
represented by discrete points in the arrays u and t.
Return lists minima and maxima of (t[i],u[i]) extreme points.
"""
minima = []; maxima = []
for n in range(1, len(u)-1, 1):
if u[n-1] > u[n] < u[n+1]:
... |
def _pack_data(X, Y, metadata):
"""
After modifying / preprocessing inputs,
reformat the data in preparation for JSON serialization
"""
if not any(metadata):
# legacy list of list format is acceptable
return list(zip(X, Y))
else:
# newer dictionary-based format is requir... |
def le2int(buf):
"""little endian buffer to integer."""
integer = 0
shift = 0
for byte in buf:
integer |= ord(byte) << shift
shift += 8
return integer |
def valid_name(name):
"""
Replace dashes and underscores by spaces, and lowercase.
>>> valid_name('TALOS_Metapkg-ros_control_sot')
'talos metapkg ros control sot'
"""
return name.replace('_', ' ').replace('-', ' ').lower() |
def get_luminance(color):
""" Return the luminance from a RGB value 0-255 """
return (0.2126*color[0]) + (0.7152*color[1]) + (0.0722*color[2]) |
def calc_avg_HR(list): # test
"""Calculates average of previous heart rates in list
Args:
list (int): list of previous heart rates
Returns:
int: average heart rate
"""
sum = 0
for entry in list:
sum += entry
avg = sum / len(list)
return int(avg) |
def pick(c):
"""Return an element from container `c`.
If `c` is empty, return `None`.
"""
return next(iter(c), None) |
def validate_variables_dict(value, _):
"""
Check that each key in vriables_dict respect the format.
"""
if value:
dime = len(value.get_dict().keys())
for k, v in value.get_dict().items():
if not isinstance(v, (tuple, list)):
return "the values for each key mus... |
def dirname_to_title(dirname):
""" Return a page tile obtained from a directory name. """
title = dirname
title = title.replace('-', ' ').replace('_', ' ')
# Capitalize if the dirname was all lowercase, otherwise leave it as-is.
if title.lower() == title:
title = title.capitalize()
retu... |
def vsum(pos, delta):
"""Sums two vectors in tuple/list format"""
return (pos[0]+delta[0],pos[1]+delta[1]) |
def delete_central_gateway(vpn, elements):
"""
Delete a central gateway.
:param PolicyVPN vpn: policy VPN reference
:param list elements: list of element references
:return: True | False depending on whether an operation taken
:raises PolicyCommandFailed: failure during deletion
"""
... |
def get_subtree(tree, start_node):
"""
take tree_dict tree. return subtree whose root is start_node
"""
plot_nodes = [start_node]
finished=False
while not finished:
extra_nodes = []
for node in plot_nodes:
children = []
if "yes_br... |
def sum_with_none(v1,v2):
""" Sum treating None as zero """
p1 = v1 is None
p2 = v2 is None
if p1 and p2:
return None
elif p1:
return v2
elif p2:
return v1
else:
return v1 + v2 |
def search_for_duplicates(examples):
"""If there are any duplicates in given strings list.
Returns count of duplicate names & dictionary containing numbers of
repeating for every duplicate name."""
nur = {} # names' uniqueness rate
for name in examples:
if name in nur:
nur[name] = nur[n... |
def f_raw(xpts, *coefficients):
"""
The raw function call, performs no checks on valid parameters..
:return:
"""
res = 0.0
for i, p in enumerate(coefficients):
res += p*xpts**i
return res |
def _ensure_sum_divisible_by_6(a, b):
"""Adjust two numbers by incrementing them until their sum is divisible by 6.
Used in adjusting convolutional layer sizes in Squeezenet's 'expand' modules."""
rev = False
while (a + b) % 6 != 0:
b, a = a+1, b
rev = not rev
return (b, a) if rev el... |
def decode(value, encoding='utf-8') -> str:
"""Decode a value from bytes, if hasn't already been.
Note: ``PreparedRequest.body`` is always encoded in utf-8.
"""
return value.decode(encoding) if isinstance(value, bytes) else value |
def pluralizeRussian(number, nom_sing, gen_sing, gen_pl):
"""
Changes the hours, minutes, seconds to plural
"""
s_last_digit = str(number)[-1]
if int(str(number)[-2:]) in range(11,20):
#11-19
return gen_pl
elif s_last_digit == '1':
#1
return nom_sing
elif int(s_last_digit) in range(2,5):
#2,3,4
retu... |
def is_valid_input(ext):
""" Checks if input file format is compatible with Open Babel """
formats = ["dat", "ent", "fa", "fasta", "gro", "inp", "log", "mcif", "mdl", "mmcif", "mol", "mol2", "pdb", "pdbqt", "png", "sdf", "smi", "smiles", "txt", "xml", "xtc"]
return ext in formats |
def clamp_profile(centerline_id, number_of_points):
"""
Profile used for gradually translating a branch to be clamped.
Currently using a linear profile, ranging from 0 to 1.
Args:
centerline_id (int): ID at current centerline point
number_of_points (int): Number of centerline points
... |
def make_shape_channels_first(shape):
"""Makes a (N, ..., C) shape into (N, C, ...)."""
return shape[:1] + shape[-1:] + shape[1:-1] |
def delete_application(connection):
"""SQL test statements for the DeleteAppTests suite.
Args:
connection (django.db.backends.base.BaseDatabaseWrapper):
The connection being tested.
Returns:
dict:
The dictionary of SQL mappings.
"""
return {
'DeleteAppli... |
def do_strip_from_pid(string):
"""
remove PID identifier from a string
"""
if 'pid' not in string:
return string
new_key = string.split("_")
new_key = "_".join(new_key[1:])
return new_key |
def z_function(S):
"""
Z Algorithm in O(n)
:param S: text string to process
:return: the Z array, where Z[i] = length of the longest common prefix of S[i:] and S
"""
n = len(S)
Z = [0] * n
l = r = 0
for i in range(1, n):
z = Z[i - l]
if i + z >= r:
z = m... |
def average_above_zero(table):
"""
brief: computes the average of the positives values
Args:
table: a list of numeric values
Return:
the compiled average
Raises:
ValueError if no positive value is found
ValueError if input table is not a list
"""
if not(isin... |
def triangular_number(n):
"""Return the nth triangular number.
Definition: http://en.wikipedia.org/wiki/Triangular_number
"""
return ((2.0*n + 1.0)**2.0 - 1.0) / 8.0 |
def slack_username(user_id: str) -> str:
""" Generate a slack username macro """
return "<@{}>".format(user_id) |
def context_kubeconfig(name, cluster, user):
"""Generate and return a context kubeconfig object."""
return {
"name": name,
"context": {
"cluster": cluster,
"user": user,
},
} |
def _nextpow2(i):
"""Find next power of 2."""
n = 1
while n < i:
n *= 2
return n |
def list2ngrams(lst, n, exact=True):
""" Convert list into character ngrams. """
return ["".join(lst[i:i+n]) for i in range(len(lst)-(n-1))] |
def _nice_cls_repr(cls):
"""Nice repr of classes, e.g. 'module.submod.Class'
Also accepts tuples of classes
"""
return f"{cls.__module__}.{cls.__name__}" |
def encodeUleb128(value: int) -> bytes:
"""Encodes the given value in Uleb128 format.
Args:
value: The value to encode.
Returns:
The encoded number
"""
if value == 0:
return b"\x00"
data = bytearray()
while value != 0:
currentSlice = value & 0x7f
value >>= 7
if value != 0:
currentSlice |= 0x... |
def partition_list(l, num_sublists):
""" splits a single list l into even sublists """
l = iter(l)
list_new = [[] for _ in range(num_sublists)]
count = 0
for item in l:
index = count % num_sublists
list_new[index].append(item)
count += 1
return list_new |
def filterAlns(alns, poaConfig):
"""
Given alns (already clipped to the window bounds), filter out any
that are deemed insufficiently high-quality for POA.
By and large we avoid doing any filtering to avoid potential
reference bias in variant calling.
However at the moment the POA (and potenti... |
def format_file_size(v):
"""Format file size into a human friendly format"""
if abs(v) > 10**12:
return '%.2f TB' % (v / 10**12)
elif abs(v) > 10**9:
return '%.2f GB' % (v / 10**9)
elif abs(v) > 10**6:
return '%.2f MB' % (v / 10**6)
elif abs(v) > 10**3:
return '%.2f kB' % (v / 10**3)
else:
... |
def miles_per_gallon(start_miles, end_miles, amount_gallons):
"""Compute and return the average number of miles
that a vehicle traveled per gallon of fuel.
Parameters
start_miles: An odometer value in miles.
end_miles: Another odometer value in miles.
amount_gallons: A fuel amount in U.S. gallons.
Return: Fuel... |
def str_join_safe(delim, str_vec, append=False):
"""Version of `str.join` that is guaranteed to be invertible.
Parameters
----------
delim : str
Delimiter to join the strings.
str_vec : list(str)
List of strings to join. A `ValueError` is raised if `delim` is present in any of these... |
def _uint_size_in_bytes(x):
"""
Computes the number of bytes needed to hold an unsigned integer of
arbitrary length.
"""
assert type(x) is int, "`x` should be of type `int`"
assert 0 <= x, "`x` should be >= 0"
size = 0
while True:
x >>= 8
size += 1
if x == 0:
... |
def batch_number(data, batch_size, num_epochs):
"""
Compute the number of batch to process during the epoch loop
"""
return int((len(data)-1)/batch_size) + 1 |
def parse_channel(dataobject, show_kwargs):
"""
Create the labels from a channel
selection
Parameters
----------
dataobject : one derived from :class:`~syncopy.datatype.base_data`
Syncopy datatype instance, needs to have a `channel` property
show_kwargs : dict
The keywords ... |
def parse_content_type(value):
# type: (str) -> str
"""
Parse out the content type from a content type header.
>>> parse_content_type('application/json; charset=utf8')
'application/json'
"""
if not value:
return ''
return value.split(';')[0].strip() |
def _to_byte(byte):
"""Make sure an object really represents an integer from 0 to 255,
and return the integer.
"""
byte = float(byte)
assert byte.is_integer(), f"Got a non-integer byte: {byte}!"
byte = int(byte)
assert byte >= 0, f"Got a negative value for a byte: {byte}!"
assert byte <... |
def rle(seq):
""" Create RLE """
counts = []
count = 0
prev = None
for char in seq:
# We are at the start
if prev is None:
prev = char
count = 1
# This letter is the same as before
elif char == prev:
count += 1
# This is a ... |
def _PrefixMatches(prefix, possible_matches):
"""Returns the subset of possible_matches that start with prefix.
Args:
prefix: str, The prefix to match.
possible_matches: [str], The list of possible matching strings.
Returns:
[str], The subset of possible_matches that start with prefix.
"""
retur... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.