content stringlengths 42 6.51k |
|---|
def tile2xystr(tile):
"""indexed from 0"""
return "{:02d},{:02d}".format(tile['x'], tile['y']) |
def sorted_data(data, reversed):
"""
Sorted data by date desc
"""
data_tuple = data['locations']
data_tuple = sorted(data_tuple, key=lambda k: k.get('total', 0), reverse=reversed)
return {
'data': data_tuple,
'total': data['total']
} |
def region_matches_partition(region, partition):
"""
Returns True if the provided region and partition are a valid pair.
"""
valid_matches = [
("cn-", "aws-cn"),
("us-gov-", "aws-us-gov"),
("us-gov-iso-", "aws-iso"),
("us-gov-iso-b-", "aws-iso-b"),
]
for prefix, ... |
def cap_feature(s):
"""
Capitalization feature:
0 = low caps
1 = all caps
2 = first letter caps
3 = one capital (not first letter)
"""
if s.lower() == s:
return 0
elif s.upper() == s:
return 1
elif s[0].upper() == s[0]:
return 2
else:
... |
def _no_stop_codon(aa_seq):
""" Returns True if a sequence does not contain a stop codon,
otherwise returns False
"""
if '*' not in aa_seq:
return True
else:
return False |
def get_output_filename(dest_dir, class_name):
"""Creates the output filename.
Args:
dataset_dir: The dataset directory where the dataset is stored.
split_name: The name of the train/test split.
Returns:
An absolute file path.
"""
return '%s/PASCAL3D_%s.tfrecord' % (dest_dir, class... |
def find(path, data):
"""
Extract element from nested dictionary given a path using dot notation
Parameters
----------
path : str
Path to nested element using dot notation
E.g. 'NEMSPDCaseFile.NemSpdInputs.RegionCollection.Region'
data : dict
Nested dictionary
Retu... |
def get_start_position(grid_data, clue_num):
"""Find the start co-ordinates for a particular clue number in ipuz data."""
for y, row in enumerate(grid_data):
for x, cell in enumerate(row):
if cell == clue_num:
return {'x': x, 'y': y}
return None |
def merge_dict(a, b, path=None):
"""
Merge dict b into a
"""
if not path:
path = []
for key in b:
if key in a:
if isinstance(a[key], dict) and isinstance(b[key], dict):
merge_dict(a[key], b[key], path + [str(key)])
else:
continu... |
def merge_dicts(a, b):
"""
Merge dicts a and b, with values in b overriding a
Merges at the the second level. i.e. Merges dict top level values
:return: New dict
"""
c = a.copy()
for k in b:
if k not in c:
c[k] = b[k]
else:
c[k].update(b[k])
retur... |
def get_dbtype_from_file_exten(infp):
"""Determine data type from fasta filename extension.
"""
dbtype = None
exten = infp.rsplit('.', 1)[1]
if exten == 'faa':
dbtype = 'prot'
elif exten == 'fna':
dbtype = 'nucl'
elif exten == 'hmmdb':
dbtype = 'prot'
elif exten =... |
def glitter_head(context):
"""
Template tag which renders the glitter CSS and JavaScript. Any resources
which need to be loaded should be added here. This is only shown to users
with permission to edit the page.
"""
user = context.get('user')
rendered = ''
template_path = 'glitter/includ... |
def dsigmoid(x):
"""
return differential for sigmoid
"""
##
# D ( e^x ) = ( e^x ) - ( e^x )^2
# - --------- --------- ---------
# Dx (1 + e^x) (1 + e^x) (1 + e^x)^2
##
return x * (1 - x) |
def _reverse(lst):
"""Return the reverse of lst without mutating lst"""
nlst = lst.copy()
nlst.reverse()
return nlst |
def url_pattern(pattern: str):
"""
Convert a string *pattern* where any occurrences of ``{{NAME}}`` are replaced by an equivalent
regex expression which will assign matching character groups to NAME. Characters match until
one of the RFC 2396 reserved characters is found or the end of the *pattern* is r... |
def _key_labels_layout(sign, zero_vals, labels):
""" Format the leaf labels to be shown on the axis. """
layout = {
"tickvals": [sign * zv for zv in zero_vals],
"ticktext": labels,
"tickmode": "array",
}
return layout |
def gcd(a, b):
"""
gcDen(a, b) -> number
A traditional implementation of Euclid's algorithm
for finding the greatest common denominator.
"""
while b > 0:
a, b = b, a % b
return a |
def addND(v1, v2):
"""Adds two nD vectors together, itemwise"""
return [vv1 + vv2 for vv1, vv2 in zip(v1, v2)] |
def camel_to_snake(name: str) -> str:
"""Change name from CamelCase to snake-case."""
return name[0].lower() + \
''.join(['-' + x.lower() if x.isupper() else x for x in name][1:]) |
def addMiddlePoints(p1, p2, n = 2):
""" Function to calculate the middle point between two points
Args:
p1: (Required) set of coordinates of first point
p2: (Required) set of coordinates of second point
n: (Required) number of divisions
"""
x_1 = p1[0]
y_1 = p1[1]
... |
def cloudtrail_network_acl_ingress_anywhere(rec):
"""
author: @mimeframe
description: Alert on AWS Network ACLs that allow ingress from anywhere.
reference_1: http://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/VPC_ACLs.html
reference_2: http://docs.aws.amazon.com/AWSEC2/
... |
def select_zmws(zmws, min_requested_bases):
"""
>>> select_zmws([], 0)
([], 0)
>>> select_zmws([], 10)
([], 0)
>>> select_zmws([('zmw/1', 1), ('zmw/2', 2), ('zmw/3', 5), ('zmw/4', 7), ('zmw/5', 10), ('zmw/6', 15)], 10)
(['zmw/1', 'zmw/2', 'zmw/3', 'zmw/4'], 15)
>>> select_zmws([('zmw/1',... |
def dev(default):
"""Function which is used by entry points for getting settings for dev environment.
:param default: it is dependency which will be calculated in moment of getting settings from this env.
"""
default['ANSWER'] = 42
return default |
def _extract_error_from_ansible_stderr(stderr: str):
"""
Extract ansible error message from ansible stderr log
>>> this = _extract_error_from_ansible_stderr
>>> this('''
... [WARNING]: conditional statements should not include jinja2 templating
... [DEPRECATION WARNING]: Use errors="ignore" ins... |
def ccall_except_check(x):
"""
>>> ccall_except_check(41)
42
>>> ccall_except_check(-2)
-1
>>> ccall_except_check(0)
Traceback (most recent call last):
ValueError
"""
if x == 0:
raise ValueError
return x+1 |
def readdata(file, size):
"""read and return data from file
file: file object with read(size) method
size: read this many bytes
returns: bytes object of data read
raises: EOFError if end of file is encountered before all bytes are read
"""
data = file.read(size)
if len(data) < size:
... |
def tree_normalize(tree):
"""
Takes a list of line segments defining a tree and normalizes them by
making all coordinates positive.
"""
# Find the minimum x and y values
x_vals = [(i[0], i[2]) for i in tree]
x_vals = [item for sublist in x_vals for item in sublist]
y_vals = [(i[1], i[3]... |
def clamp(x, x0, x1):
"""Clamp a provided value to be between x0 and x1 (inclusive). If value is
outside the range it will be truncated to the min/max value which is closest.
"""
if x > x1:
return x1
elif x < x0:
return x0
else:
return x |
def list_from_generator(generator_function):
"""Utility method for constructing a list from a generator function"""
ret_val = []
for list_results in generator_function:
ret_val.extend(list_results)
return ret_val |
def skip_trna(entry):
"""
Some tRNAs should not be drawn and need to be skipped.
"""
if 'pseudo' in entry['note'] or entry['isotype'] in ['Undet', 'Sup']:
return True
return False |
def fnv1a_64(string):
""" Hashes a string using the 64 bit FNV1a algorithm
For more information see:
https://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function
@param string The key to hash
@returns Hashed key
"""
fnv_offset = 0xcbf29ce484222325 # The standard FNV 64 bit... |
def parse(arg):
"""Convert a series of zero or more arguments to a string tuple."""
return tuple(arg.split()) |
def ceaser_cipher(text: str, s: int) -> str:
""" Returns the input text in encrypted form """
result = ""
for i in range(len(text)): # Traverse the text
char = text[i]
# Encrypt According to the case
if (char.isupper()):
result += chr((ord(char) + s - 65) % 26 + 65)
... |
def concatenate_url(endpoint, url):
""" concatenate endpoint & url
:param endpoint: the base url for example http://localhost:port/v1
:param url: the target url for example "/dashboard"
:return: concatenated url for example http://localhost:port/v1/dashboard
"""
return "%s/%s" % (endpoint.rstrip... |
def mean_tuple(*args):
"""Return the mean values along the columns of the supplied values."""
return tuple(sum(x) / len(x) for x in zip(*args)) |
def _WrapLogicOp(op_fn, sentences, ctx, item):
"""Wrapper for logic operator functions.
"""
return op_fn(fn(ctx, item) for fn in sentences) |
def A002275(n: int) -> int:
"""Repunits: (10^n - 1)/9. Often denoted by R_n."""
if n == 0:
return 0
return int("1" * n) |
def make_title(text,underline="="):
"""
Turn a string into a Markdown/rst title
Arguments:
text (str): text to make into title
underline (str): underline character (defaults to
'=')
Returns:
String: title text.
"""
return "%s\n%s" % (text,underline*len(text)) |
def _ToWebSafeString(per_result, internal_cursor):
"""Returns the web safe string combining per_result with internal cursor."""
return str(per_result) + ':' + internal_cursor |
def ip_string_to_int(ipstr):
""" Convert a string IPv4 address to integer"""
if ipstr == '':
return 0
if len(ipstr) > 15: # max len of ipv4 in string (could be less)
#print "Damn:", ipstr
return 0
parts = ipstr.split('.')
return (int(parts[0]) << 24) + (int(parts[1]) << 16) ... |
def partition_1(a,l,r):
"""
partition array a[l...r]
Pivot: Always the 1st element of the array
"""
p = a[l]
i = l+1
j = l+1
while j <= r:
if a[j] <= p:
temp = a[j]
a[j] = a[i]
a[i] = temp
i+=1
j+=1
else:
... |
def trimArray(a):
"""Deletes entries which are empty strings in an array."""
return [e for e in a if e != ""] |
def sub(val, char="-"):
"""
Message formatter used to block off sections in log files with visually
distinctive separators. Defined as individual functions to reduce call
length.
Sub: For sub-critical messages, describing things like notes and warnings
.. rubric::
>>> print(msg.mnr("Su... |
def isImageType(t):
"""
Checks if an object is an image object.
.. warning::
This function is for internal use only.
:param t: object to check if it's an image
:returns: True if the object is an image
"""
return hasattr(t, "im") |
def get_field_or_message(message, field_str):
"""Get the field value or entire message if it is already a leaf."""
data = message
if field_str is not None:
fields = field_str.split('/')
while len(fields) > 0:
field = fields.pop(0)
data = getattr(data, field)
retur... |
def getdistname(distribname=None):
"""
Translates probability distribution names into scipy.stats names.
Arguments:
distribname - the distribution name, or None.
Returns:
If distribname is given (and not None), the "scipy.stats" name for
the probability distribution given in ... |
def getter_name(a):
"""
>>> getter_name('userId')
'getUserId'
"""
return 'get%s%s' % (a[0].upper(), a[1:]) |
def chart_type(arg):
"""
Set the chart type. Valid arguments are anything the chart API understands,
or the following human-readable alternates:
* 'line'
* 'xy'
* 'xy' / 'line-xy'
* 'bar' / 'bar-grouped'
* 'column' / 'column-grouped'
* 'bar-stacked'
... |
def assume(mapping, a, b):
"""assume that a -> b and return the resulting mapping"""
res = {k: v.copy() for k, v in mapping.items()}
res[a] = set(b)
for k, v in res.items():
if b in v and k != a:
v.remove(b)
return res |
def _FirewallSourceRangesToCell(firewall):
"""Comma-joins the source ranges of the given firewall rule."""
return ','.join(firewall.get('sourceRanges', [])) |
def get_filter_value_from_question_option(option):
"""
Processes `option` into a search term value suitable for the Search API.
The Search API does not allow commas in filter values, because they are used
to separate the terms in an 'OR' search - see `group_request_filters`. They
are removed from t... |
def name_matches_classpath(cls):
"""
Decorates a class, ensuring that its ``name`` attribute matches its
classpath.
This is useful for providing a convenient way to configure
:py:class:`TriggerTask` subclasses in trigger configurations during
unit tests.
"""
cls.name = '{cls.__module__}... |
def metric_format(num, unit="s", digits=1, align_unit=False):
# type: (float, str, int, bool) -> str
"""Format and scale output with metric prefixes.
Example
-------
>>> metric_format(0)
'0.0 s'
>>> metric_format(0, align_unit=True)
'0.0 s '
>>> metric_format(0.002, unit='B')
'... |
def set_device(c):
"""
returns a string for training on cpu or gpu
"""
if c['CPU_ONLY']:
return '/cpu:0'
else:
return '/device:GPU:1' |
def release_object_group(objectGroup: str) -> dict:
"""Releases all remote objects that belong to a given group.
Parameters
----------
objectGroup: str
Symbolic object group name.
"""
return {
"method": "Runtime.releaseObjectGroup",
"params": {"objectGroup": objectGr... |
def FFT(w, s):
""""
w should be a complex numbers such that w^n = 1
where n is the number of elements in the list s
of numbers.
"""
n = len(s)
if n==1: return [s[0]]
f0 = FFT(w*w, [s[i] for i in range(n) if i % 2 == 0])
f1 = FFT(w*w, [s[i] for i in range(n) if i % 2 == 1])
return... |
def reverse(x: int) -> int:
"""
Given a 32-bit signed integer, reverse digits of an integer.
"""
str_num = str(x)
is_negative = False
if str_num[0] == '-':
is_negative = True
str_num = str_num[1:]
sign = '-' if is_negative else '+'
num = int(sign + "".join(list(reversed... |
def multipleNumbers(i):
"""
Function with logic to know if numbers are multiples of 3, 5 or 3 and 5
"""
entry = ''
if i%3 == 0:
entry += 'Three'
if i%5 == 0:
entry += 'Five'
if not entry:
entry += str(i)
return entry |
def mutate_string(string: str, position: int, character: str) -> str:
"""
>>> mutate_string('abracadabra', 5, 'k')
'abrackdabra'
"""
lst = list(string)
lst[position] = character
return ''.join(lst) |
def levenshtein(s1: str, s2: str) -> int:
"""
Compute the Levenshtein edit distance between 2 strings.
Args:
s1 (str): First string
s2 (str): Second string
Returns:
int: Computed edit distance
"""
if len(s1) < len(s2):
return levenshtein(s2, s1)
if len(s2)... |
def black(pixel):
"""
Determinates if a pixel is black
Parameters
----------
pixel(color) : RGB pixel
Returns
-------
bool : T if black || F if not black
"""
if(pixel[0]== 255):
return False
else:
return True |
def getMonth(month):
"""Method to return the month in a number format
Args:
month (string): the month in a string format
Returns:
string: month in the number format
"""
if month == 'Jan':
return '01'
elif month == 'May':
return '05'
elif month == 'Jun':
... |
def FloatDivision(x1, x2):#{{{
"""
Return the division of two values
"""
try:
return float(x1)/x2
except ZeroDivisionError:
return 0.0 |
def update_yeardatatext(value):
"""
Function to update HTML text for Yearly Data Plot
Input: value
Output: html.Div child text
"""
return "Data for year {}".format(value) |
def _fix_package_name(package_name: str) -> str:
"""
Fix the package name so it could be placed in the __init__.py file.
:param package_name: mystery package name.
:type package_name: str
:return: fixed mystery package name.
:rtype: str
"""
# Transform to eligible package name.
fixe... |
def determine_rad_rad(rxn_muls):
""" determine if reaction is radical-radical
"""
rct_muls = rxn_muls[0]
if len(rct_muls) > 1:
mul1, mul2 = rct_muls
rad_rad = bool(mul1 > 1 and mul2 > 1)
else:
prd_muls = rxn_muls[1]
if len(prd_muls) > 1:
mul1, mul2 = prd_m... |
def to_years(days):
""" Convert days to approximate years and days """
return "{} y {} d".format(int(days/365), days % 365) |
def sexpr2str(e):
"""convert a sexpr into Lisp-like representation."""
if not isinstance(e, list):
return e
return "(" + " ".join(map(sexpr2str, e)) + ")" |
def is_white(r, g, b):
"""
Check if an RGB code is white.
:param r: Red byte.
:param g: Green byte.
:param b: Blue byte.
:return: True if the pixel is white, False otherwise.
"""
if r == 255 and g == 255 and b == 255:
return True
else:
return False |
def mean(F):
"""Return the mean of the Fourier series with coefficients F."""
n = len(F)
mu = F[int(n/2)]
return mu |
def print_columns(objects, cols=3, gap=2):
""" Print a list of items in rows and columns """
# if the list is empty, do nothing
if not objects:
return ""
# make sure we have a string for each item in the list
str_list = [str(x) for x in objects]
# can't have more columns than items
... |
def units_distance(p, q, distance):
"""
Parameters
----------
p: list
first element is x1 val and second element is y1 value
q: list
first element is x2 val and second element is y2 value
distance: float
what is going to be the upper threshold to calculating distance betw... |
def num_sevens(n):
"""Returns the number of times 7 appears as a digit of n.
>>> num_sevens(3)
0
>>> num_sevens(7)
1
>>> num_sevens(7777777)
7
>>> num_sevens(2637)
1
>>> num_sevens(76370)
2
>>> num_sevens(12345)
0
>>> from construct_check import check
>>> che... |
def getIsotropicFactor(tags):
"""
factor to get x_resolution to equal z resolution.
"""
x = tags['x_resolution']
sp = tags['spacing']
return x*sp |
def mean(data):
"""
Return the sample arithmetic mean of data.
"""
n = len(data)
if n < 1:
raise ValueError('mean requires at least one data point')
return sum(data) / float(n) |
def integerize(number):
"""
Check if number is integer, if False make it integer
"""
if isinstance(number,int): return number
if isinstance(number,float):
if number.is_integer(): return int(number)
else: return integerize(number*10) |
def rotate_point(x0, y0, x1, y1, phi):
"""Rotate the coordinates of a point.
Args:
x0 (float) : X coordinate of ceter of rotation.
y0 (float) : Y coordinate of center of rotation.
x1 (float) : X coordinate of point to be rotated.
y1 (float) : Y coordinate of point to be rotated.... |
def znes_colors(n=None):
"""Return dict with ZNES colors.
Examples
--------
>>> znes_colors().keys() # doctest: +ELLIPSIS
dict_keys(['darkblue', 'red', 'lightblue', 'orange', 'grey',...
Original author: @ckaldemeyer
"""
colors = {
'darkblue': '#00395B',
'red': '#B54036... |
def get_loc(x:float, domain:list,closest=False):
"""
Returns the indices of the entries in domain that border 'x'
Raises exception if x is outside the range of domain
Assumes 'domain' is sorted!! And this _only_ works if the domain is length 2 or above
This is made for finding bin numbers on a li... |
def fact_o(n):
"""
>>> fact_o(5)
120
"""
p= 1
for i in range(2, n+1):
p *= i
return p |
def best_geo_match(possibles, ordered_locations):
"""Pick the dataset from ``possibles`` whose location is first in ``ordered_locations``.
``possibles`` is an interable with the field ``location``.
``ordered_locations`` is a list of locations in sorting order.
Returns an element from ``possibles``, o... |
def find_cols(defline, header_char='='):
"""
return a sorted list of (start, end) indexes into defline that
are the beginning and ending indexes of column definitions
based on a reStructuredText table header line.
Note that this is a braindead simple version that only understands
header_chars an... |
def z_inverse(x, mean, std):
"""The inverse of function z_score"""
return x * std + mean |
def is_intersecting(trace, dt1, dt2, timestamp_key):
"""
Check if a trace is intersecting in the given interval
Parameters
-----------
trace
Trace to check
dt1
Lower bound to the interval
dt2
Upper bound to the interval
timestamp_key
Timestamp attribute
... |
def transform_globs_into_regexes(globs):
"""Turns glob patterns into regular expressions."""
return [glob.replace("*", ".*").replace("?", ".") for glob in globs] |
def getFiles(inDirectory):
"""
Reads files from given directory
"""
listOfFiles = list()
from os import walk, path
for root, subFolders, files in walk(u"" + inDirectory):
for eachFile in files:
listOfFiles.append(path.join(root, eachFile))
return listOfFi... |
def index_tuples_log_ces(factor, factors, period):
"""Index tuples for the log_ces production function."""
ind_tups = [("transition", period, factor, rhs_fac) for rhs_fac in factors]
return ind_tups + [("transition", period, factor, "phi")] |
def slice_name_to_components( slice_name ):
"""
Decomposes a slice name into a map of its unique components. This is the
inverse of build_slice_name(). Also handles slice_name's which have been
converted into a path or URL as a prefix.
Takes 1 argument:
slice_name - String specifying the s... |
def map_int(to_int) -> int:
"""Maps value to integer from a string.
Parameters
----------
to_int: various (usually str)
Value to be converted to integer
Returns
-------
mapped_int: int
Value mapped to integer.
Examples
--------
>>> number_one = "1"
>>> err... |
def num_full_weekends(x,wkendtype):
"""
Returns number of full weekends (both days) worked in a given weekends worked pattern.
Inputs:
x - list of 2-tuples representing weekend days worked. Each list
element is one week. The tuple of binary values represent the
first and s... |
def listmofize(x):
"""
Return x inside a list if it isn't already a list or tuple.
Otherwise, return x.
>>> listmofize('abc')
['abc']
>>> listmofize(['abc', 'def'])
['abc', 'def']
>>> listmofize((1,2))
(1, 2)
"""
if not isinstance(x, (list, tuple)): return [x]
else: ... |
def generate_single_type_function_pointer_declarations(functions):
"""
Generate lines "extern tFoo foo_impl;"
"""
if not functions:
return []
lines = []
suffix = "_impl" if functions[0].type == 'WRAPPER' else ""
for function in functions:
line = "extern t{} {}{};" . format(fu... |
def hamming_distance(s1, s2):
"""return the Hamming distance b/t equal-length sequences
"""
if len(s1) != len(s2):
raise ValueError("undefined for sequences of unequal length")
result = sum(ch1 != ch2 for ch1, ch2 in zip(s1, s2))
return (len(s1) - result) / len(s1) |
def cross_product(u, v):
"""returns the cross product (vector) of vectors u and v"""
if len(u) == len(v) == 3:
return (u[1]*v[2] - u[2]*v[1],
u[2]*v[0] - u[0]*v[2],
u[0]*v[1] - u[1]*v[0])
else:
print('Cross product not calculated: dimension mismatch')
... |
def MakeMajorChords(n_semis, base_i):
"""Given a count of notes ascending by semitones, and an index into
that (virtual) array, generate indices to the notes, including all
extensions and reflections that can comprise the major chord based
on the indexed semitone. Return an array of indices of these no... |
def is_parameter(value):
"""Returns True if the given value is a reference to a template parameter.
Parameters
----------
value: string
String value in the workflow specification for a REANA template
Returns
-------
bool
"""
# Check if the value matches the template paramet... |
def str_replace(string, value, new_value, occurences = -1):
"""
Replaces the value of `value` to `new_value` in `string`.
If occurences is defined, will only replace the first n occurences. A negative value replaces all values.
"""
return string.replace(value, new_value, occurences) |
def int2fl(x, deci=3):
"""
Convert integer to floating point number.
"""
return round(float(x / pow(10, deci)), int(deci)) |
def _is_x_first_dim(dim_order):
"""Determine whether x is the first dimension based on the value of dim_order."""
if dim_order is None:
dim_order = 'yx'
return dim_order == 'xy' |
def subtract_offset(sequence, offset):
"""Subtracts an offset from the sequence number while considering wraparound"""
new_sequence = sequence - offset
if new_sequence < 0:
new_sequence += 0x100000000
return new_sequence |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.