content stringlengths 42 6.51k |
|---|
def color_temp_post_response_ok(devid, color_temp):
"""Return color temp change response json."""
return '''
{
"idForPanel": "''' + devid + '''",
"colorTemperature": ''' + str(int(color_temp)) + '''
}''' |
def moment_from_magnitude(magnitude):
"""
Compute moment from moment magnitude.
Args:
magnitude (float):
Moment magnitude.
Returns:
float: Seismic moment (dyne-cm).
"""
# As given in Boore (2003):
# return 10**(1.5 * magnitude + 10.7)
# But this appears to be correct:
return 10**(1.5 * magnitude + 16.05) |
def deep_update(a, b):
"""Updates data structures
Dicts are merged, recursively
List b is appended to a (except duplicates)
For anything else, the value of a is returned"""
if type(a) is dict and type(b) is dict:
for key in b:
if key in a:
a[key] = deep_update(a[key], b[key])
else:
a[key] = b[key]
return a
if type(a) is list and type(b) is list:
return a + [i for i in b if i not in a]
return a if a is not None else b |
def bit_not(n: int, numbits: int = 64):
""" Python's ints are signed, so use this instead of tilda """
return (1 << numbits) - 1 - n |
def change_from_change_spec(change):
"""Converts a change in change_spec format to buildbucket format.
For more info on change_spec format, see
master.chromium_step.AnnotationObserver.insertSourceStamp.
Buildbucket change format is described in README.md.
"""
create_ts = None
if 'when_timestamp' in change:
# Convert from seconds to microseconds since Unix Epoch.
assert isinstance(change['when_timestamp'], (int, float))
create_ts = change['when_timestamp'] * 1000 * 1000
return {
'revision': change.get('revision'),
'author': {
# Assuming author is email.
'email': change.get('author'),
},
'create_ts': create_ts,
'files': [{'path': f} for f in change.get('files', [])],
'message': change.get('comments'),
'branch': change.get('branch'),
'url': change.get('revlink'),
'project': change.get('project'),
} |
def string_to_ascii(string: str):
"""return string of ascii characters with _ as seperator"""
return '_'.join(str(ord(c)) for c in string) |
def partition(items, low, high):
"""Return index `p` after in-place partitioning given items in range
`[low...high]` by choosing a pivot (The last item) from
that range, moving pivot into index `p`, items less than pivot into range
`[low...p-1]`, and items greater than pivot into range `[p+1...high]`.
Running time: O(n) as it loops over each element once
Memory usage: O(1) as it declares a constant number of variables
"""
# Last item is pivot
pivot = items[high]
i = low # Left counter
j = high - 1 # Right counter
# Loop until left meets right
while i < j:
# Count down until finding a smaller item
if items[j] >= pivot:
j -= 1
# Count up until finding a larger item
if items[i] < pivot:
i += 1
# If two items are in the wrong place, switch them
if items[i] >= pivot and items[j] < pivot:
items[i], items[j] = items[j], items[i]
j -= 1
i += 1
# Put pivot into the right place
if items[i] < pivot:
i += 1
items[i], items[high] = items[high], items[i]
return i |
def clean_parsons_lines(code_lines):
"""Return list of lines of code, stripped of whitespace.
Args:
code (list): Code to be cleaned.
Returns:
List of cleaned code.
"""
clean_lines = list()
for line in code_lines:
stripped_line = line.strip()
if stripped_line:
clean_lines.append(stripped_line)
return clean_lines |
def split_thousands(s, tSep='\'', dSep='.'):
"""
Splits a number on thousands.
http://code.activestate.com/recipes/498181-add-thousands-separator-commas-to-formatted-number/
>>> split_thousands(1000012)
"1'000'012"
"""
# Check input #
if s is None: return 0
# Check for int #
if round(s, 13) == s: s = int(s)
# Make string #
if not isinstance(s, str): s = str(s)
# Unreadable code #
cnt = 0
numChars = dSep + '0123456789'
ls = len(s)
while cnt < ls and s[cnt] not in numChars: cnt += 1
lhs = s[0:cnt]
s = s[cnt:]
if dSep == '': cnt = -1
else: cnt = s.rfind(dSep)
if cnt > 0:
rhs = dSep + s[cnt+1:]
s = s[:cnt]
else:
rhs = ''
splt=''
while s != '':
splt= s[-3:] + tSep + splt
s = s[:-3]
return lhs + splt[:-1] + rhs |
def get_src_ids(sources):
"""
:returns:
a string with the source IDs of the given sources, stripping the
extension after the colon, if any
"""
src_ids = []
for src in sources:
long_src_id = src.source_id
try:
src_id, ext = long_src_id.rsplit(':', 1)
except ValueError:
src_id = long_src_id
src_ids.append(src_id)
return ' '.join(set(src_ids)) |
def hasZ(pointlist):
""" determine if points inside coordinates have Z values """
points = pointlist[0]
first = points[0]
if len(first) == 3:
return True
else:
return False |
def _param_fort_validation(args):
"""Validates the input parameters for the forward models
Returns
-------
input_args : dict
Dictionary with the input parameters for the forward models.
"""
temp = args.get('ptemp', 1000)
chem = args.get('pchem', 'noTiO')
cloud = args.get('cloud', '0')
pmass = args.get('pmass', '1.5')
m_unit = args.get('m_unit', 'M_jup')
reference_radius = args.get('refrad', 1)
r_unit = args.get('r_unit', 'R_jup')
rstar = args.get('rstar', 1)
rstar_unit = args.get('rstar_unit', 'R_sun')
input_args = {'temp': temp, 'chem': chem, 'cloud': cloud, 'pmass': pmass,
'm_unit': m_unit, 'reference_radius': reference_radius,
'r_unit': r_unit, 'rstar': rstar, 'rstar_unit': rstar_unit}
return input_args |
def has_one_of_attributes(node,*args) :
"""
Check whether one of the listed attributes is present on a (DOM) node.
@param node: DOM element node
@param args: possible attribute names
@return: True or False
@rtype: Boolean
"""
if len(args) == 0 :
return None
if isinstance(args[0], tuple) or isinstance(args[0], list) :
rargs = args[0]
else :
rargs = args
return True in [ node.hasAttribute(attr) for attr in rargs ] |
def latex_float(f):
"""
Convert floating point number into latex-formattable string for visualize.
Might relocate to viz.py
Args:
f (float): A floating point number
Returns:
float_str (str): A latex-formatted string representing f.
"""
float_str = "{0:.3g}".format(f)
if "e" in float_str:
base, exponent = float_str.split("e")
return r"{0} \times 10^{{{1}}}".format(base, int(exponent))
else:
return float_str |
def f(x): # 2
"""Simple recursive function.""" # 3
if x == 0: # 4
return 1 # 5
return 1 + f(x - 1) |
def render_user_label(user):
"""Returns a HMTL snippet which can be inserted for user representation.
"""
return {
'user': user
} |
def process_key(key: str) -> str:
"""
This function is for creating safe keys
Currently this only replaces '..', should be expanded to be (or use) a full sanitizer in the future
"""
key = key.replace("..", "__") # Don't allow keys to traverse back a directory
return key |
def RefundablePayrollTaxCredit(was_plus_sey_p, was_plus_sey_s,
RPTC_c, RPTC_rt,
rptc_p, rptc_s, rptc):
"""
Computes refundable payroll tax credit amounts.
"""
rptc_p = min(was_plus_sey_p * RPTC_rt, RPTC_c)
rptc_s = min(was_plus_sey_s * RPTC_rt, RPTC_c)
rptc = rptc_p + rptc_s
return (rptc_p, rptc_s, rptc) |
def _hostname_simple(hostname):
""" Strips off domain name, ".(none)", etc """
if hostname[0].isdigit():
return hostname # IP address
return hostname.split('.')[0] |
def days_until_launch(current_day, launch_day):
""""Returns the days left before launch.
current_day (int) - current day in integer
launch_day (int) - launch day in integer
"""
day=launch_day - current_day
return( day if day >= 0 else 0) |
def tokenize_table_name(full_table_name):
"""Tokenize a BigQuery table_name.
Splits a table name in the format of 'PROJECT_ID.DATASET_NAME.TABLE_NAME' to
a tuple of three strings, in that order. PROJECT_ID may contain periods (for
domain-scoped projects).
Args:
full_table_name: BigQuery table name, as PROJECT_ID.DATASET_NAME.TABLE_NAME.
Returns:
A tuple of project_id, dataset_name, and table_name.
Raises:
ValueError: If full_table_name cannot be parsed.
"""
delimiter = '.'
tokenized_table = full_table_name.split(delimiter)
if not tokenized_table or len(tokenized_table) < 3:
raise ValueError('Table name must be of the form '
'PROJECT_ID.DATASET_NAME.TABLE_NAME')
# Handle project names with periods, e.g. domain.org:project_id.
return (delimiter.join(tokenized_table[:-2]),
tokenized_table[-2],
tokenized_table[-1]) |
def check_if_all_tss_are_bad(tss):
""" Check if all time series in a list are not good.
'Not good' means that a time series is None or all np.nan
"""
def bad(ts):
return True if ts is None else ts.isnull().all()
return all([bad(ts) for ts in tss]) |
def get_options(args, mutators, converters={}):
"""
Returns a list of 2-tuple in the form (option, value) for all options
contained in the `mutators` collection if they're also keys of the `args`
and have a non-None value. If the option (non- prefixed) is also a key of
the `converters` dictionary then the associated value should be another
dictionary indicating convertions to be done on the value found in `args`.
e.g.
args = {'deadline': 'none'}
mutators = {'deadline'}
converters = {'deadline': {'none': None}}
=> [('deadline', None)]
"""
options = []
for mutator in mutators:
if mutator in args and args[mutator] is not None:
val = args[mutator]
convertions = converters.get(mutator)
if convertions is not None and val in convertions:
val = convertions[val]
options.append((mutator, val))
return options |
def parse_int_or_float(src, key, nentries=1):
"""
Parse a dictionary ``src`` and return an int or float or a list of int or
float specified by ``key``. This function checks that the value or values
specified by ``key`` is of type int or float or list of int or float and
raises a ``ValueError`` otherwise.
:param dict src: the source dictionary
:param str key: the key specifing the directory name
:param int nentries: the number of floats to parse
:returns: read float(s)
:rtype: float or list of float
:raises ValueError: if the parsed values are not valid
:raises KeyError: if the attribute ``key`` is not found in ``src``
"""
if nentries < 1:
raise ValueError('expected number of entries must be greater than zero')
if key in src:
val = src.get(key)
if type(val) == int or type(val) == float:
if nentries != 1:
msg = 'attribute ' + key + ' has 1 entry, expected ' + str(nentries)
raise ValueError(msg)
return val
elif type(val) == list:
nval = len(val)
if nval != nentries:
msg = 'attribute ' + key + ' has ' + str(nval)
msg += ' entries, expected ' + str(nentries)
raise ValueError(msg)
for m in range(0, nval):
if type(val[m]) != int and type(val[m]) != float:
raise ValueError('entry ' + str(m + 1) + ' is not int or float')
return val
else:
raise ValueError('attribute ' + key + ' is not of type int or float or list')
else:
raise KeyError('attribute not found!', key) |
def export_host_info(inventory):
"""Pivot variable information to be a per-host dict
This command is meant for exporting an existing inventory's information.
The exported data re-arranges variable data so that the keys are the host,
and the values are hostvars and groups.
Two top level keys are present: 'hosts' and 'all'. 'hosts' is a dictonary
of the host information. 'all' represents global data, mostly the load
balancer and provider network values. It is taken from
inventory['all']['vars'].
"""
export_info = {'hosts': {}}
host_info = export_info['hosts']
export_info['all'] = inventory['all']['vars']
for host, hostvars in inventory['_meta']['hostvars'].items():
host_info[host] = {}
host_info[host]['hostvars'] = hostvars
for group_name, group_info in inventory.items():
if group_name in ('_meta', 'all'):
continue
for host in group_info['hosts']:
if 'groups' not in host_info[host]:
host_info[host]['groups'] = []
host_info[host]['groups'].append(group_name)
return export_info |
def krishnamurti(number) -> bool:
"""It will check whether the entered number is a krishnamurti number or not."""
s = 0
n = number
a = n
while(n != 0):
f = 1
r = n % 10
for i in range(1, r+1):
f = f*i
s = s+f
n = n//10
if(s == a):
return True
else:
return False |
def clean_currency(x):
""" Remove comma in currency numeric
Add space between currency symbol and value
"""
if isinstance(x, int) or isinstance(x, float):
return ('', x)
if isinstance(x, str):
numeric_start_at = 0
for i in range(len(x)):
if x[i].isnumeric():
numeric_start_at = i
break
return (x[0:numeric_start_at], x[numeric_start_at:].replace(',', ''))
return('', x) |
def process_addresses_list(
addresses_list, idx=0, limit=100, sortby=None, sortdir="asc"
):
"""Receive an address list as parameter and sort it or slice it for pagination.
Parameters: addresses_list: list of dict with the keys
(index, address, label, used, utxo, amount)
idx: pagination index (current page)
limit: maximum number of items on the page
sortby: field by which the list will be ordered
(index, address, label, used, utxo, amount)
sortdir: 'asc' (ascending) or 'desc' (descending) order"""
if sortby:
def sort(addr):
val = addr.get(sortby, None)
final = val
if val:
if isinstance(val, str):
final = val.lower()
return final
addresses_list = sorted(addresses_list, key=sort, reverse=sortdir != "asc")
if limit:
page_count = (len(addresses_list) // limit) + (
0 if len(addresses_list) % limit == 0 else 1
)
addresses_list = addresses_list[limit * idx : limit * (idx + 1)]
else:
page_count = 1
return {"addressesList": addresses_list, "pageCount": page_count} |
def checkRules(puzzle):
""" this function receives a sudoku puzzle as a 9x9 list.
and checks if it satisfies the rules of Sudoku, specifically
(i): if all the numbers in rows are unique.
(ii): if all the numbers in columns are unique
(iii): if all the numbers in cells are unique"""
# Checking condition (i)
# Checking numbers to be unique in rows
rowCheck = True;
for i in range(9):
for j in range(9):
if not puzzle[i][j]==0:
if puzzle[i][:].count(puzzle[i][j]) != 1:
rowCheck = False;
# Checking condition (ii)
# checking to be unique in columns
colCheck = True;
for i in range(9):
col = [row[i] for row in puzzle]
for j in range(9):
if not col[j]==0:
if col.count(col[j]) != 1:
colCheck = False;
# Checking condition (iii)
# Checking numbers to be unique in each cell
cellCheck = True;
for i in range(3):
for j in range(3):
cell = [];
cell = [row[3*i:3*(i+1)] for row in puzzle[3*i:3*(i+1)]];
cell_flat = [];
for row in cell:
cell_flat = cell_flat + row;
for k in range(9):
if not cell_flat[k]==0:
if cell_flat.count(cell_flat[k])!=1:
cellCheck=False;
return rowCheck and colCheck and cellCheck |
def is_number(in_value):
"""Checks if a value is a valid number.
Parameters
----------
in_value
A variable of any type that we want to check is a number.
Returns
-------
bool
True/False depending on whether it was a number.
Examples
--------
>>> is_number(1)
True
>>> is_number(1.0)
True
>>> is_number("1")
True
>>> is_number("1.0")
True
>>> is_number("Hello")
False
You can also pass more complex objects, these will all be ``False``.
>>> is_number({"hello": "world"})
False
>>> from datetime import datetime
>>> is_number(datetime.now())
False
Even something which contains all numbers will be ``False``, because it is not itself a number.
>>> is_number([1, 2, 3, 4])
False
"""
try:
float(in_value)
return True
except (ValueError, TypeError):
return False |
def _get_tag_value(x, key):
"""Get a value from tag"""
if x is None:
return ''
result = [y['Value'] for y in x if y['Key'] == key]
if result:
return result[0]
return '' |
def _bits_to_bytes_len(length_in_bits):
"""
Helper function that returns the numbers of bytes necessary to store the
given number of bits.
"""
return (length_in_bits + 7) // 8 |
def nu(x, beta):
"""
Eq. (6) from Ref[1] (coeffient of alpha**2)
Note that 'x' here corresponds to 'chi = x/rho' in the paper.
"""
return 3 * (1 - beta**2 - beta**2 * x) / beta**2 / (1+x) |
def split_gems(frags, thr):
"""
Split GEMs into sub-GEMs depending on cutoff threshold thr.
Args:
frags (list of list): [chrom,start,end] for each fragment
thr (int): cutoff threshold in bps
Returns:
subgems (list of list)
"""
subgems = []
tmpgem = [frags[0]]
for i in range(len(frags)-1):
fragdist = frags[i+1][1]-frags[i][2]
if fragdist < thr:
tmpgem.append(frags[i+1])
else:
subgems.append(tmpgem)
tmpgem = [frags[i+1]]
subgems.append(tmpgem)
fin_subgems = [x for x in subgems if len(x)>1]
return fin_subgems |
def get_winner(state):
"""Return winning player if any"""
winning = [(0, 1, 2), (3, 4, 5), (6, 7, 8), (0, 3, 6), (1, 4, 7),
(2, 5, 8), (0, 4, 8), (2, 4, 6)]
for player in ['X', 'O']:
for i, j, k in winning:
if [state[i], state[j], state[k]] == [player, player, player]:
return player
return '' |
def get_class(result, class_label='status'):
"""Get a normalized result for the specified class.
Get a normalized result for the specified class. Currently supported
classes are only one, 'status'. This returns a single value which
defines the class the example belongs to.
"""
if class_label == 'status':
status = result['status']
passed_statuses = [0, 'Success']
status = 0 if status in passed_statuses else 1
return status
elif class_label == 'node_provider':
provider = result['node_provider']
if provider.startswith('rax'):
return 'rax'
elif provider.startswith('ovh'):
return 'ovh'
elif provider.startswith('vexxhost'):
return 'vexxhost'
else:
return provider
elif class_label == 'node_provider_all':
return result['node_provider']
else:
return result[class_label] |
def str2bool(v):
"""
used in argparse, to pass booleans
codes from : https://stackoverflow.com/questions/15008758/parsing-boolean-values-with-argparse
"""
if v.lower() in ('yes', 'true', 't', 'y', '1'):
return True
elif v.lower() in ('no', 'false', 'f', 'n', '0'):
return False
else:
raise UserWarning |
def rtable_q_propagate(route_entry):
"""
Args:
route_entry: (dict)
Returns:
string: returns route propagation
"""
if str(
route_entry.get('Origin')
) == 'EnableVgwRoutePropagation':
return 'True'
else:
return 'False' |
def merge_dicts(dict1, dict2):
"""Recursively merge two dictionaries.
Values in dict2 override values in dict1. If dict1 and dict2 contain a dictionary as a
value, this will call itself recursively to merge these dictionaries.
This does not modify the input dictionaries (creates an internal copy).
Parameters
----------
dict1: dict
First dict.
dict2: dict
Second dict. Values in dict2 will override values from dict1 in case they share the same key.
Returns
-------
return_dict: dict
Merged dictionaries.
"""
return_dict = dict1.copy()
for k, v in dict2.items():
if k not in dict1:
return_dict[k] = v
else:
if isinstance(v, dict):
return_dict[k] = merge_dicts(dict1[k], dict2[k])
else:
return_dict[k] = dict2[k]
return return_dict |
def differ_paths(old, new):
""" Compare old and new paths """
if old and old.endswith(('\\', '/')):
old = old[:-1]
old = old.replace('\\', '/')
if new and new.endswith(('\\', '/')):
new = new[:-1]
new = new.replace('\\', '/')
return (new != old) |
def chop(lst, n):
""" This function returns a list of lists derived from a list that was
chopped up into pieces with n elements each. The last element might be
any length between 1 and n."""
return [lst[i:i+n] for i in range(0, len(lst), n)] |
def do(*exprs):
"""Helper function for chaining expressions.
The expressions have already been evaluated when this function is called, so this function just returns the last one.
If the list of expressions is empty, it returns ``None``.
"""
# You've already done them; just return the right value.
if len(exprs) > 0:
return exprs[-1]
else:
return None |
def fib2(n):
"""Return a list containing the Fibonacci series up to n."""
result = []
a, b = 0, 1
while a < n:
result.append(a)
a, b = b, a+b
return str(result).strip() |
def _scrub_key(key):
"""
RETURN JUST THE :. CHARACTERS
"""
if key == None:
return None
output = []
for c in key:
if c in [":", "."]:
output.append(c)
return "".join(output) |
def add_multiple_values(*args):
""" Adds a list of integers
Arguments:
args: A list of integers e.g. 1,2,3,4,5
"""
sum_ = 0
for number in args:
sum_ = sum_ + number
return sum_ |
def is_clinical_in_cases(clinical_obj, cases):
"""Checks to see if clinical object representation is part of cases to assess
Example:
>>> clin_obj = xml_to_raw_clinical_patient("Test_Data/nationwidechildrens.org_clinical.TCGA-MH-A562.xml")
>>> cases = set(["ad7ba244-67fa-4155-8f13-424bdcbb12e5", "dc39df39-9945-4cb6-a852-d3b42177ac80", "b877d608-e4e0-4b28-9235-01dd65849cf7"])
>>> is_clinical_in_cases(clin_obj, cases)
False
>>> cases = set(["ad7ba244-67fa-4155-8f13-424bdcbb12e5", "dc39df39-9945-4cb6-a852-d3b42177ac80", "b877d608-e4e0-4b28-9235-01dd65849cf7", "45bdcfd6-1e3f-4be8-b843-ae949e8e43eb"])
>>> is_clinical_in_cases(clin_obj, cases)
True
"""
def get_days_to_birth():
pass
def get_days_to_death():
"""This returns either the censored value of the"""
pass
patient_uuid = clinical_obj['kirp:patient']['shared:bcr_patient_uuid']['#text']
patient_uuid = patient_uuid.strip().lower()
return patient_uuid in cases |
def format_message(fname, expected, actual, flag):
"""
Convenience function that returns nicely formatted error/warning messages
"""
def _format(types):
return ', '.join([str(t).split("'")[1] for t in types])
expected, actual = _format(expected), _format(actual)
msg = "'{}' method ".format(fname) + ('accepts', 'returns')[flag] + ' ({}), but '.format(expected) + \
('was given', 'result is')[flag] + ' ({})'.format(actual)
return msg |
def oscale(l):
"""Convert from 0.0-1.0 in linear gamma to gamma table format (0-1023 gamma 2.2)"""
omax = 1023
out_gamma = 1/2.2
if l < 0:
o = 0
else:
o = (l ** out_gamma) * omax
oi = int(round(o, 0))
if oi >= omax:
oi = omax
return oi |
def TrimBytes(byte_string):
"""Trim leading zero bytes."""
trimmed = byte_string.lstrip(b'\x00')
if len(trimmed) == 0: # was a string of all zero byte_string
return b'\x00'
else:
return trimmed |
def heritingFrom(instanceOrType):
"""
Return classes name this is heriting from
"""
klasses = []
if isinstance(instanceOrType, type):
bases = instanceOrType.__bases__
else:
bases = instanceOrType.__class__.__bases__
for base in bases:
klasses.append(base.__name__)
return klasses |
def determiner_to_num(tag):
"""Converts a/an to 1."""
if tag[1] != "DET": return False, None
if tag[0].lower() in ("a","an"): return True, ("1","NUM")
return False, None |
def get_focal_value(tags):
"""Extracts focal length value from given tags
"""
if tags and "EXIF FocalLength" in tags:
return eval(str(tags["EXIF FocalLength"]))
return None |
def common_prefix(a: str, b: str) -> str:
"""Determine the common prefix of *a* and *b*."""
if len(a) > len(b):
a, b = b, a
for i in range(len(a)):
if a[i] != b[i]:
return a[:i]
return a |
def normalize_id(entity_type, entity_id):
"""return node type and node id for a given entity type and id"""
if entity_type == 'Chemical':
if entity_id == '':
return None
if entity_id[:5] == 'CHEBI':
return 'ChEBI', entity_id[6:]
elif entity_id[0] == 'D' or entity_id[0] == 'C':
return 'MeSH', entity_id
elif entity_id[:4] == 'MESH':
return 'MeSH', entity_id[5:]
raise Exception('Unknown ID', (entity_type, entity_id))
elif entity_type == 'Disease':
if entity_id == '':
return None
if entity_id[0] == 'D' or entity_id[0] == 'C':
return 'MeSH', entity_id
if entity_id[:4] == 'MESH':
return 'MeSH', entity_id[5:]
elif entity_id[:4] == 'OMIM':
return 'OMIM', entity_id[5:]
raise Exception('Unknown ID', (entity_type, entity_id))
elif entity_type == 'Gene':
# '3630', '18024(Tax:10090)', '6647;6648',
return 'Gene', entity_id
elif entity_type == 'DNAMutation':
# c|SUB|C|1107|G
return 'DNAMutation', entity_id
elif entity_type == 'ProteinMutation':
# p|SUB|V|158|M
return 'ProteinMutation', entity_id
elif entity_type == 'SNP':
# rs2910164
return 'SNP', entity_id
elif entity_type == 'Species':
return 'Taxonomy', entity_id
elif entity_type == 'CellLine':
return 'CellLine', entity_id[5:]
elif entity_type == 'DomainMotif':
return 'DomainMotif', entity_id
raise Exception('Unknown ID', (entity_type, entity_id)) |
def channels(channel):
"""Return a mock of channels."""
return [channel("level", 8), channel("on_off", 6)] |
def mongodb_generate_run_command(mongodb_config):
"""
Generate run command for mongodb from config dictionary
:param mongodb_config: mongodb config dictionary
:return: A list of string representing the running command
"""
# Return fundamental args
return [
mongodb_config["exe"],
"--replSet",
mongodb_config["replica_set"],
"--bind_ip",
mongodb_config["listen"]["address"],
"--port",
mongodb_config["listen"]["port"],
"--dbpath",
mongodb_config["data_dir"]
] |
def _get_descendants(page_dict, page_ids):
"""
Returnes all descendants for a list of pages using a page dict
built with _ordered_pages_to_dict method.
"""
result = []
for page_id in page_ids:
result.append(page_id)
children_ids = page_dict.get(page_id, None)
if children_ids:
result.extend(_get_descendants(page_dict, children_ids))
return result |
def text_first_line(target, strip=False):
"""
Return the first line of text; if `strip` is True, return all but the first
line of text.
"""
first_line, _, rest = target.partition("\n")
if strip:
return rest
else:
return first_line |
def subdict(fromdict, fields, default=None, force=False):
"""
Return a dictionary with the specified selection of keys from `fromdict`.
If `default` is not None or `force` is true, set missing requested keys to
the value of `default`.
(Argument `force` is only needed if the desired default is None)
"""
if default is not None:
force = True
return { k: fromdict.get(k, default) for k in fields if k in fromdict or force } |
def num_conv(number, plural=False):
"""Converts card numbers into their proper names
Args:
number (int): The number intended to be converted
plural (bool): Determines if the result should be in plural or single form
Returns:
The proper name to be used for the card number
"""
if plural:
plural_s = "s"
else:
plural_s = ""
if number == 1 or number == 14:
number_string = f"Ace{plural_s}"
elif number == 11:
number_string = f"Jack{plural_s}"
elif number == 12:
number_string = f"Queen{plural_s}"
elif number == 13:
number_string = f"King{plural_s}"
else:
number_string = f"{str(number)}{plural_s}"
return number_string |
def boxed_string(text: str) -> str:
"""Returns passed text string wrapped in triple backticks."""
return '```' + text + '```' |
def is_perfect_square(num):
"""Test whether a given number is a perfect square.
Tests whether a given number is a perfect square or not based
on the Babylonian method for computing square roots.
Args:
num (int): The number to test whether it is a perfect square
Returns:
bool: True if num is a perfect square, otherwise False
"""
if num < 0:
return False
if num == 0 or num == 1:
return True
x = num // 2
y = {x}
while x * x != num:
x = (x + (num // x)) // 2
if x in y:
return False
y.add(x)
return True |
def get_sorted_dict(dct: dict):
"""Returns dictionary in sorted order"""
return dict(sorted(dct.items())) |
def check_jumbo_opt(enable_jumbo, max_pkt_len):
"""Check if jumbo frame option is valid.
Jumbo frame is enabled with '--enable-jumbo' and max packet size is
defined with '--max-pkt-len'.
'--max-pkt-len' cannot be used without '--enable-jumbo'.
"""
if (enable_jumbo is None) and (max_pkt_len is not None):
print('Error: --enable-jumbo is required')
return False
if max_pkt_len is not None:
if (max_pkt_len < 64) or (max_pkt_len > 9600):
print('Error: --max-pkt-len {0:d} should be {1:d}-{2:d}'.
format(max_pkt_len, 64, 9600))
return False
return True |
def extract_values(obj, key):
"""Pull all values of specified key from nested JSON.
Taken from: https://hackersandslackers.com/extract-data-from-complex-json-python/"""
arr = []
def extract(obj, arr, key):
"""Recursively search for values of key in JSON tree."""
if isinstance(obj, dict):
for k, v in obj.items():
if isinstance(v, (dict, list)):
extract(v, arr, key)
elif k == key:
arr.append(v)
elif isinstance(obj, list):
for item in obj:
extract(item, arr, key)
return arr
results = extract(obj, arr, key)
return results |
def list_dropdownTS(dic_df):
"""
input a dictionary containing what variables to use, and how to clean
the variables
It outputs a list with the possible pair solutions.
This function will populate a dropdown menu in the eventHandler function
"""
l_choice = []
for key_cat, value_cat in dic_df['var_continuous'].items():
l_choice.append(value_cat['name'])
l_choice = ['-'] + l_choice
return l_choice |
def intersect(ra, rb):
"""Given two ranges return the range where they intersect or None.
>>> intersect((0, 10), (0, 6))
(0, 6)
>>> intersect((0, 10), (5, 15))
(5, 10)
>>> intersect((0, 10), (10, 15))
>>> intersect((0, 9), (10, 15))
>>> intersect((0, 9), (7, 15))
(7, 9)
"""
# preconditions: (ra[0] <= ra[1]) and (rb[0] <= rb[1])
sa = max(ra[0], rb[0])
sb = min(ra[1], rb[1])
if sa < sb:
return sa, sb
else:
return None |
def get_metric_name(metric_label):
"""Returns pushgateway formatted metric name."""
return 'mq_queue_{0}'.format(metric_label) |
def formSentence(inList,searchChr):
"""
Checking all words rowwise in list and creating a str contains the first letter of word is same with searched character
Parameters:
inList(list): the input list
searchChr(str): the value going to check
returns:
String : return rev
"""
res = ""
for i in inList:
for j in i:
if j[0].lower() == searchChr.lower():
res += j+' '
return res |
def checkNearlyEqual(value1, value2, dE = 1e-5):
"""
Check that two values are nearly equivalent by abs(val1-val2) < abs(dE*val1)
"""
if abs(value1-value2) <= abs(dE*value1) or abs(value1-value2) <= abs(dE*value2) or abs(value1-value2) <= dE:
return True
else:
return False |
def path_escape(path):
"""Escape a path by placing backslashes in front of disallowed characters"""
for char in [' ', '(', ')']:
path = path.replace(char, '\%s' % char)
return path |
def fmt2(f1, f2):
"""Format two floats as f1/f2
"""
return "%.1f/%.1f" % (f1, f2) |
def level_points(level: int) -> int:
"""
Returns the number of points required to reach the given level
"""
# determined with https://www.dcode.fr/function-equation-finder
return int(((5*level**3)/3 + (45*level**2)/2 + 455*level/6)) |
def sepdelimited_keydata_to_json(data: dict, sep: str='.'):
"""Store a dict to JSON that originally has the following format:
{
"a.bc.def": "value1",
"a.bc.ghi": "value2",
"j": "value3"
}
The resulting JSON will be as follows:
{
"a": {
"bc": {
"def": "value1",
"ghi": "value2"
}
},
"j": "value3"
}
The keypart separator can be specified via the ``sep`` parameter.
"""
jsondata = {}
for key, value in list(data.items()):
if key.find(sep) < 0:
# the key is not nested, just store it as-is
jsondata[key] = value
continue
jsonsubdict = jsondata
keyparts = key.split(sep)
max_i = len(keyparts)
for i in range(max_i):
keypart = keyparts[i]
if i+1 < max_i:
# we've not reached the last keypart yet
try:
jsonsubdict = jsonsubdict[keypart]
except KeyError:
jsonsubdict[keypart] = {}
jsonsubdict = jsonsubdict[keypart]
else:
# this is the last keypart
jsonsubdict[keypart] = value
return jsondata |
def lift_split_buffers(lines):
"""Lift the split buffers in the program
For each module, if we find any split buffers with the name "buf_data_split",
we will lift them out of the for loops and put them in the variable declaration
section at the beginning of the module.
Parameters
----------
lines:
contains the codelines of the program
"""
code_len = len(lines)
for pos in range(code_len):
line = lines[pos]
if line.find("variable=buf_data_split") != -1:
# Search for the variable declaration section
decl_pos = -1
prev_pos = pos - 1
while prev_pos >= 0:
prev_line = lines[prev_pos]
if prev_line.find("Variable Declaration") != -1:
decl_pos = prev_pos
break
prev_pos -= 1
# Move the two code lines at [pos - 1] and [pos] to [decl_pos] and
# [decl_pos + 1]
indent = lines[decl_pos].find("/*")
line1 = " " * indent + lines[pos - 1].lstrip()
line2 = " " * indent + lines[pos].lstrip()
del lines[pos - 1]
del lines[pos - 1]
lines.insert(decl_pos, line1)
lines.insert(decl_pos + 1, line2)
return lines |
def wrap_accumulator(acc):
"""
Wraps accumulator!!!
:param acc:
:return:
"""
if acc > 1:
acc -= 1
elif acc < -1:
acc += 1
else:
acc = 0
return acc |
def is_relation(s: str) -> bool:
"""Checks if the given string is a relation name.
Parameters:
s: string to check.
Returns:
``True`` if the given string is a relation name, ``False`` otherwise.
"""
return s[0] >= 'F' and s[0] <= 'T' and s.isalnum() |
def max_team(assignment):
""" people are random arrange in team. Search for max value of team. Help function for num_teams"""
length = len(assignment)
max = -1
for i in range(length):
if assignment[i] > max:
max = assignment[i]
return max + 1 |
def extract_category(url):
"""
Extracts category of the article from URL
Input : URL
Output : Category
"""
if "/opinion/" not in url :
return "regular"
elif "/editorial/" in url:
return "editorial"
elif "/op_ed_commentaries/" in url :
return "oped"
elif "/letter_to_editor/" in url or "/letters_to_editor/" in url or "/readers_vent/" in url:
return "other"
elif "/columnists/" in url or "guest" in url or "/daily_mail_opinion/" in url:
return "guest"
else:
return "other" |
def get_groups_from_list(group_ids, alignments):
"""
Given a list of IDs and a list of alignments, return a list with
all alignments that belong the nodes in the group.
"""
# Create an inverted list of alignments names from all alignments.
inverted_list_alignments = {}
alignment_idx = 0
for alignment in alignments:
inverted_list_alignments[alignment.name] = alignment_idx
alignment_idx += 1
# Lookup the inverted list to get the index of the alignment based on the
# node names specified in the group node ids.
group_alignments = list()
for id in group_ids:
if id in inverted_list_alignments:
group_alignments.append(
alignments[inverted_list_alignments[id]])
return group_alignments |
def _StandardizeTargetLabel(label):
"""Convert labels of form //dir/target to //dir/target:target."""
if label is None:
return label
tokens = label.rsplit('/', 1)
if len(tokens) <= 1:
return label
target_base = tokens[0]
target = tokens[1]
if '...' in target or ':' in target:
return label
return label + ':' + target |
def lustre_client_id(fsname, mnt):
"""
Return the Lustre client ID
"""
return "%s:%s" % (fsname, mnt) |
def rus_check_json(rus_player_json):
"""Expected JSON for rus_check model-fixture"""
return {"type": "check", "player": rus_player_json} |
def is_Chinese(uchar):
"""unicode char to be Chinese character"""
if uchar >= u'\u4e00' and uchar<=u'\u9fa5':
return True
else:
return False |
def get_dugaire_image_label(return_format = 'string'):
""" Get the default label used when building images. """
default_label_key = 'builtwith'
default_label_value = 'dugaire'
default_label = {default_label_key: default_label_value}
if return_format == 'string':
return f'{default_label_key}={default_label_value}'
if return_format == 'dockerfile':
return f'{default_label_key}="{default_label_value}"'
return default_label |
def return_txt(fn: str) -> list:
"""
Opens a file and returns the whole file as a list
Args:
fn (str): File name to open
Returns:
list: return whole file as a list
"""
try:
with open(fn, "r") as f:
return f.readlines()
except FileNotFoundError as e:
print(f"File not Found :: {e}")
return [] |
def myfunction_ter(x):
"""Multiply the value by 3."""
if isinstance(x, int):
xx = 3 * x
else:
xx = None
return xx |
def int2ap(num):
"""Convert integer to A-P string representation."""
val = ''
ap = 'ABCDEFGHIJKLMNOP'
num = int(abs(num))
while num:
num, mod = divmod(num, 16)
val += ap[mod:mod + 1]
return val |
def convert_login_customer_id_to_str(config_data):
"""Parses a config dict's login_customer_id attr value to a str.
Like many values from YAML it's possible for login_customer_id to
either be a str or an int. Since we actually run validations on this
value before making requests it's important to parse it to a str.
Args:
config_data: A config dict object.
Returns:
The same config dict object with a mutated login_customer_id attr.
"""
login_customer_id = config_data.get("login_customer_id")
if login_customer_id:
config_data["login_customer_id"] = str(login_customer_id)
return config_data |
def compare_versions(version_1: str, version_2: str) -> int:
"""Compares two version strings with format x.x.x.x
Returns:
-1, if version_1 is higher than version_2
0, if version_1 is equal to version_2
1, if version_1 is lower than version_2 """
version_1 = version_1.strip('v')
version_2 = version_2.strip('v')
version_1_split = version_1.split('.')
version_2_split = version_2.split('.')
for i in range(0, len(version_1_split)):
if version_1_split[i] < version_2_split[i]:
return 1
elif version_1_split[i] > version_2_split[i]:
return -1
return 0 |
def lift(a):
"""Lifts a signal from [-1,1] to [0,1]"""
return a / 2 + 0.5 |
def generateFrameRange(first, last, padding):
"""Generate a string with all numbers in the frame range.
Args:
Something (str): Shit.
First (int): The number that will be starting the string.
Last (int): The last number of the string.
Padding (int): The padding of the numbers.
Returns:
string: The string with all numbers in frame range.
"""
assert isinstance(first, int)
assert isinstance(last, int)
numbersList = list(map(str, range(first, last + 1)))
resultRange = []
for _, number in enumerate(numbersList):
curPadding = len(number)
if curPadding < padding:
newNumber = ""
for _ in range(0, padding - curPadding):
newNumber += "0"
newNumber += number
else:
newNumber = number
resultRange.append(newNumber)
resultString = ",".join(resultRange)
return resultString |
def int_max_value(bits,signed=True):
"""Returns the maximum int value of a signed or unsigned integer
based on used bits.
Arguments:
bits -- How many bits, e.g., 16
signed -- True if a signed int
Returns:
max_value -- The maximum int value based on given parameters
"""
if signed:
# Signed int
max_value = pow(2,bits-1)-1
else:
# Unsigned int
max_value = pow(2,bits)-1
return max_value |
def non_negative_int(s, default):
"""Parse a string into an int >= 0. If parsing fails or the result is out
of bounds, return a default."""
try:
i = int(s)
if i >= 0:
return i
except (ValueError, TypeError):
pass
return default |
def evaluate_expr(op1, op2, operator):
"""Operation helper function.
Assuming the only operation we will do is addition, substration,
multiplication and division
"""
if operator == '*':
return op1 * op2
elif operator == "/":
return op1 / op2
elif operator == "+":
return op1 + op2
elif operator == "-":
return op1 - op2
elif operator == "%":
return op1 % op2 |
def pycli_of_str(s):
"""
:param s: a string assumed to be python code
:return: a string that would correspond to this code written in a python cli (you know, with the >>> and ...)
"""
ss = ''
for line in s.split('\n'):
if len(line) == 0:
ss += '>>> ' + line + '\n'
elif line[0].isspace() and line[0] != '\n':
ss += '...' + line + '\n'
else:
ss += '>>> ' + line + '\n'
return ss |
def append_csv_data(file_strings):
""" Append data from multiple csv files for the same time period
Parameters
-----------
file_strings : array-like
Lists or arrays of strings, where each string contains one file of data
Returns
-------
out_string : string
String with all data, ready for output to a file
"""
# Start with data from the first list element
out_lines = list()
head_line = None
# Cycle through the lists of file strings, creating a list of line strings
for fstrings in file_strings:
file_lines = fstrings.split('\n')
# Remove and save the header line
head_line = file_lines.pop(0)
# Save the data lines
out_lines.extend(file_lines)
# Sort the output lines by date and station (first two columns) in place
out_lines.sort()
# Remove all zero-length lines from front, add one to back, and add header
i = 0
while len(out_lines[i]) == 0:
out_lines.pop(i)
out_lines.insert(0, head_line)
out_lines.append('')
# Join the output lines into a single string
out_string = "\n".join(out_lines)
return out_string |
def checkPalindrome(inputString):
""" Given any string, check if it is a palindrome. -> boolean """
stringLen = len(inputString)
if (stringLen == 1):
return True
l = stringLen//2
for i in list(range(l)):
if (inputString[i] == inputString[-i-1]):
pass
else:
return False
return True |
def str_or_none(value):
"""
a type function to check if a value cN be either a string or nonr
:param value:
:return:
"""
try:
return str(value)
except BaseException:
return None |
def micro_avg_precision(guessed, correct, empty=None):
"""
Tests:
>>> micro_avg_precision(['A', 'A', 'B', 'C'],['A', 'C', 'C', 'C'])
0.5
>>> round(micro_avg_precision([0,0,0,1,1,1],[1,0,0,0,1,0], empty=0), 6)
0.333333
>>> round(micro_avg_precision([1,0,0,0,1,0],[0,0,0,1,1,1], empty=0), 6)
0.5
>>> round(micro_avg_precision([1,0,0,0,1,0],[], empty=0), 6)
1.0
"""
correctCount = 0
count = 0
idx = 0
if len(guessed) == 0:
return 1.0
elif len(correct) == 0:
return 1.0
while idx < len(guessed):
if guessed[idx] != empty:
count += 1
if guessed[idx] == correct[idx]:
correctCount +=1
idx +=1
precision = 0
if count > 0:
precision = correctCount / count
return precision |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.