content stringlengths 42 6.51k |
|---|
def say_hello(name):
"""
The starship Enterprise has run into some problem when creating a program to greet everyone as they come aboard.
It is your job to fix the code and get the program working again!
:param name: A string value.
:return: A greeting to the person.
"""
return "Hello, " + name |
def runSingleThreaded(runFunction, arguments):
"""
Small overhead-function to iteratively run a function with a pre-determined input arguments
:param runFunction: The (``partial``) function to run, accepting ``arguments``
:param arguments: The arguments to passed to ``runFunction``, one run at a time
:return: List of any results produced by ``runFunction``
"""
results = []
for arg in arguments:
results.append(runFunction(*arg))
return results |
def unpack(dic):
"""
Unpack lists with only one member
Parameters
----------
dic : dict
A nested dictionary
Returns
-------
dict
A dictionary that its value unlisted
"""
if dic == None:
return None
dix = dict()
for x, y in dic.items():
if isinstance(y, list) and len(y) == 1:
dix[x] = y[0]
elif y == []:
dix[x] = None
else:
dix[x] = y
return dix |
def isstruct(ob):
""" isstruct(ob)
Returns whether the given object is an SSDF struct.
"""
if hasattr(ob, '__is_ssdf_struct__'):
return bool(ob.__is_ssdf_struct__)
else:
return False |
def p_testlist_single(p, el):
"""testlist_plus : test"""
return [el], el |
def get_valid_options(temp_str,lead_in_text):
"""
This parses a string of the format:
temp_str = 'These are the options: test1,test2,test3'
lead_in_text = 'options:'
get_valid_options(temp_str,lead_in_text)
=> ['test1','test2','test3']
"""
I = temp_str.find(lead_in_text)
temp_str2 = temp_str[I+len(lead_in_text):]
temp_values = temp_str2.split(',')
current_values = sorted([x.strip() for x in temp_values])
return current_values |
def intify(x):
"""
Turn an integral float into an int, if applicable.
"""
if isinstance(x, float) and x.is_integer():
return int(x)
return x |
def loose_bool(s: str) -> bool:
"""Tries to 'loosely' convert the given string to a boolean. This is done
by first attempting to parse it into a number, then to a boolean. If this
fails, a set of pre-defined words is compared case-insensitively to the
string to determine whether it's positive/affirmative or negative.
Parameters
----------
* s: `str` - The string to convert.
Returns
-------
* `bool`: The resulting boolean.
Raises
------
* `ValueError` when the boolean value can't be determined.
"""
s = s.strip()
try:
return bool(float(s))
except ValueError:
pass
s = s.lower()
if s in ['y', 'yes', 't', 'true', 'do', 'ok']:
return True
elif s in ['n', 'no', 'f', 'false', 'dont']:
return False
else:
raise ValueError(f"String {repr(s)} cannot be loosely casted to a boolean") |
def read_raw_message(raw_data: bytes) -> tuple:
"""Splits the message header from the data bytes of the message.
:param raw_data: Full UDP packet
:type raw_data: bytes
:raises ValueError: When there header line is not present.
:return: (Header, Data bytes)
:rtype: Tuple
"""
for i in range(len(raw_data)):
if raw_data[i] == ord("\n"):
return raw_data[0:i].decode("utf-8"), raw_data[i + 1 :]
raise ValueError("Unable to find the end of line") |
def serialize_last_resort(X):
""" last attempt at serializing """
return "{}".format(X) |
def _str_trunc(x: object) -> str:
"""Helper function of :func:`recursive_diff`.
Convert x to string. If it is longer than 80 characters, or spans
multiple lines, truncate it
"""
x = str(x)
if len(x) <= 80 and "\n" not in x:
return x
return x.splitlines()[0][:76] + " ..." |
def average_odds_difference(fpr_unpriv, fpr_priv, tpr_unpriv, tpr_priv):
"""Calculate the average odds difference fairness metric."""
return ((fpr_unpriv - fpr_priv) + (tpr_unpriv - tpr_priv)) / 2 |
def t_cmp(calculated_t, critical_t):
"""
Given Critical T Value and T score,
Return if its Significant or Not.
"""
return abs(calculated_t) > abs(critical_t) |
def mean(li):
"""
Calculate mean of a list.
>>> mean([0.5,2.0,3.5])
2.0
>>> mean([])
"""
if li:
return sum(li) / len(li)
return None |
def is_leap_year(year):
"""
returns True for leap year and False otherwise
:param int year: calendar year
:return bool:
"""
return (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0) |
def decode_name(nbname):
"""
Return the NetBIOS first-level decoded nbname.
"""
if len(nbname) != 32:
return nbname
l_ = []
for i in range(0, 32, 2):
l_.append(
chr(
((ord(nbname[i]) - 0x41) << 4) |
((ord(nbname[i + 1]) - 0x41) & 0xf)
)
)
return ''.join(l_).split('\x00', 1)[0] |
def probability(vr_norm, pmax, cross_sections): # still per cell
""" Returns the collisions probability associated with the possibly colliding couples.
Args:
vr_norm (np.ndarray): array of size (number of candidates) with the relative speed norm for each couple.
Can be computed using something like : np.linalg.norm((arr[choices][:,1,2:]-arr[choices][:,0,2:]), axis = 1)
pmax (float): maximum probability for the current cell
cross_sections (np.ndarray): array of size (number of candidates) containing the cross sections for each couple.
Note that a *float* can also be used and it will return the right result.
It is useful when dealing with constant cross sections accross couples.
Returns:
[np.ndarray]: 1D-array of size (number of candidates) containing the probability of collisions for each couple.
"""
return cross_sections/pmax*vr_norm |
def check_file_content(path, expected_content):
"""Check file has expected content.
:API: public
:param str path: Path to file.
:param str expected_content: Expected file content.
"""
with open(path, 'r') as input:
return expected_content == input.read() |
def get_app_friendly_name(app):
"""
>>> my_app = {'_id': 1111, 'env': 'prod', 'name': 'app1', 'role': 'webfront', 'autoscale': {'name': 'asg-mod1'}, 'environment_infos': {'instance_tags':[]}}
>>> get_app_friendly_name(my_app)
'app1/prod/webfront'
"""
return "{0}/{1}/{2}".format(app['name'], app['env'], app['role']) |
def find_exsit_name(plugins, name, group):
"""
get name from plugins pth list
"""
for index, item in enumerate(plugins):
if (
item[0] is not None
and item[0] == name
and item[3] is not None
and item[3] == group
):
return index + 1
return 0 |
def _get_unique_field_names(field_names):
"""Append a digit to fieldname duplicates
:param field_names:
:return: list of field names without duplicates
"""
import collections
repeated_fieldnames = {c: -2 for c, count in list(collections.Counter(field_names).items()) if count > 1}
new_filed_names = list()
for field_name in field_names:
if field_name in repeated_fieldnames:
repeated_fieldnames[field_name] += 1
if repeated_fieldnames[field_name] >= 0:
field_name += str(repeated_fieldnames[field_name])
new_filed_names.append(field_name)
return new_filed_names |
def xor_string(string: str, xor_int_value=42):
"""Takes a given string and does an XOR operation on the converted ord() value of each character with the "xor_int_value", which by default is 42
Examples:
>>> string2encode = 'Now is better than never.'\n
>>> xor_string(string2encode)\n
'dE]\nCY\nHO^^OX\n^BKD\nDO\\OX\x04'
>>> xor_string('dE]\nCY\nHO^^OX\n^BKD\nDO\\OX\x04')\n
'Now is better than never.'
>>> chr(97)\n
'a'
>>> ord('a')\n
97
>>> hex(97)\n
'0x61'
>>> int('0x61', 16)\n
97
>>> xor_string(string2encode, xor_int_value = 97)\n
'/\x0e\x16A\x08\x12A\x03\x04\x15\x15\x04\x13A\x15\t\x00\x0fA\x0f\x04\x17\x04\x13O'
>>>
>>> xor_string('/\x0e\x16A\x08\x12A\x03\x04\x15\x15\x04\x13A\x15\t\x00\x0fA\x0f\x04\x17\x04\x13O', 97)\n
'Now is better than never.'
Args:
string (str): The string you want to XOR (each character will be XORed by the xor_int_value)
xor_int_value (int, optional): The integer value that is used for the XOR operation. Defaults to 42.
Returns:
str: Returns an XORed string
"""
xored_result = "".join([chr(ord(c) ^ xor_int_value) for c in string])
return xored_result |
def get_fix_param(var, val):
"""
var: variable name.
val: variable value to fix.
"""
out = {}
for i, j in zip(var, val):
out[i] = j
return out |
def temp_c_to_f(temp_c: float, arbitrary_arg=None):
"""Convert temp from C to F. Test function with arbitrary argument, for example."""
x = arbitrary_arg
return 1.8 * temp_c + 32 |
def angstroms_to_ev(array):
"""convert lambda array in angstroms to energy in eV
Parameters:
===========
array: numpy array or number in Angstroms
Returns:
========
numpy array or value of energy in eV
"""
return 81.787 / (1000. * array ** 2) |
def find_key_value(rec_dict, searchkey, target, depth=0):
"""
find the first key with value "target" recursively
also traverse lists (arrays, oneOf,..) but only returns the first occurance
returns the dict that contains the search key.
so the returned dict can be updated by dict[searchkey] = xxx
:param rec_dict: dict to search in, json schema dict, so it is combination of dict and arrays
:param searchkey: target key to search for
:param target: target value that belongs to key to search for
:param depth: depth of the search (recursion)
:return:
"""
if isinstance(rec_dict, dict):
# direct key
for key, value in rec_dict.items():
if key == searchkey and value == target:
return rec_dict
elif isinstance(value, dict):
r = find_key_value(value, searchkey, target, depth + 1)
if r is not None:
return r
elif isinstance(value, list):
for entry in value:
if isinstance(entry, dict):
r = find_key_value(entry, searchkey, target, depth + 1)
if r is not None:
return r |
def load_user(payload):
"""The user handler is very simple; it returns whatever the "user" claim is
in the payload.
"""
return payload.get('user') |
def PC_S_calc(classes):
"""
Calculate percent chance agreement for Bennett-et-al.'s-S-score.
:param classes: confusion matrix classes
:type classes : list
:return: percent chance agreement as float
"""
try:
return 1 / (len(classes))
except Exception:
return "None" |
def get_date_from_datetime(date_time, **kwargs):
"""
Pass a keyword argument called "default" if you wish to have a specific
value returned when the date cannot be extracted from date_time, otherwise
date_time will be returned.
"""
try:
return date_time.date()
except Exception:
return kwargs.get("default", date_time) |
def fetch_exon(start, cigar):
"""
return the exon information, the start site must be 0-based
:param start:
:param cigar:
:return:
"""
exonbound = []
for c, l in cigar:
if c == 0: # for match
exonbound.append((start, start + l))
start += l
elif c == 1: # for insert
continue
elif c == 2: # for del
start += l
elif c == 3: # for intron
start += l
elif c == 4: # soft clip
# start += l
continue
else:
continue
return exonbound |
def getClusterCharCount(cluster):
"""Calculates the total number of characters occurring in a cluster."""
charCount = 0
for fromTo in cluster:
charCount += fromTo["to"] - fromTo["from"] + 1;
return charCount |
def f(n:int, a: int, b: int) -> int:
"""f(n) = n^2 + an + b"""
return n * n + a * n + b |
def bool_arg(x):
"""Argument type to be used in parser.add_argument()
When a boolean like value is expected to be given
"""
return (str(x).lower() != 'false') \
and (str(x).lower() != 'no') \
and (str(x).lower() != '0') |
def combinations_list(max_length):
"""
returns list of combinations of ACGT of all lengths possible
"""
letters = ["0", "A", "C", "G", "T"]
# max_length = 4
b = len(letters) - 1
# base to convert to
n = 0
k = 0
while k < max_length:
n = (n * b) + b
k += 1
# number of combinations
i = 1
l = []
while i <= n:
current = i
# m and q_n in the formula
combination = ""
while True:
remainder = current % b
if remainder == 0:
combination += letters[b]
current = int(current / b) - 1
else:
combination += letters[remainder]
current = int(current / b)
if (current > 0) == False:
break
l.append(combination)
i += 1
return l |
def sign_extremum(y):
"""Says whether the sign of the data with largest absolute value
is positive, negative, or zero.
"""
import numpy as np
mxabs = np.max(np.abs(y))
if mxabs == 0.0:
return 0
else:
mx = np.max(y)
if mxabs == mx:
return 1
else:
return -1 |
def keys_by_value(dictionary, val):
"""Get keys of a dictionary by a value."""
res = []
for key, value in dictionary.items():
if value == val:
res.append(key)
return res |
def func_x_args_kwargs(x, *args, **kwargs):
"""func.
Parameters
----------
x: float
args: tuple
kwargs: dict
Returns
-------
x: float
args: tuple
kwargs: dict
"""
return x, None, None, None, args, None, None, kwargs |
def getBit(n, bit):
"""
Name: getBit(n, bit)
Args: n, the original integer you want the bit of
bit, the index of the bit you want
Desc: Returns the bit at position "bit" of integer "n"
>>> n = 5
>>> bit = 2
>>> getBit(n, bit)
1
>>> bit = 0
>>> getBit(n, bit)
1
"""
return int(bool((int(n) & (1 << bit)) >> bit)) |
def s3_unicode(s, encoding="utf-8"):
"""
Convert an object into a str, for backwards-compatibility
@param s: the object
@param encoding: the character encoding
"""
if type(s) is str:
return s
elif type(s) is bytes:
return s.decode(encoding, "strict")
else:
return str(s) |
def _is_numeric(x):
"""Return true if x is a numeric value, return false else
Inputs:
x: string to test whether something is or not a number
"""
try:
float(x)
except:
return False
return True |
def SSBenefits(MARS, ymod, e02400, SS_thd50, SS_thd85,
SS_percentage1, SS_percentage2, c02500):
"""
Calculates OASDI benefits included in AGI, c02500.
"""
if ymod < SS_thd50[MARS - 1]:
c02500 = 0.
elif ymod < SS_thd85[MARS - 1]:
c02500 = SS_percentage1 * min(ymod - SS_thd50[MARS - 1], e02400)
else:
c02500 = min(SS_percentage2 * (ymod - SS_thd85[MARS - 1]) +
SS_percentage1 *
min(e02400, SS_thd85[MARS - 1] -
SS_thd50[MARS - 1]), SS_percentage2 * e02400)
return c02500 |
def hasTwoIns(mvarDict):
"""Not the same ins"""
oneIns = len(mvarDict['reference']) < len(mvarDict['allele1Seq'])
twoIns = len(mvarDict['reference']) < len(mvarDict['allele2Seq'])
return oneIns and twoIns |
def _board_is_full(board):
"""
Returns True if all positions in given board are occupied.
:param board: Game board.
"""
for row in board:
for space in row:
if space == "-":
return False
else:
continue
return True |
def checkvalid(h,s):
"""check if the packet is inside"""
return h["afteroffset"] <= s |
def is_disconnected(ret: int):
"""
check whether connection is lost by return value of OesApi/MdsApi
106 : ECONNABORTED
107 : ECONNREFUSED
108 : ECONNRESET
maybe there is more than there error codes indicating a disconnected state
"""
return ret == -106 or ret == -107 or ret == -108 |
def merge_dict(base, delta, merge_lists=True, skip_empty=True,
no_dupes=True, new_only=False):
"""
Recursively merging configuration dictionaries.
Args:
base: Target for merge
delta: Dictionary to merge into base
merge_lists: if a list is found merge contents instead of replacing
skip_empty: if an item in delta is empty, dont overwrite base
no_dupes: when merging lists deduplicate entries
new_only: only merge keys not yet in base
"""
for k, d in delta.items():
b = base.get(k)
if isinstance(d, dict) and isinstance(b, dict):
merge_dict(b, d, merge_lists, skip_empty, no_dupes, new_only)
else:
if new_only and k in base:
continue
if skip_empty and not d and d is not False:
# dont replace if new entry is empty
pass
elif all((isinstance(b, list), isinstance(d, list), merge_lists)):
if no_dupes:
base[k] += [item for item in d if item not in base[k]]
else:
base[k] += d
else:
base[k] = d
return base |
def handle_result(api_dict):
"""Extract relevant info from API result"""
result = {}
for key in {
"objectID",
"version",
"title",
"id",
"permalink",
"content",
"categories",
}:
result[key] = api_dict[key]
return result |
def all_but_last(seq):
"""
Returns a new list containing all but the last element in the given list.
If the list is empty, returns None.
For example:
- If we call all_but_last([1,2,3,4,5]), we'll get [1,2,3,4] in return
- If we call all_but_last(["a","d",1,3,4,None]), we'll get ["a","d",1,3,4] in return
- If we call all_but_last([]), we'll get None in return
"""
# your code here
if seq!=[]:
seq1=list(seq[ :-1])
return seq1
else:
return None |
def any_lowercase2(s):
""" incorrect - checks if 'c' is lower case, which is
always True, and returns a string not a Boolean"""
for c in s:
if 'c'.islower():
return 'True'
else:
return 'False' |
def sieve_of_eratosthenes(n):
# Create a boolean array "prime[0..n]" and
# initialize all entries it as true. A value
# in prime[i] will finally be false if i is
# Not a prime, else true.
"""
t0 = time.time()
c = sieve_of_eratosthenes(100000)
print("Total prime numbers in range:", c)
t1 = time.time()
print("Time required:", t1 - t0)
"""
prime = [True for i in range(n+1)]
p = 2
while(p * p <= n):
# If prime[p] is not changed, then it is a prime
if (prime[p] == True):
# Update all multiples of p
for i in range(p * 2, n + 1, p):
prime[i] = False
p += 1
c = 0
# Print all prime numbers
for p in range(2, n):
if prime[p]:
c += 1
return c |
def transform_boolean(value):
"""Transfroms boolean to `1` or `0`.
:param value: Boolean value.
:type value: boolean
:return: number representation of boolean `1` or `0`.
:rtype: str
"""
if value:
return '1'
else:
return '0' |
def str2floatlist(v):
"""Converts a string of comma separated values to a list of float."""
if len(v) == 0:
return []
return [float(item) for item in v.split(",")] |
def infoReplaceAcAn(oldInfo, totalCalls, altCounts):
"""If oldInfo includes AC and AN, strip them out. Add AN (totalCalls) and AC (altCounts)."""
infoParts = oldInfo.split(';')
newInfoParts = []
for tagVal in infoParts:
(tag, val) = tagVal.split('=')
if (tag not in ('AC', 'AN')):
newInfoParts.append(tagVal)
newInfoParts.append('AC=' + ','.join(map(str, altCounts)))
newInfoParts.append('AN=%d' % (totalCalls))
return ';'.join(newInfoParts) |
def handle_multi_v(html, answer, qvars):
""" Convert MULTIV answer tags into appropriate HTML. (radio buttons)
Keeps the original order (doesn't shuffle the options)
Expects something like <ANSWERn MULTIV a,b,c,d>
"""
try:
start = html.index("<ANSWER%d MULTIV " % answer)
except ValueError:
return None, None
try:
end = html.index(">", start) + 1
except ValueError:
return None, None
params = html[start + len("<ANSWER%d MULTIV " % answer):end - 1]
match = html[start:end]
paramlist = params.split(',')
pout = ["", ]
if paramlist:
pout = ["", ]
pcount = 0
for param in paramlist:
pcount += 1
pt = 'abcdefghijklmnopqrstuvwxyz'[pcount - 1]
if param in qvars:
pout += ["<tr><th>%s)</th><td>" % pt, ]
pout += "<INPUT class='auto_save' TYPE='radio' NAME='ANS_%d' VALUE='%d' Oa_CHK_%d_%d>" % (
answer, pcount, answer, pcount)
pout += "</td><td CLASS='multichoicecell'> %s</td></tr>" % qvars[param]
else:
pout += ["""<tr><td> </td><td><FONT COLOR="red">ERROR IN QUESTION DATA</FONT></td></tr>"""]
ret = "<table border=0><tr><th>Please choose one:</th></tr>"
ret += ''.join(pout)
ret += "</table><br />\n"
return match, ret |
def note_to_frequency(note):
""" Translates a MIDI sequential note value to its corresponding frequency
in Hertz (Hz). Note values are of integer type in the range of 0 to
127 (inclusive). Frequency values are floating point. If the input
note value is less than 0 or greater than 127, the input is
invalid and the value of None is returned. Ref: MIDI Tuning Standard
formula.
"""
if 0 <= note <= 127:
return pow(2, (note - 69) / 12) * 440
else: return None |
def set_fluentd_facts_if_unset(facts):
""" Set fluentd facts if not already present in facts dict
dict: the facts dict updated with the generated fluentd facts if
missing
Args:
facts (dict): existing facts
Returns:
dict: the facts dict updated with the generated fluentd
facts if they were not already present
"""
if 'common' in facts:
if 'use_fluentd' not in facts['common']:
use_fluentd = False
facts['common']['use_fluentd'] = use_fluentd
return facts |
def cache_version(request, event, version=None):
"""We want to cache all pages except for the WIP schedule site.
Note that unversioned pages will be cached, but no cache headers
will be sent to make sure users will always see the most recent
changes.
"""
if version and version == "wip":
return False
return True |
def validate_structure(value, _):
"""
Validate structure input port. It takes care to check that no alchemical atoms
are passed, since they are not supported.
"""
# Even though structure is mandatory here, other workchain might change this requirement
# (see iterator) and therefore the "if" is still needed.
if value:
for kind in value.kinds:
if len(kind.symbols) > 1:
return "alchemical atoms not supported; structure must have one single symbol per kind." |
def diameter(d_2):
"""Calculate internal diameter at the start angle.
:param d_2 (float): diameter of the impeller at section 2 [m]
:return d (float): diameter [m]
"""
d = round(1.1 * d_2, 3)
return d |
def get_digits(n):
"""
Get the array of digits for n
"""
digits = []
while n > 0:
digits.append(n % 10)
n //= 10
return digits |
def overlap(t1start, t1end, t2start, t2end):
"""
Find if two date ranges overlap.
Parameters
----------
datastart, dataend : datetime, float
Observation start and end datetimes.
modelstart, modelend : datetime, float
Observation start and end datetimes.
Returns
-------
overlap : bool
True if the two periods overlap at all, False otherwise.
References
----------
Shamelessly copied from http://stackoverflow.com/questions/3721249
"""
return (t1start <= t2start <= t1end) or (t2start <= t1start <= t2end) |
def lowercase_dict(dictionary: dict) -> dict:
"""
Convert all string keys and values in a dictionary to lowercase.
Args:
dictionary (dict): A dictionary to process.
Raises:
TypeError: If ``dictionary`` is not a ``dict`` instance.
Returns:
dict: A dictionary with all string keys and values lowercase.
"""
if not isinstance(dictionary, dict):
raise TypeError(f'Expected a dictionary, got a {type(dictionary)}')
new_dict = dict()
for key, val in dictionary.items():
new_key = key.lower() if isinstance(key, str) else key
if isinstance(val, dict):
val = lowercase_dict(val)
new_val = val.lower() if isinstance(val, str) else val
new_dict[new_key] = new_val
return new_dict |
def dayofweek(weekday):
"""
convert string to number
"""
if weekday == 'Mon':
return 1
elif weekday == 'Tue':
return 2
elif weekday == 'Wed':
return 3
elif weekday == 'Thu':
return 4
elif weekday == 'Fri':
return 5
elif weekday == 'Sat':
return 6
else:
return 7 |
def right_pad_list(lst, length, value):
"""Returns a copy of the lst padded to the length specified with the
given value.
"""
return lst + [value] * (length - len(lst)) |
def get_app_label_and_model_name(path):
"""Gets app_label and model_name from the path given.
:param str path: Dotted path to the model (without ".model", as stored
in the Django `ContentType` model.
:return tuple: app_label, model_name
"""
parts = path.split('.')
return (''.join(parts[:-1]), parts[-1]) |
def convert_from_bytes_if_necessary(prefix, suffix):
"""
Depending on how we extract data from pysam we may end up with either
a string or a byte array of nucleotides. For consistency and simplicity,
we want to only use strings in the rest of our code.
"""
if isinstance(prefix, bytes):
prefix = prefix.decode('ascii')
if isinstance(suffix, bytes):
suffix = suffix.decode('ascii')
return prefix, suffix |
def reverse_the_list(head, tail):
"""Reverses a linkedlist"""
if head == tail:
return head, tail
if None in (head, tail):
return -1, -1
curr = head
ahead = head.next
if ahead.next is not None:
alternate = ahead.next
else:
alternate = ahead
head.next = None
tail = curr
while alternate:
ahead.next = curr
curr = ahead
if ahead == alternate:
head = ahead
return head, tail
else:
ahead = alternate
if alternate.next is not None:
alternate = alternate.next
else:
head = alternate
head.next = curr
return head, tail |
def flatten(a_list_of_lists):
"""
Flattens a list of lists into a single list.
:param a_list_of_lists: The list of list to flatten.
:return: The flattened list.
"""
flattened_list = []
for sub_list in a_list_of_lists:
for element in sub_list:
flattened_list.append(element)
return flattened_list |
def max_sum_subsequence(numbers):
"""
Parameters
----------
numbers : list
A list of integers
Returns
-------
int
The maximum sum of non adjacent numbers in the list
>>> max_sum_subsequence([1, 6, 10, 14, -5, -1, 2, -1, 3])
25
"""
# base case
list_size = len(numbers)
if list_size <= 0:
return 0
if list_size == 1:
return numbers[0]
if list_size == 2:
return max(numbers)
max_sums = [num for num in numbers]
for i in range(2, list_size):
max_sums[i] = max(max_sums[i] + max_sums[i - 2], max_sums[i - 1], max_sums[i - 2])
return max_sums[-1] |
def Cnp(n,p, l=None, res=None):
""" calculates p-uplets among n elements and returns a list of the p-uplets """
if l is None: l=[]
if res is None: res=[]
if p==0:
res.append(l)
return res
if n==0:
return res
else:
l1=list(l)
l1.append(n)
Cnp(n-1, p-1, l1, res)
Cnp(n-1, p, l, res)
return res |
def test_attrs(challenge, standard):
"""
test_attrs()
Compare list or val the standard.
- return True if at least one item from chalange list is in standard list
- False if no match
"""
stand_list = standard if type(standard) is list else [standard]
chal_list = challenge if type(challenge) is list else [challenge]
for chal in chal_list:
if chal in stand_list:
return True
return False |
def nested_select(d, v, default_selected=True):
"""
Nestedly select part of the object d with indicator v. If d is a dictionary, it will continue to select the child
values. The function will return the selected parts as well as the dropped parts.
:param d: The dictionary to be selected
:param v: The indicator showing which part should be selected
:param default_selected: Specify whether an entry is selected by default
:return: A tuple of two elements, the selected part and the dropped part
Examples:
>>> person = {'profile': {'name': 'john', 'age': 16, 'weight': 85}, \
'relatives': {'father': 'bob', 'mother': 'alice'}}
>>> nested_select(person, True)
({'profile': {'name': 'john', 'age': 16, 'weight': 85}, 'relatives': {'father': 'bob', 'mother': 'alice'}}, {})
>>> nested_select(person, {'profile': False})
({'relatives': {'father': 'bob', 'mother': 'alice'}}, {'profile': {'name': 'john', 'age': 16, 'weight': 85}})
>>> nested_select(person, {'profile': {'name': False}, 'relatives': {'mother': False}})
({'profile': {'age': 16, 'weight': 85}, 'relatives': {'father': 'bob'}},
{'profile': {'name': 'john'}, 'relatives': {'mother': 'alice'}})
"""
if isinstance(v, dict):
assert isinstance(d, dict)
choosed = d.__class__()
dropped = d.__class__()
for k in d:
if k not in v:
if default_selected:
choosed.setdefault(k, d[k])
else:
dropped.setdefault(k, d[k])
continue
if isinstance(v[k], dict):
assert isinstance(d[k], dict)
child_choosed, child_dropped = nested_select(d[k], v[k])
if child_choosed:
choosed.setdefault(k, child_choosed)
if child_dropped:
dropped.setdefault(k, child_dropped)
else:
if v[k]:
choosed.setdefault(k, d[k])
else:
dropped.setdefault(k, d[k])
return choosed, dropped
else:
other = d.__class__() if isinstance(d, dict) else None
return (d, other) if v else (other, d) |
def filter_list(obj):
"""
Filters a list by removing all the None value within the list.
"""
if isinstance(obj, (list, tuple)):
return [item for item in obj if item is not None]
return obj |
def inverse_stack(stack, remove_function_name) -> list:
"""
Helper function to inverse a stack.
:param stack: stack
:param remove_function_name: function name to remove top item
:return: inverted stack
"""
inverted_stack = list()
while len(stack) > 0:
inverted_stack.append(getattr(stack, remove_function_name)())
return inverted_stack |
def phase_times(times, period, offset=0):
"""Phase times by period."""
phased = (times - offset) % period
phased = phased / period
return phased |
def get_histogram_x(parsed_mutations):
"""Get x data values binned by Plotly when producing the histogram.
This is just the positions containing mutations, with duplicates
permitted for mutations shared by strains.
:param parsed_mutations: A dictionary containing multiple merged
``get_parsed_gvf_dir`` return "mutations" values.
:type parsed_mutations: dict
:return: List of x data values used in histogram view
:rtype: list[str]
"""
ret = []
for strain in parsed_mutations:
for pos in parsed_mutations[strain]:
for mutation in parsed_mutations[strain][pos]:
hidden_cell = mutation["hidden_cell"]
if not hidden_cell:
ret.append(pos)
return ret |
def jsontemplate(projectname,relay1,relay2,relay3,relay4,updated1,updated2,updated3,updated4):
""" Auto JSON template generator """
ilovecake = {
"canakit1104": {
"light_system_project_name" : projectname,
"relay" : {
1: {
"state": relay1,
"lastchange" : updated1,
},
2: {
"state": relay2,
"lastchange" : updated2,
},
3: {
"state": relay3,
"lastchange" : updated3,
},
4: {
"state": relay4,
"lastchange" : updated4,
},
}
}, "x-i-made-this" : "jonkelley@rackspace.com"
}
return ilovecake |
def get_keys(iter_, prefix=[]):
"""Return all different incremental paths
within the the given iterable.
A path is given as the sequence of keys obtained
from dictionaries within the iterable given.
"""
if type(iter_) == list:
out = set()
for element in iter_:
keys = get_keys(element, prefix)
out.update(tuple([key for key in keys]))
return out
elif type(iter_) == dict:
keys = list(iter_.keys())
out = set()
for key in keys:
out.add(tuple(prefix + [key]))
child = iter_[key]
if type(child) == dict or type(child) == list:
out.update(get_keys(child, prefix + [key]))
return out
return set() |
def list_index(ls, indices):
"""numpy-style creation of new list based on a list of elements and another
list of indices
Parameters
----------
ls: list
List of elements
indices: list
List of indices
Returns
-------
list
"""
return [ls[i] for i in indices] |
def _is_list_of_strings(thing):
"""Is ``thing`` a list of strings?"""
if isinstance(thing, list):
for element in thing:
if not isinstance(element, str):
return False
return True
else:
return False |
def find_nested_meta_first_bf(d, prop_name):
"""Returns the $ value of the first meta element with
the @property that matches @prop_name (or None).
"""
m_list = d.get('meta')
if not m_list:
return None
if not isinstance(m_list, list):
m_list = [m_list]
for m_el in m_list:
if m_el.get('@property') == prop_name or m_el.get('@rel') == prop_name:
return m_el
return None |
def mean(array: list) -> float:
"""
Calculates the mean of a given array.
"""
arr_sum = 0
for element in array:
arr_sum = arr_sum + element
return arr_sum/len(array) |
def formatTweetURL(user, status_id):
"""Returns formatted URL for tweets."""
return f'https://twitter.com/{user}/status/{status_id}' |
def joindigits(digits, base=10):
"""
>>> joindigits([])
0
>>> joindigits([1, 3])
13
"""
i = 0
for j in digits:
i *= base
i += j
return i |
def get_initial_states(data):
"""Defines initial states."""
global NUM_ROWS
NUM_ROWS = max([len(i) for i in data['cols']])
if data.get('init') == None:
data['init'] = [0] * NUM_ROWS
else:
data['init'] += [0] * (NUM_ROWS - len(data['init']))
return data |
def _as_float(string, default: float = 0.0):
"""Return first sequence as float."""
return float(string.strip().partition(" ")[0] or default) |
def leadingzero(number, minlength):
"""
Add leading zeros to a number.
:type number: number
:param number: The number to add the leading zeros to.
:type minlength: integer
:param minlength: If the number is shorter than this length than add leading zeros to make the length correct.
:return: The number with a leading zero
:rtype: string
>>> leadingzero(1, 2)
'01'
"""
# Return the number as a string with the filled number
return str(number).zfill(int(minlength)) |
def get_country_name(country_list, code):
"""
for item in the country list
if the code in the list matches the code provided then return the name
:param country_list - list of country names and their codes:
:param code - country code as string:
:return country_name - full country name:
"""
for item in country_list:
country_code = item[0]
country_name = item[1]
if country_code == code:
return country_name
return "Kosovo" |
def classifier_string_has_a_dog(classifier_string, dogs_dic):
"""
Classifier string contains string separated by "," so evalue
every value in the dogs dictionary to validate if it's a dog
"""
classifier_values = classifier_string.split(",")
for value in classifier_values:
if value.strip() in dogs_dic:
return True
return False |
def mysplit3(s) -> str:
"""Do a simple split of numbers and ."""
head = s.rstrip('0123456789')
tail = s[len(head):].zfill(2)
return head + tail |
def sha_padding(used_bytes, align_bytes):
"""
The SHA3 padding function
"""
padlen = align_bytes - (used_bytes % align_bytes)
if padlen == 1:
return [0x86]
elif padlen == 2:
return [0x06, 0x80]
else:
return [0x06] + ([0x00] * (padlen - 2)) + [0x80] |
def xstr(s):
"""If None convert to empty string"""
if s is None:
return u''
return s |
def init_parameters(parameter):
"""Auxiliary function to set the parameter dictionary
Parameters
----------
parameter: dict
See the above function NMFdiag for further information
Returns
-------
parameter: dict
"""
parameter = dict() if parameter is None else parameter
parameter['distMeas'] = 'divergence' if 'distMeas' not in parameter else parameter['distMeas']
parameter['numOfIter'] = 50 if 'fixW' not in parameter else parameter['numOfIter']
parameter['fixW'] = False if 'fixW' not in parameter else parameter['fixW']
parameter['continuity'] = {'length': 10,
'grid': 5,
'sparsen': [1, 1],
'polyphony': 5} if 'continuity' not in parameter else parameter['continuity']
parameter['vis'] = False if 'vis' not in parameter else parameter['vis']
return parameter |
def converter_tuple(obj) -> tuple:
"""
Convert input to a tuple. ``None`` will be converted to an empty tuple.
Parameters
----------
obj: Any
Object to convert.
Returns
-------
obj: Tuple[Any]
Tuple.
"""
if obj is None:
return ()
elif hasattr(obj, "__iter__") and not isinstance(obj, (str, bytes)):
return tuple(x for x in obj)
else:
return (obj,) |
def dehomogenize(xyzw):
"""Dehomogenise a list of vectors.
Parameters
----------
xyzw : sequence[[float, float, float, `w`]]
A list of vectors.
Returns
-------
list[[float, float, float]]
Dehomogenised vectors.
Examples
--------
>>>
"""
return [[x / w, y / w, z / w] if w else [x, y, z] for x, y, z, w in xyzw] |
def fracDiff1D(x1, x2):
"""
Fractional difference between 2 1d vectors
"""
dx = abs(x2 - x1)
meanx = 0.5*(abs(x1) + abs(x2))
return dx/meanx |
def parse_devices(device_string):
"""
device string format as '0,1,2,3...'
:param device_string:
:return:
"""
return [int(d) for d in device_string.split(',')] |
def update_config(config, new_config):
"""Updates configuration in a hierarchical level.
For key-value pair {'a.b.c.d': v} in `new_config`, the `config` will be
updated by
config['a']['b']['c']['d'] = v
"""
if new_config is None:
return config
assert isinstance(config, dict)
assert isinstance(new_config, dict)
for key, val in new_config.items():
hierarchical_keys = key.split('.')
temp = config
for sub_key in hierarchical_keys[:-1]:
temp = temp[sub_key]
temp[hierarchical_keys[-1]] = val
return config |
def request_reset_password(id):
"""
This function generates a password reset key and sends an email with to the user.
:param id: Id of the user.
:return: 200 on success, 404 on user does not exists, 400 incorrect input parameters.
"""
# Send Email
return [] |
def same_abs(num1, num2):
""" (number, number) -> bool
Return True iff (if and only if)
num1 and num2 have the same absolute value.
>>> same_abs(-3, 3)
True
>>> same_abs(3, 3.5)
False
"""
return abs(num1) == abs(num2) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.