content stringlengths 42 6.51k |
|---|
def summarize_broken_packages(broken):
"""
Create human-readable summary regarding missing packages.
:param broken: tuples with information about the broken packages.
:returns: the human-readable summary.
"""
# Group and sort by os, version, arch, key
grouped = {}
for os_name, os_ver,... |
def getGitRepositoryDownloadUrl(url: str) -> str:
"""
Takes a git repository url 'url' and returns the url to the master zip.
:param url: The url to a Github repository.
:return: The url to the master archive of the repository.
"""
return url + ('/' if url[-1] != '/' else '') + 'archive/master.... |
def _differ_lists(l1, l2):
""" Compare two lists of objects
Parameters
----------
l1, l2: lists
Returns:
True if different
"""
is_different = False
l2_copy = list(l2)
for dev in l1:
if not dev in l2_copy:
is_different = True
break
els... |
def wrap_check_stop(l, stop):
"""Check that stop index falls in (-l, l] and wrap negative values to l + stop.
For convenience, stop == 0 is assumed to be shorthand for stop == l.
"""
if (stop <= -l) or (stop > l):
raise IndexError('stop index out of range')
elif stop <= 0:
... |
def gen_Command(drone_id, state):
"""Generate a Command object."""
command = {
"@type": "Command",
"DroneID": drone_id,
"State": state
}
return command |
def display_warnings(_warnings):
"""
Return a string that displays a list of unexpected warnings
Parameters
----------
_warnings : iterable
List of warnings to be displayed
Returns
-------
msg : str
String containing the warning messages to be displayed
"""
if l... |
def letter_for_axis(axis):
"""Returns K, J, or I for axis; axis as required for axis arguments in FineCoarse methods."""
assert isinstance(axis, int) and 0 <= axis < 3
return 'KJI'[axis] |
def make_batches(size, batch_size):
"""Returns a list of batch indices (tuples of indices).
# Arguments
size: Integer, total size of the data to slice into batches.
batch_size: Integer, batch size.
# Returns
A list of tuples of array indices.
"""
num_batches = (size + batch... |
def one(iterable, too_short=None, too_long=None):
"""Return the first item from *iterable*, which is expected to contain only
that item. Raise an exception if *iterable* is empty or has more than one
item. Taken from `more_itertools.one`.
"""
it = iter(iterable)
try:
value = next(it)
... |
def _capitalize_first_letter(word):
"""
Capitalizes JUST the first letter of a word token.
Note that str.title() doesn't work properly with apostrophes.
ex. "john's".title() == "John'S"
"""
if len(word) == 1:
return word.upper()
else:
return word[0].upper() + word[1:] |
def _check_minsize(fa, minsize):
"""
Raise ValueError if there is any sequence that is shorter than minsize.
If minsize is None the size will not be checked.
"""
if minsize is None:
return fa
for name, seq in fa.items():
if len(seq) < minsize:
raise ValueError(f"sequ... |
def sort(listtosort, key=None, reversesort=False):
"""
Sort a list alphabetically
listtosort:
The list which will be sorted
key:
The key to use when sorting. The default is None.
reverse:
If to sort backwards. The default is False.
"""
return sorted(listtosort, key=key, rev... |
def _run_task_hook(hooks, method, task, queue_name):
"""Invokes hooks.method(task, queue_name).
Args:
hooks: A hooks.Hooks instance or None.
method: The name of the method to invoke on the hooks class e.g.
"enqueue_kickoff_task".
task: The taskqueue.Task to pass to the hook method.
queue_na... |
def sum_of_squares(n):
"""Sum of squares of postive integers
smaller than n
Args:
n (int): Highest number
>>> sum_of_squares(10)
285
>>> sum_of_squares(20)
2470
>>> sum_of_squares(500)
41541750
>>> sum_of_squares(37)
16206
>>> sum_of_squares(-1)
False
""... |
def get_amplify_cookie_names(client_id, cookies_or_username):
"""Return mapping dict for cookie names for amplify."""
key_prefix = f"CognitoIdentityServiceProvider.{client_id}"
last_user_key = f"{key_prefix}.LastAuthUser"
if isinstance(cookies_or_username, str):
token_user_name = cookies_or_user... |
def title_to_snake_case(text):
"""Converts "Column Title" to column_title
"""
return text.lower().replace(' ', '_').replace('-', '_') |
def repetition_plane(repetitions, n=8):
"""
:param int repetitions: Number of times a chess position (state) has been reached.
:param int n: Chess game dimension (usually 8).
:return: An n x n list containing the same value for each entry, the repetitions number.
:rtype: list[list[in... |
def _num_tokens_of(rule):
"""Calculate the total number of tokens in a rule."""
total = len(rule.get("tokens"))
for _ in ("prev_classes", "prev_tokens", "next_tokens", "next_classes"):
val = rule.get(_)
if val:
total += len(val)
return total |
def mock_id_formatter(issue, format='long', **kwargs):
"""
Always return the issue id converted to its string representation.
"""
return str(issue['id']) |
def _pretty_hex(hex_str):
"""
Nicely formats hex strings
"""
if len(hex_str) % 2 != 0:
hex_str = "0" + hex_str
return ":".join([hex_str[i : i + 2] for i in range(0, len(hex_str), 2)]).upper() |
def assemble_addresses_internal_results(address, s, results):
"""
Refactored into this self-contained solution. It works.
"""
for pos in range(len(address)):
if address[pos] != "X":
s += address[pos]
else:
results = assemble_addresses_internal_results(address[pos+... |
def get_field_models(self, request, field_name = None, model = None, data_type = int):
"""
Retrieves the complete set of models for the various identifiers
defined in the field with the provided name.
In case at least one model fails to be retrieved, an error is raised.
:type request: Reque... |
def centroid(list_of_points):
"""Returns the centroid of the list of points."""
sum_x = 0
sum_y = 0
sum_z = 0
n = float(len(list_of_points))
for p in list_of_points:
sum_x += float(p[0])
sum_y += float(p[1])
sum_z += float(p[2])
return [sum_x / n, sum_y / n, sum_z / n... |
def remove_nodes_without_edges(nodes, edges):
"""Removes nodes without edges
Args:
nodes ([Array]): [nodes]
edges ([Array]): [edges]
Returns:
[Array]: [nodes without edges]
"""
filtered_nodes = []
for node in nodes:
id = node.get('id')
has_edges = F... |
def maybe_parse(val, parse_func):
"""Parse argument value with function if string.
"""
if val is None:
return []
if isinstance(val, (bytes, str)):
return parse_func(val)
if isinstance(val, dict):
return list(val.items())
if isinstance(val, (list, tuple)):
return l... |
def replace_dots(son):
"""Recursively replace keys that contains dots"""
for key, value in son.items():
if '.' in key:
new_key = key.replace('.', '_')
if isinstance(value, dict):
son[new_key] = replace_dots(
son.pop(key)
)
... |
def _null_terminate(value: str) -> str:
"""Null terminate the given string."""
if "\x00" in value:
value = value.split("\x00")[0]
return f"{value}\x00" |
def _calc_errors(actual, expected):
"""Return the absolute and relative errors between two numbers.
>>> _calc_errors(100, 75)
(25, 0.25)
>>> _calc_errors(100, 100)
(0, 0.0)
Returns the (absolute error, relative error) between the two arguments.
"""
base = max(abs(actual), abs(expected)... |
def _strip_fragment(url: str) -> str:
"""Returns the url with any fragment identifier removed."""
fragment_start = url.find("#")
if fragment_start == -1:
return url
return url[:fragment_start] |
def dumps_dict(dic: dict) -> str:
"""
Dumps a dictionary in a pretty-ish format to the logger.
Args:
dic (dict): The dictionary to print
Returns:
str: The pretty-ish string representation of the dict argument
"""
import json
return json.dumps(dic, indent=4) |
def best_pairing(current_end, end_dict, inverse_dict, blast_hits, l_min_score, r_min_score):
"""
Returns a dict of possible connections to a scaffold end, based on adjacency in reference genomes.
"""
#this duplicates part of trio_hits - should try to rewrite that to use this function
l_flange =... |
def find(f, seq):
"""Return first item in sequence where f(item) == True."""
for item in seq:
if f(item):
return item |
def _getFeatDict(mol, featFactory, features):
""" **INTERNAL USE ONLY**
>>> import os.path
>>> from rdkit import Geometry, RDConfig, Chem
>>> fdefFile = os.path.join(RDConfig.RDCodeDir,'Chem/Pharm3D/test_data/BaseFeatures.fdef')
>>> featFactory = ChemicalFeatures.BuildFeatureFactory(fdefFile)
>>>... |
def da_empty(da):
"""Returns True if all elements of dict da have values that are
lists, and all of these lists are empty. This done to verify
that when using single_file mode, ci values, such as:
ci['only_in']['A']['dataset'], ci['only_in']['B']['group'])
do not have values."""
for key in da:
... |
def parse_mem_str_to_gbsize(strmem):
"""
String like 845 MB 677.8 MB to GB size
:param strtime:
:return:
"""
strmem = strmem.strip()
if strmem.endswith('MB'):
memgb = float(strmem[:-2]) / 1024
elif strmem.endswith('GB'):
memgb = float(strmem[:-2])
elif strmem.endswit... |
def _hypotenuse(base: float, side: float) -> float:
"""Calculate the hypotenuse with other two sides known."""
return (base ** 2 + side ** 2) ** 0.5 |
def seconds_converter(duration):
"""
This is a function that process a strig and convert it to a more workable format
It is used to extract the duration from yt requests in a more approachable way
@:param duration:
A string in a yt format that represent the duration of a video
@:return:
... |
def _postcrement_to_modifier(postcrement: float) -> int:
"""Convert a postcrement value (in -4..4) to a modifier value (in 0..8)."""
return (7, 6, 5, 4, 8, 0, 1, 2, 3)[int(postcrement) + 4] |
def isWithinUnitedStates(latitude, longitude):
"""Returns true if the latitude longitude pair is roughly within the
boundaries of the United States. Returns false otherwise"""
return (25 < latitude and latitude < 50) and (-127 < longitude and longitude < -65) |
def degrees_as_hex(angle_degrees, seconds_decimal_places=2):
"""
:param angle_degrees: any angle as degrees
:return: same angle in hex notation, unbounded.
"""
if angle_degrees < 0:
sign = "-"
else:
sign = "+"
abs_degrees = abs(angle_degrees)
milliseconds = round(abs_degr... |
def is_palindrome(value):
"""Returns true if the input number is palindrome otherwise false"""
temp = value
reverse = 0
while temp != 0:
last_digit = temp % 10
reverse = reverse * 10 + last_digit
temp = temp // 10
return value == reverse |
def remove_adj(e2e, remove):
"""Remove adjacent elements from list of IDs.
Parameters
----------
e2e : dict
The element-to-element relationships. This is either an
'x2x' relationship or 'x2y' relationship.
remove : list
The keys to remove from list.
Returns
-------
... |
def normDiff_band_names(collection):
"""
Earth Engine normDiff bands
"""
dic = {
'Sentinel2': ['ndvi', 'ndwi'],
'Landsat7': ['ndvi', 'ndwi'],
'CroplandDataLayers': []
}
return dic[collection] |
def replace_all(text, dic):
"""perfrom text.replace(key, value) for all keys and values in dic"""
for old, new in dic.items():
text = text.replace(old, new)
return text |
def grab_data(array, index):
"""
This is a helper function for parsing position output.
:param array: any array that's items are lists
:param index: desired index of the sublists
:return: subset: a list of all of the values at the given index in each sublist
"""
subset = []
for i in arra... |
def check_form(form_data):
"""
Function that perform a small check on submited form data
"""
# check if there are any empty fields
for key, value in form_data:
if value == "":
return None
return form_data |
def join_paths(args):
"""
A little helper that allows us to specify directories with the help of a particular base path
"""
import os
def combine_path(basedir, other):
if other.startswith("/") or other.startswith("gs://"):
return other
else:
return os.path.joi... |
def get_property_from_dss_string(string, property):
"""Get the value of the given property within the dss string."""
L = string.split(" ")
result = []
for l in L:
if "=" in l:
ll = [x.strip() for x in l.split("=")]
if ll[0].lower() == property.lower():
res... |
def compile_word(word):
"""Compile a word of uppercase letters as numeric digits.
E.g., compile_word('YOU') => '(1*U+10*O+100*Y)'
Non-uppercase words unchanged: compile_word('+') => '+'"""
# Your code here.
if word.isupper():
terms = [('%s*%s') % (10**i,d) for i,d in enumerate(word[::-1])]
... |
def calculate_computation(computation, num, operation): # O(1)
"""
If values exist in array concatenate with operation, else return number
>>> calculate_computation([], 42, '+')
[42]
>>> calculate_computation([112], 42, '^')
[112, '^', 42]
"""
if computation: ... |
def filter_insertchars(s,chars=None,space=' '):
"""insertchars(s,chars=None,space=' ') -> str
Insert space before each occurence of a character in chars."""
xchars = str(chars)
out = ''
for x in s:
if x in xchars:
out += space
out += x
return out |
def get_Canadian_to_USD_exchange_rate(year):
"""
Return exchange rate (Canadian $/USD)
From https://www.federalreserve.gov/releases/h10/current/ on 09/07/2020
:param year:
:return:
"""
er = ({'2000': '1.4855',
'2001': '1.5487',
'2002': '1.5704',
'2003': '1.40... |
def dnContainedIn(child, parent):
"""
Return True if child dn is contained within parent dn, otherwise False.
"""
return child[-len(parent):] == parent |
def problem_1_7(arr):
""" Write an algorithm such that if an element in an MxN matrix is 0, its
entire row and column is set to 0
"""
m = len(arr)
if m == 0:
return arr
n = len(arr[0])
# Step 1: pass through the array and find columns and rows should be zeroed.
rows = set([])
... |
def preprocess(lr, hr):
"""Preprocess lr and hr batch"""
lr = lr / 255.0
hr = (hr / 255.0) * 2.0 - 1.0
return lr, hr |
def get_fps_number(avg_fps_msg: str) -> float:
"""Decodes FPS number from given "Avg FPS" string output by Peeking Duck
in the format: "... Avg FPS over last n frames: x.xx ..."
Args:
avg_fps_msg (str): Peeking Duck's average FPS message string
Returns:
float: Frames per second number
... |
def getport_connaddr(pack):
"""
get port from connaddr
"""
return (pack >> 48) & 0xffff |
def find_multiplicity(knot, knot_vector, **kwargs):
""" Finds knot multiplicity over the knot vector.
:param knot: knot
:type knot: float
:param knot_vector: knot vector
:type knot_vector: list, tuple
:return: multiplicity of the knot
:rtype: int
"""
# Get tolerance value
tol = ... |
def drain_pipes(popen_list, ignore_stderr=False):
""" Read the output from piped output (see exec_binaries() above)
:param pipes: list of Popen objects
:return: A list of strings Output from the subprocesses. Output from pipes is
not interleaved. Blocks until all output is drained.
"""
results=[]
... |
def EscapeJs(t):
"""Replaces javascript special characters in the supplied string.
Characters are replaced with a textual representation of their integer
ordinal."""
js_escapes = {
'\\': '\\u005C',
'\'': '\\u0027',
'"': '\\u0022',
'>': '\\u003E',
'<': '\\u003C',
'&': '\\u0026',
'=':... |
def format_size(size):
"""
Returns string representation of file size in human readable format (using kB, MB, GB, TB units)
:param size: Size of file in bytes.
:return: String representation of size with SI units.
"""
if size < 1000:
return "{:d} B".format(size)
for unit in ["k", "M"... |
def str_ellipsis(string: str, max_length: int = 40) -> str:
"""
Reduces the length of a given string, if it is over a certain length, by inserting str_ellipsis.
Args:
string: The string to be reduced.
max_length: The maximum length of the string.
Returns:
A string with a maximu... |
def is_palindrome(string: str) -> bool:
"""
Check if a string is a palindrome.
A palindrome is a string that reads the same forwards as backwards.
:param string: The string to check.
:return: True if `string` is a palindrome, False otherwise.
"""
# backwards = string[::-1]
# return backw... |
def rgb2hex(r, g, b):
"""
Takes (R,G,B) format and returns Hex color format.
@param r: int
@param g: int
@param b: int
@return: hex color format
"""
return "{:02x}{:02x}{:02x}".format(r, g, b) |
def replace_offset(text: str) -> str:
"""Overrides the offset for better timezones"""
return text.replace("UTC\+05:30", "IST").replace("UTC\+01:00", "BST") |
def _get_umbrella_header_declaration(basename):
"""Returns the module map line that references an umbrella header.
Args:
basename: The basename of the umbrella header file to be referenced in the
module map.
Returns:
The module map line that references the umbrella header.
"""
... |
def find_new_refs(old, last=None):
"""Finds references in old, which are not in last."""
result = []
if old['type'] == 'way' and 'refs' in old:
nhash = {}
if last is not None and 'refs' in last:
for nd in last['refs']:
nhash[nd] = True
for nd in old['refs'... |
def get_handler_filename(handler):
"""Shortcut to get the filename from the handler string.
:param str handler:
A dot delimited string representing the `<module>.<function name>`.
"""
module_name, _ = handler.split('.')
return '{0}.py'.format(module_name) |
def is_numeric(obj):
"""Check whether object is a number or not, include numpy number, etc."""
try:
float(obj)
return True
except (TypeError, ValueError):
# TypeError: obj is not a string or a number
# ValueError: invalid literal
return False |
def convert_coco_category(category_id):
"""
Convert continuous coco class id to discontinuous coco category id (0..79 --> 0..90)
"""
match = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
11, 13, 14, 15, 16, 17, 18, 19, 20, 21,
22, 23, 24, 25, 27, 28, 31, 32, 33, 34,
35, 3... |
def fix_country_name_sorting(countries):
"""Ensure that US States sort with the 'United States' country name"""
def mangle(string):
if string == "United States":
return "United States zzzzzzz"
elif string == "Canada":
return "Canada zzzzzzz"
else:
retu... |
def _GetPermissionErrorDetails(error_info):
"""Looks for permission denied details in error message.
Args:
error_info: json containing error information.
Returns:
string containing details on permission issue and suggestions to correct.
"""
try:
if 'details' in error_info:
details = error_i... |
def splitOut(aa):
"""Splits out into x,y,z, Used to simplify code
Args:
aa - dictionary spit out by
Returns:
outkx, outky, outkz (numpy arrays) - arrays of the x, y, and values of the points
"""
outkx = aa['x'][::3]
outky = aa['x'][1::3]
outkz = aa['x'][2::3]
return out... |
def ajoute_a_la_valeur(ajout, valeur1):
"""Ajoute la valeur ajout a valeur1."""
if valeur1 == "0":
valeur1 = ajout
else:
valeur1 += ajout
return valeur1 |
def _join_strings(x):
"""Joins adjacent Str elements found in the element list 'x'."""
for i in range(len(x)-1): # Process successive pairs of elements
if x[i]['t'] == 'Str' and x[i+1]['t'] == 'Str':
x[i]['c'] += x[i+1]['c']
del x[i+1] # In-place deletion of element from list
... |
def inverse(xs, scale, x0):
"""A simple parametrized inverse function (`1/x`), applied element-wise.
Args:
xs (np.ndarray or float): Input(s) to the function.
scale (float): Linear scaling factor.
x0 (float): Horizontal offset.
"""
ys = scale / (xs - x0)
return ys |
def human_readable_int(x):
"""
Transforms the integer `x` into a string containing thousands separators.
"""
assert isinstance(x, int)
in_str = str(x)
digit_count = len(in_str)
out_str = ""
for (n_digit, digit) in enumerate(in_str):
if (n_digit > 0) and (((digit_count - n_digit) ... |
def sdfSetChangeProp(mol, sdfprop, sdfvalue):
"""
sdfSetChangeProp() sets property sdfprop to value sdfvalue for molecule mol.
If the sdfprop is already defined in mol, the value is changed.
returns a pair made of Boolean True and of the new molecule
"""
sdfkeyvals = mol["keyvals"]
sdfkeys = [pair[0] for pair in... |
def bin_gcd(a, b):
"""
Return the greatest common divisor of a and b using the binary
gcd algorithm.
"""
if a == b or b == 0:
return a
if a == 0:
return b
if not a & 1:
if not b & 1:
return bin_gcd(a >> 1, b >> 1) << 1
else:
return bi... |
def user_thumbnail(user):
"""
User Thumbnail if facebook if fb_uid else thumnail obj
"""
return {'user': user} |
def chatter(nwords):
""" Hodor gets talkative
Parameters
-----------------
nwords : int
Number of words Hodor should speak
"""
return('Hodor ' * nwords) |
def get_attr(obj, attr_name):
"""
Get attribute from object
:param obj: object
"""
attrs = []
for attr in dir(obj):
if attr_name in attr:
attrs.append(attr)
return attrs |
def human_size(nbytes):
"""
Provides human readable file size
source: https://stackoverflow.com/a/14996816
:param nbytes: int of file size (bytes)
:param units: list of unit abbreviations
:returns: string of human readable filesize
"""
suffixes = ['B', 'K', 'M', 'G', 'T', 'P']
i... |
def _closest_below_index(l,n):
"""
Helper function. Returns index of closest number in `l`
to `n`, without going over.
"""
best = -1
best_i = -1
for i in range(len(l)):
if l[i] < n:
if n - l[i] < n - best:
best_i = i
best = l[i]
return ... |
def get_crop_box(width=600, height=1400, center_x=1000, margin_y=15):
"""
Calculate a cropping rectangle.
Args:
width (int): The width of the output image.
height (int): The height of the output image.
center_x (int): Position along the X-axis for the center of the rectangle.
... |
def _dT_d_dt(U, T_g, T_d, RTI):
"""[Eq. 11.5]
:param U: [m/s]
:param T_g: [K]
:param T_d: [K]
:param RTI: [-]
:return dT_d_dt: [K/s]
"""
dT_d_dt = U ** (1 / 2) * (T_g - T_d) / RTI
return dT_d_dt |
def calc_f1(precision, recall):
"""
Compute F1 metric from the score dictionary
inputs:
precision float with the precision value
recall float with the recall value
output:
f1 float with the F1 value
"""
f1 = (2 * precision * recall) / (precision + recall)... |
def isiterable(obj):
"""
Tests if the argument is an iterable
:param obj: Object
:type obj: any
:rtype: boolean
"""
try:
iter(obj)
except TypeError:
return False
else:
return True |
def missed_cleavages(peptides, missed, protein_name):
"""Concatenates peptides and returns a combined list of peptides with 0-n missed
cleavages."""
combined_peptides = []
for n in range(1, missed + 2): # number of peptides to combine
for i in range(len(peptides) - n + 1): # index of first pept... |
def dict_of_relay_branches(relays, branches):
"""
Create dictionaries of the branch keys from the
relay elements
"""
relay_branches = {k: list() for k in relays.keys()}
for branch_name, branch in branches.items():
branch_relay_mappings = branch['relay']
for r in branch_relay_map... |
def get_identifier(iri, prefix):
"""Return a valid Python variable name based on a KG object UUID"""
return prefix + "_" + iri.split("/")[-1].replace("-", "") |
def fm_id(M,gamma):
"""Function that takes in the Mach number and isentropic expansion factor,
and outputs a value for f(M) that's commonly used in compressible flow
calculations.
Inputs:
M [-]
gamma [-]
Outputs:
fm [-]
Spurce:
https://web.stanford.edu/~cantwell/A... |
def ts_truncate_seconds(timestamp):
"""
Set seconds to zero in a timestamp.
:param ts: Timestamp in seconds.
:type ts: int
:return: Timestamp in seconds, but without counting them (ie: DD-MM-YY HH:MM:00)
:rtype: int
"""
return timestamp - (timestamp % 60) |
def d_d_theta_inv(y, alpha):
"""
xi'(y) = 1/theta''(xi(y)) > 0
= alpha / (1 - |y|)^2
Nikolova et al 2014, table 1, theta_2 and eq 5.
"""
assert -1 < y < 1 and alpha > 0
denom = 1 - abs(y)
return alpha / (denom*denom) |
def get_contigous_borders(indices):
"""
helper function to derive contiguous borders from a list of indices
Parameters
----------
indicies : all indices at which a certain thing occurs
Returns
-------
list of groups when the indices starts and ends (note: last e... |
def IpDecimalToBinary(decimal_ip, binary_size=32):
"""
:param decimal_ip: IPv4 in decimal notation, e.g. 167772161
:param binary_size: IP size in binary, default is 32 for IPv4
:return: IPv4 in binary notation, e.g. 00001010000000000000000000000001
"""
return ('0'*binary_size + bin(decimal_ip)[2... |
def create_coordinate_matrix(sp, xn, yn, lons, lats):
"""
Creates xn times yn matrix of GNSS points.
:param sp: Starting GNSS point.
:param xn: Number of rectangles (columns).
:param yn: Number of rectangles (rows).
:param lons: Longitude step.
:param lats: Latitude step.
:return: Matrix... |
def is_palindrome_v1(head) -> bool:
"""Use slicing"""
pal = []
node = head
# Change a linked list for a list
while node is not None:
pal.append(node.val)
node = node.next
# Use slicing
return pal == pal[::-1] |
def _which_ip_protocol(element):
"""
Validate the protocol addresses for the element. Most elements can
have an IPv4 or IPv6 address assigned on the same element. This
allows elements to be validated and placed on the right network.
:return: boolean tuple
:rtype: tuple(ipv4, ipv6)
"""
... |
def move_loop(arr, range_from, range_to, move_value=2):
"""
Perform array moving
:param arr: array to move
:param range_from: range() from param
:param range_to: range() to param
:param move_value: class to move
:return: moved array
"""
for i in range(range_from, range_to, -1):
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.