content
stringlengths 42
6.51k
|
---|
def precedence(char):
"""Return integer value representing an operator's precedence, or
order of operation.
https://en.wikipedia.org/wiki/Order_of_operations
"""
dictionary = {"+": 1, "-": 1, "*": 2, "/": 2, "^": 3}
return dictionary.get(char, -1)
|
def IRADCTaxCredit(e03150, e03300, IRADC_credit_c, IRADC_credit_rt, iradctc):
"""
Computes refundable retirement savings tax credit amount.
"""
# calculate refundable credit amount
tot_retirement_contributions = e03150 + e03300
if IRADC_credit_rt > 0.:
iradctc = min(tot_retirement_contributions * IRADC_credit_rt, IRADC_credit_c)
else:
iradctc = 0.
return (iradctc)
|
def genSummary(compList, compLockList, lockRet):
"""Generate a summary of management nodes locked and any errors that occurred."""
print("Operation Summary")
print("=================")
print("Found %d management nodes and BMCs:" % (len(compList)))
print(" " + ','.join(compList))
print("Found %d management nodes and BMCs to lock:" % (len(compLockList)))
print(" " + ','.join(compLockList))
if lockRet['Counts']['Success'] > 0:
print("Successfully locked %d management nodes and BMCs:" % (lockRet['Counts']['Success']))
compStr = ','.join(lockRet['Success']['ComponentIDs'])
print(" " + compStr)
if lockRet['Counts']['Failure'] > 0:
print("Failed to lock %d management nodes and BMCs:" % (lockRet['Counts']['Failure']))
for comp in lockRet['Failure']:
print(" " + comp['ID'] + " - " + comp['Reason'])
print("")
return lockRet['Counts']['Failure']
|
def get_action(head, M, N):
"""Given the location of the head of the snake, returns an action for that location.
Args:
head (tuple): a tuple of length 2 representing the location of the head of the snake on a 2D grid.
Returns:
int: an action
"""
# top left corner goes down.
if head == (0, 0):
return 2
# top row goes left.
if head[0] == 0:
return 1
# last column goes up.
if head[1] == N - 1:
return 0
# head is on an even column.
if head[1] % 2 == 0:
# turn right if at the bottom.
if head[0] == M - 1:
return 3
# continue down otherwise.
return 2
#head is on an odd column.
if head[0] == 1:
# turn right if on the first row.
# otherwise, will hit body.
return 3
# continue up otherwise.
return 0
|
def rget(source, keys):
"""Get a value from nested dictionaries.
Params
------
* source (dict) : (possibly) nested dictionary
* keys (str, list): a string of nested keys seperated by "." or the
resulting list split from such a string
Returns
-------
(Any) The final value
Examples
-------
>>> org = {'ops': { 'manager': "Joe Smith"}, 'manager': "Bill Jones"}
>>> rget(org, "manager")
'Bill Jones'
>>> rget(org, "ops.manager")
'Joe Smith'
"""
# Return None for empty keys
if not keys or not source: return
# split {keys} strings by "."
if isinstance(keys, str):
keys = keys.split(".")
# get the first key from the list
this_key = keys.pop(0)
# recursively call rget() if there are keys remaining
if len(keys):
return rget(source.get(this_key, {}), keys)
# if this was the last key, return the final value
else:
return source.get(this_key)
|
def hasCycle(head):
"""
Use two pointers(one slow, one fast) to traverse the list.
Two pointers are bound to meet if there is a cycle;
otherwise, fast pointer will reach the end eventually.
"""
slow = head
fast = head
while fast and fast.next: # note the condition
slow = slow.next
fast = fast.next.next
if slow == fast:
return True
return False
|
def is_jsfunc(func: str) -> bool: # not in puppeteer
"""Heuristically check function or expression."""
func = func.strip()
if func.startswith('function') or func.startswith('async '):
return True
elif '=>' in func:
return True
return False
|
def get_where_clause(columns_to_query_lst):
"""
get_where_clause returns the where clause from the given query list.
:param columns_to_query_lst: columns for where clause.
:return:
"""
where_str = "where "
equals_str =[]
for row in columns_to_query_lst:
temp_str = "c." + row + " = t." + row
equals_str.append(temp_str)
joined_str = " AND ".join(equals_str)
where_str = where_str + joined_str
return where_str
|
def get_lam2(membrane_geometry):
""" dimensionless geometry coefficient lambda2
The corresponding definition (of different separability factor) is provided in Table 1 in [2].
Note that the definition in [2] is slightly different due to the use of hydraulic radius of channel.
This means that the lam2 in this code is 4, 3/2, and 3/4 respectively for CM, FMM, and FMS.
However, the lambda1 in reference [2] is 2, 3/2, and 3/4 respectively for CM, FMM, and FMS (divided by RH/R from lam2 here)
"""
# the default value will be the case of 'HF'
lam2 = 4.
if (membrane_geometry=='FMM'):
lam2 = 3/2.
elif (membrane_geometry=='FMS'):
lam2 = 3/4.
return lam2
|
def find_bands(bands, target_avg, target_range, min_shows):
"""
Searches dictionary of bands with band name as keys and
competition scores as values for bands that are within the
range of the target average and have performed the minimum
number of shows. Returns a list of bands that meet the search
criteria.
Parameters:
bands: Dictionary with band name as keys and scores as values.
target_avg: Tuple containing the average to look for and the
amount of scores to look at.
target_range: Range to look away from the target average.
min_shows: Minimum number of shows to be eligible.
Returns:
List of bands that meet the search criteria.
>>> DCI = {'Blue Devils': [98.2, 97.1, 99.1, 97.3, 98.2], \
'Blue Coats': [98, 96.5, 97.2, 93, 92.1, 92, 97.4], \
'Carolina Crown': [75.7, 82.8, 86.1, 98.2], \
'The Cadets': [96.1, 93.4, 81, 78, 57.9, 86, 71.2, 35.5], \
'Mandarins': [89.3, 88.1, 85.6, 83.8, 79.1, 88.4, 75.7], \
'Little Rocks':[42], \
'Logan Colts':[98.2, 84.4, 69.2, 42, 84]}
>>> find_bands(DCI, (0, 10), 30, 2)
[]
>>> find_bands(DCI, (90, 5), 5, 7)
['Mandarins']
>>> find_bands(DCI, (70, 8), 10, 5)
['The Cadets', 'Logan Colts']
>>> find_bands(DCI, (95, 3), 5, 4)
['Blue Devils', 'Blue Coats', 'The Cadets']
# My doctests
>>> find_bands(DCI, (42, 10), 1, 1)
['Little Rocks']
>>> find_bands(DCI, (87, 10), 5, 5)
['Mandarins']
>>> DCI2 = {'UCSD': [100, 99, 100, 100, 100, 100], \
'UCLA': [50, 49, 100, 100, 100], \
'UCD': [90, 90, 87, 45, 79]}
>>> find_bands(DCI2, (95, 3), 5, 4)
['UCSD']
>>> find_bands(DCI2, (75, 5), 10, 4)
['UCLA', 'UCD']
"""
search_range = [target_avg[0] - target_range, target_avg[0] + target_range]
lower_bound = search_range[0]
upper_bound = search_range[1]
noted_scores = target_avg[1]
score_index = 1
in_range = lambda avg: (avg >= lower_bound and avg <= upper_bound)
score_avg = lambda scores, kept_scores: sum(scores) / len(scores) \
if len(scores) <= kept_scores \
else sum(scores[0:kept_scores]) / kept_scores
return list(map(lambda name: name[0], \
list(filter(lambda band: \
in_range(score_avg(band[score_index], noted_scores)), \
filter(lambda band: True if len(band[score_index]) >= min_shows \
else False, list(bands.items()))))))
|
def int_to_hex(value, octets=2):
""" hex representation as network order with size of ``octets``
ex) int_to_hex(1) # => "0001"
int_to_hex(32, 4) # => "00000020"
"""
return ('%%0%dx' % (octets * 2)) % value
|
def merge_lists(first, second):
"""
Merges two lists alternately.
E.g.:
first = [1, 2]
second = ["A", "B"]
result = [1, "A", 2, "B"]
"""
return [item for pair in zip(first, second) for item in pair]
|
def staff_pick_statistics(contributions):
"""Returns a list of contributions that were staff picked."""
staff_picks = []
for contribution in contributions:
# If contribution wasn't staff picked skip it
if not contribution["staff_picked"]:
continue
staff_picks.append(contribution)
return {"staff_picks": staff_picks}
|
def factorial(x: int) -> int:
"""
Test Methodmake
>>> factorial(5)
120
>>> factorial(4)
24
>>> factorial(7)
5040
"""
aux: int = 1
for i in range(1, x+1):
aux = aux*i
return aux
|
def parse_sexp(string):
"""
Parses an S-Expression into a list-based tree.
parse_sexp("(+ 5 (+ 3 5))") results in [['+', '5', ['+', '3', '5']]]
"""
sexp = [[]]
word = ''
in_str = False
for c in string:
if c == '(' and not in_str:
sexp.append([])
elif c == ')' and not in_str:
if word:
sexp[-1].append(word)
word = ''
temp = sexp.pop()
sexp[-1].append(temp)
elif c in (' ', '\n', '\t') and not in_str:
if word != '':
sexp[-1].append(word)
word = ''
elif c == '\"':
in_str = not in_str
else:
word += c
return sexp[0]
|
def get_level_name(adeptus: str, level: int):
"""
Get level name.
:param level: an integer
:param adeptus: an alphabetic string
:precondition: level must be an integer
:precondition: adeptus must me an alphabetic string
:postcondition: returns a common for all adepts name if level is not 3
:postcondition: returns a unique name based on the chosen adeptus if level is 3
:return: a unique name if level is 3, else a common name
>>> get_level_name("Adeptus Officio Assassinorum", 3)
Night Haunter
>>> get_level_name("Adeptus Astra Telepathica", 2)
Inquisitor
"""
level_dictionary = {"Adeptus Astra Telepathica": "Magister Telepathicae", "Adeptus Astra Militarum":
"Legionary Astartes", "Adeptus Mechanicus": "Techno-Priest", "Adeptus Officio Assassinorum":
"Night Haunter", 1: "Acolyte", 2: "Inquisitor"}
if level != 3:
return [level, level_dictionary[level]]
else:
return [level, level_dictionary[adeptus]]
|
def get_sfe_per_part(sfe_map, bp_list):
"""
Tries to retrieve the sfe per body part.
The corresponding body part will be either
the second or the third element of the body parts list.
"""
_main_part, penalty_part, sfe_part = bp_list
try:
sfe = sfe_map[sfe_part]
except KeyError:
sfe = sfe_map[penalty_part]
return sfe
|
def scale(y, a, b):
"""
Scales the vector y (assumed to be in [0,1]) to [a,b]
:param y:
:param a:
:param b:
:return:
"""
return a*y + (b-a)*y
|
def normalise_days(periodType, value):
"""
This is a helper function to normalise periodtype
to always reflect the number of days
"""
periodType = periodType.lower()
normalised_days = 0
if periodType == 'weeks':
normalised_days = value * 7
elif periodType == 'months':
normalised_days = value * 30
else:
normalised_days = value
return normalised_days
|
def endtime(task, events):
""" Endtime of task in list of events """
for e in events:
if e.task == task:
return e.end
|
def decode_ascii(string):
"""Decodes a string as ascii."""
return string.decode("ascii")
|
def read_file(path):
"""return the content of the file"""
content = ""
with open(path, 'rb') as f:
content = f.read()
return content
|
def get_max_indices(my_list):
""" Gets a list of the maximum values' indices in a list.
Args:
my_list (list of ordinal): The list to find the maximums from.
Returns:
list of int: The indices where max values exist.
"""
assert len(my_list) > 0
max_indices = [0]
curr_max = my_list[0]
for i in range(1, len(my_list)):
if my_list[i] > curr_max:
# Reset
curr_max = my_list[i]
max_indices = [i]
elif my_list[i] == curr_max:
# Add the index
max_indices.append(i)
return max_indices
|
def byte_chars(byte_string):
"""Return list of characters from a byte string (PY3-compatible).
In PY2, `list(byte_string)` works fine, but in PY3, this returns
each element as an int instead of single character byte string.
Slicing is used instead to get the individual characters.
Parameters
----------
byte_string : bytes
Byte string to be split into characters.
Returns
-------
chars : list
The individual characters, each as a byte string.
"""
return [byte_string[i:i+1] for i in range(len(byte_string))]
|
def ignore(value, function, *args, **kwargs):
"""
Invoke ``function`` with ``*args`` and ``*kwargs``.
Use this to add a function to a callback chain that just ignores the
previous value in the chain::
>>> d = defer.succeed(42)
>>> d.addCallback(ignore, print, 37)
37
"""
return function(*args, **kwargs)
|
def findmodifiers(command):
"""
Find any of +-@% prefixed on the command.
@returns (command, isHidden, isRecursive, ignoreErrors, isNative)
"""
isHidden = False
isRecursive = False
ignoreErrors = False
isNative = False
realcommand = command.lstrip(' \t\n@+-%')
modset = set(command[:-len(realcommand)])
return realcommand, '@' in modset, '+' in modset, '-' in modset, '%' in modset
|
def g(n):
"""Return the value of G(n), computed recursively.
>>> g(1)
1
>>> g(2)
2
>>> g(3)
3
>>> g(4)
10
>>> g(5)
22
>>> from construct_check import check
>>> # ban iteration
>>> check(HW_SOURCE_FILE, 'g', ['While', 'For'])
True
"""
"*** YOUR CODE HERE ***"
if n <= 3:
return n
else:
return g(n - 1) + 2 * g(n - 2) + 3 * g(n - 3)
|
def PreOpN(op, items):
""" Naive PreOp algorithm """
k = len(items)
output = [None]*k
output[0] = items[0]
for i in range(1, k):
output[i] = op(output[i-1], items[i])
return output
|
def stations_highest_rel_level(stations, N):
"""
Function that returns the N number of most at risk stations.
Args:
stations (list): List of stations (MonitoringStation).
N (int): Length of the desired list
Returns:
list: List of stations (MonitoringStation).
"""
return sorted(filter(
lambda x: x.relative_water_level() is not None,
stations
),
key=lambda x: x.relative_water_level(),
reverse=True
)[:N]
|
def check_is_number(expression):
"""Checks whether expression is a number.
Args:
expression: Sympy expression.
Returns:
Boolean.
"""
# NOTE(leeley): If sympy expression is a single numerical value, it may be
# represented as float or int instead of sympy expression.
# For example,
# sympy.sympify('1.') is sympy.core.numbers.Float
# sympy.sympify('c', locals={'c': 1.}) is float.
return isinstance(expression, (int, float)) or expression.is_number
|
def lorentz(v, v0, I, w):
"""
A lorentz function that takes linewidth at half intensity (w) as a
parameter.
When `v` = `v0`, and `w` = 0.5 (Hz), the function returns intensity I.
Arguments
---------
v : float
The frequency (x coordinate) at which to evaluate intensity (y
coordinate).
v0 : float
The center of the distribution.
I : float
the relative intensity of the signal
w : float
the peak width at half maximum intensity
Returns
-------
float
the intensity (y coordinate) for the Lorentzian distribution
evaluated at frequency `v`.
"""
# Adding a height scaling factor so that peak intensities are lowered as
# they are more broad. If I is the intensity with a default w of 0.5 Hz:
scaling_factor = 0.5 / w # i.e. a 1 Hz wide peak will be half as high
return scaling_factor * I * (
(0.5 * w) ** 2 / ((0.5 * w) ** 2 + (v - v0) ** 2))
|
def double_quoted(s):
"""
Function to put double quotes around a string.
Parameters
----------
s: str
String.
Returns
-------
str
String in double quotes.
"""
return '"' + s + '"'
|
def get_text(block, blocks_map):
"""Retrieves text associated with a block.
Args:
block (dict): Information related to one Block Object
blocks_map (dict): All Block objects analyzed by textract.
Returns:
str: Text associated with a Block.
"""
text = ''
if 'Relationships' in block:
for relationship in block['Relationships']:
if relationship['Type'] == 'CHILD':
for child_id in relationship['Ids']:
word = blocks_map[child_id]
if word['BlockType'] == 'WORD':
text += word['Text'] + ' '
return text
|
def get_accuracy_score(mean_silhouette_coverage: float) -> float:
"""Calculate the accuracy score given the coverage of the graph by the silhouette between means.
Return the accuracy score.
Arguments:
mean_silhouette_coverage -- Coverage of the total graph by the respective silhouette between
means.
"""
return 0.5 + (0.5 * mean_silhouette_coverage)
|
def precision2eml(precision):
"""convert e.g., 3 to 1e-3 where 3 is the
number of decimal places"""
# FIXME is that correct?
return '1e-{}'.format(precision)
|
def palindrome(value: str) -> bool:
"""
This function determines if a word or phrase is a palindrome
:param value: A string
:return: A boolean
"""
value = value.replace(" ", "").lower()
return value == value[::-1]
|
def ordered_node_greedy_best_first(node, h, node_tiebreaker):
"""
Creates an ordered search node (basically, a tuple containing the node
itself and an ordering) for greedy best first search (the value with lowest
heuristic value is used).
@param node The node itself.
@param h The heuristic value.
@param node_tiebreaker An increasing value to prefer the value first
inserted if the ordering is the same.
@returns A tuple to be inserted into priority queues.
"""
f = h
return (f, h, node_tiebreaker, node)
|
def port_from_datastore_start_cmd(args):
""" Extracts appscale-datastore server port from command line arguments.
Args:
args: A list representing command line arguments of server process.
Returns:
An integer representing port where server is listening on.
Raises:
ValueError if args doesn't correspond to appscale-datastore.
"""
if len(args) < 2 or not args[1].endswith('appscale-datastore'):
raise ValueError('Not a datastore start command')
return int(args[args.index('--port') + 1])
|
def verify_allow(value, expected):
"""
Verify Allow header methods.
"""
if value is None:
return False
if value[-1] == ",":
value = value[:-1]
methods = value.split(",")
methods = [m.strip() for m in methods]
if len(expected) != len(methods):
return False
for exp in expected:
if exp not in methods:
return False
return True
|
def GroupByProject(locations):
"""Group locations by project field."""
result = {}
for location in locations or []:
if location.project not in result:
result[location.project] = []
result[location.project].append(location)
return result
|
def is_str_int(n: str, rounding_error=1e-7) -> bool:
"""Check whether the given string is an integer or not. """
try:
if int(n) - float(n) < rounding_error:
return True
else:
return False
except ValueError:
return False
|
def is_palindrome2(w):
"""Strip outermost characters if same, return false when mismatch."""
while len(w) > 1:
if w[0] != w[-1]: # if mismatch, return False
return False
w = w[1:-1] # strip characters on either end; repeat
return True # must have been a Palindrome
|
def task_mask (current_task):
""" Defines whether or not the given task is eligible for
execution.
"""
## allow = mcscript.approx_equal(current_task["hw"],20.,0.1)
allow = True
return allow
|
def Sgn(num):
"""Return the sign of a number"""
n = float(num)
if n < 0:
return -1
elif n == 0:
return 0
else:
return 1
|
def is_macs_header(line):
"""Returns if the line is a header line used in MACS/MACS2 xls."""
line = line.strip()
if line.startswith('#') or line.split('\t')[0] == 'chr':
return True
else:
return False
|
def list_merge_values(d, d2, in_place=True):
"""
Parameters
----------
d
d2
in_place : bool, optional (default is True)
Do the update in-place.
Examples
--------
>>> list_merge_values({1:[2]}, {1:[3]})
{1: [2, 3]}
Returns
-------
"""
d3 = d.copy() if not in_place else d
for key, val in d2.items():
if key not in d3:
d3[key] = val
else:
d3[key].extend(val)
return d3
|
def largest_palindrome(string):
"""
Runtime: O(
"""
max_len = len(string)+1
# Begin with the largest possible palindrome
for length in range(max_len,2,-1):
start = 0
end = length
while (end < max_len):
curr = string[start:end]
rev = curr[::-1]
if curr == rev:
return curr
start += 1
end += 1
|
def make_cvss_scores(metrics):
"""
[
{
"cvss_v2": {
"base_metrics": {
...
},
"vector_string": "AV:N/AC:L/Au:N/C:P/I:P/A:P",
"version": "2.0"
},
"cvss_v3": {
"base_metrics": {
...
},
"vector_string": "CVSS:3.0/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H",
"version": "3.0"
},
"id": "CVE-2019-1234"
},
{
"cvss_v2": {
"base_metrics": {
...
},
"vector_string": "AV:N/AC:L/Au:N/C:P/I:P/A:P",
"version": "2.0"
},
"cvss_v3": {
"base_metrics": {
...
},
"vector_string": "CVSS:3.0/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H",
"version": "3.0"
},
"id": "CVE-2019-3134"
},
]
:param metrics:
:return:
"""
score_list = []
for metric in metrics:
new_score_packet = {
"id": metric.get("id"),
}
score_list.append(new_score_packet)
for i in [3, 2]:
cvss_dict = metric.get("cvss_v{}".format(i), {})
base_metrics = cvss_dict.get("base_metrics", {}) if cvss_dict else {}
tmp = base_metrics.get("base_score", -1.0)
base_score = float(tmp) if tmp else -1.0
tmp = base_metrics.get("exploitability_score", -1.0)
exploitability_score = float(tmp) if tmp else -1.0
tmp = base_metrics.get("impact_score", -1.0)
impact_score = float(tmp) if tmp else -1.0
new_score_packet["cvss_v{}".format(i)] = {
"base_score": base_score,
"exploitability_score": exploitability_score,
"impact_score": impact_score,
}
return score_list
|
def _modeToListOfFlags(mode):
"""
Transforms a number representing a mode to a list of flags.
"""
mode_flags = {
777: 'S_IRWXA', 700: 'S_IRWXU', 400: 'S_IRUSR', 200: 'S_IWUSR',
100: 'S_IXUSR', 70: 'S_IRWXG', 40: 'S_IRGRP', 20: 'S_IWGRP',
10: 'S_IXGRP', 7: 'S_IRWXO', 4: 'S_IROTH', 2: 'S_IWOTH',
1: 'S_IXOTH'}
list_of_flags = []
# check for all permissions.
if mode == 777:
list_of_flags.append(mode_flags[777])
else:
# deal with each entity (digit) at a time (user then group
# then other)
mode_string = str(mode)
# used to translate eg 7 to 700 for user.
entity_position = 10**(len(mode_string)-1)
for mode_character in str(mode):
try:
entity = int(mode_character)
except ValueError:
raise Exception("Unexpected mode format: " + str(mode))
# is the mode in the correct format?
if entity < 0 or entity > 7:
raise Exception("Unexpected mode format: " + str(mode))
# check if current entity has all permissions
if entity == 7:
list_of_flags.append(mode_flags[entity*entity_position])
else:
# check entity for each flag.
for flag in mode_flags:
if flag > 7*entity_position or flag < entity_position:
continue
compare = int(str(flag).strip('0'))
if entity & compare == compare:
list_of_flags.append(mode_flags[flag])
entity_position /= 10
return list_of_flags
|
def two_sum(nums, target=0, distinct=True):
"""
Return the indices of two numbers in `nums` that sum to `target` if such
numbers exist; None otherwise.
nums -- a list of numbers
target -- a number (default 0)
distinct -- if True only return distinct indices, i.e. there must be two
entries (not necessarily with distinct values) that sum to
target - we don't accept a single entry being repeated;
allow repeats otherwise
Time complexity: O(n)
Space complexity: O(n)
"""
# insert all nj's in a dict, which will remember their index in `nums`
num_to_index = dict()
for j, nj in enumerate(nums):
num_to_index[nj] = j
# iterate through nums
for i, ni in enumerate(nums):
# if ni's complement (w.r.t. target) exists
if (target - ni) in num_to_index:
# do we want distinct entries? or do we allow repeats?
if distinct and i == num_to_index[target - ni]:
continue
# return the indices of ni and its complement
return i, num_to_index[target - ni]
# else
return None
|
def pre_treat_message(message):
""" removes punctuation (:;,.?!) and converts message to upper case """
treated_message = message
# remove punctuation, one symbol at a time
treated_message = treated_message.replace(':', '') # remove colons
treated_message = treated_message.replace(';', '') # remove semicolons
treated_message = treated_message.replace(',', '') # remove commas
treated_message = treated_message.replace('.', '') # remove periods
treated_message = treated_message.replace('?', '') # remove question marks
treated_message = treated_message.replace('!', '') # remove exclamation points
# convert to uppercase
treated_message = treated_message.upper()
return treated_message
|
def base_resolve_path(project_slug, filename, version_slug=None, language=None, private=False,
single_version=None, subproject_slug=None, subdomain=None, cname=None):
""" Resolve a with nothing smart, just filling in the blanks."""
if private:
url = '/docs/{project_slug}/'
elif subdomain or cname:
url = '/'
else:
url = '/docs/{project_slug}/'
if subproject_slug:
url += 'projects/{subproject_slug}/'
if single_version:
url += '{filename}'
else:
url += '{language}/{version_slug}/{filename}'
return url.format(
project_slug=project_slug, filename=filename,
version_slug=version_slug, language=language,
single_version=single_version, subproject_slug=subproject_slug,
)
|
def separate_artists_list_by_comparing_with_another(
another_artists_list, compared_artist_list
):
"""
Input: Two list of artists_id
Return two lists containing:
- Every artist in compared_artist_list that are in another_artists_list
- Every artist in compared_artist_list that are not in another_artists_list
"""
is_in_artist_list = []
is_not_in_artist_list = []
for artist in compared_artist_list:
if artist in another_artists_list:
is_in_artist_list.append(artist)
else:
is_not_in_artist_list.append(artist)
return is_in_artist_list, is_not_in_artist_list
|
def _in_bounds(point, bounds):
"""Is the point in the given rectangular bounds?"""
for i in range(len(bounds['x1'])):
if point[0] > bounds['x1'][i] and point[0] < bounds['x2'][i] and \
point[1] > bounds['y1'][i] and point[1] < bounds['y2'][i]:
return True
return False
|
def _spectrum_byte_offset(spectrum_index, n_records_per_spectrum, spec_rec_start_index=83):
""" Gives byte offset in file for where spectrum should occur
spectrum_index begins with index 1
"""
return 256 * (spec_rec_start_index + n_records_per_spectrum * (spectrum_index - 1) - 1)
|
def merge(left, right):
"""Performs the merge of two lists."""
result = None
if left == None: return right
if right == None: return left
if left.value > right.value:
result = right
result.next = merge(left, right.next)
else:
result = left
result.next = merge(left.next, right)
result.next.prev = result
return result
|
def collect_specific_bytes(bytes_object: bytes, start_position: int = 0, width: int = 0):
"""
Collects specific bytes within a bytes object.
:param bytes_object: an opened bytes object
:param start_position: the position to start to read at
:param width: how far to read from the start position
:param relative_to: position relative to 0 -> start of file/object, 1 -> current position of seek head,
2 -> end of file/object
:return: the bytes starting at position
"""
# navigate to byte position
content = bytes_object[start_position: start_position + width]
return {"content": content, "new_position": start_position + width}
|
def urlstring(f, baseUrl, dropExtension=False) :
"""Forms a string with the full url from a filename and base url.
Keyword arguments:
f - filename
baseUrl - address of the root of the website
dropExtension - true to drop extensions of .html from the filename in urls
"""
if f[0]=="." :
u = f[1:]
else :
u = f
if len(u) >= 11 and u[-11:] == "/index.html" :
u = u[:-10]
elif u == "index.html" :
u = ""
elif dropExtension and len(u) >= 5 and u[-5:] == ".html" :
u = u[:-5]
if len(u) >= 1 and u[0]=="/" and len(baseUrl) >= 1 and baseUrl[-1]=="/" :
u = u[1:]
elif (len(u)==0 or u[0]!="/") and (len(baseUrl)==0 or baseUrl[-1]!="/") :
u = "/" + u
return baseUrl + u
|
def duration_hms(time_delta):
"""time_delta -> 1:01:40"""
minutes, s = divmod(time_delta, 60)
h, minutes = divmod(minutes, 60)
return "%d:%02d:%02d" % (h, minutes, s)
|
def alt1(n, m):
"""Build up number, taking modulo as you go. Slow but simple."""
mod = 10**m
res = 1
for _ in range(n):
res = (res << 1) % mod
return res
|
def mock_get_response(url):
"""Mock _get_response() function."""
json_data = False
if url.lower().startswith('https'):
json_data = {'titles': ['title is found']}
return json_data
|
def verifyQtyProtContigs(qtyProteins, dictProteins, dictContigs):
"""
Verify if all the proteins of the bacteriophage are mapped into the contigs
:param qtyProteins: List of all the proteins of the bacteriophage
:param dictProteins: List of all the contigs of the bacteriophage
:param dictContigs: List of all the contigs of the bacteriophage
:type qtyProteins: List[Protein]
:type dictProts: dictionary{int: list[Proteins]}
:type dictConts: dictionary{int: Contig}
:return: True if the number of the proteins are exact of false in case of contrary and qty of counted proteins
:rtype bool and int
"""
qtyCountProt = 0
for key, value in dictContigs.items():
if key in dictProteins.keys():
qtyCountProt += len(dictProteins[key])
if qtyCountProt == qtyProteins:
return True, qtyCountProt
else:
return False, qtyCountProt
|
def linear_series(z, a, delta):
"""
returns a + (a + delta) * z + (a + 2 * delta) * z ** 2 + ...
"""
z1 = 1 - z
return (a - (a + delta) * z) / (z1 * z1)
|
def deg2gon(ang):
""" convert from gon to degrees
Parameters
----------
ang : unit=degrees, range=0...360
Returns
-------
ang : unit=gon, range=0...400
See Also
--------
gon2deg, deg2compass
"""
ang *= 400/360
return ang
|
def __path_similarity(p1, p2):
"""
test a path for % similarity
Very rough and ready, just measures the number of nodes in common, not the order or edges.
I should check the Diez paper for a better arrangement.
"""
A = set(p1)
B = set(p2)
AB = A & B
return len(AB) / float(min(len(A),len(B))) * 100.0
|
def nvcc_kernel(name, params, body):
"""Return the c code of a kernel function.
:param params: the parameters to the function as one or more strings
:param body: the [nested] list of statements for the body of the
function. These will be separated by ';' characters.
"""
paramstr = ', '.join(params)
def flatbody():
for b in body:
if isinstance(b, (list, tuple)):
for bb in b:
yield bb
else:
yield b
bodystr = ';\n'.join(flatbody())
return """__global__ void %(name)s (%(paramstr)s)
{
%(bodystr)s;
}
""" % locals()
|
def decode(encoded_message, rails):
"""
Decode a message with the rail fence cipher.
:param message string - The encoded text.
:param rails int - The number of rails to use to decode.
:return string - The decoded text.
"""
rail_index_max = rails - 1
zigzag = []
while rails > 0:
zigzag.append(["."] * len(encoded_message))
rails -= 1
rail_index = 0
col_index = 0
alternate = True
for index, char in enumerate(encoded_message):
if rail_index > rail_index_max:
break
zigzag[rail_index][col_index] = char
# move index over to account for rows below (or above)
from_horizontal_edge = min(rail_index_max - rail_index, abs(0 - rail_index))
if from_horizontal_edge > 0 and alternate:
col_index += from_horizontal_edge * 2
else:
col_index += (rail_index_max * 2) - (from_horizontal_edge * 2)
if alternate:
alternate = False
else:
alternate = True
if col_index >= len(encoded_message):
rail_index += 1
col_index = rail_index
if rail_index > rail_index_max // 2:
alternate = True
else:
alternate = False
decoded_message = ""
direction = '+'
rail_index = 0
for index, char in enumerate(encoded_message):
decoded_message += zigzag[rail_index][index]
if rail_index == rail_index_max:
direction = '-'
elif rail_index == 0:
direction = '+'
if direction == '+':
rail_index += 1
elif direction == '-':
rail_index -= 1
return decoded_message
|
def calc_masksize(width):
""" Computes number of bytes for AND mask. """
return int((width + 32 - width % 32 if (width % 32) > 0 else width) / 8)
|
def mean(list):
"""calculate mean of numeric list"""
total = 0
for item in list:
total += item
mean = total / len(list)
return mean
|
def max_contig_sum(L):
""" L, a list of integers, at least one positive
Returns the maximum sum of a contiguous subsequence in L """
max_contiguous_sum = 0
point = 0
for subsequence in range(len(L)):
current_subsequence = []
for index, number in enumerate(L[point:]):
if not current_subsequence and number <= 0:
continue
else:
try:
if sum(current_subsequence) + number > sum(current_subsequence) or sum(current_subsequence) + L[index + 1] > sum(current_subsequence) + number:
current_subsequence.append(number)
if sum(current_subsequence) > max_contiguous_sum:
max_contiguous_sum = sum(current_subsequence)
else:
current_subsequence = []
except IndexError:
if sum(current_subsequence) + number > sum(current_subsequence):
current_subsequence.append(number)
if sum(current_subsequence) > max_contiguous_sum:
max_contiguous_sum = sum(current_subsequence)
point += 1
return max_contiguous_sum
|
def split_date(date):
"""
Splits date from format %y%m%d to %y-%m-%d
"""
date = str(date)
y = date[:4]
m = date[4:6]
d = date[6:]
return '-'.join([y, m, d])
|
def searching_in_a_matrix(m1, value):
""" searches an element in a matrix where in every row, the values are increasing from left to
right, but the last number in a row is smaller than the first number in the next row.
The naive brute force solution scan all numbers and cost O(nm). However, since the numbers are
already sorted, the matrix can be viewed as a 1D sorted array. The binary search algorithm is
suitable. The efficience is O(logmn)."""
rows = len(m1)
cols = len(m1[0])
lo = 0
hi = rows*cols
while lo < hi:
mid = (lo + hi)//2
row = mid//cols
col = mid%cols
v = m1[row][col]
if v == value: return True
elif v > value: hi = mid
else: lo = mid+1
return False
|
def rotate_blocks(blocks,r):
"""rotates a set of points in 2D space by r*90 degrees"""
r = r % 4
if r == 0:
return blocks
for i in range(len(blocks)):
block = blocks[i]
if r == 1:
blocks[i] = (-block[1], block[0])
elif r == 2:
blocks[i] = (-block[0], -block[1])
elif r == 3:
blocks[i] = (block[1],-block[0])
return blocks
|
def checkOneEndOverlap(xa, xb, ya, yb):
"""
check the overlap of a region for the same chromosome
"""
if (ya <= xa <= yb) or (ya <= xb <= yb) or (ya <= xa <= xb <= yb):
return True
if (xa <= ya <= xb) or (xa <= yb <= xb) or (xa <= ya <= yb <= xb):
return True
return False
|
def stringify_access(rights):
""" convert list or string to list with commas """
# [u'frank', u'bob'] => 'frank, bob'
# u'joe' => 'joe'
if type(rights) == type('') or type(rights) == type(''):
return str(rights)
else:
return str(', '.join(rights))
|
def map_affine(x, l0, h0, l1=0., h1=1.):
"""Affine map from interval [l0, h0] to [l1, h1].
Broadcasting is used to match corresponding dimensions.
"""
x = l1 + (x - l0) / (h0 - l0) * (h1 - l1)
return x
|
def move_position(old_position, move):
"""Move from old_position by move."""
return tuple(
position + change
for position, change in zip(old_position, move)
)
|
def parse_elapsed_time_string( dstr ):
"""
Such as 11:27 or 21:42:39 or 1-20:21:50
"""
dy = 0
hr = 0
mn = 0
sc = 0
sL = dstr.split('-',1)
if len(sL) == 1:
hms = dstr
else:
try:
dy = int( sL[0] )
hms = sL[1]
except Exception:
return None
nL = hms.split(':')
try:
sc = int( nL[-1] )
if sc < 0 or sc >= 60:
return None
except Exception:
return None
if len(nL) > 1:
try:
mn = int( nL[-2] )
if mn < 0 or mn >= 60:
return None
except Exception:
return None
if len(nL) > 2:
try:
hr = int( nL[-3] )
if hr < 0 or hr > 24:
return None
except Exception:
return None
return dy*24*60*60 + hr*60*60 + mn*60 + sc
|
def add_two_polynomials(polynomial_1: list, polynomial_2: list) -> list:
"""
This function expects two `polynomials` and returns a `polynomial` that contains
their `sum`.
:param polynomial_1: First polynomial
:param polynomial_2: Second polynomial
:return: A polynomial representing the sum of the two polynomials
"""
# declaring the polynomial that will be returned (the sum)
return_polynomial = []
# storing the length of the shortest polynomial via the inbuilt min() function
minimum_length = min(len(polynomial_1), len(polynomial_2))
# adding the coefficients for every power of X up until the shortest one ends and appending the sum
for k in range(minimum_length):
return_polynomial.append(polynomial_1[k] + polynomial_2[k])
# figuring out which polynomial is longer and appending all of the coefficients that are left
if len(polynomial_1) > len(polynomial_2):
# using the inbuilt function range() to iterate through the coefficients that are left
for k in range(len(polynomial_2), len(polynomial_1)):
return_polynomial.append(polynomial_1[k])
else:
# I intentionally checked both for '>' and '<' in order to rule out the case in which they are equal
if len(polynomial_1) < len(polynomial_2):
# using the inbuilt function range() to iterate through the coefficients that are left
for k in range(len(polynomial_1), len(polynomial_2)):
return_polynomial.append(polynomial_2[k])
return return_polynomial
|
def is_next_south_cell_empty(i, j, field):
"""
check if next below cell is empty
:param i:
:param j:
:param field:
:return: True if next below cell is empty, False otherwise
"""
if i == len(field) - 1:
if field[0][j] == '.':
return True
return False
if field[i + 1][j] == '.':
return True
return False
|
def factorial(n):
"""
Return factorial of integer n.
Raises ValueError if n is not exact integer or is negative.
>>> factorial(0)
1
>>> factorial(1)
1
>>> factorial(5)
120
>>> [factorial(i) for i in range(6)]
[1, 1, 2, 6, 24, 120]
>>> factorial('121')
Traceback (most recent call last):
...
ValueError: Argument n must be integer!
>>> factorial([1])
Traceback (most recent call last):
...
ValueError: Argument n must be integer!
>>> factorial(1.12)
Traceback (most recent call last):
...
ValueError: Argument n must be integer!
>>> factorial(-10)
Traceback (most recent call last):
...
ValueError: Argument n must be nonnegative!
>>> import math
>>> n = 1000
>>> math.factorial(n) == factorial(n)
True
>>> import random
>>> n = random.randint(1500, 2000)
>>> math.factorial(n) == factorial(n)
True
"""
if not isinstance(n, int):
raise ValueError("Argument n must be integer!")
if not n >= 0:
raise ValueError("Argument n must be nonnegative!")
result = 1
for value in range(1, n+1):
result = result * value
return result
|
def isWhole(text, start, end):
"""
Checks whether the string is a whole word or not.
@param {string} text Text containing a string.
@param {number} start Start position of a string.
@param {number} end End position of the string.
@result {boolean} True if a string is a whole word.
False if it's not.
"""
alpha = 'abcdefghijklmnopqrstuvwxyz'
if end - start == len(text):
return True
if start:
start -= 1
if (text[start].lower() in alpha or text[end].lower() in alpha) or \
(text[start] == '#' and (text[end] == '(' or end == len(text))) or \
(text[start] == '.' or text[end] == '.'):
return False
return True
|
def KK_RC13_fit(params, w, t_values):
"""
Kramers-Kronig Function: -RC-
Kristian B. Knudsen ([email protected] / [email protected])
"""
Rs = params["Rs"]
R1 = params["R1"]
R2 = params["R2"]
R3 = params["R3"]
R4 = params["R4"]
R5 = params["R5"]
R6 = params["R6"]
R7 = params["R7"]
R8 = params["R8"]
R9 = params["R9"]
R10 = params["R10"]
R11 = params["R11"]
R12 = params["R12"]
R13 = params["R13"]
return (
Rs
+ (R1 / (1 + w * 1j * t_values[0]))
+ (R2 / (1 + w * 1j * t_values[1]))
+ (R3 / (1 + w * 1j * t_values[2]))
+ (R4 / (1 + w * 1j * t_values[3]))
+ (R5 / (1 + w * 1j * t_values[4]))
+ (R6 / (1 + w * 1j * t_values[5]))
+ (R7 / (1 + w * 1j * t_values[6]))
+ (R8 / (1 + w * 1j * t_values[7]))
+ (R9 / (1 + w * 1j * t_values[8]))
+ (R10 / (1 + w * 1j * t_values[9]))
+ (R11 / (1 + w * 1j * t_values[10]))
+ (R12 / (1 + w * 1j * t_values[11]))
+ (R13 / (1 + w * 1j * t_values[12]))
)
|
def calculate_radius(m_e, hv, mfield):
"""
m_e= mass/charge
hv= accelerating voltage (V)
mfield= magnet field (H)
"""
r = ((2 * m_e * hv) / mfield ** 2) ** 0.5
return r
|
def SplitSequence(seq, size):
"""Split a list.
Args:
seq: sequence
size: int
Returns:
New list.
Recipe From http://code.activestate.com/recipes/425397/ (Modified to not return blank values)
"""
newseq = []
splitsize = 1.0/size*len(seq)
for i in range(size):
newseq.append(seq[int(round(i*splitsize)):int(round((i+1)*splitsize))])
return [x for x in newseq if x]
|
def sql_replace_where_in(sql, q_count):
"""Support 'WHERE IN' SQL templates. Replace the first occurence of the
string '(?...?)' with some number of qmarks, e.g. '(?,?,?)'."""
qs = ','.join('?' * q_count)
sql2 = sql.replace('?...?', qs)
return sql2
|
def validate_manager_options(user_input):
"""Validation function that checks if 'user_input' argument is an int 0-3. No errors."""
switcher = {
'0': (True, '0'),
'1': (True, '1'),
'2': (True, '2'),
}
return switcher.get(user_input, (True, None))
|
def _process_predictions(y, y_pred1, y_pred2):
"""Pre-process the predictions of a pair of base classifiers for the
computation of the diversity measures
Parameters
----------
y : array of shape = [n_samples]:
class labels of each sample.
y_pred1 : array of shape = [n_samples]:
predicted class labels by the classifier 1 for each sample.
y_pred2 : array of shape = [n_samples]:
predicted class labels by the classifier 2 for each sample.
Returns
-------
N00 : Percentage of samples that both classifiers predict the wrong label
N10 : Percentage of samples that only classifier 2 predicts the wrong label
N10 : Percentage of samples that only classifier 1 predicts the wrong label
N11 : Percentage of samples that both classifiers predict the correct label
"""
size_y = len(y)
if size_y != len(y_pred1) or size_y != len(y_pred2):
raise ValueError(
'The vector with class labels must have the same size.')
N00, N10, N01, N11 = 0.0, 0.0, 0.0, 0.0
for index in range(size_y):
if y_pred1[index] == y[index] and y_pred2[index] == y[index]:
N11 += 1.0
elif y_pred1[index] == y[index] and y_pred2[index] != y[index]:
N10 += 1.0
elif y_pred1[index] != y[index] and y_pred2[index] == y[index]:
N01 += 1.0
else:
N00 += 1.0
return N00 / size_y, N10 / size_y, N01 / size_y, N11 / size_y
|
def add_person_tokens(responses, first_speaker=None, last_speaker=1):
"""Converts a list of responses into a single tag-separated string
Args:
responses: list of responses (strings)
first_speaker: either 1 or 2; the owner of the first response
last_speaker: either 1 or 2; the owner of the last response
NOTE: if first_speaker is provided, it overrides last_speaker
Output:
text: the concatenated text
e.g.,
responses = ["How are you?", "I'm doing fine!", "I'm glad to hear it!"]
result = add_person_tokens(responses)
result: "__p1__ How are you? __p2__ I'm doing fine! __p1__ I'm glad to
hear it!"
"""
if first_speaker is None:
first_speaker = (last_speaker + len(responses)) % 2 + 1
speaker = first_speaker
text = ''
for response in responses:
tag = f"__p{speaker}__"
text += (' ' + tag + ' ' + response)
speaker = 1 if speaker == 2 else 2
return text.strip()
|
def flatten(lst):
"""
Returns a list containing the items found in sublists of lst.
"""
return [item for sublist in lst for item in sublist]
|
def contains_common_item_3(arr1, arr2):
"""
convert array 1 to a set object
loop through the second array and check if item in second array exists in the created set
"""
array1_set = set(arr1)
for item2 in arr2:
if item2 in array1_set:
return True
return False
|
def spatpix_ref_to_frame(spatpix_ref, frame='dms', subarray='SUBSTRIP256', oversample=1):
"""Convert spatpix from nat coordinates in SUBSTRIP256 to the specified frame and subarray.
:param spatpix_ref: spatpix coordinates in the dms frame of SUBSTRIP256.
:param frame: the output coordinate frame.
:param subarray: the output coordinate subarray.
:param oversample: the oversampling factor of the input coordinates.
:type spatpix_ref: array[float]
:type frame: str
:type subarray: str
:type oversample: int
:returns: spatpix - the input coordinates transformed to the requested coordinate frame and subarray.
:rtype: array[float]
"""
if (frame == 'nat') & (subarray == 'SUBSTRIP256'):
spatpix = spatpix_ref
elif (frame == 'dms') & (subarray == 'SUBSTRIP256'):
spatpix = 255*oversample - spatpix_ref
elif (frame == 'sim') & (subarray == 'SUBSTRIP256'):
spatpix = spatpix_ref
elif (frame == 'nat') & (subarray == 'SUBSTRIP96'):
spatpix = spatpix_ref - 150*oversample
elif (frame == 'dms') & (subarray == 'SUBSTRIP96'):
spatpix = 245*oversample - spatpix_ref
elif (frame == 'sim') & (subarray == 'SUBSTRIP96'):
spatpix = spatpix_ref - 150*oversample
else:
raise ValueError('Unknown coordinate frame or subarray: {} {}'.format(frame, subarray))
return spatpix
|
def getenv(envarray, key, keyname="name", valname="value"):
"""get a value from a k8s "env" object (array of {"name":x,"value":y}); return None if not found"""
for e in envarray:
if e[keyname] == key:
return e[valname]
return None
|
def has_data(data):
"""
check if data exists. compares dict to empty dict else to None
Args:
data (obj): dat ato validate
Returns:
bool: whether data is present
"""
if isinstance(data, dict):
state = data != {}
else:
state = data is not None
return state
|
def parse_cimis_coordinate_str(coord_str: str) -> float:
"""Parses the coordinate string format used by CIMIS.
Args:
coord_str: Coordinate string in the format 'HMS / DD'.
Returns:
float: The coordinate in decimal degrees.
"""
[hms, dd] = coord_str.split('/')
return float(dd)
|
def filter_by_states(providers, states):
"""Filter providers by list of states to reduce the quantity of data we're processing."""
return [provider for provider in providers if provider['state'] in states]
|
def rename_header(headers: list) -> list:
"""This function is replacing all the column names of the given excel sheet with the field names of the Type8"""
for i in range(len(headers)):
headers[i] = headers[i].replace("Transaction ID", "transaction_id") \
.replace("Value Date", "transaction_value_date") \
.replace("Txn Posted Date", "transaction_posted_date") \
.replace("Description", "mode_of_payment") \
.replace("Cr/Dr", "credit") \
.replace("Transaction Amount(INR)", "transaction_amount")
return headers
|
def _toOperation(info, resource, handler):
"""
Augment route info, returning a Swagger-compatible operation description.
"""
operation = dict(info)
operation['tags'] = [resource]
# Operation Object spec:
# Unique string used to identify the operation. The id MUST be unique among
# all operations described in the API.
if 'operationId' not in operation:
operation['operationId'] = str(resource) + '_' + handler.__name__
return operation
|
def landscape(pagesize):
"""Use this to get page orientation right"""
a, b = pagesize
if a < b:
return (b, a)
else:
return (a, b)
|
def split_seq(seq, n_chunks):
"""Split the given sequence into `n_chunks`. Suitable for distributing an
array of jobs over a fixed number of workers.
>>> split_seq([1,2,3,4,5,6], 3)
[[1, 2], [3, 4], [5, 6]]
>>> split_seq([1,2,3,4,5,6], 2)
[[1, 2, 3], [4, 5, 6]]
>>> split_seq([1,2,3,4,5,6,7], 3)
[[1, 2], [3, 4, 5], [6, 7]]
"""
newseq = []
splitsize = 1.0/n_chunks*len(seq)
for i in range(n_chunks):
newseq.append(seq[int(round(i*splitsize)):int(round((i+1)*splitsize))])
return newseq
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.