content stringlengths 42 6.51k |
|---|
def totaler(products):
"""Totals the total value of each product."""
totalDict = {'base': 0, 'VAT': 0, 'total': 0};
for h in products:
totalDict['base'] += h['base'];
totalDict['VAT'] += h['VAT'];
totalDict['total'] += h['total'];
return totalDict; |
def argmax(arr):
"""Get index of max
:param: arr, list
"""
imax, vmax = 0, 0
for index, value in enumerate(arr):
if vmax < value:
vmax = value
imax = index
return imax |
def escape(x):
"""Encode strings with backslashes for python/go"""
return x.replace('\\', "\\\\").replace('"', r'\"').replace("\n", r'\n').replace("\t", r'\t') |
def transform_wiki_url(file_name: str) -> str:
"""
Transforms attach url to original wiki url
:param file_name: name of the file
:return: file url
>>> transform_wiki_url('1040017000.png')
'http://gbf-wiki.com/attach2/696D67_313034303031373030302E706E67.png'
>>> b'img'.hex().upper()
'696D... |
def parse_density_line(r):
"""parse density data line in numerical values
Args:
r (str): input row string, like
(sr.exe) Target Density = 1.0597E+00 g/cm3 = 1.0903E+23 atoms/cm3
(srmodule.exe) Density = 1.0597E+00 g/cm3 = 1.0902E+23 atoms/cm3
... |
def myfunc(myarg):
"""prints some text combined with a string from argument"""
print("my function", myarg)
return "return value" |
def chunk_it(seq, num):
"""
Chunk a sequence in N equal segments
:param seq: Sequence of numbers
:param num: Number of chunks
:return: chunked start and end positions
"""
# find average chunk size
avg = len(seq) / float(num)
out = []
last = 0.0
# until the end of sequence
... |
def control_1_7_password_policy_symbol(passwordpolicy):
"""Summary
Args:
passwordpolicy (TYPE): Description
Returns:
TYPE: Description
"""
result = True
failReason = ""
offenders = []
offenders_links = []
control = "1.7"
description = "Ensure IAM password policy... |
def cylinder_flow(Position, t, v=1, r=1):
"""
This is an auxiliar function to be used with Scipy's odeint.
Given a point in the space it returns the velocity that an
incompressible fluid flowing around a cylinder placed along
the y axis would have at that point.
Input:
... |
def remove_pairs(cards):
""" Goes through a list of cards and removes any extra pairs. """
cards = sorted(cards)
newlist = []
for i, c in enumerate(sorted(cards)):
if i == 0:
newlist.append(c)
elif c.rank != cards[i - 1].rank:
newlist.append(c)
return newlist |
def add_space(string, symbol=" ", direction="all"):
"""
Add a placeholder to the string
:params direction: support left or right or all.
"""
if direction == "left":
return "{}{}".format(symbol, string)
elif direction == "right":
return "{}{}".format(string, symbol)
return "{}... |
def _get_countries(area):
"""
:param area: a country or the name set of countries
:return: countries that belong to the area
"""
if area == "EU":
countries = {"France", "Germany", "Spain", "Italy", "Netherlands",
"Portugal", "Belgium", "Sweden", "Finland", "Greece",
... |
def to_unicode(string, encoding='utf-8'):
"""Convert byte string to unicode."""
return str(string, encoding) if isinstance(string, bytes) else string |
def __polygon_intersection(verts, x, y):
"""
Computes the intersection with a polygon.
Algorithm from:
W. Randolph Franklin (WRF)
https://wrf.ecse.rpi.edu//Research/Short_Notes/pnpoly.html#The Method
"""
intersection = False
for i in range(len(verts)):
j = (i + len(verts) - 1) %... |
def is_pentagonal(n):
"""function to check if the number
is pentagonal number or not"""
if (1+(24*n+1)**0.5) % 6 == 0:
return True
return False |
def to_string(in_int):
"""Converts an integer to a string"""
out_str = ""
prefix = ""
if in_int < 0:
prefix = "-"
in_int = -in_int
while in_int / 10 != 0:
out_str = chr(ord('0') + in_int % 10) + out_str
in_int = in_int / 10
out_str = chr(ord('0') + in_int % 10) + ... |
def seasonFromDate(date):
"""
Returns the value of season from month and day data of the timestamp
Parameters
----------
date : String
Timestamp or date string in format of YYYY-MM-DD or followed by timestamp
Returns
-------
season : STRING
Season correspond... |
def is_subpath_of(file_path: str, potential_subpath: str) -> bool:
""" Case insensitive, file paths are not normalized when converted from uri"""
return file_path.lower().startswith(potential_subpath.lower()) |
def dayLookingFor(day_num_string):
"""
attempts to convert which day asked for, into an integer. If it can't, it a code instead.
"""
translation_dictionary = {'1st':1,'2nd':2,'3rd':3, '4th':4, 'last':9, 'teenth':6 }
return translation_dictionary[day_num_string] |
def str_to_doctest(code_lines, lines):
"""
Converts a list of lines of Python code ``code_lines`` to a list of doctest-formatted lines ``lines``
Args:
code_lines (``list``): list of lines of python code
lines (``list``): set of characters used to create function name
Returns:
... |
def _merge_2(list_, i, mid, j):
"""
Merge the two sorted halves list_[i:mid + 1] and
list_[mid + 1:j + 1] and return them in a new list.
Notice that list_[mid] belongs in the left half and list_[j]
belongs in the right half -- the indices are inclusive.
@param list list_: list to sort
@para... |
def diagnosis_from_description(description):
""" Return the diagnosis in each description """
diagnosis = description["meta"]["clinical"]["diagnosis"]
if diagnosis not in ["nevus", "melanoma", "seborrheic keratosis"]:
raise ValueError(diagnosis)
return diagnosis |
def inany(el, seq):
"""Returns the first sequence element that el is part of, else None"""
for item in seq:
if el in item:
return item
return None |
def kvalue(p,a,b):
"""
Determines the k-value of the point p on the line segment a-b. The k-value is the normalized
location on the line ab, with k(a)=0 and k(b)=1
Parameters
----------
p : (x,y)
Coordinates of a point. The point is assumed to be on the line through a & b.
... |
def bracket_sub (sub, comment=False):
""" Brackets a substitution pair.
Args:
sub (tuple): The substitution pair to bracket.
comment (bool): Whether or not to comment the bracketed pair.
Returns:
tuple: The bracketed substitution pair.
"""
if comment:
return ('\(\*\... |
def sanitize_domain(domain: str) -> str:
"""Makes a potential malicous domain not render as a domain in most systems
:param domain: Original domain
:return: Sanitized domain
"""
return domain.replace('.', '[.]') |
def listify(x):
""" Coerce iterable object into a list or turn a scalar into single element list
>>> listify(1.2)
[1.2]
>>> listify(range(3))
[0, 1, 2]
"""
try:
return list(x)
except:
if x is None:
return []
return [x] |
def remove_list_duplicates(lista, unique=False):
"""
Remove duplicated elements in a list.
Args:
lista: List with elements to clean duplicates.
"""
result = []
allready = []
for elem in lista:
if elem not in result:
result.append(elem)
else:
a... |
def provided(*args):
"""checks if given flags are specified during command line usage"""
if any(flag is not None for flag in args):
return True |
def tail(iterable):
"""Get tail of a iterable is everything except the first element."""
r = [x for x in iterable]
return r[1:] |
def format_multiple_values(value):
"""Reformat multi-line key value for PDS3 labels.
For example if the ``MAKLABEL`` key value has multiple entries, it needs to
be reformatted.
:param value: PDS3 key value
:type value: str
:return: PDS3 key value reformatted
:rtype: str
"""
if ',' ... |
def render_cells(cells, width=80, col_spacing=2):
"""Given a list of short (~10 char) strings, display these aligned in
columns.
Example output::
Something like this can be
used to neatly arrange long
sequences of values in ... |
def find_id(concept, h):
"""
:type concept: Collection.iterable
"""
id_found = 0
for e in concept:
if e['id'] == h:
return id_found
id_found += 1
return None |
def gcd(x, y):
""" The function returns the greatest common divisor
"""
while x > 0 and y > 0:
if x >= y:
x = x - y
else:
y = y - x
return x+y |
def special_string(instance: object, **kwargs) -> str:
""" Return a string that can be used if a standard 'eval repr' is
not appropriate.
"""
class_name = instance.__class__.__name__
if not kwargs:
return f'<{class_name}>'
else:
args = ' '.join(f'{name}={value!r}' for n... |
def _cross_2D(A, B):
""" Compute cross of two 2D vectors """
return A[0] * B[1] - A[1] * B[0] |
def _get_target_connection_details(target_connection_string):
"""
Returns a tuple with the raw connection details for the target machine extracted from the connection string provided
in the application arguments. It is a specialized parser of that string.
:param target_connection_string: the connection... |
def EndsWith(field, value):
"""
A criterion used to search for objects having a text field's value end with `value`.
It's a wildcard operator that adds the `*` if not specified, at the beginning of `value`. For example:
* search for filename observables ending with `.exe`
Arguments:
field... |
def LEFT(text, n):
"""Slices string(s) a specified number of characters from left.
Parameters
----------
text : list or string
string(s) to be sliced from left.
n : integer
number of characters to slice from left. Must be greater than zero.
Returns
-------
list or strin... |
def get_substitute_lines(text):
"""Helper functionality to split on filter."""
substitute_lines = []
for line in text.splitlines():
regex_replacement, regex_search = line.split("|||")
substitute_lines.append({"regex_replacement": regex_replacement, "regex_search": regex_search})
return s... |
def convert_simple(csv):
"""
csv should be a string that meets the RFC 4180 specification,
with the additional requirement of a header line.
This function returns a list of dictionaries.
"""
csv = csv.rstrip().strip()
lines = csv.splitlines()
# fetch the first line
header = lines.pop... |
def get_ei(oi, pi):
"""
"""
n = sum(oi)
ei = [(n * pi[x]) for x in range(len(oi))]
return ei |
def baumwelch(bw, O, num_iter):
"""
This convenience function runs the Baum--Welch algorithm in a way that looks
similar to the C version of the library.
Parameters
----------
bw : baumwelch_t
Specifies the context for the Baum--Welch algorithm.
O : sequence of integers between 0 a... |
def decode_pos(pos):
"""Decoes a scalar position on the board as a pair (i, j)."""
return pos // 3, pos % 3 |
def circumference_triangle(a, b, c):
"""
Calculate the circumference of a triangle.
param a: one side of the triangle
param b: other side of the triangle
param c: third side of the triangle
return: circumference of the triangle
"""
return a + b + c |
def mvt(a, b, fx = lambda x: x):
"""
Mean value theorem
Params:
a: start of interval
b: end of interval
fx: function
Returns:
f_c: derivative of some point c that is a <= c <= b
"""
return (fx(b) - fx(a))/(b - a) |
def make_mapper_ranges(num_chunks, num_mappers):
"""kappa:ignore"""
base = num_chunks // num_mappers
extras = num_chunks % num_mappers
mapper_ranges = []
start = 0
for i in range(num_mappers):
chunks = base
if i < extras:
chunks += 1
mapper_ranges.append((sta... |
def parse_name(name):
"""Parse cpdb name field.
"""
simple_name = name[0:name.rfind('(')]
db = name[name.rfind('(') + 1:-1]
return simple_name, db |
def source_location_to_tuple(locpb):
"""Converts a SourceLocation proto into a tuple of primitive types."""
if locpb is None:
return None
if not locpb.file() and not locpb.line() and not locpb.function_name():
return None
return locpb.file(), locpb.line(), locpb.function_name() |
def on_off(tag):
"""Return an ON/OFF string for a 1/0 input. Simple utility function."""
return ['OFF','ON'][tag] |
def _dedentlines(lines, tabsize=8, skip_first_line=False):
"""_dedentlines(lines, tabsize=8, skip_first_line=False) -> dedented lines
"lines" is a list of lines to dedent.
"tabsize" is the tab width to use for indent width calculations.
"skip_first_line" is a boolean indicating if the first... |
def func1 (x,y,a=1.0,b=2.0):
""" Evaluates a*x+b*y """
return a*x+b*y |
def bytes_as_hex(data):
"""
Parse bytes as a hexademical value for printing or debugging purposes
:param data: raw data read from the disk
:type data: bytes
:rtype: string
"""
return " ".join('{:02x}'.format(x) for x in data) |
def get_index_by_node_id(data):
""" Indexes a Dynalist data object by node for easy navigation. """
index = {}
for node in data["nodes"]:
index[node["id"]] = node
return index |
def ali_so_vrstice_enako_dolge(sez):
""" Definicija sprejme seznam, katerega
elementi so dolzine vsake vrstice """
for element in sez:
if len(sez) == 0:
return False
elif len(sez) == 1:
return True
elif sez[0] != sez[1]:
return False
else:... |
def test_closure(a):
"""This is the closure test in the paper."""
def x1(b):
def x4(c):
return b
return x4
x2 = x1(a)
x3 = x2(1.0)
return x3 |
def strip_repl_characters(code):
"""Removes the first four characters from each REPL-style line.
>>> strip_repl_characters('>>> "banana"') == '"banana"'
True
>>> strip_repl_characters('... banana') == 'banana'
True
"""
stripped_lines = []
for line in code.splitlines():
if line.s... |
def getBin(value, bins):
"""
Get the bin of "values" in axis "bins".
Not forgetting that we have more bin-boundaries than bins (+1) :)
"""
for index, bin in enumerate (bins):
# assumes bins in increasing order
if value < bin:
return index-1
print (' overfl... |
def make_feature_dict( feature_sequence ):
"""A feature dict is a convenient way to organize a sequence of Feature
object (which you have got, e.g., from parse_GFF).
The function returns a dict with all the feature types as keys. Each value
of this dict is again a dict, now of feature names. The values... |
def get_phase_number(total_number_of_phases, phase_number):
"""Summary
Parameters
----------
total_number_of_phases : TYPE
Description
phase_number : TYPE
Description
Returns
-------
TYPE
Description
"""
# wrap around the phases (use this to find... |
def Title(word):
"""Returns the given word in title case. The difference between
this and string's title() method is that Title('4-ary') is '4-ary'
while '4-ary'.title() is '4-Ary'."""
return word[0].upper() + word[1:] |
def _cast_dict_keys(data, key_cast):
"""Converts all dict keys in `data` using `key_cast`, recursively.
Can be used on any type, as this method will apply itself on dict and list
members, otherwise behaving as no-op.
>>> _cast_dict_keys({'key': 'value', 'other': {'a': 'b'}}, str.capitalize)
{'Key'... |
def cohen_d(t, n):
"""Utility function for computing Cohen's D given t statistics and n
"""
d = (2*t) / ((n-1) ** 0.5)
return d |
def get_edge_nodes(edge, nodes):
"""Get first and last nodes of an edge.
Parameters
----------
edge : dict
the edge information
nodes : list of dict
all available nodes
Returns
-------
dict
information on the first node
dict
information on the last n... |
def wc_int_to_string(tint):
""" tint: The ternary integer for (we'll really a quaternary however
we don't expect a z)
"""
as_str = ""
while tint:
part = tint & 3
assert part
if part == 1:
as_str += '0'
elif part == 2:
as_str += '1'
... |
def get_ack_status(code):
"""Get ack status from code."""
ack_status = {0: "No", 1: "Yes"}
if code in ack_status:
return ack_status[code] + " (" + str(code) + ")"
return "Unknown ({})".format(str(code)) |
def sqrt(x):
"""Calculates square root of x. Appends result to x.children if x is a
Reverse object.
Arguments:
x {Reverse, Float} -- Value to calculate square root for.
Returns:
Reverse -- Input raised to the 0.5
"""
return x ** (1 / 2) |
def data_to_hex_str(data):
"""convert raw data to hex string in groups of 4 bytes"""
if not data: return ''
dlen = len(data) # total length in bytes
groups = (dlen+3) // 4 # number of 4-byte blocks to create
remain = dlen
retstr = '' # return string
for group in range(groups):... |
def find_next_square2(sq):
""" Alternative method, works by evaluating anything non-zero as True (0.000001 --> True) """
root = sq**0.5
return -1 if root % 1 else (root+1)**2 |
def save_div(a, b, ret=0):
"""Division without 0 error, ret is returned instead."""
if b == 0:
return ret
return a/b |
def get_single_data(url, lst, f):
"""
Tries a url with a certain category, then if it returns the correct data type
and doesn't errror, then it will add the score from the category into the
list. Returns the list.
"""
try:
temp = f.main(url)
except:
return "?"... |
def merge(line):
"""
Function that merges a single row or column in 2048.
"""
# replace with your code
result_list = [0] * len(line)
find_merge = False
flag_index = []
# merge same element (from left to right)
for dummy_i in range(len(line)):
if line[dummy_i] != 0 and du... |
def validate_required(value):
"""
Method to raise error if a required parameter is not passed in.
:param value: value to check to make sure it is not None
:returns: True or ValueError
"""
if value is None:
raise ValueError('Missing value for argument')
return True |
def safe_check(comp, state, expected, default=False):
"""Check that components's state has expected value or return default if state is not defined."""
try:
return getattr(comp.state, state) == expected
except AttributeError:
return default |
def even_fibonacci_numbers(limit = 4000000):
"""
Returns the sum of the even-valued terms in the Fibonacci sequence,
whose values do not exceed four million.
"""
n1, n2 = 1, 2
even_sum = 0
while (n2 <= limit):
if n2%2 == 0:
even_sum += n2
temp = n2 + n1
n1 = n2
n2 = temp
return even_sum |
def extract_first(data_list, default=None):
"""
:return
"""
if len(data_list) > 0:
return data_list[0]
else:
return default |
def calculate_diagnosis_match_score(section):
"""Process metadata function."""
for ann in section:
if ann.get("seen_in_diagnosis") == "True":
ann["score"] = 1.0
else:
diagnosis_annotation = [ann.get("system", 0), ann.get("organ", 0), ann.get(
"histology_0"... |
def _add_extra_longitude_points(gjson):
"""
Assume that sides of a polygon with the same latitude should
be rendered as curves following that latitude instead of
straight lines on the final map projection
"""
import math
fuzz = 0.00001
if gjson[u'type'] != u'Polygon':
return gjso... |
def get_labels(label_string):
"""
This function converts label from string to array of labels
Input: "(1, 2, 3, 4, 5)"
Output: [1, 2, 3, 4, 5]
"""
label_array = label_string[1:-1]
label_array = label_array.split(',')
label_array = [int(label) for label in label_array if len(l... |
def getFuelLatticeCell(cellNum, surfaceNum, assemblyUniverse, latticeUniverse, comment):
"""Create a hexagonal lattice cell."""
cellCard = "{} 0 -{} u={} fill={} imp:n=1 {}".format(cellNum, surfaceNum, assemblyUniverse, latticeUniverse,
comment)
asser... |
def check_row_winner(row):
"""
Return the player number that wins for that row.
If there is no winner, return 0.
"""
if row[0] == row[1] and row[1] == row[2]:
return row[0]
return 0 |
def flatten_kv_dict(orig_dict, join_char=":"):
"""
>>> flatten_kv_dict({'a': {'b': 2, 'c': 3}, 'd': 4})
"""
flat_dict = {}
for k in orig_dict:
v = orig_dict[k]
if isinstance(v, dict):
flattened_dict = flatten_kv_dict(v, join_char=join_char)
for k_ in flattened... |
def merge_dictionaries(to_dict, from_dict, depth=3, replace=True):
"""
Merges both dictionaries, if replace is True, overwriting data in to_dict with from_dict data
with the same keys.
Note: Although function does return merged data, actions are inplace and rewrite to_dict.
:return: merged dictionar... |
def quote_string(text: str) -> str:
"""Quotes and returns the text with escaped \" characters."""
return '"' + text.replace('"', '\\"') + '"' |
def replace_in_keys(src, existing='.', new='_'):
"""
Replace a substring in all of the keys of a dictionary (or list of dictionaries)
:type src: ``dict`` or ``list``
:param src: The dictionary (or list of dictionaries) with keys that need replacement. (required)
:type existing: ``s... |
def percentile(N, percent, key=lambda x:x):
"""
Find the percentile of a list of values.
@parameter N - is a list of values. Note N MUST BE already sorted.
@parameter percent - a float value from 0 to 100.
@parameter key - optional key function to compute value from each element of N.
@return ... |
def filter_list(input_list, key_fn=(lambda x: x), filter_keys=None):
"""Filter a list with a list of keys
Args:
input_list: list to be filtered
key_fn: a function to generate keys from elements in the list
filter_keys: keys to intersect with
Returns:
filtered_input_list: fi... |
def oi_to_args(issues):
""" Return a set containing all arguments in the list of open issues."""
res = set()
for i in issues:
res &= set(i.arguments)
return res |
def generate_report(data):
""" Process the property data from the web page, build summary dictionary containing:
* 'property_name' - Name of property
* 'property_type' - Type of property e.g. 'Apartment'
* 'room_type' - Type or number of bedrooms
* 'room_number' - Number of bedrooms
* 'ba... |
def comma_and_and(*values, period=True):
""" Return a properly formatted string, eg: a, b and c. """
period = '.' if period else ''
len_values = len(values)
if len_values == 0:
return ""
elif len_values == 1:
return f"{values[0]}{period}"
else:
return f"{', '.join(values[... |
def manhattan_distance_with_heading(current, target):
"""
Return the Manhattan distance + any turn moves needed
to put target ahead of current heading
current: (x,y,h) tuple, so: [0]=x, [1]=y, [2]=h=heading)
heading: 0:^:north 1:<:west 2:v:south 3:>:east
"""
md = abs(current[0] - target[... |
def _make_header(text: str, level: int) -> str:
"""Create a markdown header at a given level"""
return f"{'#' * (level + 1)} {text}" |
def decode_from_bioes(tags):
"""
Decode from a sequence of BIOES tags, assuming default tag is 'O'.
Args:
tags: a list of BIOES tags
Returns:
A list of dict with start_idx, end_idx, and type values.
"""
res = []
ent_idxs = []
cur_type = None
def flush():
... |
def accuracy(prediction, actual):
"""
:param prediction:
:param actual:
:return accuaracy:
Simple function to compute raw accuaracy score quick comparision.
"""
correct_count = 0
prediction_len = len(prediction)
for idx in range(prediction_len):
if int(prediction[... |
def validate_var(d, var, *string):
"""check validate variables in string set var."""
return set(var) - {'walk_result', 'get_result', 'last_result', 'time',
'snmp', 'last', 'options', 'time', 're'} - d['all_var'] |
def add_three(a, b, c, wb, wc):
"""add three vectors with weights
Note this modifies the input vector a.
:param a: array
:param b: array
:param c: array
:param wb: real number
:param wc: real number
:return: vector a+ wb*b + wc*c
"""
for i in range(len(a)):
a[i] += wb*b... |
def sort_str(string):
"""
Sort a string of wires and segments.
"""
return "".join(sorted(string)) |
def _data_filed_conversion(field):
"""
converts fields in the sample sheet generated by the LIMS in fields that can be used by bcl2fastq2.17
"""
datafieldsConversion = {'FCID': 'FCID',
'Lane': 'Lane',
'SampleID' : 'Sample_ID',
... |
def check_next_url(next_url):
"""
Checks to make sure the next url is not redirecting to another page.
Basically it is a minimal security check.
"""
if not next_url or '://' in next_url:
return None
return next_url |
def is_mlcmt(line,mlcmto,mlcmtc):
"""Test if the line has an start, end
or both of multiple line comment delimiters
"""
return [line.find(mlcmto),line.find(mlcmtc)] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.