content stringlengths 42 6.51k |
|---|
def translate_order(order):
"""
Translates 'row_major' or 'col_major' to 'C' or 'F' respectively that numpy.reshape wants as an argument
Parameters
----------
order: str
Must be one of ["row_major", "col_majr"]
Output
------
'C' (row major) or 'F' (col major)
"""
if order == 'row_major':
np_ord = 'C'
elif order == 'col_major':
np_ord = 'F'
else:
raise ValueError('order must be one of ["row_major", "col_majr"], '
'not {}'.format(order))
return np_ord |
def pname(name, levels=None):
"""
Return a prettified taxon name.
Parameters
----------
name : str
Taxon name.
Returns
-------
str
Prettified taxon name.
Examples
--------
.. code:: python3
import dokdo
dokdo.pname('d__Bacteria;p__Actinobacteriota;c__Actinobacteria;o__Actinomycetales;f__Actinomycetaceae;g__Actinomyces;s__Schaalia_radingae')
# Will print: 's__Schaalia_radingae'
dokdo.pname('Unassigned;__;__;__;__;__;__')
# PWill print: 'Unassigned'
dokdo.pname('d__Bacteria;__;__;__;__;__;__')
# Will print: 'd__Bacteria'
dokdo.pname('d__Bacteria;p__Acidobacteriota;c__Acidobacteriae;o__Bryobacterales;f__Bryobacteraceae;g__Bryobacter;__')
# Will print: 'g__Bryobacter'
dokdo.pname('d__Bacteria;p__Actinobacteriota;c__Actinobacteria;o__Actinomycetales;f__Actinomycetaceae;g__Actinomyces;s__Schaalia_radingae', levels=[6,7])
# Will print: 'g__Actinomyces;s__Schaalia_radingae'
"""
if levels is None:
ranks = list(reversed(name.split(';')))
for i, rank in enumerate(ranks):
if rank in ['Others', 'Unassigned']:
return rank
if rank == '__':
continue
if rank.split('__')[1] is '':
return ranks[i+1] + ';' + rank
return rank
else:
ranks = name.split(';')
if 'Others' in ranks:
return 'Others'
if 'Unassigned' in ranks:
return 'Unassigned'
return ';'.join([ranks[x-1] for x in levels]) |
def _sabr_implied_vol_hagan_A11_fprime_by_strike(
underlying, strike, maturity, alpha, beta, rho, nu):
"""_sabr_implied_vol_hagan_A11_fprime_by_strike
See :py:func:`_sabr_implied_vol_hagan_A11`.
:param float underlying:
:param float strike:
:param float maturity:
:param float alpha: must be within :math:`[0, 1]`.
:param float beta: must be greater than 0.
:param float rho: must be within :math:`[-1, 1]`.
:param float nu: volatility of volatility. This must be positive.
:return: value of factor.
:rtype: float.
"""
one_minus_beta_half = (1.0 - beta) / 2.0
one_plus_beta_half = (1.0 + beta) / 2.0
factor = (one_minus_beta_half * (underlying ** one_minus_beta_half))
return factor * (strike ** (-one_plus_beta_half)) |
def int2hex(i):
"""Used to turn ints into hex for web-colors"""
if i<16:
return "0" + '%X'%i
else:
return '%X'%i |
def get_payload(message):
"""Parses a payload from a message
Parameters"
message: the facebook message object (dict)
Returns
pay: list of payload objects (list)
"""
pay = None
if "message" in message.keys():
if "quick_reply" in message["message"].keys():
if "payload" in message["message"]["quick_reply"].keys():
pay = message['message']['quick_reply']['payload']
return pay |
def set_node_stack_traces_enabled(enable: bool) -> dict:
"""Sets if stack traces should be captured for Nodes. See `Node.getNodeStackTraces`. Default is disabled.
Parameters
----------
enable: bool
Enable or disable.
**Experimental**
"""
return {"method": "DOM.setNodeStackTracesEnabled", "params": {"enable": enable}} |
def swagger_escape(s): # pragma: no cover
"""
/ and ~ are special characters in JSON Pointers,
and need to be escaped when used literally (for example, in path names).
https://swagger.io/docs/specification/using-ref/#escape
"""
return s.replace('~', '~0').replace('/', '~1') |
def find_first_diff_pos(str1: str, str2: str) -> int:
"""Finds the first difference position. Returns `-1` if both strings are identical."""
if str1 == str2:
return -1
shorter, longer = sorted((str1, str2), key=len)
shorter_len = len(shorter)
return next(
(i for i in range(shorter_len) if shorter[i] != longer[i]),
shorter_len,
) |
def varint(n):
"""Varint encoding."""
data = b''
while n >= 0x80:
data += bytes([(n & 0x7f) | 0x80])
n >>= 7
data += bytes([n])
return data |
def take(c, *items):
"""
Takes the specified items from collection c, creating a new collection
:param c: The collection to take the items from
:param items: The items to take
:return: the new collection
>>> take([1, 2, 3], 0, 2)
[1, 3]
>>> take((1, 2, 3), 1)
(2,)
>>> take({"a": 1, "b": 2, "c": 3}, "a", "c")
{'a': 1, 'c': 3}
"""
if isinstance(c, tuple):
return tuple(c[i] for i in items)
elif isinstance(c, list):
return [c[i] for i in items]
elif isinstance(c, dict):
return {i: c[i] for i in items} |
def _date_string(x):
"""Convert two integers to a string for the date and time."""
date = x[0] # Date. Example: 19801231
time = x[1] # Time. Example: 1230
return "{0}{1:04d}".format(date, time) |
def get_overlap(a, b):
"""
Retrieve the overlap of two intervals
(number of values common to both intervals).
a and b are supposed to be lists of 2 elements.
"""
return max(-1, min(a[1], b[1]) - max(a[0], b[0]) + 1) |
def sxs_metadata_file_description(representation):
"""Find metadata file from highest Lev for this simulation"""
from os.path import basename
files = representation.get('files', [])
metadata_files = [f for f in files if basename(f.get('filename', '')) == 'metadata.json']
metadata_files = sorted(metadata_files, key=lambda f: f['filename'])
if not metadata_files:
return None
return metadata_files[-1] |
def choices2list(choices_tuple):
"""
Helper function that returns a choice list tuple as a simple list of stored values
:param choices_tuple:
:return:
"""
return [c[0] for c in choices_tuple] |
def green(s):
"""
Return the given string (``s``) surrounded by the ANSI escape codes to
print it in green.
:param s: string to console-color green
:type s: str
:returns: s surrounded by ANSI color escapes for green text
:rtype: str
"""
return "\033[0;32m" + s + "\033[0m" |
def _all_are_equal(list_of_objects):
"""Helper function to check if all the items in a list are the same."""
if not list_of_objects:
return True
if isinstance(list_of_objects[0], list):
list_of_objects = [tuple(obj) for obj in list_of_objects]
return len(set(list_of_objects)) == 1 |
def drop_private_keys(full_dict):
"""Filter for entries in the full dictionary that have numerical values"""
return {key: value for key, value in full_dict.items() if key[0] != '_'} |
def getreltype(reltype):
"""Returns search relation codes for posting requests to http://apps.webofknowledge.com/UA_GeneralSearch.do"""
if reltype == 'and':
rel = 'AND'
elif reltype == 'or':
rel = 'OR'
elif reltype == 'not':
rel = 'NOT'
else:
raise Exception('Error relType invalid')
return rel |
def get_sig_indices(sig_stars_list):
"""
=================================================================================================
get_sig_indices(sig_stars_list)
=================================================================================================
Arguments:
sig_stars_list -> The list of lists of significance stars for the
=================================================================================================
Returns: The indices of lists where significance stars exist.
=================================================================================================
"""
# Use list comprehension to get the indeices where there
# is one or more star characters
return [i for i in range(len(sig_stars_list)) if "*" in sig_stars_list[i] or "**" in sig_stars_list[i] or "***" in sig_stars_list[i]] |
def __to_int(val):
"""Convert val into an integer value."""
try:
return int(val)
except (ValueError, TypeError):
return 0 |
def split_qname(qname):
"""
>>> split_qname("dnstests.fr.")
['.', 'fr.', 'dnstests.fr.']
"""
splitted_qname = qname.split(".")[::-1]
out = []
current = ''
for entry in splitted_qname:
if entry == "":
out.append(".")
else:
current = "%s.%s" % (entry, current)
out.append(current)
return out |
def parse_target_composition_row(r):
"""parse target composition row data in numerical values
Args:
r (str): input row string, like
H 1 061.54 010.60
Returns:
tuple of (
Symbol,
Atomic number,
Atomic Percent,
Mass Percent)
Raises:
Error: raised when number of columns or data is not sufficient.
"""
c = r.split()
d = (
c[0], # Symbol
float(c[1]), # Atomic Number
float(c[2]), # Atomic Percent
float(c[3]) # Mass Percent
)
return d |
def apply(instance, args=()):
"""
Executes instance(*args), but just return None on error occurred
"""
try:
code = instance(*args)
except Exception:
code = None
return code |
def count_list_freq(l):
"""
Find the frequency of elements in a list
"""
freq = {}
for items in l:
freq[items] = l.count(items)
return freq |
def compare_sequences(target, structure, ignore_gaps=True):
"""Compare a template sequence and a target"""
assert len(target['sequence']) == len(structure['sequence'])
match = 0
mismatch = 0
for i in range(len(target['sequence'])):
if (target['sequence'][i] == '-') and (structure['sequence'][i] == '-'):
continue
if (target['sequence'][i] == '-') or (structure['sequence'][i] == '-'):
if ignore_gaps:
continue
else:
mismatch += 1
continue
if target['sequence'][i] == structure['sequence'][i]:
match += 1
else:
mismatch += 1
return match, mismatch |
def sol(num):
"""
By definition of sparse number two 1s cannot be adjacent but zeroes can be
If two 1s are adjacent and we want to make a bigger number we cannot
make the either of the bits 0, so only option left is we make the third
bit 1 if it is 0 or we add an extra bit
"""
b = list(bin(num)[2:])
b.insert(0, "0")
# We might have to add an extra bit lets add it.
# Adding a zero does not change the number
#print(b)
n = len(b)
i=n-2
while i >= 1:
# Search for the sequence where two adjacents bits are set and the
# third bit to the left is not set and unset all the bits to its right
# including both the set bits
if b[i] == b[i+1] == "1" and b[i-1] == "0":
for j in range(i, n):
b[j] = '0'
b[i-1] = "1"
# Set the third bit
i-=1
num = 0
n = len(b)
#print(b)
for i in range(n):
p = n-1-i
num += int(b[i])*(2**p)
return num |
def get_filter_by(by):
"""
convert the filter parameters from the client to list of string with the Keepers API format
:param by: input dictionary from the client
:return: filter by list to match the Keepers API
"""
filter_parameters = ["easy", "heavy", "medium"]
output = []
for key, value in by.items():
for param in filter_parameters:
if param in str(key).lower() and value:
output.append(param)
return output |
def _set_extra_info(extra_info):
"""Check input and return extra_info dictionary."""
if extra_info is None:
return {}
if isinstance(extra_info, dict):
return extra_info
raise RuntimeError(
"extra_info must be None or a dict, but got {}".format(extra_info)
) |
def pretty_print_table(table, bar_color_func, value_color_func):
"""Pretty-print the given Table"""
column_widths = [max(len(str(col)) for col in row) for row in zip(*table)]
colored_bar = bar_color_func("|")
pretty_table = []
for row in table:
pretty_row = "{0} {1} {0}".format(
colored_bar,
bar_color_func(" | ").join(
value_color_func("{1: <{0}}").format(column_widths[col_idx], col_value)
for col_idx, col_value in enumerate(row)
),
)
pretty_table.append(pretty_row)
return "\n".join(pretty_table) |
def parseMinutes(mn):
"""returns a textual form of minutes"""
mn = list(map(lambda x: int(x), mn))
fp = ['oh', '', 'twenty', 'thirty', 'fourty', 'fifty', 'sixty'][mn[0]]
sp = ['','one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'][mn[1]]
result = "{} {}".format(fp * (not mn[0]==mn[1]== 0), sp)
if mn[0] == 1:
result = ['ten', 'elevn', 'twelve', 'thirteen', 'fourteen','fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen'][mn[1]]
return result |
def numderiv(f, xs):
"""numderiv(f, xarray): Numerical differentiation."""
n = len(xs)
list = []
# f'(x) ~= [ f(x+h) - f(x) ] / h
x0 = xs[0]; x1 = xs[1]
y0 = f(x0); y1 = f(x1)
list.append((y1 - y0) / (x1 - x0))
for i in range(1, n-1):
# f'(x) ~= [ f(x+h) - f(x-h) ] / 2h
x0 = xs[i-1]; x1 = xs[i+1]
y0 = f(x0); y1 = f(x1)
list.append((y1 - y0) / (x1 - x0))
# f'(x) ~= [ f(x) - f(x-h) ] / h
x0 = xs[n-2]; x1 = xs[n-1]
y0 = f(x0); y1 = f(x1)
list.append((y1 - y0) / (x1 - x0))
return list |
def get_smiles_of_user_entity_ids(cursor, unification_table, user_entity_ids):
"""
Get the smiles using their BIANA user entity ids
"""
query_smiles = ("""SELECT SM.value, DB.databaseName
FROM externalEntitySMILES SM, {} U, externalEntity E, externalDatabase DB
WHERE U.externalEntityID = SM.externalEntityID AND SM.externalEntityID = E.externalEntityID AND E.externalDatabaseID = DB.externalDatabaseID AND U.userEntityID = %s
""".format(unification_table))
print('\nRETRIEVING SMILES IDS ASSOCIATED TO USER ENTITY IDS...\n')
ueid_to_smiles_to_databases = {}
for ueid in user_entity_ids:
cursor.execute(query_smiles, (ueid,))
for row in cursor:
smiles, database = row
#print(ueid, smiles)
ueid_to_smiles_to_databases.setdefault(ueid, {})
ueid_to_smiles_to_databases[ueid].setdefault(smiles, set()).add(database)
print('NUMBER OF USER ENTITIES ASSOCIATED WITH SMILES IDS: {}'.format(len(ueid_to_smiles_to_databases)))
return ueid_to_smiles_to_databases |
def interpret_blockstructures(blockstructures):
"""Conversion between short-hand and long-hand
for MTL block structures.
"""
conversion = {
'I' : 'trueshare',
'Y' : 'mhushare',
'V' : 'split',
'W' : 'attenshare',
}
labels = []
for blockstructure in blockstructures:
labels.append(conversion[blockstructure])
return labels |
def hex2rgb(hexstr):
"""
Convert a hexadecimal color format to RGB array
"""
_str = hexstr.lstrip("#")
rgb = [int(_str[k:k+2],16) for k in range(0,len(_str),2)]
return rgb |
def __renumber(dictionary):
"""Renumber the values of the dictionary from 0 to n
"""
values = set(dictionary.values())
target = set(range(len(values)))
if values == target:
# no renumbering necessary
ret = dictionary.copy()
else:
# add the values that won't be renumbered
renumbering = dict(zip(target.intersection(values),
target.intersection(values)))
# add the values that will be renumbered
renumbering.update(dict(zip(values.difference(target),
target.difference(values))))
ret = {k: renumbering[v] for k, v in dictionary.items()}
return ret |
def create_entry_dict(column_type: str, column_value: str) -> dict:
"""
Creates an entry dictionary
"""
return {"type": column_type, "value": column_value} |
def to_float_hours(hours, minutes, seconds):
""" (int, int, int) -> float
Return the total number of hours in the specified number
of hours, minutes, and seconds.
Precondition: 0 <= minutes < 60 and 0 <= seconds < 60
>>> to_float_hours(0, 15, 0)
0.25
>>> to_float_hours(2, 45, 9)
2.7525
>>> to_float_hours(1, 0, 36)
1.01
"""
return hours + (minutes/60) + (seconds/3600) |
def clean_doc(name: str) -> str:
"""Returns a clean docstring"""
# replace_map = {
# " ": " ",
# " ": " ",
# " ": " ",
# " ": ",",
# " ": " ",
# "\n": " ",
# "\n\n": " ",
# }
# for k, v in list(replace_map.items()):
# name = name.replace(k, v)
# name = ",".join(name.split('\n'))
# name = " ".join(name.split())
return name |
def flatten(l):
"""
Parameters:
l (list) -- input list 2d array list
Returns:
(list) -- output list flatten
"""
return [item for sublist in l for item in sublist] |
def tail( f, lines ):
"""
https://stackoverflow.com/questions/136168/get-last-n-lines-of-a-file-with-python-similar-to-tail
Parameters
----------
f : opened file object
This is not the name of the file, but the object returned from Python open().
lines : integer
Number of lines desired from the tail end of the file.
"""
if lines == 0:
return []
BUFSIZ = 1024
f.seek(0, 2)
remaining_bytes = f.tell()
size = lines + 1
block = -1
data = []
while size > 0 and remaining_bytes > 0:
if remaining_bytes - BUFSIZ > 0:
# Seek back one whole BUFSIZ
f.seek(block * BUFSIZ, 2)
# read BUFFER
bunch = f.read(BUFSIZ)
else:
# file too small, start from beginning
f.seek(0, 0)
# only read what was not read
bunch = f.read(remaining_bytes)
bunch = bunch.decode('utf-8')
data.insert(0, bunch)
size -= bunch.count('\n')
remaining_bytes -= BUFSIZ
block -= 1
return ''.join(data).splitlines()[-lines:] |
def difference_update(d: dict, remove) -> dict:
"""Change and return d.
d: mutable mapping, remove: iterable.
There is such a method for sets, but unfortunately not for dicts.
>>> d = {'a': 1, 'b': 2, 'c': 3}
>>> remove = ('b', 'outlier')
>>> d_altered = difference_update(d, remove)
>>> d_altered is d
True
>>> d == {'a': 1, 'c': 3}
True
"""
for k in remove:
if k in d:
del(d[k])
return d # so that we can pass a call to this fn as an arg, or chain |
def isPracticalFactorization(f):
"""Test whether f is the factorization of a practical number."""
f = list(f.items())
f.sort()
sigma = 1
for p,x in f:
if sigma < p - 1:
return False
sigma *= (p**(x+1)-1)//(p-1)
return True |
def translate(mRNA):
""" this funtion is translate mRNA to protein. """
TranList = {
'ATA':'I', 'ATC':'I', 'ATT':'I', 'ATG':'M',
'ACA':'T', 'ACC':'T', 'ACG':'T', 'ACT':'T',
'AAC':'N', 'AAT':'N', 'AAA':'K', 'AAG':'K',
'AGC':'S', 'AGT':'S', 'AGA':'R', 'AGG':'R',
'CTA':'L', 'CTC':'L', 'CTG':'L', 'CTT':'L',
'CCA':'P', 'CCC':'P', 'CCG':'P', 'CCT':'P',
'CAC':'H', 'CAT':'H', 'CAA':'Q', 'CAG':'Q',
'CGA':'R', 'CGC':'R', 'CGG':'R', 'CGT':'R',
'GTA':'V', 'GTC':'V', 'GTG':'V', 'GTT':'V',
'GCA':'A', 'GCC':'A', 'GCG':'A', 'GCT':'A',
'GAC':'D', 'GAT':'D', 'GAA':'E', 'GAG':'E',
'GGA':'G', 'GGC':'G', 'GGG':'G', 'GGT':'G',
'TCA':'S', 'TCC':'S', 'TCG':'S', 'TCT':'S',
'TTC':'F', 'TTT':'F', 'TTA':'L', 'TTG':'L',
'TAC':'Y', 'TAT':'Y', 'TAA':'_', 'TAG':'_',
'TGC':'C', 'TGT':'C', 'TGA':'_', 'TGG':'W',
}
protein = ""
if len(mRNA) % 3 == 0:
for i in range(0,len(mRNA),3):
codon = mRNA[i:i+3]
protein += TranList[codon]
return protein |
def _assert_tensors_equal(a, b, atol=1e-12, prefix=""):
"""If tensors not close, or a and b arent both tensors, raise a nice Assertion error."""
if a is None and b is None:
return True
try:
if _assert_tensors_equal(a, b, atol=atol):
return True
raise
except Exception:
if len(prefix) > 0:
prefix = f"{prefix}: "
raise AssertionError(f"{prefix}{a} != {b}") |
def last_node(level: int, *, fanout: int) -> int:
"""Return the last node at `level`."""
return (fanout ** (level + 1) - 1) // (fanout - 1) |
def collatz_odd(number):
"""Return 3n+1 for a given number."""
return (number * 3) + 1 |
def is_scalar(value):
"""Checks if the supplied value can be converted to a scalar."""
try:
float(value)
except (TypeError, ValueError):
return False
else:
return True |
def query_humanize(str,fieldname,table,is_string=True):
"""
busca en 'str' un asignacion del campo 'fieldname'
para cambiarlo por el format de la 'table'
y con el is_string = True tiene en cuenta que sea un cadena
"""
sep='"' if is_string else ' '
strout=str
fieldname0=fieldname+"="+sep
i=str.find(fieldname0)
if i>-1:
i=i+len(fieldname0)
f=str.find(sep,i+1)
if f==-1: f=len(str)
id=str[i:f]
row=table[id]
if row:
name=table._format(table[id])
strout= str[:i]+name.flatten()+str[f:]
return strout |
def sone_aproximation(loudness_level: float) -> float:
"""
loudness_level: in phon, >40
typically between 1 and 1024
"""
return 2 ** ((loudness_level-40)/float(10)) |
def sim_minmax(column):
"""Similarity score using the range between min and max
for a value
Args:
column: a given feature column
Returns:
tuple: A tuple of the form (min, max)
"""
return min(column), max(column) |
def listmode(lst: list):
"""
Get the most frequently occurring value in a list.
"""
return max(set(lst), key=lst.count) |
def strip_off_start(s: str, pre: str) -> str:
"""
Strips the full string `pre` from the start of `str`.
See `Tools.strip_off` for more info.
"""
assert isinstance(pre, str), "{} is not a string".format(pre)
if s.startswith(pre):
s = s[len(pre):]
return s |
def sanitize_cr(clientscoperep):
""" Removes probably sensitive details from a clientscoperep representation
:param clientscoperep: the clientscoperep dict to be sanitized
:return: sanitized clientrep dict
"""
result = clientscoperep.copy()
if 'secret' in result:
result['secret'] = 'no_log'
if 'attributes' in result:
if 'saml.signing.private.key' in result['attributes']:
result['attributes']['saml.signing.private.key'] = 'no_log'
return result |
def _pf1d1(val1, val2):
"""
"""
return int(val1 + int(val2[0])) |
def _safe_filter_fun(filter_function, d, i):
"""Helper function that returns False if an exception occurs instead of stopping the loop."""
try:
return filter_function(d, i)
except:
return False |
def index_to_sq(ix):
"""Convert an index to a column and rank"""
return (ix % 8, ix // 8) |
def check_validity(option):
"""Check if the input received is a valid digit 1 to 4 inclusive."""
if option.isdigit():
numeric_option = int(option)
if numeric_option >=1 and numeric_option <= 5:
return numeric_option
else:
return -1
else:
return -1 |
def choices_to_dict_list(choices):
"""
:param choices:
:return:
"""
if not choices:
return None
results = []
for k, v in choices:
results.append({
'value': k,
'display_name': v
})
return results |
def unfold(vc: set, folded_verts: list):
"""
Compute final vc given the partial vc and list of folded vertices (unreversed)
:param vc: partial vc as a set
:param folded_verts: list of folded vertices as 3-tuples
:return: final vertex cover as a set
"""
final_vc = set(vc)
for u, v, w in folded_verts[::-1]:
if u in final_vc:
final_vc.remove(u)
final_vc.add(v)
final_vc.add(w)
else:
final_vc.add(u)
return final_vc |
def cleanup_document_keys(document_keys):
"""
Cleaning up key/value pairs that have empty values from CouchDB search request
"""
if document_keys:
del_list = []
for key, value in document_keys.iteritems():
if not value:
del_list.append(key)
for key in del_list:
del document_keys[key]
return document_keys |
def take(n, seq):
"""Returns first n values from the given sequence."""
seq = iter(seq)
result = []
try:
for i in range(n):
result.append(next(seq))
except StopIteration:
pass
return result |
def validate_input_cli(user_input):
"""
This function validates the input of the user during 2nd menu
:param user_input:
:return: bool
"""
if user_input in ('0', '1', '2', '3'):
return True
return False |
def tournamentWinner(competitions, results):
"""
### Description
tournamentWinner returns the team with the best score.
### Parameters
- competitions: matrix containing the teams' names in each match.
- results: list containing the result of every competition.
### Returns
The name of the best team.
"""
competitors = {"": 0}
bestTeam = ""
currentMatch = 0
while currentMatch < len(results):
winner = competitions[currentMatch][0] if results[currentMatch] == 1 else competitions[currentMatch][1]
if winner in competitors:
competitors[winner] = competitors[winner] + 3
else:
competitors[winner] = 3
if competitors[bestTeam] < competitors[winner]:
bestTeam = winner
currentMatch += 1
return bestTeam |
def get_techno_dicts_translator(ref_techno_dict, new_techno_dict):
""" Return dict where k, v are resp. indices in reference and new techno matrix
Applicable to both products (rows in A matrix) and
activities (columns in A and B matrices)
The names of the databases do not need to be the same, but the codes
should be common
"""
ref_bd_name = list(ref_techno_dict.keys())[0][0]
new_bd_name = list(new_techno_dict.keys())[0][0]
return {ref_techno_dict[(ref_bd_name, k[1])]: new_techno_dict[(new_bd_name, k[1])] for k in
new_techno_dict.keys()} |
def create_bounty_submissions_response(submissions, **kwargs):
""" returns a submission response from the given submissions. """
return {
'submissions': submissions,
'meta': {
'count': kwargs.get('count', len(submissions)),
'offset': kwargs.get('offset', None),
'total_hits': kwargs.get('total_hits', len(submissions)),
},
} |
def mention_user_nick_by_id(user_id):
"""
Mentions the user's "nick" by the user's identifier.
Parameters
----------
user_id : `int`
The user's identifier.
Returns
-------
user_nick_mention : `str`
"""
return f'<@!{user_id}>' |
def add(key, old, new):
""" doc me """
if key in old:
new[key] = old[key]
return new |
def compose_aug_inchi_key(inchi_key, ulayer=None, player=None):
"""
Composes an augmented InChI Key by concatenating the different pieces
as follows:
XXXXXXXXXXXXXX-XXXXXXXXXX-ux,x,xxx
Uses hyphens rather than forward slashes to avoid messing up file paths.
"""
aug_inchi_key = inchi_key
for layer in filter(None, [ulayer, player]):
aug_inchi_key += '-' + layer[1:]#cut off the '/'
return aug_inchi_key |
def attachments(*args):
"""Simple attachments base element containing multiple attachment"""
return {'attachments': [*args]} |
def as_currency(amount, rate):
"""
Formats the given amount as a currency.
:type amount: Number (int or float).
:param rate: Multiply 'amount' by 'rate'.
:return: String in the format of "200.00".
"""
total = float(amount) * float(rate)
str_total = "{:,.2f} test test".format(total)
return str_total |
def make_args(opts):
"""
Converts a dict to a helm-style --set and --set-string arguments.
Helm allows you to set one property at a time, which is desirable because
it's effectively a merge.
The drawback is the redundancy and readability.
This function allows a dict to represent all of the options.
"""
args = ""
def recurse(candidate, accumulator=""):
nonlocal args
if isinstance(candidate, dict):
nonlocal args
for k, v in candidate.items():
dotOrNot = "" if accumulator == "" else f"{accumulator}."
recurse(v, f"{dotOrNot}{k}")
elif isinstance(candidate, str):
args += f'--set-string {accumulator}="{candidate}" '
elif isinstance(candidate, int):
args += f"--set {accumulator}={candidate} "
else:
raise ValueError("Leaves must be strings or ints.")
recurse(opts)
return args |
def human_string(text: str) -> str:
"""
Transform text to human string
Args:
text: string to be converted
Returns:
converted string
Examples:
>>> human_string('test_str')
'Test Str'
>>> human_string("")
''
"""
if not text:
return ""
return ' '.join(word.title() for word in text.split('_')) |
def _find_used(activity, predicate):
"""Finds a particular used resource in an activity that matches a predicate."""
for resource in activity['used']:
if predicate(resource):
return resource
return None |
def extract_ids(records):
"""
Given a list of records from a remote server, return a list of ids contained therein.
"""
ids = []
for record in records:
ids.append(record['id'])
return ids |
def get_references(name, references):
"""Generate section with references for given operator or module"""
name = name[12:] # remove nvidia.dali prefix
result = ""
if name in references:
result += ".. seealso::\n"
for desc, url in references[name]:
result += f" * `{desc} <../{url}>`_\n"
return result |
def read_emo_lemma(aline):
"""
Splits a line into lemma l, emotion e, and l(e).
l(e) := 1 if lemma l has emotion e according to the lexicon
l(e) := 0 otherwise
"""
split = aline.split()
return split[0], split[1], int(split[2]) |
def remove_closest_element(x,l):
"""
removes the closest element, to be used in conjunction with the previous function
"""
temp=[]
for i in l:
temp.append(abs(x-i))
u=min(temp)
for j in l:
if abs(x-j)==u:
l.remove(j)
return l |
def partition_node(node):
"""Split a host:port string into (host, int(port)) pair."""
host = node
port = 27017
idx = node.rfind(':')
if idx != -1:
host, port = node[:idx], int(node[idx + 1:])
if host.startswith('['):
host = host[1:-1]
return host, port |
def clean_list(input_list):
"""removes unnecessary characters from a list."""
output_list = list()
for i in input_list:
var = i.replace('\n', '')
output_list.append(var)
return output_list |
def calc_iou(box_a, box_b):
"""
Calculate the Intersection Over Union of two boxes
Each box specified by upper left corner and lower right corner:
(x1, y1, x2, y2), where 1 denotes upper left corner, 2 denotes lower right corner
Returns IOU value
"""
# Calculate intersection, i.e. area of overlap between the 2 boxes (could be 0)
# http://math.stackexchange.com/a/99576
x_overlap = max(0, min(box_a[2], box_b[2]) - max(box_a[0], box_b[0]))
y_overlap = max(0, min(box_a[3], box_b[3]) - max(box_a[1], box_b[1]))
intersection = x_overlap * y_overlap
# Calculate union
area_box_a = (box_a[2] - box_a[0]) * (box_a[3] - box_a[1])
area_box_b = (box_b[2] - box_b[0]) * (box_b[3] - box_b[1])
union = area_box_a + area_box_b - intersection
iou = intersection / union
return iou |
def list_(project_id, user_id=None, **kwargs):
"""List quotas of a project (and user)"""
url = '/os-quota-sets/%s' % project_id
if user_id:
url = '%s?user_id=%s' % (url, user_id)
return url, {} |
def counting_sort(arr: list) -> list:
"""
Time Complexity: O(n+k), where k is the range of values
Space Complexity: O(k)
"""
first, last = min(arr), max(arr)
count_arr: list = [0] * (last - first + 1)
for integer in arr:
count_arr[integer - first] += 1
for index in range(1, len(count_arr)):
count_arr[index] += count_arr[index - 1]
res_arr: list = [0] * len(arr)
for integer in arr:
res_arr[count_arr[integer - first] - 1] = integer
count_arr[integer - first] -= 1
return res_arr |
def blacklist_ports(ports, blacklist):
"""
Removes port present on the blacklist
"""
new_ports = dict()
for key, ports in ports.items():
new_ports[key] = []
for name, width, assoc_clock in ports:
if name not in blacklist:
new_ports[key].append([name, width, assoc_clock])
return new_ports |
def _get_min_max_value(min, max, value=None, step=None):
"""Return min, max, value given input values with possible None."""
if value is None:
if not max > min:
raise ValueError('max must be greater than min: (min={0}, max={1})'.format(min, max))
value = min + abs(min-max)/2
value = type(min)(value)
elif min is None and max is None:
if value == 0.0:
min, max, value = 0.0, 1.0, 0.5
elif value == 0:
min, max, value = 0, 1, 0
elif isinstance(value, (int, float)):
min, max = (-value, 3*value) if value > 0 else (3*value, -value)
else:
raise TypeError('expected a number, got: %r' % value)
else:
raise ValueError('unable to infer range, value from: ({0}, {1}, {2})'.format(min, max, value))
if step is not None:
# ensure value is on a step
r = (value - min) % step
value = value - r
return min, max, value |
def hasblocks(hashlist):
"""Determines which blocks are on this server"""
print("HasBlocks()")
return hashlist |
def delta_percent(a, b, warnings=False):
"""(float, float) => float
Return the difference in percentage between a nd b.
If the result is 0.0 return 1e-09 instead.
>>> delta_percent(20,22)
10.0
>>> delta_percent(2,20)
900.0
>>> delta_percent(1,1)
1e-09
>>> delta_percent(10,9)
-10.0
"""
# np.seterr(divide='ignore', invalid='ignore')
try:
x = ((float(b) - a) / abs(a)) * 100
if x == 0.0:
return 0.000000001 # avoid -inf
else:
return x
except Exception as e:
if warnings:
print(f"Exception raised by delta_percent(): {e}")
return 0.000000001 |
def _deg_ord_idx(deg, order):
"""Get the index into S_in or S_out given a degree and order."""
# The -1 here is because we typically exclude the degree=0 term
return deg * deg + deg + order - 1 |
def levenshtein_distance(a, b):
"""Calculates the Levenshtein distance between a and b."""
n, m = len(a), len(b)
if n > m:
# Make sure n <= m, to use O(min(n,m)) space
a,b = b,a
n,m = m,n
current = range(n+1)
for i in range(1, m+1):
previous, current = current, [i] + [0] * n
for j in range(1, n+1):
add, delete = previous[j] + 1, current[j-1] + 1
change = previous[j-1]
if a[j-1] != b[i-1]:
change = change + 1
current[j] = min(add, delete, change)
return current[n] |
def split_lengths_for_ratios(nitems, *ratios):
"""Return the lengths of the splits obtained when splitting nitems
by the given ratios"""
lengths = [int(ratio * nitems) for ratio in ratios]
i = 1
while sum(lengths) != nitems and i < len(ratios):
lengths[-i] += 1
i += 1
assert sum(lengths) == nitems, f'{sum(lengths)} != {nitems}\n{ratios}'
return lengths |
def numberformat(value):
"""Formats value as comma-separated"""
return f"{value:,.0f}" |
def convert_tag(t):
"""Converts tags so that they can be used by WordNet:
| Tag begins with | WordNet tag |
|-----------------|-------------|
| `N` | `n` |
| `V` | `v` |
| `J` | `a` |
| `R` | `r` |
| Otherwise | `None` |
"""
if t[0].lower() in {'n', 'v', 'r'}:
return t[0].lower()
elif t[0].lower() == 'j':
return 'a'
else:
return None |
def yubico_verify_false(yubikey_otp):
"""
utils.yubikey_authenticate function that will always return False
:param yubikey_otp: Yubikey OTP
:type yubikey_otp: str
:return: True
:rtype: Boolean
"""
# Take exactly 1 argument which we will happily ignore afterwards
assert yubikey_otp
return False |
def get_mlp_default_settings(kind):
"""Get default setting for mlp model."""
if kind == "hidden_sizes":
return [64, 64]
elif kind == "activation":
return "tanh"
else:
raise KeyError("unknown type: {}".format(kind)) |
def _analyze_system_results(results):
"""
This helper method get list of results internal dict and return if test failed or not with summary log
return dict with keys:
1. state - true\false for passing test
2. failures - list of not passing services
3. pass = list of passing services
"""
failed_services = []
running_services = []
state = True
for res in results:
if not res['url_valid']:
state = False
failed_services.append(f'Service {res["name"]} failed with details: {res}')
else:
res['content'] = 'Exists'
running_services.append(f'Service {res["name"]} pass with details: {res}')
results_dict = {'state': state, 'failure': failed_services, 'pass': running_services}
return results_dict |
def formatFilename(prefix,
width, height, depth,
bits, unsigned):
"""
Generates a filename using a prefix and the base parameters of all images.
"""
return format("%s_%dx%dx%d_%d%s") % (prefix,
width, height, depth,
bits, "u" if unsigned == 0 else "s" ) |
def check_dfs_empty(fetched_data_dict):
"""Check whether dataframes saved in dictionary are all empty
Argumentss:
*fetched_data_dict*: dictionary with df saved as valyes
Returns:
True if all dataframes are empty, or false when at least one dataframe is not empty
"""
fetched_data_empty = []
for group in fetched_data_dict:
fetched_data_empty.append(fetched_data_dict[group].empty)
return all(elem == True for elem in fetched_data_empty) |
def angle_difference(angle1: float, angle2: float) -> float:
"""The difference of two angle values.
Args:
angle1, angle2:
The values are expected in degrees.
Returns:
Value in the range [-180.0, 180.0]"""
return (abs(angle1 - angle2) + 180) % 360 - 180 |
def line_to_tensor(line, EOS_int=1):
"""Turns a line of text into a tensor
Args:
line (str): A single line of text.
EOS_int (int, optional): End-of-sentence integer. Defaults to 1.
Returns:
list: a list of integers (unicode values) for the characters in the `line`.
"""
# Initialize the tensor as an empty list
tensor = []
# for each character:
for c in line:
# convert to unicode int
c_int = ord(c)
# append the unicode integer to the tensor list
tensor.append(c_int)
# include the end-of-sentence integer
tensor.append(EOS_int)
return tensor |
def is_fq(name):
"""Return True if the supplied 'name' is fully-qualified, False otherwise.
Usage examples:
>>> is_fq('master')
False
>>> is_fq('refs/heads/master')
True
:name: string name of the ref to test
:returns: bool
"""
return name.startswith('refs/') |
def _get_fuzzer_module_name(fuzzer: str) -> str:
"""Returns the name of the fuzzer.py module of |fuzzer|. Assumes |fuzzer| is
an underlying fuzzer."""
return 'fuzzers.{}.fuzzer'.format(fuzzer) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.