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_contr... |
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("Foun... |
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)... |
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
---... |
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.ne... |
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 + "... |
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 ... |
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
... |
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(cont... |
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 ... |
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
... |
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:
... |
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 * 3... |
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]
... |
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
-... |
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
"""
re... |
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(comm... |
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 HE... |
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... |
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.symp... |
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
co... |
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 'Relationshi... |
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
... |
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 valu... |
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 correspo... |
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 ... |
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... |
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 n... |
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]
... |
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": {
...
... |
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... |
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
... |
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(';', '') # remo... |
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}/'
el... |
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 anothe... |
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(lef... |
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
... |
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]=="." :
... |
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: L... |
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(... |
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 = ', '.... |
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:
... |
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 n... |
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 num... |
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[... |
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:
... |
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 t... |
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 fie... |
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 (... |
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 whol... |
def KK_RC13_fit(params, w, t_values):
"""
Kramers-Kronig Function: -RC-
Kristian B. Knudsen (kknu@berkeley.edu / kristianbknudsen@gmail.com)
"""
Rs = params["Rs"]
R1 = params["R1"]
R2 = params["R2"]
R3 = params["R3"]
R4 = params["R4"]
R5 = params["R5"]
R6 = params["R6"]
... |
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... |
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]:
... |
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 th... |
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.
:para... |
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_v... |
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 o... |
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]... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.