content stringlengths 42 6.51k |
|---|
def ravel_group_params(parameters_group):
"""Take a dict(group -> {k->p}) and return a dict('group:k'-> p)
"""
return {f'{group_name}:{k}': p
for group_name, group_params in parameters_group.items()
for k, p in group_params.items()} |
def multiply_list(input_list):
"""
"""
result = 1
for number in input_list:
result = result * number
return(result) |
def calculate_z(maxiter, zs, cs):
"""Calculate output list using Julia update rule"""
output = [0] * len(zs)
for i in range(len(zs)):
n = 0
z = zs[i]
c = cs[i]
while n < maxiter and (z.real * z.real + z.imag * z.imag) < 4:
z = z * z + c
n += 1
... |
def sanitise_name(name):
"""
Take a name for a language or a feature which has come from somewhere like
a CLDF dataset and make sure it does not contain any characters which
will cause trouble for BEAST or postanalysis tools.
"""
return name.replace(" ", "_") |
def isclass(obj):
""" ** Extracted from inspect module for optimisation purposes **
Return true if the object is a class.
Class objects provide these attributes:
__doc__ documentation string
__module__ name of module in which this class was defined"""
return isinstance(obj... |
def split_title_line(title_text, max_words=5):
"""
A function that splits any string based on specific character
(returning it with the string), with maximum number of words on it
"""
seq = title_text.split()
return '\n'.join([' '.join(seq[i:i + max_words]) for i in range(0, len(seq), max_words)... |
def GetProQ3Option(query_para):#{{{
"""Return the proq3opt in list
"""
yes_or_no_opt = {}
for item in ['isDeepLearning', 'isRepack', 'isKeepFiles']:
if item in query_para and query_para[item]:
yes_or_no_opt[item] = "yes"
else:
yes_or_no_opt[item] = "no"
proq3... |
def force_noslashend(path):
"""
Return ``path`` with any trailing ``/`` removed.
"""
if path.endswith('/'):
path = path.rstrip('/')
return path |
def interpolate_real(r1, r2, t):
"""Linearly interpolate between two real color components."""
r1 = float(r1)
r2 = float(r2)
return r1 + t * (r2 - r1) |
def format_float(x, precision=None):
"""
Format float in a portable manner, standardizing the
number of digits in the exponent.
"""
if not type(x) is float:
raise TypeError("Argument " + str(x) + " is not a float")
tmp = str(x)
if not ("E" in tmp or "e" in tmp):
return tmp
... |
def format_time(seconds: float, decimal_places: int = 4):
"""
Formats time with a prefix
"""
for fractions, unit in (
(1.0, "s"),
(1e-03, "ms"),
(1e-06, "\u03bcs"),
(1e-09, "ns"),
(1e-12, "ps"),
(1e-15, "fs"),
(1e-18, "as"),
(1e-21, "zs"),
... |
def pot_temp(p, t):
"""
Computes potential temperature in [K] from pressure and temperature.
Arguments:
p -- pressure in [Pa]
t -- temperature in [K]
p and t can be scalars of NumPy arrays. They just have to either both
scalars, or both arrays.
Returns: potential temperature in [K]. S... |
def subsequence(niddle, haystack):
"""
Check if niddle is subsequence of haystack
"""
niddle, haystack = niddle.lower(), haystack.lower()
if not niddle:
return True
offset = 0
for char in niddle:
offset = haystack.find(char, offset) + 1
if offset <= 0:
ret... |
def get_mat_str(arr):
"""Get Latex (Matrix) representation of an array.
Args:
arr (number): Matrix as a nested list
Returns:
str: raw string represention of array
"""
temp = (" & ".join(str(col) for col in row) for row in arr)
arrstr = " \\ ".join(row for row in temp)
retur... |
def split_n_trim(txt, sep='\n'):
"""Return list of non-empty strings from input splitted by blank chars
"""
lst = txt.split(sep)
return [x.strip() for x in lst if x.strip()] |
def _cacheable(string, c):
""" Returns whether the contract c defined by string string is cacheable. """
# XXX need a more general way of indicating
# whether a contract is safely cacheable
return '$' not in string |
def ngram_slices(i, n, l):
"""
Given index i, n-gram width n and array length l, returns slices
for all n-grams containing an ith element
"""
out = []
a = i - n + 1
if a < 0:
a = 0
b = i + 1
if b + n > l:
b = l - n + 1
d = b - a
for k in range(d):
... |
def double_char(s):
"""Return word with double characters."""
word = ''
for i in s:
word += i * 2
return word |
def sort_files(files):
"""Returns a sorted version of the given list of File's (or other structures
that define an 'id' data member). The files will be sorted according to their
id, and duplicate entries will be removed.
Parameters
----------
files : list of :py:class:`bob.db.base.File`
The list of f... |
def get_first_valid_entry(input_dict, key_list):
"""Iterates over key_list and returns the value of the first key that exists in the dictionary. Or returns None"""
for key in key_list:
if key in input_dict:
return input_dict.get(key)
return None |
def of_link(str_id, bln_not_folder):
"""Build a link to a folder or task from an OmniFocus id"""
if (bln_not_folder):
return ''.join(['link=\"omnifocus:///task/', str_id, '\" '])
else:
return ''.join(['link=\"omnifocus:///folder/', str_id, '\" ']) |
def spatial_scale_pooling_2x2_stride_2(s, p):
"""
This method computes the spatial scale of 2x2 pooling layer with stride 2 in terms of its input feature map's
spatial scale value (s) and spatial overal value (p).
"""
return (2-p) ** 2 * s |
def union_crops(crop1, crop2):
"""Union two (x1, y1, x2, y2) rects.
Adapted from https://github.com/danvk/oldnyc/blob/master/ocr/tess/crop_morphology.py
Copyright 2015 danvk.
http://www.apache.org/licenses/LICENSE-2.0
:param crop2: crop coordinates
:type crop2: tuple
:param crop2: crop coo... |
def merge_dicts(ds):
"""Convert an iterable of dictionaries.
In the case of key collisions, the last value wins.
Parameters
----------
ds : iterable of dicts
Returns
-------
dict
"""
merged = {}
for d in ds:
merged.update(d)
return merged |
def nu(x, beta):
"""
Eq. (6) from Ref[1] (coeffient of alpha**2)
Note that 'x' here corresponds to 'chi = x/rho' in the paper.
"""
return 3 * (1 - beta**2 - beta**2*x) / beta**2 / (1+x) |
def _clean(item):
"""Return a stripped, uppercase string."""
return str(item).upper().strip() |
def search_id_in_list(list_sheets, name):
"""
find id with name in list_sheet=c.list_ssheets(folder_id)
"""
for sheet in list_sheets:
if sheet['name'] == name:
return sheet['id']
return None |
def counting(elements, k):
"""Counting Sort Algorithm
Fill an array with the number of times that a number appears in given elements
Traverse the array and fill up a new one with the same length, for every element
different from 0 move its value to the new array, decrement the value by one and
cont... |
def del_none(d):
"""
Delete keys with the value ``None`` in a dictionary, recursively.
This alters the input so you may wish to ``copy`` the dict first.
"""
# d.iteritems isn't used as you can't del or the iterator breaks.
for key, value in d.items():
if value is None:
del d... |
def rdb(sep, *args):
"""
Builds a regular expression for separated digits.
"""
parts = []
for numDigits in args:
parts.append(r'(\d{{{:d}}})'.format(numDigits))
return sep.join(parts) |
def maior_elemento(lista):
"""[Recebe uma lista e devolve o maior elemento]
Arguments:
lista {[lista]} -- [lista]
Returns:
[int] -- [maior elemento da lista recebida]
"""
maior = max(lista)
return maior |
def get_account_id(event):
"""Returns the account ID in a given event.
:type event: dict
:param event: event from CodePipeline.
:rtype: str
:return: account ID in ``event``.
:raises KeyError: if ``event`` does not have a necessary property.
"""
return event['CodePipeline.job']['accoun... |
def zero_crossings(x, y):
"""Given x the abscissa and y the ordinate, return the values of x
for which y crosses zero.
"""
n = len(x)
x_zc = []
for i in range(n-1):
if y[i] == 0.0:
x_zc.append(x[i])
elif ( (y[i] > 0.0 and y[i+1] < 0.0)
or (y[i] < 0.0 and y... |
def get_min_max(ints):
"""
Return a tuple(min, max) out of list of unsorted integers.
Time Complexity O(n)
Space Complexity O(1)
Args:
ints(list): list of integers containing one or more integers
"""
# Test that ints is an not empty array
if len(ints) == 0:
return ... |
def subset(obj: dict, keys: str):
"""Returns subset of the dictionary object with only the specified keys (as comma separated list)"""
return [obj[key] for key in keys.split(',')] |
def get_color(my_color):
"""Given a pixel string it prepares a pixel dictionary."""
my_color = my_color.replace(" ", "")
my_color = {c.split(":")[0]: float(c.split(":")[1]) for c in my_color.split("|")}
return my_color |
def ie(value):
"""Display Included / Excluded"""
value = value.strip()
if value == 'E':
return 'excluding '
return '' |
def has_tag(item, filter_tags, match_all):
""" Check if an item has a tag that matches one of the tags in filter_tags """
if not filter_tags:
return True
# Check for the tags in YAML file
options = item.get("tags")
arch_found = False
if options == None:
options=[]
# if the ta... |
def is_option_valid(obj_id, obj_list):
"""Validates that a user's selection is in a list.
Parameters
----------
obj_id : str
A string id for a class instance.
obj_list : list
A list of instances for the same class.
Returns
-------
bool
True if successful, False ... |
def sortBySize(a, b):
"""
Sorts a set of satellite definitions by size.
@param a: a satellite definition
@type a: L{str}
@param b: a satellite definition
@type b: L{str}
@return: L{int}
"""
if isinstance(a, list) and isinstance(b, list):
a = " ".join(a)
b = " ".join(b... |
def get_quadrant_labels(values, brackets=None):
"""Create the quadrant labels and include bracketed value if needed."""
labels = []
for i in range(0, len(values)):
if brackets:
label = '%i(%i)%%' %(values[i], brackets[i])
else:
label = '%i%%' %(values[i])
lab... |
def DetermineTrend(now, soon):
""" returns text describing if the trend of the river is rising or falling.
now = float value of current level of river
soon = float value of future level of river
"""
if now > soon:
return "Falling"
if now < soon:
return "Rising"
return "Flat" |
def dict_raise_on_duplicates(ordered_pairs):
"""Reject duplicate keys"""
return_dict = {}
for key, value in ordered_pairs:
if key in return_dict:
raise ValueError("duplicate key: {:}".format(key))
return_dict[key] = value
return return_dict |
def _swap_slashes(s):
"""in-place slash swapping"""
if s == None: return
return s.replace('/','\\') |
def _decode_amount(value):
"""Decode fee"""
value = value.replace(",", ".")
return value |
def trim_description(description):
"""Trim description, if it is longer than 160 characters."""
if len(description) > 160:
description = description[0:161] + '...'
return description |
def get_event_action(event_type: str) -> str:
"""Return the second part of the event_type
e.g.
>>> Event.event_type = 'experiment.deleted'
>>> Event.get_event_action() == 'deleted'
"""
return event_type.split(".")[1] |
def roundany(x, base):
"""
rounds the number x (integer or float) to
the closest number that increments by `base`.
"""
return base * round(x / base) |
def construct_torch_dist_launcher_cmd(
num_trainers: int,
num_nodes: int,
node_rank: int,
master_addr: str,
master_port: int
) -> str:
"""Constructs the torch distributed launcher command.
Helper function.
Args:
num_trainers:
num_nodes:
node_rank:
master_... |
def CreateLogResourceName(project, log_id):
"""Creates the full log resource name.
Args:
project: The project id, e.g. my-project.
log_id: The log id, e.g. my-log.
Returns:
Log resource, e.g. projects/my-project/logs/my-log.
"""
# Also handle the case where we already have the correct format.
... |
def to_fahrenheit(celsius):
"""Convert degrees Celsius to degrees Fahrenheit"""
return (celsius * 1.8) + 32 |
def add_source_link_to_description(description: str, link: str) -> str:
"""Add the source ticket URL to the description.
Args:
description: The original ticket's description.
link: The URL to the source ticket.
Returns:
The modified description for the ticket.
"""
link_mess... |
def closest_perfect_square(n):
""" http://stackoverflow.com/questions/15390807/integer-square-root-in-python """
x = n
y = (x + 1) // 2
while y < x:
x = y
y = (x + n // x) // 2
return x |
def isclose(a, b, rel_tol=1e-09, abs_tol=0.0001):
"""
returns boolean whether abs(a-b) is less than abs_total or rel_total*max(a, b)
"""
return abs(a-b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol) |
def file_extension(path):
"""Get the file extension of a path/filename."""
return path.split('/')[-1].split('.')[-1] |
def are_strings_in_subdict(mapper, subdict, strings_of_interest, string_for_mapper):
"""
Search an element of a sub-dictionary to determine whether a particular string is present in it. Mostly for use in
calculating outputs in the model runner module.
Args:
mapper: Dictionary describing the pur... |
def mapk(actual, predicted, k=10):
"""
Computes the average precision at k.
This function computes the average prescision at k between two lists of
items.
Parameters
----------
actual : list
A list of elements that are to be predicted (order doesn't matter)
predicted : list
... |
def extract_bouts_in_range(gui, total_bouts, first_index, last_index):
"""
Extracts vertices falling into a specified window of index values.
Args:
gui (GUIClass)
total_bouts (list): every bout identified for the current input file
first_index (int)
... |
def multiply_matricies(m, n):
"""
1 2 1 2 3 4 11 14 17 20
3 4 X 5 6 7 8 = 23 30 37 44
"""
n = zip(*n)
return [[sum(a * b for a, b in zip(row_m, col_n)) for col_n in n] for row_m in m] |
def api_url(host):
"""
Make api url to obtain configuration
:param host: str
:return: str
"""
return '{}/api/serializers/'.format(host) |
def get_extension(format, default, **alternates):
"""get the extension for the result, needs a default and some specialisations
Example:
filetype = get_extension(format, "png", html="svg", latex="eps")
"""
try:
return alternates[format]
except KeyError:
return default |
def get_last_frame(traceback):
"""Extract last frame from a traceback."""
# In some rare case, the given traceback might be None
if traceback is None:
return None
while traceback.tb_next:
traceback = traceback.tb_next
return traceback.tb_frame |
def get_bits(data,offset,bits=1):
"""
Get specified bits from integer
>>> bin(get_bits(0b0011100,2))
'0b1'
>>> bin(get_bits(0b0011100,0,4))
'0b1100'
"""
mask = ((1 << bits) - 1) << offset
return (data & mask) >> offset |
def within_tolerance(a_vec, b_vec, tol_vec):
"""Check if two vectors are equals with a given tolerance."""
for a, b, tol in zip(a_vec, b_vec, tol_vec):
if abs(a - b) > tol:
return False
return True |
def parse_int_ge0(value):
"""Returns value converted to an int. Raises a ValueError if value cannot
be converted to an int that is greater than or equal to zero.
"""
value = int(value)
if value < 0:
msg = ('Invalid value [{0}]: require a whole number greater than or '
'equal t... |
def transform(data):
"""Prepare the data for plotting
Parameters
----------
data : list
A list of tuples. First element is the title of the question and the
second one is a dictionary which maps the possible answer to the number
of times the answer was given.
[("Question... |
def add (p1, p2):
""" Adds the two Polynomials, 'p1' and 'p2'
The arguments can be a sequence of coefficients or an instance of the Polynomial class. """
res = [x[0] + x[1] for x in zip(p1, p2)]
n = len(res)
res.extend(max(p1, p2, key=len)[n:])
return res |
def to_megabytes(size_bytes):
"""
Convert size in bytes to megabytes
"""
return size_bytes * 1024 * 1024 |
def partition(iter, pred):
"""Split iter into two lists based on a test predicate.
Returns (trues, falses) where "trues" are the elements from iter for
which pred returns true, and "falses" are the ones for which pred returns
false.
"""
trues = []
falses = []
for x in iter:
(tru... |
def force_space(value, chars=40):
"""Forces spaces every `chars` in value"""
chars = int(chars)
if len(value) < chars:
return value
else:
out = []
start = 0
end = 0
looping = True
while looping:
start = end
end += chars
... |
def compare_metrics(best_eval_result, current_eval_result):
"""Compares two evaluation results."""
# Bad evaluation comparison. Will be replaced by official evaluation.
return best_eval_result["f1"] < current_eval_result["f1"] |
def divrem(x, y):
"""A simple implementation of the remainder of a division.
Parameters
----------
x : int
Dividend or numerator.
y : int
Divisor or denominator.
Returns
-------
int
Remainder of `x`/`y`.
"""
signx = 1 if x >= 0 else -1
x = abs(x)
... |
def configuration_signature(floor_set):
"""Calculates a signature for a given configuration.
Generates the same signature for `similar` configurations (one generator/microchip pair is swapped with another).
"""
generators_ordered = [device for floor in floor_set for device in floor if device.islower()... |
def get_class_from_tag(full_tag):
""" strips the BIO prefix from the tag and returns the class """
if full_tag == 'O':
return full_tag
return full_tag.split('-')[1] |
def get_subj_ses(cli_args):
"""
:param cli_args: Dictionary containing all command-line arguments from user
:return: String which combines --subject and --ses from command line
"""
return '_'.join((cli_args['subject'], cli_args['ses'])) |
def get_device_button(device_name, event_code):
"""
The wires were connected on abitrary postions onto
the board, this maps goes from the code the keyboard
emmitted to the postion on the device.
"""
return { 'a403': [28, 2, 106, 57, 103, 3, 108, 17, 105, 30, 31, 32],
'a496': [108, 1... |
def determine_cursor(response):
"""
Function to determine whether a response ahs a cursor or not
:param response: Response of the URL as a json object
:return: Nonetype or the Cursor String if cursor was present in the response
"""
if 'cursor' in response:
cursor = response['cursor']
... |
def get_rotations(digit: int):
"""
The number, 197 has following rotations of the digits:
197, 971, and 719
:param digit:
:return rotations:
"""
rotations = set()
rotations.add(digit)
digits = [d for d in str(digit)]
for n in range(1, len(digits)):
temp = []
f... |
def greet_all(greeting: str, names: list) -> list:
"""Return a list of strings that consist of the greeting messages for each person in names.
The format of each greeting message is '<greeting>, <name>',
where greeting is the given greeting and <name> is an element of <names>.
The returned list should... |
def is_valid_mac(possible_mac):
"""check if an object is a mac."""
valid = False
if len(possible_mac) == 12:
valid = True
for c in possible_mac:
if c not in ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'a', 'b', 'c', 'd', 'e', 'f']:
... |
def asdicts(rows):
"""
Converts list of named tuples to list of dicts.
"""
return [row._asdict() for row in rows] |
def decompose_mask_status( x ):
"""
Given a mask value, decompose what sub-status compose it
Example:
One pixel mask value is 928:
928 decompose into 32, 128, 256, 512
:Parameters:
x: int
Mask value
:Returns:
powers: list of int
List of powers of 2 ma... |
def chunks(L, n):
""" Yield successive n-sized chunks from L.
"""
chunks = []
for i in range(0, len(L), n):
chunks.append(L[i:i+n])
return chunks |
def get_sparsification_factor(arr_len):
"""Determine with which multiple we
subsample the array (for easier plotting)."""
sparsification_factor = None
if arr_len > 100000:
sparsification_factor = 1000
elif arr_len > 10000:
sparsification_factor = 100
elif arr_len > 1000:
... |
def connected_four(position) -> bool:
"""
Return True, when the player has connected 4
Arguments:
position: bit representation of the board with players pieces
Return:
bool: True for 4 connected
"""
# Horizontal check
m = position & (position >> 7)
if m & (m >> 14):
... |
def parse_title_link(onclick):
"""Parse the onclick element of WA section title links for a query.
It's a window.open call, and we only care about the first arg."""
start_s = "window.open('"
start = onclick.find(start_s)+len(start_s)
end = onclick.find("'", start)
return onclick[start:end] |
def normalise(lst, denoms):
"""Normalise a list of values by dividing by sum of list."""
return [lst[i] / denoms[i] for i in range(len(lst))] |
def render_from_template(
template: str,
data: dict
) -> str:
"""
Updates the template text with the provided data.
:param template: `str` The name of the template file
:param data: The `dict` of str values with which to update the template text
:returns The adjusted template text
... |
def calc_energy_t1(forage_quality):
"""Look up energy content of forage given its forage quality, from IPCC 2006
table 10.8."""
quality_table = { # IPCC 2006 table 10.8
u'grain': 8.,
u'high': 7.,
u'moderate': 6.,
u'low': 4.5,
}
MJ_per_kg_DM = quality_table... |
def stateful_flags(rep_restart_wait=None, quorum_loss_wait=None,
standby_replica_keep=None, service_placement_time=None):
"""Calculate an integer representation of flag arguments for stateful
services"""
flag_sum = 0
if rep_restart_wait is not None:
flag_sum += 1
if quoru... |
def main(dict):
"""Hello world."""
if 'name' in dict:
name = dict['name']
else:
name = "stranger"
if 'place' in dict:
place = dict['place']
else:
place = "unknown"
msg = "Hello, " + name + " from " + place
return {"greeting": msg} |
def count_kwords(source, k, delimiter=''):
"""Makes dict of {word:count} for specified k."""
result = {}
#reset to beginning if possible
if hasattr(source, 'seek'):
source.seek(0)
elif hasattr(source, 'reset'):
source.reset()
if isinstance(source, str):
if delimiter:
... |
def get_link_title(properties):
"""Gets a link title from a properties dictionary."""
if not properties:
return "Unknown title"
# Try plausible fields for link titles.
possible_title_field_names = ['name', 'title', 'heading', 'main']
for title in possible_title_field_names:
for k in... |
def transformed_equal(name, key):
""" Return True if ``name`` can be mapped to the transformed ``key`` such that ``key`` is a valid
python identifier.
The following transformation of ``key`` will be considered:
' ' ==> '_'
'-' ==> '_'
'.' ==> '_'
'[0-9]' ==> _... |
def urljoin(*args):
""" Join urls, since os.path.join doesn't work with urls
It looks ugly, but it's faster than stripping either side of the args
"""
joined = args[0]
for i in range(1, len(args)):
if joined[-1] == '/' and args[i][0] == '/':
joined += args[i][1:]
elif... |
def create_motifs_from_residues(sequence, motif_size=5, residues=None, extremity='X'):
"""
Fragments the proteins in motifs centred to certain residues.
:param str sequence: protein sequence
:param int motif_size: number of residues per motif
:param srt extremity: character symbol for termination ch... |
def dict_compare_keys(dictionary1, dictionary2, key_path=''):
"""
Compare two dicts recursively and see if dict1 has any keys that dict2 does not
Returns: list of key paths
"""
res = []
if not dictionary1:
return res
if not isinstance(dictionary1, dict):
return res
for k ... |
def F1(p, r):
""" Calculate F1 score from precision and recall.
Returns zero if one of p, r is zero.
"""
return (2*p*r/(p+r)) if p != 0 and r != 0 else 0 |
def calc_check_digit(number):
"""Calculate the EAN check digit for 13-digit numbers. The number passed
should not have the check bit included."""
return str((10 - sum((3, 1)[i % 2] * int(n)
for i, n in enumerate(reversed(number)))) % 10) |
def calc_brightness(value: float, actual_brightness_value: int, max_brightness_value: int, function: str) -> int:
"""Calculate brightness value based on actual and maximal brightness.
The function calculates a brightness value using the `function` string and the `value` as a percentage.
If `function` is em... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.