content stringlengths 42 6.51k |
|---|
def row_sum_odd_numbers(n):
"""
Given the triangle of consecutive odd numbers
"""
result = 0
start = (n * n)-(n - 1)
end = start+n * 2
for i in range(start, end, 2):
result += i
return result |
def to_char(keyval_or_char):
"""Convert a event keyval or character to a character"""
if isinstance(keyval_or_char, str):
return keyval_or_char
return chr(keyval_or_char) if 0 < keyval_or_char < 128 else None |
def title_case(sentence, str):
"""
Convert a string to title case.
Parameters
----------
sentence : string
String to be converted to title case
Returns
--------
str : string
String converted to title case
Example
--------
>>> title_case('ThIS IS a StrinG to BE ConVerTed.')
'This Is A String To Be Converted.'
"""
#Check that input is string
if not isinstance(sentence, str):
raise TypeError('Invalid input %s - Input must be type string' %(sentence))
# Error if empty string
if len(sentence) == 0:
raise ValueError('Cannot apply title function to empty string.')
ret = sentence[0].upper()
for i in range(1, len(sentence)):
if sentence[i-1] == ' ':
ret +=sentence[i].upper()
else:
ret += sentence[i].lower()
return(ret) |
def overlap(s1, s2):
"""Two strings: s1, s2.
Reutnrs x,y,z such as:
s1 = xy
s2 = yz
"""
if len(s2) == 0:
return s1, (), s2
i1, i2 = 0, 0
#i1, i2: indices in s1, s2
s2_0 = s2[0]
istart = max( 0, len(s1) - len(s2) )
for i in range(istart, len(s1)):
s1_i = s1[i]
if s1_i == s2_0:
if s1[i+1:] == s2[1:len(s1)-i]:
return s1[:i], s1[i:], s2[len(s1)-i:]
return s1, (), s2 |
def broken_fit(p,xax):
"""Evaluate the broken power law fit with the parameters chosen
Parameters:
p[0] - breakpoint
p[1] - scale
p[2] - lower slope (xax < breakpoint)
p[3] - higher slope (xax >= breakpoint)
"""
xdiff=xax-p[0]
lfit=(p[2]*xdiff+p[1])*(xdiff < 0)
ufit=(p[3]*xdiff+p[1])*(xdiff >= 0)
return lfit+ufit |
def angle(d, m, s):
"""Return an angle data structure
from d degrees, m arcminutes and s arcseconds.
This assumes that negative angles specifies negative d, m and s."""
return d + ((m + (s / 60)) / 60) |
def choose_small_vocabulary(index, concepts):
"""
Choose the vocabulary of the small frame, by eliminating the terms which:
- contain more than one word
- are not in ConceptNet
"""
vocab = [term for term in index if '_' not in term and term in concepts]
return vocab |
def catch(func, handle=lambda e: e, *args, **kwargs):
"""Helper function to enable the list comprehension in xmltolist.
Whenenver a data field doesn't have an entry, put an empty string.
cf. http://stackoverflow.com/a/8915613
"""
try:
return func(*args, **kwargs)
except KeyError:
return '' |
def elias_encode(a):
"""
Elias gamma encode the integer a.
"""
e = ''
n = 0
while a != 0:
e = str(a&1) + e
a >>= 1
n += 1
return '0'*(n-1) + e |
def get_doi_url(doi):
"""
Given a DOI, get the URL for the DOI
"""
return "https://doi.org/%s" % doi |
def argmin(seq, fn):
"""Return an element with lowest fn(seq[i]) score; tie goes to first one.
>>> argmin(['one', 'to', 'three'], len)
'to'
"""
best = seq[0]; best_score = fn(best)
for x in seq:
x_score = fn(x)
if x_score < best_score:
best, best_score = x, x_score
return best |
def layout_end(layout):
"""Find the ending token for the layout."""
tok = layout[0]
if tok == '{':
end = '}'
elif tok == '[':
end = ']'
else:
return -1
skip = -1
for i, c in enumerate(layout):
if c == end and skip == 0:
return i
elif c == end and skip > 0:
skip -= 1
elif c == tok:
skip += 1
return -1 |
def create_pipeline_message_text(channel, pipeline):
"""
Creates a dict that will be sent to send_message for pipeline success or failures
"""
emote = ":red_circle:" if pipeline.get("state") == "FAILED" else ":white_check_mark:"
return {
"channel": channel,
"text": (
f"{emote} Pipeline {pipeline['name']} on {pipeline['account_id']} "
f"has {pipeline['state']}"
),
} |
def check_duration_index(cross):
"""Verify the duration location"""
assert len(cross) > 0, \
'(ValueError) Coda fit line does not cross noise threshold'
return None |
def seq_into_tuple(sequence):
"""
Extract all repeating motifs.
:param sequence: str - motif sequence in ACATCAG,3-TGT,CATCGACT format
:return: list(tuple) - motif sequence in list((seq, rep)) format
"""
modules = sequence.split(',')
return [(m.split('-')[-1], 1 if len(m.split('-')) == 1 else int(m.split('-')[0])) for m in modules] |
def patch_metadata(metadata: dict, patch: dict) -> dict:
"""Replace the fields mentioned in the patch, while leaving others as is.
The first argument's content will be changed during the process.
"""
for key in patch.keys():
val = patch[key]
if isinstance(val, dict):
patch_metadata(metadata[key], val)
else:
metadata[key] = val
return metadata |
def primary_secondary(url):
""" return just the secondary.primary domain part, as a single string """
if len(url) >= 2:
url_split = url.split('.')
url_join = '.'.join(url_split[-2:])
return url_join
# To consider: Would a single-length case ever happen?
else:
return url |
def bbcode_content(value):
"""
Ref. http://code.djangoproject.com/wiki/CookBookTemplateFilterBBCode
"""
import re
pat = re.compile(r'<([^>]*?)>', re.DOTALL | re.M)
value = re.sub(pat, '<\\1>', value)
bbdata = [
(r'\[url\](.+?)\[/url\]', r'<a href="\1">\1</a>'),
(r'\[url=(.+?)\](.+?)\[/url\]', r'<a class="link-segment" href="\1">\2</a>'),
(r'\[email\](.+?)\[/email\]', r'<a href="mailto:\1">\1</a>'),
(r'\[email=(.+?)\](.+?)\[/email\]', r'<a href="mailto:\1">\2</a>'),
(r'\[img\](.+?)\[/img\]', r'<img src="\1">'),
(r'\[img=(.+?)\](.+?)\[/img\]', r'<img src="\1" alt="\2">'),
(r'\[b\](.+?)\[/b\]', r'<b>\1</b>'),
(r'\[i\](.+?)\[/i\]', r'<i>\1</i>'),
(r'\[u\](.+?)\[/u\]', r'<u>\1</u>'),
(r'\[quote\](.+?)\[/quote\]', r'<blockquote class="content-quote">\1</blockquote>'),
(r'\[center\](.+?)\[/center\]', r'<div align="center">\1</div>'),
(r'\[code\]\s?(.+?)\[/code\]', r'<blockquote class="code-segment"><code><pre>\1</pre></code></blockquote>'),
(r'\[big\](.+?)\[/big\]', r'<big>\1</big>'),
(r'\[small\](.+?)\[/small\]', r'<small>\1</small>'),
]
for bbset in bbdata:
p = re.compile(bbset[0], re.DOTALL)
value = p.sub(bbset[1], value)
#The following two code parts handle the more complex list statements
temp = ''
p = re.compile(r'\[list\](.+?)\[/list\]', re.DOTALL)
m = p.search(value)
if m:
items = re.split(re.escape('[*]'), m.group(1))
for i in items[1:]:
temp = temp + '<li>' + i + '</li>'
value = p.sub(r'<ul>'+temp+'</ul>', value)
temp = ''
p = re.compile(r'\[list=(.)\](.+?)\[/list\]', re.DOTALL)
m = p.search(value)
if m:
items = re.split(re.escape('[*]'), m.group(2))
for i in items[1:]:
temp = temp + '<li>' + i + '</li>'
value = p.sub(r'<ol type=\1>'+temp+'</ol>', value)
return value |
def closest_perfect_kth_root(x, k): # x is the number of interest, k is the power
""" naive method by KJL """
y = 2
while y <= x:
y = y**k
if y > x:
return y**(1/k) - 1
if y == x:
y**(1/k)
y = y**(1/k)
y += 1 |
def sum_using_formula(arr, n):
""" It works only if array is sequential"""
return n * (n + 1) / 2 |
def setlsb(component, bit):
"""
Set Least Significant Bit of a colour component.
"""
return component & ~1 | int(bit) |
def append_byte(bytes_array, bytes_add):
"""Append bytes to a byte array.
Parameters:
bytes_array (bytes): Byte array
bytes_add (bytes): Bytes to be added
Returns:
bytes: Resulting byte array
"""
bytes_array += bytes_add
return bytes_array |
def kind(n, ranks):
"""Return the card for which there is n-of-a-kind, else return None"""
for card in ranks:
if ranks.count(card) == n: return card
return None |
def fib(n):
"""Returns the nth Fibonacci number.
>>> fib(0)
0
>>> fib(1)
1
>>> fib(2)
1
>>> fib(3)
2
>>> fib(4)
3
>>> fib(5)
5
>>> fib(6)
8
>>> fib(100)
354224848179261915075
"""
"*** YOUR CODE HERE ***"
a = 0
b = 1
# a, b = 0, 1
for i in range(n):
# a, b = b, a + b
# # note: everything on the right side of the assignment is
# evaluated before the assignment happens so the single line above is the same as the
# next 3 lines:
temp = a
a = b
b = temp + b
return a |
def round_masses(mass):
"""
Round all the masses for the output to 8 digits after comma
"""
if mass == '-':
return '-'
else:
return round(mass, 8) |
def _border_trim_slice(n, ps, pstr):
"""
Helper function for remove_borders. Produce slices to trim t_n pixels
along an axis, t_n//2 at the beginning and t_n//2 + t_n%2 at the end.
"""
t_n = (n - ps) % pstr
t_start, t_end = t_n // 2, t_n // 2 + t_n % 2
assert t_start < n - t_end
return slice(t_start, n - t_end) |
def mapParts(lib, libid):
""" Assign a unique index to each part """
cmap = {}
for i in range(0, len(lib)):
construct = lib[i]
try:
constructid = libid[i]
except:
constructid = lib[i]
for p in constructid:
if p not in cmap:
cmap[p] = len(cmap)
return cmap |
def calculate_job_percentage(total_files, files_finished):
"""
Do some maths to calculate the job percentage :)
Parameters
----------
total_files: int
Total number of files for a job
files_finished: int
Files finished for a job
Returns
-------
An int representation of the job percentage
"""
job_percentage = 0
if total_files != 0 and files_finished != 0:
job_percentage = round(files_finished / total_files * 100)
# Little bit of a hack here, the front end doesn't build resources as fast as they are
# returned so to get around the FE hanging on 100% for a few seconds, we'll display 99.
if job_percentage == 100:
job_percentage = 99
return job_percentage |
def reorder(index_list, list_to_reorder):
"""Curried function to reorder a list according to input indices.
Parameters
----------
index_list : list of int
The list of indices indicating where to put each element in the
input list.
list_to_reorder : list
The list being reordered.
Returns
-------
reordered_list : list
The reordered list.
Examples
--------
>>> list1 = ['foo', 'bar', 'baz']
>>> reorder([2, 0, 1], list1)
['baz', 'foo', 'bar']
"""
return [list_to_reorder[j] for j in index_list] |
def escape(orig):
"""Because Lua hates unescaped backslashes."""
return '"{}"'.format(orig.replace('\\', '\\\\').replace('"', '\\"')) |
def check_bucket_valid(bucket):
"""
Check bucket name whether is legal.
:type bucket: string
:param bucket: None
=======================
:return:
**Boolean**
"""
alphabet = "abcdefghijklmnopqrstuvwxyz0123456789-"
if len(bucket) < 3 or len(bucket) > 63:
return False
if bucket[-1] == "-" or bucket[-1] == "_":
return False
if not (('a' <= bucket[0] <= 'z') or ('0' <= bucket[0] <= '9')):
return False
for i in bucket:
if not i in alphabet:
return False
return True |
def _nollToZernInd(j):
"""
Authors: Tim van Werkhoven, Jason Saredy
See: https://github.com/tvwerkhoven/libtim-py/blob/master/libtim/zern.py
"""
if (j == 0):
raise ValueError("Noll indices start at 1, 0 is invalid.")
n = 0
j1 = j-1
while (j1 > n):
n += 1
j1 -= n
m = (-1)**j * ((n % 2) + 2 * int((j1+((n+1)%2)) / 2.0 ))
return n, m |
def rchop(s, sub):
"""Chop ``sub`` off the end of ``s`` if present.
>>> rchop("##This is a comment.##", "##")
'##This is a comment.'
The difference between ``rchop`` and ``s.rstrip`` is that ``rchop`` strips
only the exact suffix, while ``s.rstrip`` treats the argument as a set of
trailing characters to delete regardless of order.
"""
if s.endswith(sub):
s = s[:-len(sub)]
return s |
def highlight_text(snippets, article):
"""Add HTML higlighting around each snippet found in the article."""
for snippet in snippets:
try:
idx = article.index(snippet)
except ValueError:
pass
else:
new_article = (
article[:idx]
+ '<span style="background-color: #FFFF00"> **'
+ article[idx : idx + len(snippet)]
+ "** </span>"
+ article[idx + len(snippet) :]
)
article = new_article
return article |
def _routes_to_set(route_list):
"""Convert routes to a set that can be diffed.
Convert the in-API/in-template routes format to another data type that
has the same information content but that is hashable, so we can put
routes in a set and perform set operations on them.
"""
return set(frozenset(r.items()) for r in route_list) |
def not_x_or_y(x_or_y, K_sets, on_keys=None):
"""not tags-any=x_or_y"""
s_xy = set(x_or_y)
xy_s = [k for k, S in K_sets.items()
if (on_keys is None or k in on_keys) and len(S & s_xy) == 0]
return xy_s |
def is_outlook_msg(content):
"""
Checks if the given content is a Outlook msg OLE file
Args:
content: Content to check
Returns:
bool: A flag the indicates if a file is a Outlook MSG file
"""
return type(content) == bytes and content.startswith(
b"\xD0\xCF\x11\xE0\xA1\xB1\x1A\xE1") |
def partition_range(max_range):
"""partition for milla website in lengths of 3 or 4
>>> partition_range(3)
[[0], [1], [2]]
>>> partition_range(5)
[[0], [1], [2], [3, 4]]
>>> partition_range(8)
[[0, 1], [2, 3], [4, 5], [6, 7]]
>>> partition_range(12)
[[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]]
"""
lst = range(max_range)
if max_range <= 4:
return [[i] for i in lst]
elif max_range == 5:
L = [[i] for i in range(4)]
L[3].append(4)
return L
elif max_range == 6:
return [[0, 1], [2, 3], [4, 5]]
elif max_range == 7:
return [[0], [1, 2], [3, 4], [5, 6]]
elif max_range == 8:
return [[0, 1], [2, 3], [4, 5], [6, 7]]
else:
return [lst] |
def flattenjson(obj, delim="__"):
"""
Flattens a JSON object
Arguments:
obj -- dict or list, the object to be flattened
delim -- string, delimiter for sub-fields
Returns:
The flattened JSON object
"""
val = {}
for i in obj:
if isinstance(obj[i], dict):
ret = flattenjson(obj[i], delim)
for j in ret:
val[i + delim + j] = ret[j]
else:
val[i] = obj[i]
return val |
def forward_integrate(init: float, delta: float, sampling_time: float) -> float:
"""
Performs a simple euler integration
:param init: initial state
:param delta: the rate of chance of the state
:return: The result of integration
"""
return init + delta * sampling_time |
def normalize(dict):
"""
Normalized given dictionary value to [0,1] and sum(dict.values()) = 1
"""
total = sum([v for v in dict.values()])
for i, v in dict.items():
dict[i] = v/total
return dict |
def decode(string):
"""Decodes a String"""
dec_string = string \
.replace('&', '&') \
.replace('<', '<') \
.replace('>', '>')
return dec_string |
def iseventtask(task):
"""
Return True if `task` is considered an event task, meaning one that
acts on `tkinter` events.
Return False otherwise.
"""
return getattr(task, "next_event", -1) >= 0 |
def human_to_bytes(size):
"""
Given a human-readable byte string (e.g. 2G, 30M),
return the number of bytes. Will return 0 if the argument has
unexpected form.
.. versionadded:: 2018.3.0
"""
sbytes = size[:-1]
unit = size[-1]
if sbytes.isdigit():
sbytes = int(sbytes)
if unit == "P":
sbytes *= 1125899906842624
elif unit == "T":
sbytes *= 1099511627776
elif unit == "G":
sbytes *= 1073741824
elif unit == "M":
sbytes *= 1048576
else:
sbytes = 0
else:
sbytes = 0
return sbytes |
def is_image_file(filename):
"""
determines whether the arguments is an image file
@param filename: string of the files path
@return: a boolean indicating whether the file is an image file
"""
return any(filename.endswith(extension) for extension in [".png", ".jpg", ".jpeg"]) |
def to_list(data_in):
"""Convert the data into a list. Does not pack lists into a new one.
If your input is, for example, a string or a list of strings, or a
tuple filled with strings, you have, in general, a problem:
- just iterate through the object will fail because it iterates through the
characters of the string.
- using list(obj) converts the tuple, leaves the list but splits the strings
characters into single elements of a new list.
- using [obj] creates a list containing a string, but also a list containing
a list or a tuple, which you did not want to.
Solution: use to_list(obj), which creates a new list in case the object is
a single object (a string is a single object in this sence) or converts
to a list if the object is already a container for several objects.
Parameters
----------
data_in : any obj
So far, any object can be entered.
Returns
-------
out : list
Return a list containing the object or the object converted to a list.
"""
if isinstance(data_in, (str, int, float)):
data_in = [data_in]
data_in = list(data_in)
return data_in |
def extent(shape, offset):
"""
Compute shifted array extent
Parameters
----------
shape : array_like
Array shape
offset : array_like
Array offset
Returns
-------
rmin, rmax, cmin, cmax : int
Indices that define the span of the shifted array.
Notes
-----
To use the values returned by ``extent()`` in a slice, ``rmax`` and ``cmax``
should be increased by 1.
See Also
--------
lentil.field.boundary : compute the extent around a number of Fields
"""
if len(shape) < 2:
shape = (1, 1)
rmin = int(-(shape[0]//2) + offset[0])
cmin = int(-(shape[1]//2) + offset[1])
rmax = int(rmin + shape[0] - 1)
cmax = int(cmin + shape[1] - 1)
return rmin, rmax, cmin, cmax |
def str_decode(text, coding=None):
"""Decode bytes to string."""
if isinstance(text, str):
return text
elif isinstance(text, bytes):
if coding:
return text.decode(coding)
else:
return text.decode()
else:
raise Exception('String decoding error:%s' % text) |
def do_indent(s, width=4, indentfirst=False):
"""
{{ s|indent[ width[ indentfirst[ usetab]]] }}
Return a copy of the passed string, each line indented by
4 spaces. The first line is not indented. If you want to
change the number of spaces or indent the first line too
you can pass additional parameters to the filter:
.. sourcecode:: jinja
{{ mytext|indent(2, True) }}
indent by two spaces and indent the first line too.
"""
indention = ' ' * width
if indentfirst:
return u'\n'.join([indention + line for line in s.splitlines()])
return s.replace('\n', '\n' + indention) |
def encode_to_bytes(string, encoding="ascii"):
"""Helper function to encode a string as a bytestring"""
if not isinstance(string, bytes):
string = string.encode(encoding)
return string |
def spline_grid_from_range(spline_size, spline_range, round_to=1e-6):
"""
Compute spline grid spacing from desired one-sided range
and the number of activation coefficients.
Args:
spline_size (odd int):
number of spline coefficients
spline_range (float):
one-side range of spline expansion.
round_to (float):
round grid to this value
"""
if int(spline_size) % 2 == 0:
raise TypeError('size should be an odd number.')
if float(spline_range) <= 0:
raise TypeError('spline_range needs to be a positive float...')
spline_grid = ((float(spline_range) /
(int(spline_size) // 2)) // round_to) * round_to
return spline_grid |
def heaps(arr: list) -> list:
"""
Pure python implementation of the iterative Heap's algorithm,
returning all permutations of a list.
>>> heaps([])
[()]
>>> heaps([0])
[(0,)]
>>> heaps([-1, 1])
[(-1, 1), (1, -1)]
>>> heaps([1, 2, 3])
[(1, 2, 3), (2, 1, 3), (3, 1, 2), (1, 3, 2), (2, 3, 1), (3, 2, 1)]
>>> from itertools import permutations
>>> sorted(heaps([1,2,3])) == sorted(permutations([1,2,3]))
True
>>> all(sorted(heaps(x)) == sorted(permutations(x))
... for x in ([], [0], [-1, 1], [1, 2, 3]))
True
"""
if len(arr) <= 1:
return [tuple(arr)]
res = []
def generate(n: int, arr: list):
c = [0] * n
res.append(tuple(arr))
i = 0
while i < n:
if c[i] < i:
if i % 2 == 0:
arr[0], arr[i] = arr[i], arr[0]
else:
arr[c[i]], arr[i] = arr[i], arr[c[i]]
res.append(tuple(arr))
c[i] += 1
i = 0
else:
c[i] = 0
i += 1
generate(len(arr), arr)
return res |
def green_bold(payload):
"""
Format payload as green.
"""
return '\x1b[32;1m{0}\x1b[39;22m'.format(payload) |
def to_lists(*args):
"""Convert to lists of the same length."""
# tuple to array
args = list(args)
# entries to arrays
for ix, arg in enumerate(args):
if not isinstance(arg, list):
args[ix] = [arg]
# get length
length = max(len(arg) for arg in args)
# broadcast singulars
for ix, arg in enumerate(args):
if len(arg) == 1 and len(arg) != length:
args[ix] = [arg[0]] * length
# check length consistency
if any(len(arg) != length for arg in args):
raise AssertionError(f"The argument lengths are inconsistent: {args}")
if len(args) == 1:
return args[0]
return args |
def format_text_to_float(text):
"""Returns text after removing and adding characters in order to be casted to a float number.
Parameters
----------
text : str
the text to be formatted.
Returns
-------
str
a string formatted to be casted to float.
"""
return text.replace(u'\xa0', '').replace(' ', '').replace('.', '').replace(',', '.') |
def f_x(x, threshold, reld) :
""" Function in range 0 to 1, to set soil water and groundwater
flow to 0 below a user-specified threshold
x: float
threshold: f(x) is 0 below this threshold
reld: relative "activation distance", the distance from the
threshold (as a proportion of the threshold), at which
f(x) is 1
returns float f(x) evaluated at x
"""
def f_x0(x): return -2*x**3 + 3*x**2
d = threshold*reld
if x < threshold : return 0
if x > threshold + d : return 1
else: return f_x0( (x-threshold) / d ) |
def timezones(zone):
"""This function is used to handle situations of Daylight Saving Time that the standard library can't recognize."""
zones = {
"PDT": "PST8PDT",
"MDT": "MST7MDT",
"EDT": "EST5EDT",
"CDT": "CST6CDT",
"WAT": "Etc/GMT+1",
"ACT": "Australia/ACT",
"AST": "Atlantic/Bermuda",
"CAT": "Africa/Johannesburg",
}
try:
zones[zone]
except:
return zone
return zones[zone] |
def _get_ws_location(water_surface_elev, zmax, zmin):
"""
Return one of three values depending on the location of the water surface
relative to the elevations of the discretized cross-section points.
Vectorized below.
Returns:
(str) one of the following: 'below' if above zmax (and automatically
zmin), 'triangle' if between zmax and zmin, and 'trapezoid'
if below zmin. This corresponds to the geometry that will be used
to calculate the wetted perimeter and area of the induced polygon.
"""
if water_surface_elev > zmax:
return 'trapezoid'
elif water_surface_elev <= zmax and water_surface_elev > zmin:
return 'triangle'
else:
return 'below' |
def get_chrom_start_end_from_string(s):
"""Get chrom name, int(start), int(end) from a string '{chrom}__substr__{start}_{end}'
...doctest:
>>> get_chrom_start_end_from_string('chr01__substr__11838_13838')
('chr01', 11838, 13838)
"""
try:
chrom, s_e = s.split('__substr__')
start, end = s_e.split('_')
return chrom, int(start), int(end)
except Exception:
raise ValueError("String %s must be of format '{chrom}__substr__{start}_{end}'" % s) |
def rocks(n):
"""
>>> rocks(13)
17
>>> rocks(36123011)
277872985
The trick here is to compute correctly the number of the digits from given n
E.g,
13 --> there're (13-9)*2 + 9 = 17 digits
100 --> there're (100-99)*3 + (99-9)*2 + 9
So you know the rule
"""
s = 0
l = len(str(n))
while l > 1:
# the trick here is magic of python: '9'*3 = '999'
s += (n - int('9'*(l-1))) * l
n = int('9'*(l-1))
l -= 1
return s + 9 |
def ke(item):
"""
Used for sorting names of files.
"""
if item[0].isdigit():
return int(item.partition(' ')[0])
else:
return float('inf') |
def initial_state():
"""
Set the factory settings for the application.
The settings are stored in a dictionary.
Returns:
An empty dict()
"""
defstate = dict()
return defstate |
def solve(input):
"""find the sum of all digits that match the next digit in the list"""
input = [int(c) for c in input]
result = 0
previous = input[0]
for c in input[1:]:
if c == previous:
result += c
previous = c
if previous == input[0]:
result += previous
# print 'result=' + str(result)
return result |
def verify_new_attending(in_dict):
"""
This function verifies the input information for post_new_attending()
This function receives the dictionary containing the input
from the function post_new_attending(). The function uses a for
loop to check if the key strings are the same as the expected
key strings and that the value types are the same as
the expected value types. If the keys are incorrect, then a
string notifying the client that a key is missing is returned.
If a value type is incorrect, then a string is returned
to the patient saying that a specific value is of the wrong type.
If nothing is wrong, then this function returns True.
:param in_dict: a dictionary sent from the client
:return: True if the dictionary has the correct keys and value
types and a string explaining why the dictionary is wrong
otherwise.
"""
expected_keys = ("attending_username", "attending_email",
"attending_phone")
expected_values = (str, str, str)
for key, ty in zip(expected_keys, expected_values):
if key not in in_dict.keys():
return "{} key not found in input".format(key)
if type(in_dict[key]) != ty:
return "{} value is not the correct type".format(key)
return True |
def strBool(bool_str):
"""
Take the string "true" or "false" of any case and return a
boolean object.
"""
if bool_str.lower() == "true":
return True
elif bool_str.lower() == "false":
return False
else:
raise Exception(
"argument for strBool must be string either 'True' or 'False'.") |
def pascalcase(var): # SomeVariable
"""
Pascal case convention. Include an uppercase at every first element.
:param var: Variable to transform
:type var: :py:class:`list`
:returns: **transformed**: (:py:class:`str`) - Transformed input in ``PascalCase`` convention.
"""
result = ""
for element in var:
element = list(element)
element[0] = element[0].upper()
result += "".join(element)
return result |
def get_sign(x):
"""
Returns the sign of x.
:param x: A scalar x.
:return: The sign of x.
"""
if x > 0:
return +1
elif x < 0:
return -1
elif x == 0:
return 0 |
def binary(n):
"""Returns n in binary form.
First while loop finds the largest '1' bit, and the second while loop incrementally fills the lower value bits.
"""
if n == 0:
return 0
ans = '1'
a = 0
while n - (2 ** a) >= 0:
a += 1
a -= 2
n -= (2 ** (a+1))
while a >= 0:
if n - (2 ** a) < 0:
ans += '0'
a -= 1
else:
ans += '1'
n -= (2 ** a)
a -= 1
return ans |
def gf_sub_const(f, a, p):
"""Returns f - a where f in GF(p)[x] and a in GF(p). """
if not f:
a = -a % p
else:
a = (f[-1] - a) % p
if len(f) > 1:
return f[:-1] + [a]
if not a:
return []
else:
return [a] |
def generate_numbers(limit):
"""
@param:
limit - length of the sequence of natural numbers to be generated
@return:
list_of_numbers - list of the generated sequence
"""
if limit <= 0:
raise ValueError('Invalid limit specified')
list_of_numbers = list()
for i in range(1,limit+1):
list_of_numbers.append(False)
return list_of_numbers |
def remove_brackets(list1):
"""Remove brackets from text"""
return str(list1).replace('[','').replace(']','') |
def format_seconds(seconds):
"""Convert seconds to a formatted string
Convert seconds: 3661
To formatted: " 1:01:01"
"""
hours = seconds // 3600
minutes = seconds % 3600 // 60
seconds = seconds % 60
return "{:4d}:{:02d}:{:02d}".format(hours, minutes, seconds) |
def get_amazon_link(product_id: str, page: int) -> str:
"""
Generates an amazon review link for the following parameters
:param product_id: unique id of the product
:param page: review page number
:return: amazon review page without any filter
"""
result = (
"https://www.amazon.com/-/de/product-reviews/"
+ product_id
+ "/ref=cm_cr_arp_d_viewopt_sr?ie=UTF8&filterByStar=all_stars&reviewerType=all_reviews&pageNumber="
+ str(page)
)
return result |
def summy(string_of_ints):
"""This function takes a string of numbers with spaces and returns the sum of the numbers."""
numbers = string_of_ints.split()
answer = 0
for i in numbers:
answer = answer + int(i)
return answer |
def prim_value(row):
"""Extract primary key value from DAS record"""
prim_key = row['das']['primary_key']
key, att = prim_key.split('.')
if isinstance(row[key], list):
for item in row[key]:
if item.has_key(att):
return item[att]
else:
return row[key][att] |
def lineIntersectLine(x1: float, y1: float, x2: float, y2: float, x3: float, y3: float, x4: float, y4: float):
"""Checks if line from `x1, y1` to `x2, y2` intersects line from `x3, y3` to `x4, y4`"""
divisorA = ((y4-y3)*(x2-x1) - (x4-x3)*(y2-y1))
divisorB = ((y4-y3)*(x2-x1) - (x4-x3)*(y2-y1))
if divisorA == 0 or divisorB == 0:
return False
uA = ((x4-x3)*(y1-y3) - (y4-y3)*(x1-x3)) / divisorA
uB = ((x2-x1)*(y1-y3) - (y2-y1)*(x1-x3)) / divisorB
# uA = jsdiv( ((x4-x3)*(y1-y3) - (y4-y3)*(x1-x3)) , ((y4-y3)*(x2-x1) - (x4-x3)*(y2-y1)) )
# uB = jsdiv( ((x2-x1)*(y1-y3) - (y2-y1)*(x1-x3)) , ((y4-y3)*(x2-x1) - (x4-x3)*(y2-y1)) )
if 0 <= uA <= 1 and 0 <= uB <= 1:
return True
return False |
def createLemexes(key_list):
"""
:return str: in the format of {x, y, z} from input of key_list
"""
return '{' + ', '.join(key_list) + '}' |
def convert_humidity(h):
"""Eliminate % from text so you can cast as int"""
return h.replace('%', '') |
def frequency_map(text, k):
"""[computes the frequency map of a given string text and integer k, returns a dictionary of each supplied k-mer value]
Args:
text ([string]): [input string]
k ([int]): [determine length of kmer]
Returns:
[dict]: [for every length of kmer specified by k(keys), returns how many times it occurs in text(values)]
"""
Freq = {}
TextLength = len(text)
for i in range(TextLength-k+1): # range over all possible kmer combinations
pattern = text[i:i+k]
Freq[pattern] = 0
for j in range(TextLength-k+1):
if text[j:j+k] == pattern:
Freq[pattern] += 1
return Freq |
def constrained_path(path):
"""Remove all '..' occurrences from specified path.
It is used to ensure all artifact paths are constrained to remain under
temporary artifact directory."""
return path.replace('..', '') |
def properties_predicted(body):
"""
Callback function which work when properties prediction success
:param body: MassTransit message
"""
global CLASSIC_CLASSIFICATION_PREDICTED_FLAG
CLASSIC_CLASSIFICATION_PREDICTED_FLAG = True
return None |
def clip(val):
"""Standard clamping of a value into a fixed range (in this case -4.0 to
4.0)
Parameters
----------
val: float
The value to be clamped.
Returns
-------
The clamped value, now fixed to be in the range -4.0 to 4.0.
"""
if val > 4.0:
return 4.0
elif val < -4.0:
return -4.0
else:
return val |
def _create_axis(axis_type, variation="Linear", title=None):
"""
Creates a 2d or 3d axis.
:params axis_type: 2d or 3d axis
:params variation: axis type (log, line, linear, etc)
:parmas title: axis title
:returns: plotly axis dictionnary
"""
if axis_type not in ["3d", "2d"]:
return None
default_style = {
"background": "rgb(230, 230, 230)",
"gridcolor": "rgb(255, 255, 255)",
"zerolinecolor": "rgb(255, 255, 255)",
}
if axis_type == "3d":
return {
"showbackground": True,
"backgroundcolor": default_style["background"],
"gridcolor": default_style["gridcolor"],
"title": title,
"type": variation,
"zerolinecolor": default_style["zerolinecolor"],
}
if axis_type == "2d":
return {
"xgap": 10,
"ygap": 10,
"backgroundcolor": default_style["background"],
"gridcolor": default_style["gridcolor"],
"title": title,
"zerolinecolor": default_style["zerolinecolor"],
"color": "#444",
} |
def is_rgb_color(v):
"""Checks, if the passed value is an item that could be converted to
a RGB color.
"""
try:
if hasattr(v, "r") and hasattr(v, "g") and hasattr(v, "b"):
if 0 <= int(v.r) <= 255 and 0 <= int(v.g) <= 255 and \
0 <= v.b <= 255:
return True
if len(v) >= 3:
if 0 <= int(v[0]) <= 255 and 0 <= int(v[1]) <= 255 and \
0 < int(v[2]) < 255:
return True
return False
except (TypeError, ValueError):
return False |
def replace_name_with_derivedColumnNames(original_name, derived_col_names):
"""
It replace the default names with the names of the attributes.
Parameters
----------
original_name : List
The name of the node retrieve from model
derived_col_names : List
The name of the derived attributes.
Returns
-------
col_name :
Returns the derived column name/original column name.
"""
new = str.replace(original_name, 'f', '')
if new.isdigit():
col_name = derived_col_names[int(new)]
else:
col_name = original_name
return col_name |
def app_path(value):
"""
Return the app path (remove path)
:param value:
:return:
"""
splitted = value.split('/')
return '/'.join(splitted[3:]) |
def equal(fst, snd) -> bool:
"""Returns if files are equal by calculating their hash"""
return hash(fst) == hash(snd) |
def k2s(**kwargs) -> str:
"""Maps multiple arguments to a string.
Needed since gui labels need to be strings.
"""
return ", ".join([f"{key}={value}" for key, value in kwargs.items()]) |
def is_int(val):
"""
Determines whether the specified string represents an integer.
Returns True if it can be represented as an integer, or False otherwise.
"""
try:
int(val)
return True
except ValueError:
return False |
def get_digit_prefix(characters):
"""
Get the digit prefix from a given list of characters.
:param characters: A list of characters.
:returns: An integer number (defaults to zero).
Used by :func:`compare_strings()` as part of the implementation of
:func:`~deb_pkg_tools.version.compare_versions_native()`.
"""
value = 0
while characters and characters[0].isdigit():
value = value * 10 + int(characters.pop(0))
return value |
def blockify(text, blocklen):
"""Splits data as a list of `blocklen`-long values"""
return [text[i:i + blocklen] for i in range(0, len(text), blocklen)] |
def get_enzyme_reactions(eid, db):
"""
For a given ec number return associated reaction ids
:param eid: enzyme id format "EC-x.x.x.x"
:param db: database dict
:return:
"""
erids = []
if eid[:3] != "EC-":
eid = "EC-{}".format(eid)
for rid, react in db['reactions'].items():
if 'EC-NUMBER' in react and eid in react['EC-NUMBER']:
erids.append(rid)
return erids |
def get_value_from_dict_safe(d, key, default=None):
"""
get the value from dict
args:
d: {dict}
key: {a hashable key, or a list of hashable key}
if key is a list, then it can be assumed the d is a nested dict
default: return value if the key is not reachable, default is None
return:
value
"""
assert isinstance(d, dict), f"only supports dict input, {type(d)} is given"
if isinstance(key, (list, tuple)):
for _k in key[:-1]:
if _k in d and isinstance(d[_k], dict):
d = d[_k]
else:
return default
key = key[-1]
return d.get(key, default) |
def fuzzy_string_find(string, pattern, pattern_divisor=10, min_portion=2):
"""
Finds the pattern in string by only looking at the first and last portions of pattern
"""
pattern_length = len(pattern.split())
portion = max(pattern_length//pattern_divisor, min_portion)
first_portion = pattern.split()[:portion]
last_portion = pattern.split()[-portion:]
first_portion = ' '.join(first_portion)
last_portion = ' '.join(last_portion)
first_start = string.find(first_portion)
last_start = string.rfind(last_portion)
if first_start > -1 and last_start > -1:
last_end = last_start + len(last_portion)
return first_start, string[first_start:last_end]
else:
return -1, '' |
def FormatTag(key, value):
"""Format an individual tag for use with the --tags param of Azure CLI."""
return '{0}={1}'.format(key, value) |
def _convert_dict_to_list(d):
"""This is to convert a Python dictionary to a list, where
each list item is a dict with `name` and `value` keys.
"""
if not isinstance(d, dict):
raise TypeError("The input parameter `d` is not a dict.")
env_list = []
for k, v in d.items():
env_list.append({"name": str(k), "value": str(v)})
return env_list |
def number_similarity(num1,num2):
"""
:param num1:
:param num2:
:return:
"""
count = 0
for x, y in zip(str(num1), str(num2)):
if x == y:
count = count + 1
total = max(len(str(num1)), len(str(num1)))
return count/float(total) |
def get_chunk_type(tok):
"""
Args:
tok: id of token, ex 4
idx_to_tag: dictionary {4: "B-PER", ...}
Returns:
tuple: "B", "PER"
"""
tok_split = tok.split("-")
return tok_split[0], tok_split[-1] |
def _isEmpty(number):
"""
Simple private method to check if a variable (list) is empty.
It returns a boolean evaluation.
"""
return (number == [] or number == '') |
def _to_json_dict_with_strings(dictionary):
"""
Convert dict to dict with leafs only being strings. So it recursively makes keys to strings
if they are not dictionaries.
Use case:
- saving dictionary of tensors (convert the tensors to strins!)
- saving arguments from script (e.g. argparse) for it to be pretty
e.g.
"""
if type(dictionary) != dict:
return str(dictionary)
d = {k: _to_json_dict_with_strings(v) for k, v in dictionary.items()}
return d |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.