content stringlengths 42 6.51k |
|---|
def getInwardPart(postcode):
"""Returns the Inward part of the postcode
Description
-----------
Extract the Inward part of from the postcode
It will not neccesory gives the correct Inward code.
Infact it only extracts three characters long string.
The inward code is the part of the postcode after the single spa... |
def _strip_hidden(d):
"""Return a (shallow) copy of the given dict, excluding fields starting
with underscore."""
return dict((k, v) for k, v in d.items() if not k.startswith('_')) |
def compPt(p0, p1):
"""
Returns True if 2-dim points p0 and p1
are equal. Otherwise, returns False.
"""
return p0[0] == p1[0] and p0[1] == p1[1] |
def cell_num_to_block_offsets(cell_num):
"""
:param cell_num: The cell number within the block. Precondition: 0 <= y < 9
:return: (y_offset, x_offset) where y_offset is the number of cells from the top
and x_offset is the number of cells from the bottom
"""
return int(cell_num / 3), cell_num % 3 |
def getRaw(text):
"""
Encodes text as UTF-16LE (Microsoft 'Unicode') for use in structs.
"""
return text.encode('UTF-16LE') |
def br_add_bugfix(fixing_data, bugfix, changes):
"""Update bug fixing recency data with the new bugfix
This function simply adds `bugfix` to the list of bugfixes/commits
for each file that the bugfix modified, that is each file in the
pre-image of `changes`, creating entries if necessary.
Used to ... |
def adler32(plain_text: str) -> int:
"""
Function implements adler-32 hash.
Iterates and evaluates a new value for each character
>>> adler32('Algorithms')
363791387
>>> adler32('go adler em all')
708642122
"""
MOD_ADLER = 65521
a = 1
b = 0
for plain_chr i... |
def binary_search_recursive(lst, key, start=0, end=None):
"""
Performs binary search with recursion for the given key in iterable.
Parameters
----------
lst : python iterable in which you want to search key
key : value you want to search
start : starting index
end : ending index
Re... |
def bytes_to_utf8(value):
"""
Converts byte literal to utf8 string
:param value: Byte literal
:type value: bytes
:return: UTF-8 encoded string
:rtype: str
"""
return str(value, 'utf8') |
def format_args(args):
"""
Formats the command line args program
"""
settings = {
"grep": False,
"dirs": "",
"grep_include":"",
"grep_startswith":"",
}
try: #python 2
for key,value in args.iteritems():
if key.startswith("s") and value != None:... |
def vforms_weights(vform_choice, repeats, nqubits):
"""
Returns the number of weights a certain circuit has with 1 repeat and
without any trailing gates.
@vform_choice :: String of the choice of variational form.
"""
switcher = {
"two_local": lambda: nqubits * (repeats + 1),
}
n... |
def number_of_faces(shape):
"""Number of faces in a structured quad grid.
Parameters
----------
shape : tuple of int
Shape of grid of nodes.
Returns
-------
int :
Number of faces in grid.
Examples
--------
>>> from landlab.grid.structured_quad.faces import numb... |
def rstrip_word(text, suffix):
"""Strip suffix from end of text"""
if not text.endswith(suffix):
return text
return text[:len(text)-len(suffix)] |
def repeat_to_length(string_to_expand: str, length: int) -> str:
"""
Repeat the string using a length variable
Args:
string_to_expand (`str`): string to repeat
length (`int`): length
Returns:
`str`: generated string
Examples:
>>> rep... |
def get_short_psubclass_descriptor(psubclass):
"""Generates a short descriptor of the subclass
Args:
psubclass (string): protein classification subclass
Raises:
Exception: unknown subclass given
Returns:
string: short subclass descriptor
"""
# derive a shorter psubclas... |
def get_item_image_url(item_name, image_size="lg"):
"""
Get an item image based on name
"""
return "http://media.steampowered.com/apps/dota2/images/items/{}_{}.png".format(
item_name, image_size) |
def should_use_custom_repo(args, cd_conf, repo_url):
"""
A boolean to determine the logic needed to proceed with a custom repo
installation instead of cramming everything nect to the logic operator.
"""
if repo_url:
# repo_url signals a CLI override, return False immediately
return F... |
def ppd(likelihood, prior, log=True):
"""
Compute the (non-normalized) (log)posterior
probability distribution given the (log)likelihood
and the (log)prior probability distribution.
Parameters
----------
likelihood : float or array_like
the (log)likelihood function
prior : f... |
def poly_norm(p):
"""Normalize the polynomial ``p(x)`` to have a non-zero most significant
coefficient.
"""
for i,a in enumerate(p):
if a != 0:
return p[i:]
return [] |
def get_header_value(headers, header_name):
"""
:return: The value of the header with the given name, or None if there
was no such header.
"""
if headers is None:
return None
for name, value in headers.items():
if name.lower() == header_name.lower():
return value
... |
def diff_offset(base, diff):
"""Return the index where the two parameters differ."""
if len(base) != len(diff):
raise ValueError('len(base)=%d != len(diff)=%d' % (len(base), len(diff)))
for i in range(0, len(base)):
if base[i] != diff[i]:
return i
return None |
def mark_captions(captions_list, mark_start, mark_end):
""" Mark all the captions with the start and the end marker """
captions_marked = [
[' '.join([mark_start, caption, mark_end]) for caption in captions] for captions in captions_list
]
return captions_marked |
def print_last_word(words):
"""Prints the last word after popping it off."""
word = words.pop(-1)
return print(word) |
def best_items(racers):
"""Given a list of racer dictionaries, return a dictionary mapping items to the number
of times those items were picked up by racers who finished in first place.
"""
winner_item_counts = {}
for i in range(len(racers)):
# The i'th racer dictionary
racer = racer... |
def tags_from_cloudformation_tags_list(tags_list):
"""Return tags in dict form from cloudformation resource tags form (list of dicts)"""
tags = {}
for entry in tags_list:
key = entry["Key"]
value = entry["Value"]
tags[key] = value
return tags |
def get_new_dims(h, w, target_h, target_w):
"""Returns new dimensions that respect the old aspect ratio.
`target_h` and `target_w` are usually the same value, since
target dimensions are most likely squares.
"""
if h > w:
r = target_h / float(h)
new_h = target_h
new_w = int... |
def prettyBigNum(amount, remove_zeroes: bool = True) -> str:
"""Prints, for example:
1.23e12, 123.4B, 1.23B, 123M, 1.23M, 123K, 1.23K, 123,
1.23, 0.12, 1.23e-3,
1e12, 100B, 1B, 100M, 1M, 100K, 1K, 100, 1
Remove zeros True vs False: 1.00M vs 1M
"""
if remove_zeroes:
amount = float(f"... |
def model_tavg(tmin = 0.0,
tmax = 0.0):
"""
- Name: Tavg -Version: 1.0, -Time step: 1
- Description:
* Title: Mean temperature calculation
* Author: STICS
* Reference: doi:http://dx.doi.org/10.1016/j.agrformet.2014.05.002
* Inst... |
def keypoint_scale(keypoint, scale_x, scale_y):
"""Scales a keypoint by scale_x and scale_y.
Args:
keypoint (tuple): A keypoint `(x, y, angle, scale)`.
scale_x (int): Scale coefficient x-axis.
scale_y (int): Scale coefficient y-axis.
Returns:
A keypoint `(x, y, angle, scale... |
def int_to_en(num):
"""Given an int32 number, print it in English."""
d = { 0 : 'zero', 1 : 'one', 2 : 'two', 3 : 'three', 4 : 'four', 5 : 'five',
6 : 'six', 7 : 'seven', 8 : 'eight', 9 : 'nine', 10 : 'ten',
11 : 'eleven', 12 : 'twelve', 13 : 'thirteen', 14 : 'fourteen',
15 : ... |
def juftmi(x):
"""x juft bo'lsa True, aks holda False qaytaruvchu funksiya"""
return x%2==0 |
def bbox_rel(image_width, image_height, bbox_left, bbox_top, bbox_w, bbox_h):
"""" Calculates the relative bounding box from absolute pixel values. """
x_c = (bbox_left + bbox_w / 2)
y_c = (bbox_top + bbox_h / 2)
w = bbox_w
h = bbox_h
return x_c, y_c, w, h |
def grid_maker(grid_cells, grid_rows):
"""generate new grid with specified dimensions"""
grid = []
cell_value = False
for _x in range(grid_rows):
row = []
for _y in range(grid_cells):
row.append(cell_value)
grid.append(row)
return grid |
def fix_1(lst1, lst2):
"""
Divide all of the elements in `lst1` by each element in `lst2`
and return the values in a list.
>>> fix_1([1, 2, 3], [0, 1])
[1.0, 2.0, 3.0]
>>> fix_1([], [])
[]
>>> fix_1([10, 20, 30], [0, 10, 10, 0])
[1.0, 2.0, 3.0, 1.0, 2.0, 3.0]
"""
out = []
... |
def get_partial_match_expr(word, minchars):
"""Generate regex sub-expression for matching first `minchars` of a word or
`minchars` + 1 of the word, or `minchars` + 2, ....
Adapted from user sberry at https://stackoverflow.com/a/13405331
Parameters
----------
word : str
minchars : int
... |
def add_padding(tokens: list, maxlen: int) -> list:
""" Provide padding of the encoded tokens to the maxlen; if length of tokens > maxlen, reduce it to maxlen """
padded_tokens = [0] * maxlen
for token in range(0, min(len(tokens), maxlen)):
padded_tokens[token] = tokens[token]
return padded_toke... |
def prepare_emoji_list(emoji_list,
font_size):
"""Preparing emojies to be put on picture.
"""
return list(map(lambda x: x.convert("RGBA").resize((int(font_size / 10), int(font_size / 10))), emoji_list)) |
def dip2strike(dipaz):
"""Convert dip-dipazimuth data to strike using the right-hand rule
Args:
dipaz (float): Azimuth of dip in degrees from north
Returns:
float: Strike azimuth (0-360 degrees) based on the right hand rule
"""
if dipaz < 90:
strike = (dipaz - 90) + 360
... |
def get_result(response, ctxlen):
"""Process results from OpenAI API response.
:param response: dict
OpenAI API Response
:param ctxlen: int
Length of context (so we can slice them away and only keep the predictions)
:return:
continuation_logprobs: np.array
Log probab... |
def partition_lyrics(lyrics):
""" splits lyric string into lines """
parts = lyrics.splitlines()
parts = filter(lambda p: len(p) > 0, parts)
parts = filter(lambda p: sum(c.isalpha() for c in p) > 5, parts)
parts = filter(lambda p: 7*'*' not in p, parts) # filter out copyright message
return lis... |
def int_comma(value):
"""
Converts an integer to a string containing commas every three digits
"""
val_str = str(value)
split = val_str.split(".")
val_int = split[0]
try:
val_point = "." + split[1]
except IndexError:
val_point = ""
val_list = []
for count, i in enumerate(reversed(val_int)):
val_list.... |
def col_to_excel(col):
"""
Converts the column number to the excel column name (A, B, ... AA etc)
Parameters
----------
col : INTEGER
The number of the column to convert. Note that 1 converts to A
Returns
-------
excel_col : STRING
The string which describes the name o... |
def replace_url(word):
""" replace word urls with audio filenames """
for i, _ in enumerate(word['pronunciations']):
url = word['pronunciations'][i]['url']
try:
ogg_file = url.rsplit('/', 1)[1]
mp3_file = ogg_file.split('.')[0] + '.mp3'
word['pronunciations'][i]['filename'] = mp3_file
word['pronunci... |
def join_lines(strings):
"""
Stack strings horizontally.
This doesn't keep lines aligned unless the preceding lines have the same length.
:param strings: Strings to stack
:return: String consisting of the horizontally stacked input
"""
liness = [string.splitlines() for string in strin... |
def create_and_list(list):
"""
Given a list of 1 items, return item
Given a list of 2 items, return item[0] and item[1]
Given a list of n items, return item[0], item[1], ..., and item[-1]
"""
if len(list) == 1:
return list[0]
elif len(list) == 2:
return list[0] + " and " + l... |
def str2bytes(origin_str, charset='utf-8'):
"""
:param origin_str:
:param charset:
:return:immutable struct
"""
return bytearray(origin_str, encoding=charset) |
def flash_class(category):
"""Convert flash message category to CSS class
for Twitter Bootstrap alert
:param category: Category of flash message
:type category: str
:return: CSS class for category
:rtype: str
"""
if category == 'error':
return 'danger'
return category |
def is_iterable(x):
"""
Return True if x is iterable (but not a string).
"""
try:
return not isinstance(iter(x), type(iter("")))
except TypeError:
return False |
def trapintegration(curve):
"""Will add up trapezoids defined by points in x and y.
Input:
curve: list of real valued (x,y) pairs
Result:
The real valued integral.
"""
cumval = 0.
if len(curve) > 1:
for idx in range(1, len(curve)):
#print(idx,curve[idx],curve... |
def order_lex(term_matrix):
"""
orders lexicographically
"""
# take off constant so it doesn't get sorted with variables
if len(term_matrix[0]) < 2:
return term_matrix
t = [term[1:] for term in term_matrix]
# first move around variables within terms
# then move terms around
v... |
def to_native(s, encoding="utf-8"):
"""Convert data to native str type, i.e. bytestring on Py2 and unicode on Py3."""
if type(s) is bytes:
s = str(s, encoding)
elif type(s) is not str:
s = str(s)
return s |
def check_system_query_status(data):
"""Check if any server crashed.
Args:
data (dict): dictionary of system query data obtained from
DmgCommand.system_query()
Returns:
bool: True if no server crashed, False otherwise.
"""
failed_states = ("Unknown", "Evicted", "Errore... |
def parad_bi2parad(parad: str, bimanual: bool) -> str:
"""
:param parad:
:param bimanual:
:return: parad ('unimanual', 'bimanual', etc.)
"""
if parad == 'unibimanual':
return 'bimanual' if bimanual else 'unimanual'
else:
return parad |
def separateUnit(string):
"""
Separates the unit and number in given string
e.g. '1 em' will return (float(1), 'em')
"""
# create an array of valid numbers (and '.')
nums = ['.'] + [str(x) for x in range(10)]
num_str = str()
unit_str = str()
# find first char in string that i... |
def seeds2seedpos(a_seeds, a_pos):
"""Convert set of seed terms to a set with seed terms and PoS.
@param a_seeds - set of seed terms
@param a_pos - list of part-of-speech tags of the seed terms
@return set of seed terms with their PoS
"""
return set((iterm, ipos)
for iterm in a... |
def password_validator(min, max, magic_char, password):
"""Takes in elements of a policy: min and mac occurency of a specific chareacter as well as a password to be validated against the policy."""
magic_char_count = password.count(magic_char)
is_valid = (magic_char_count >= int(min) and magic_char_count <=... |
def markdown_header(level=None):
"""Get markdown headers (without symbol).
"""
if level is None:
return r'(?:^[#]+ |\n[#]+ )([^\t\n]+)'
else:
return rf'(?:^[#]{{{level}}} |\n[#]{{{level}}} )([^\t\n]+)' |
def _set_up_hamming_weights(dom_identifier, use_same_weights, dim,
cts_hp_bounds, param_order):
""" Set up for dim_weights in hamming kernel. """
if use_same_weights or dim == 1:
return cts_hp_bounds, param_order
elif dim == 2:
cts_hp_bounds.append([0, 1])
param_order.appen... |
def iou_bbox(box1, box2):
"""
Input format is [xtl, ytl, xbr, ybr] per bounding box, where
tl and br indicate top-left and bottom-right corners of the bbox respectively
"""
#determine the (x, y)-coordinates of the intersection rectangle
xA = max(box1[0], box2[0])
yA = max(box1[1], box2[1])
... |
def bgp_state_convert(state):
"""
Given a matched BGP state, map it to a vendor agnostic version.
"""
state_dict = {'OpenSent': 'OPEN_SENT',
'OpenConfirm': 'OPEN_CONFIRM'}
return state_dict.get(state, state.upper()) |
def clean_text(text):
"""Cleans text; makes all text lower case"""
return text.strip().lower() |
def pathCountX(stairs: int, X):
"""number of unique ways to climb N stairs using 1 or 2 steps"""
#we've reached the top
if stairs == 0:
return 1
elif stairs < 0:
return 0
else:
validSteps = []
for num in X:
if stairs >= num:
validSteps.app... |
def get_raw_sequence(alignment: bytes,
len_read_name: int,
number_cigar_operations: int,
len_sequence: int, ) -> bytes:
"""Extract the raw sequence from a BAM alignment bytestring
Parameters
----------
alignment : bytes
A byte string of a bam alig... |
def zipper_merge(*lists):
"""
Combines lists by alternating elements from them.
Combining lists [1,2,3], ['a','b','c'] and [42,666,99] results in
[1,'a',42,2,'b',666,3,'c',99]
The lists should have equal length or they are assumed to have the length of
the shortest list.
This is known as ... |
def create_msearch_payload(host, st, mx=1):
"""
Create an M-SEARCH packet using the given parameters.
Returns a bytes object containing a valid M-SEARCH request.
:param host: The address (IP + port) that the M-SEARCH will be sent to. This is usually a multicast address.
:type host: str
:param ... |
def writefile(fname, data):
"""Helper function to read a file (binary).
:param fname: file name to be read
:returns: contents of file
"""
if isinstance(data, str):
data = data.encode("ascii")
with open(fname, "wb") as stream:
return stream.write(data) |
def make_name(*words):
""" Build a SnakeCase name out of words. """
import itertools
words = itertools.chain.from_iterable(w.split() for w in words)
return ''.join(w.lower().capitalize() for w in words) |
def update_project(p_dict, slug):
"""Updates project by slug"""
updated_param = {
"uri": p_dict["uri"] if "uri" in p_dict else None,
"name": p_dict["name"] if "name" in p_dict else "TimeSync API",
"slugs": p_dict["slugs"] if "slugs" in p_dict else [slug],
"created_at": "2014-04-1... |
def strip_list_whitespace(direction: str, list_of_str: list) -> list:
"""Strips whitespace from strings in a list of strings
Arguments:
direction: (string) Determines whether to strip whitespace
to the left, right, or both sides of a string
list_of_str: (list) list of strings
"""
... |
def package_already_created(error):
"""Check if error is due to package being already created."""
if type(error) != dict:
return False
status_conflict = error.get("name") == "Conflict"
status_success = "SUCCESS" in error.get("error", "")
return status_conflict and status_success |
def coalesce(*args):
"""
Return the first non-null argument.
"""
for arg in args:
if arg is not None:
return arg |
def mag2flux(mag):
"""Convert flux to arbitrary flux units"""
return 10.**(-.4 * mag) |
def string_to_sysex(string):
"""Convert a string to the type required by the PadKontrol.
string -- the string to convert. Must be 3 characters long.
"""
if len(string) != 3:
raise ValueError('String \'%s\' must be 3 characters long' % string)
return [ord(s) for s in string] |
def gib(x, s, e) -> int:
"""x[s:e]"""
return (x >> e) & ((1 << (s - e + 1))-1) |
def undict(dictionary):
"""Extracts tuple (key, value) from one-element dict.
:returns: (key, value) tuple or None.
:raises: TypeError if len(dictionary) > 1
"""
if len(dictionary) > 1:
raise TypeError("Cannot undict dictionary: {0}\n".format(dictionary) +
"Dictionar... |
def ensureUtf(string, encoding='utf8'):
"""Converts input to unicode if necessary."""
if type(string) == bytes:
return string.decode(encoding, 'ignore')
else:
return string |
def convertLispIdtoPythonId(s):
"""
Convert string s such that it can be a valid Python identifier.
"""
return s.replace('-','_').replace('.','_').replace('?','_p').replace('|','').lower() |
def concatenated_product(n_str: str) -> bool:
"""Return True if the input number is a 'concatenated product'."""
# Check all prefixes
for i in range(1, len(n_str) // 2 + 1):
seed = int(n_str[:i])
term = 1
rhs = n_str[i:]
while rhs:
term += 1
lhs = f"{t... |
def fib(n):
"""
The fibonacci numbers are [0, 1, 1, 2, 3, 5, 8, 13, ....]. Except the first 2
terms in this sequence, every term = the sum of the 2 previous terms, for example
13 = 8 + 5.
In this algorithm, we store the results we obtain in order not to compute them again
this technique is calle... |
def Reynolds(rho, U, L, mu):
"""
Calculates flow Reynolds number
"""
Re = (rho * U * L) / mu
return Re |
def getSpecificity(similarityquality):
"""
:param similarityquality: Output of getSimilarityquality()
:return: list of specificity-values in input order.
"""
return [uospecific
for similaritythreshold, symbol, mformat, quality, fieldcount, exactf, nearf, uospecific
in similarityquali... |
def parse_requirements(filename):
""" load requirements from a pip requirements file """
try:
lineiter = (line.strip() for line in open(filename))
temp = [line.replace('==','>=') for line in lineiter if line and not line.startswith("#")]
return [k for k in temp if 'scikit-learn' not in k... |
def nextpow2(i):
"""
Find 2**n that is equal to or greater than.
"""
n = 0
while (2**n) < i:
n += 1
return n |
def Boolean(value, default=None):
"""Get boolean value from the provided value.
If None, default is returned
"""
if value is None:
return default
value = value.lower()
if value == 'false' or value == '0':
return False
elif value == 'true' or value == '1':
return Tru... |
def build_run_spc_dct(spc_dct, run_obj_dct):
""" Get a dictionary of requested species matching the PES_DCT format
"""
spc_nums = run_obj_dct['spc']
run_spc_lst = []
for idx, spc in enumerate(spc_dct):
if spc != 'global':
if idx+1 in spc_nums:
run_spc_lst.append((... |
def get_split_sizes(dataset_len, split_portions):
"""Return sizes of each split given the full dataset size/length and the split portions.
Args:
dataset_len: Size of dataset (number of samples).
split_portions: Fraction of each size of the split. Example: (0.8, 0.1, 0.1).
Returns:
... |
def all_valid(ip_address):
"""
`all` uses list comprehension to filter
https://docs.python.org/3/library/functions.html#all
"""
terms = ip_address.split(".")
if not all(octet.isdecimal() for octet in terms):
return False
elif not all(0 <= int(octet) <= 255 for octet in terms):
return Fals... |
def is_close(a, b):
"""Return True if there is at most a difference of 1 at the 2d decimal"""
return abs(a - b) <= 0.01 |
def dm_delay(dm, lo, hi):
"""Calculate the dispersion delay between frequencies "lo" and "hi", both in GHz
:param dm: dispersion measure of pulsar (in cm^-3 pc) [float]
:param lo: the lowest frequency (in GHz) [float]
:param hi: the highest frequency (in GHz) [float]
:return: dispersion delay (in m... |
def merge_list(wordlists):
"""
this function merges all the wordlist(dictionary) into one, and return it
:param wordlists: an array contain all the wordlist(dictionary type)
:return: the merged word list (dictionary type)
"""
mergelist = {}
for wordlist in wordlists:
for key in word... |
def genus_spp(tokens):
"""
Input: Brassica
Output: <taxon genus="Brassica" species="" sub-prefix="" sub-species="">
<sp>Brassica</sp></taxon>
"""
genus = tokens[0]
return f'''<taxon genus="{genus}" species="" sub-prefix="" sub-species=""><sp>{genus}</sp></taxon>''' |
def json_extract(obj, key):
"""Recursively fetch values from nested JSON."""
arr = []
def extract(obj, arr, key):
"""Recursively search for values of key in JSON tree."""
if isinstance(obj, dict):
for k, v in obj.items():
if isinstance(v, (dict, list)):
... |
def _dirname(p):
"""Returns the dirname of a path.
The dirname is the portion of `p` up to but not including the file portion
(i.e., the basename). Any slashes immediately preceding the basename are not
included, unless omitting them would make the dirname empty.
Args:
p: The path whose dirn... |
def count_vowels(text):
"""Counts vowels
Args:
text ([type]): [description]
Returns:
[type]: [description]
"""
vowels = "aeiou"
v_dict = {}
for vow in vowels:
v_dict[vow] = text.count(vow)
return v_dict |
def sget(list, index, default=''):
"""
Helper function to act like dict.get(). If the index doesn't exist
or if it is an empty string then return the default given. If no default
is given then it returns the empty string.
"""
try:
# If it's empty give the default
if len(list[inde... |
def split_off_tag(xpath):
"""
Splits off the last part of the given xpath
:param xpath: str of the xpath to split up
"""
split_xpath = xpath.split('/')
if split_xpath[-1] == '':
return '/'.join(split_xpath[:-2]), split_xpath[-2]
else:
return '/'.join(split_xpath[:-1]), split... |
def check_keys(args, length):
"""Check if dict keys are provided
"""
params = ['email', 'username', 'password', 'old_password', 'fullname']
for key in args.keys():
if key not in params or len(args) != length:
return True
return False |
def MergeDictsRecursively(original_dict, merging_dict):
"""
Merges two dictionaries by iterating over both of their keys and returning the merge
of each dict contained within both dictionaries.
The outer dict is also merged.
ATTENTION: The :param(merging_dict) is modified in the process!
:para... |
def splitPath(path, sep='/'):
"""
Chops the first part of a /-separated path and returns a tuple
of the first part and the tail.
If no separator in the path, the tail is None
"""
sepIdx = path.find(sep)
if sepIdx < 0:
return (path, None)
return path[:sepIdx], path[se... |
def replace_none(idx, dim):
"""
Normalize slices to canonical form, i.e.
replace ``None`` with the appropriate integers.
Parameters
----------
idx: slice or other index
dim: dimension length
Examples
--------
>>> replace_none(slice(None, None, None), 10)
slice(0, 10, 1)
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.