content stringlengths 42 6.51k |
|---|
def is_valid_input(curr_input):
""" Gives the standard names stored within the standard dictionary.
Returns the standard names currently being stored as list.
Args:
curr_input: the LUFS or peak input a user is trying to include as a platform standard
Returns:
is_valid: a boolean value... |
def build_buddy_feed_url(user_id):
"""
>>> build_buddy_feed_url(123)
'https://5-edge-chat.facebook.com/pull?channel=p_123&seq=1&\
partition=-2&clientid=1a2b3c4d&cb=ze0&idle=0&qp=yisq=129169&\
msgs_recv=0&uid=123&viewer_uid=123&sticky_token=1058&\
sticky_pool=lla1c22_chat-proxy&state=active'
"""
retu... |
def addDice(arrLen2Int):
"""function that adds the values of two dice
_____________________________________________________________________
SYNTAX : sum = addDice(listWithALengthOfTwoIntegers)
_____________________________________________________________________
PARAMS (1): arrLen2Int : literal... |
def tag2absa(tag_sequence):
"""
transform absa tag sequence to a list of absa triplet (b, e, sentiment)
"""
n_tags = len(tag_sequence)
absa_sequence, sentiments = [], []
beg, end = -1, -1
for i in range(n_tags):
absa_tag = tag_sequence[i]
# current position and sentiment
... |
def remove_stop_words(s):
"""
Removes (English) stop words from the given string.
"""
stopwords = 'a', 'the'
words = [word for word in s.split() if word.lower() not in stopwords]
# Join remaining words and remove whitespace.
return ' '.join(words) |
def dataclasses_to_dicts(data):
""" Converts a list of dataclass instances to a list of dictionaries
Parameters
----------
data : List[Type[dataclass]]
Returns
--------
list_dict : List[dict]
Examples
--------
>>> @dataclass
>>> class Point:
... x: int
... ... |
def keys_are_equal(rec1, rec2, fkeys):
"""Check if the "keys" in two records are equal. The key fields
are all fields for which order isn't marked ignore.
Parameters
-------------------------------------------------------------------------
rec1 - The first record
rec2 - The second record
f... |
def strip_empty_lines(text: str) -> str:
"""
Remove empty lines from the start and end of `text`.
"""
lines = text.splitlines()
while lines and not lines[0].strip():
lines.pop(0)
while lines and not lines[-1].strip():
lines.pop()
return "\n".join(lines) |
def ordenamiento(lista):
"""Sorts a list of ints in ascending order.
Big-O Complexity: O(n^2)"""
for i in range(len(lista)):
key = lista[i]
j = i - 1
while j >= 0 and lista[j] > key:
lista[j + 1] = lista[j]
j -= 1
lista[j + 1] = key
return lista |
def clamp(value, minimum, maximum):
"""
Clamp: Clamps the specified 'value' between the maximum and minimum values.
Returns 'max' when 'value' is greater than 'max', 'min' when 'value' is less than 'min',
and 'value' itself when neither is true.
"""
return (min(max(value, minimum), maximum)) |
def _escape_markdown_literals(string):
"""Escape any markdown literals in ``string`` by prepending with \\
:type string: str
:rtype: str
"""
literals = list("\\`*_{}[]()<>#+-.!:|")
escape = lambda c: '\\' + c if c in literals else c
return "".join(map(escape, string)) |
def largest_odd_times(L):
""" Assumes L is a non-empty list of ints
Returns the largest element of L that occurs an odd number
of times in L. If no such element exists, returns None """
# Set frequency dictionary
freqDict = {}
for item in L:
if item in freqDict:
fre... |
def autonomous_to_manual_mode_by_ttc(world, ttc, vehicle_id, transition_time, flag_change):
"""
Function that change the driving mode in function of ttc
"""
# collision_time = transition_time * 2 + (4 - transition_time)
k1 = 5/6
k2 = -5
k3 = 55/6
collision_time = (k1 * transition_tim... |
def _eq(field, value, document):
"""
Returns True if the value of a document field is equal to a given value
"""
try:
return document.get(field, None) == value
except TypeError: # pragma: no cover Python < 3.0
return False |
def get_rank_for_user(days):
"""
Returns the rank, for the specific days in a range.
"""
rank_string = ""
rank = 0
if days == 0:
rank_string = "Private"
rank = 1
elif days == 1:
rank_string = "Private 2"
rank = 2
elif 2 <= days <= 4:
rank_stri... |
def calculate_AICc(AIC, number_of_parameters, effective_number_of_data_points):
"""
AIC is the Aikaike Information Criterion and AICc the corrected
criterion for small numbers of observations
"""
return AIC + 2.*number_of_parameters*(number_of_parameters + 1.) / (effective_number_of_data_points - nu... |
def quantidades_de_latas(litros_de_tinta):
"""
Calcula a quantidade de lastas pra a quantidade de litros de tinta dados
:param litros_de_tinta:
:return: quantidade de latas de tinta
>>> quantidades_de_latas(17)
1
>>> quantidades_de_latas(18)
1
>>> quantidades_de_latas(36)
2
>... |
def classify_median(value, expected_coverage):
"""Take a coverage median for a window (value) and an expected coverage and return a classification:
Heterozygous if: "0 < value <= EC / 1.5"
Homozygous if: "EC / 1.5 < value < EC * 1.5"
Outlier if: "value = 0 or value >= EC * ... |
def geometric_series_iter(n, r):
"""Geometric series by bottom-up DP w/ optimized space.
Time complexity: O(n).
Space complexity: O(1)
"""
s = 0
for k in range(1, n + 1):
s += pow(r, k)
return s |
def pointsAroundP(P, width, height):
""" Return a list of points surround P provided that P is within the bounds of the area
"""
Px,Py = P
if not(Px >= 0 and Px < width and Py >= 0 and Py < height):
return []
result = [
(Px-1, Py),
(Px+1, Py),
(Px, Py-1),
(Px... |
def equilikely(a, b, u):
"""
Generates an Equilikely rnd variate in *[a,b]*.
Must be a < b.
:param a: (int) lower bound.
:param b: (int) upper bound.
:param u: (float) rnd number in (0,1).
:return: (float) the Equilikely(a,b) rnd variate.
"""
return a + int((b - a + 1) * u) |
def generate_all_masks(length, masks=[""]):
"""Recursively generate a list of all possible masks of given length.
Masks consist of the following symbols (similar to the Wordle game):
0 -- green tile (correct digit and correct position);
1 -- yellow tile (correct digit but wrong position);
2 -- gray ... |
def get_required_capabilities(data: dict):
"""
Get capabilities for a given cloud formation template for the
"create_stack" call
"""
capabilities = []
for _, config in data.get("Resources", {}).items():
if config.get("Type").startswith("AWS::IAM"):
if config.get("Properties",... |
def dynamic_pressure_p_mach(p, mach):
"""Calculates dynamic pressure without options for units"""
q = 0.7 * p * mach ** 2
return q |
def float_parameter(level, maxval):
"""Helper function to scale `val` between 0 and maxval.
Args:
level: Level of the operation that will be between [0, `PARAMETER_MAX`].
maxval: Maximum value that the operation can have. This will be scaled to
level/PARAMETER_MAX.
Returns:
A float th... |
def linear_search(arr, target):
"""
Searches for the first occurance of the provided target in the given array.
If target found then returns index of it, else None
Time Complexity = O(n)
Space Complexity = O(1)
"""
for idx in range(len(arr)):
if arr[idx] == target: return idx
ret... |
def condense_duplicates_dict(list_of_lists):
"""Transforms a list of lists to a dictionary.
Duplicates in the first element(list[0]) are condensed to a single key,
contents are fused together by making dict[key].expand(list[1:])
"""
ans = dict()
for group in list_of_lists:
if group[0] n... |
def generate_bond_indices(natoms):
"""
natoms: int
The number of atoms
Finds the array of bond indices of the upper triangle of an interatomic distance matrix, in column wise order
( or equivalently, lower triangle of interatomic distance matrix in row wise order):
[[0,1], [0,2], [1,2], [0,3... |
def group_similar_exam_sections(exam_sections):
"""Groups together exam sections that have the same date, time,
and location.
Args:
exam_sections: A list of sections for an exam as returned by OpenData's
examschedule.json endpoint.
Returns a consolidated list of sections in the ... |
def guess_submission_type_from_sdrf(sdrf_data, header, header_dict):
""" Guess the basic experiment type (microarray or sequencing) from SDRF"""
if 'arraydesignref' in header_dict or 'labeledextractname' in header_dict:
return "microarray"
elif "comment" in header_dict:
for comment_index in... |
def colors_to_string(colors):
"""Transform the 3 sized tuples 'colors' into a hex string.
[(0,100,255)] --> 0064ff
[(1,2,3),(4,5,6)] --> 010203040506
"""
return ''.join(['%02x%02x%02x' % (r,g,b) for r,g,b in colors]) |
def _apply_modifiers(intervals, modifiers):
""" Given a set of tuple intervals and a set of modifiers, adjusts the intervals accordingly"""
# Replace intervals that are flatted or sharped
for i in range(len(intervals)-1, -1, -1):
for j in range(len(modifiers)-1, -1, -1):
if intervals[i][... |
def MakeImportStackMessage(imported_filename_stack):
"""Make a (human-readable) message listing a chain of imports. (Returned
string begins with a newline (if nonempty) and does not end with one.)"""
return ''.join(
reversed(["\n %s was imported by %s" % (a, b) for (a, b) in \
zip(impor... |
def _get_repeat_key(e):
"""
Generate a key to store repeats temporarily
"""
return ('repeat',) |
def csv2scsv(s):
"""Replace any occurrence of comma in the string with semicolon."""
return s.replace(',', ';') |
def sub_domain_to_tld(domain):
"""
Turn the input domain to get Top Level Domain
Args:
domain: any domain value
Returns:
TLD of input domain
"""
domain_list = domain.split('.')[-2:]
return '.'.join(domain_list) |
def correct_capitalization(s):
"""Capitalizes a string with various words, except for prepositions and articles.
:param s: The string to capitalize.
:return: A new, capitalized, string.
"""
toret = ""
if s:
always_upper = {"tic", "i", "ii", "iii", "iv", "v", "vs", "vs.", "2d",... |
def linearGain(iLUFS, goalLUFS=-16):
""" takes a floating point value for iLUFS, returns the necessary
multiplier for audio gain to get to the goalLUFS value """
gainLog = -(iLUFS - goalLUFS)
return 10 ** (gainLog / 20) |
def is_palindrome(input_string):
"""Check if a string is a palindrome
irrespective of capitalisation
Returns:
True if string is a palindrome
e.g
>>> is_palindrome("kayak")
OUTPUT : True
False if string is not a palindrome
e.g
>>> is_palindro... |
def parser_multilingual_service_name_Descriptor(data,i,length,end):
"""\
parser_multilingual_service_name_Descriptor(data,i,length,end) -> dict(parsed descriptor elements).
This descriptor is not parsed at the moment. The dict returned is:
{ "type": "multilingual_service_name", "contents" : unpa... |
def skew_area(col, n):
"""
returns (n - 1) + (n - 2) + ... + (n - col)
i.e., the number of matrix elements below the diagonal and
from column 0 to column `col`
"""
return col * (2 * n - col - 1) // 2 |
def utilization_to_state(state_config, utilization):
""" Transform a utilization value into the corresponding state.
:param state_config: The state configuration.
:type state_config: list(float)
:param utilization: A utilization value.
:type utilization: number,>=0
:return: The state corres... |
def get_mse_norm(series1, series2):
"""
normalized values
"""
assert len(series1) == len(series2)
mse = 0.0
max_v = max(max(series1), max(series2))
s1 = tuple((value/max_v for value in series1))
s2 = tuple((value/max_v for value in series2))
for index, data1 in enumerate(s1):
... |
def have_doc_extension(l):
"""Check if .doc extension is present"""
if ".doc" in str(l):
return 1
else:
return 0 |
def _raw_string(original):
"""
Wraps the given original string to
* Kotlin's raw string literal
* Escape $ in Kotlin multi line string
See: https://kotlinlang.org/docs/reference/basic-types.html#string-templates
"""
return '"""' + original.replace("$", "${'$'}") + '"""' |
def _metadata_with_prefix(prefix, **kw):
"""Create RPC metadata containing a prefix.
Args:
prefix (str): appropriate resource path.
Returns:
List[Tuple[str, str]]: RPC metadata with supplied prefix
"""
return [("google-cloud-resource-prefix", prefix)] |
def split_string(s, *ndxs):
"""String sub-class with a split() method that splits a given indexes.
Usage:
>>> print split_string('D2008022002', 1, 5, 7, 9)
['D', '2008', '02', '20', '02']
"""
if len(ndxs) == 0:
return [s]
if len(ndxs) == 1:
i = ndxs[0]
... |
def clean_seq(seq: str) -> str:
"""
Cleans the sequence: every letter is in 'ATCGN'.
:param seq: Input sequence
"""
seq = seq.upper()
assert lambda char: char in ['A', 'T', 'C', 'G', 'N'], set(seq)
return seq |
def check_voxel(xmin, ymin, xmax, ymax):
"""
Given voxel hi and low point, return true if
voxel is good, false otherwise
"""
return xmin < xmax and ymin < ymax |
def Event(time, node, token, inf_event, source=None):
"""
Arguments:
- time: float, used to order the events in the priority queue
- node: name of the affected host
- token: The putative new infectious status of the host
- inf_event: Whether the Event is an infection (True) or a
... |
def is_dict_has_key(obj, key):
"""return True/False `obj` is a dict and has `key`
"""
return isinstance(obj, dict) and key in obj |
def make_link(base, url):
"""Make URL from absolute or relative `url`"""
if '://' in url:
return url
return base + url |
def parse_policy(policy):
"""Parses a policy of nested list of tuples and converts them
into a tuple of nested list of lists. Helps with TF serializability."""
op_names = [[name for name, _, _ in subpolicy] for subpolicy in policy]
op_probs = [[prob for _, prob, _ in subpolicy] for subpolicy in policy]
... |
def is_reg_readable(reg):
"""Returns whether a Pozyx register is readable."""
if (0x00 <= reg < 0x07) or (0x10 <= reg < 0x12) or (0x14 <= reg < 0x22) or (0x22 <= reg <= 0x24) or (
0x26 <= reg < 0x2B) or (0x30 <= reg < 0x48) or (0x4E <= reg < 0x89):
return True
return False |
def plaquette_to_sites(p):
"""Turn a plaquette ``((i0, j0), (di, dj))`` into the sites it contains.
Examples
--------
>>> plaquette_to_sites([(3, 4), (2, 2)])
((3, 4), (3, 5), (4, 4), (4, 5))
"""
(i0, j0), (di, dj) = p
return tuple((i, j)
for i in range(i0, i0 ... |
def align(number: int):
""" Align the number regarding to template """
return " " + str(number) + " " * (11 - len(str(number))) |
def dot_quote(s):
"""
Return a quoted version of a (unicode) string s suitable for output in the
DOT language.
"""
# From the documentation (http://www.graphviz.org/doc/info/lang.html):
#
# In quoted strings in DOT, the only escaped character is double-quote
# ("). That is, in quoted st... |
def get_standard_metadata_values( md_map, file, metadata ):
"""
Gets metadata values from a file path
:param md_map: Dictionary of keys to callables to extract metadata.
Callables should accept a single parameter which is the file name.
:param file: The file path to search
:param metadata: ... |
def scale_vars(var_seq, scale):
"""
Scale a variable sequence.
"""
return [v * scale for v in var_seq] |
def frames_to_ms(frames: int, fps: float) -> int:
"""
Convert frame-based duration to milliseconds.
Arguments:
frames: Number of frames (should be int).
fps: Framerate (must be a positive number, eg. 23.976).
Returns:
Number of milliseconds (rounded to int).
... |
def param_string_to_dict(param_str, delim='|'):
"""
Reverse of the dict_to_param_string() function.
Note that this will not completely rebuild a dict() after being serialised as a param_string: any '=' or
{delim} characters get eaten by dict_to_param_string().
:param param_str: str
:return: di... |
def FormatEmph(s):
"""RST format a string for emphasis."""
return '*%s*' % s |
def get_universe_name(universe_id):
""" Get the name of a universe """
return 'universe_' + str(universe_id) |
def get_correctness(files, models):
""" Checks the correctness of a given rules file """
exitcode = 0
for file_index in range(0, len(files)):
if isinstance(models[file_index], dict):
print("Syntax invalid: %s" % models[file_index])
exitcode = 1
else:
print... |
def anyMoreThanOne(dict, keys):
""" Checks if any of a list of keys in a dictionary has a value more than one.
Arguments:
dict -- the dictionary
keys -- the keys
Returns:
True if any key exists in the dictionary and the value is at least one, otherwise false
"""
for key in keys:
if key in dict and... |
def clean_string_input(value: str) -> str:
"""Converts a string to lower case and and removes leading and trailing white spaces.
Parameters
----------
value: str
The user input string.
Returns
-------
str
value.lower().strip()
"""
return value.lower().strip() |
def get_hello(http_context, app):
"""
Basic "Hello world" API using HTTP method GET.
Usage:
$ export XSESSION=`curl -s -k -X POST --data '{"username":"<user>", "password":"<password>"}' https://localhost:2345/login | sed -E "s/^.+\"([a-f0-9]+)\".+$/\1/"`
$ curl -s -k -H "X-Session:$XSESSION" "https... |
def dict_to_params(params: dict) -> str:
"""
converts dict of params to query string
"""
stringed = [name + '=' + value for name, value in params.items()]
return '?' + '&'.join(stringed) |
def largest_element(a,loc=False):
""" Return the largest element of a sequence a."""
try:
maxval=a[0]
maxloc=0
for i in range(1,len(a)):
if a[i] > maxval:
maxval = a[i]
maxloc = i
if loc == True:
return maxv... |
def selection_sort(items):
"""Sort given items by finding minimum item, swapping it with first
unsorted item, and repeating until all items are in sorted order.
Running time: O(n^2) because as the numbers of items grow the so does the outter and inner loop, also the function increases in a quadratic way
... |
def get_max_hours(context):
"""Return the largest number of hours worked or assigned on any project."""
progress = context['project_progress']
return max([0] + [max(p['worked'], p['assigned']) for p in progress]) |
def polyARI(x,y,coeff):
"""ARI compressor polynomial (upper right corner)
| - | x | x2| x3|
---+---+---+---+---+
- | a | b | d | g |
y | c | e | h | - |
y2| f | i | - | - |
y3| j | - | - | - |
"""
a,b,c,d,e,f,g,h,i,j = coeff
return a + x*(x*(x*g + d) + b) + y*(y*(y... |
def format_nums(start_index):
"""
Expects an integer.
Brings numbers exceeding three digits in line with API call requirements
"""
if start_index >= 1000:
start_format = str(start_index)[:-3] + "%2C" + str(start_index)[-3:]
else:
start_format = str(start_index)
retur... |
def k5(Tn):
"""[cm^3 / s]"""
return 1.6e-12 * Tn**(0.91) |
def safe_sum(fun, seq, missing=0):
"""Return the sum of fun applied to elements in seq using missing as a replacement
for those elements on which fun throws an exception
>>> safe_sum(lambda x: x, [5, "terrible", 4, 3, "two", 1])
13
>>> safe_sum(lambda x: 1/x, [1, 2, 0, 3, None, "bad"])
1.833333... |
def bubblesort_xml(list_to_sort):
"""
This is a version of bubblesort that can be used to sort the songdata
from the xml function.
"""
for pass_no in range(len(list_to_sort) - 1, 0, -1):
for n in range(0, pass_no):
if list_to_sort[n][0] > list_to_sort[n + 1][0]:
l... |
def read_maze(file_name):
"""
Reads maze stored in a text file and returns a 2d list
with the maze representation
"""
try:
with open(file_name) as fh:
maze = [[char for char in line.strip("\n")] for line in fh]
# use number of columns in top row to check rectangularit... |
def islist(x):
"""Is an object a python list"""
return type(x) is list |
def different_local_with_stage(stage: str, ssm_env: dict, local_env:dict, filter_env: list = []):
"""returns differences between ssm stage and local env"""
for x in filter_env:
ssm_env.pop(x, None)
local_env.pop(x, None)
different_env_values = {k: {'stage': ssm_env[k], "local": local_env[k]}... |
def get_number_of_bins_nd(array_size, binning):
"""
Generate the number of bins needed in three dimensions, based on the size
of the array, and the binning.
:param array_size: Size of the image array (tuple or dict)
:param binning: How many pixels in each edge of nD equal sized bins
:return:
... |
def listify(data):
""" Ensure that the input is a list or tuple.
Parameters
----------
arr: list or array
the input data.
Returns
-------
out: list
the liftify input data.
"""
if isinstance(data, list) or isinstance(data, tuple):
return data
else:
... |
def uniquify(input_list):
"""
Finds the unique values in a list. This keeps the order of the list, as
opposed to the standard list(set()) method.
Adopted from: http://stackoverflow.com/
questions/
480214/
how-do-you-remove-duplicates-from-a-list-in-python-whilst-preserving-order
:param ... |
def formatCount(num):
"""
Get human readable number from large number.
Args:
num (str): Large number. Can be string or int.
"""
count = int(num)
if count < 1000:
return '%d' % (count)
for suffix in ['', 'K', 'M']:
if count < 1000:
return '%.1f%s' % (count,... |
def uniquify_key(dict, key, template="{} ({})"):
"""
rename key so there are no duplicates with keys in dict
e.g. if there is already a key named "dog", the second key will be reformatted to "dog (2)"
"""
n = 1
new_key = key
while new_key in dict:
n += 1
new_key = template.f... |
def regula_falsi(func, min_guess, max_guess, err_tolerance):
"""
Find the root of a function using false position method. (Bracketing method)
arguments:
func: f(x)
min_guess: minimum x as guess
max_guess: maximum x as guess
err_tolerance: value where f(root) must be less than err_tolerance
... |
def whitespace_tokenize(text):
"""Runs basic whitespace cleaning and splitting on a piece of text."""
text = text.strip()
if not text:
return []
# tokens = text.split()
tokens = list(text)
return tokens |
def convert_by_type_hint(header, value, dtype):
"""
:param str header:
:param Any value:
:param dict[str,type] dtype:
:return:
"""
if header in dtype:
return dtype[header](value)
return value |
def to_pascal_case(val: str) -> str:
"""Convert underscore_delimitered_string to PacalCase string."""
words = val.split('_')
result = ''.join(list(map(lambda x: x.title(), words)))
return result |
def keyfile_data_is_encrypted_ansible( keyfile_data:bytes ) -> bool:
""" Returns true if the keyfile data is ansible encrypted.
Args:
keyfile_data ( bytes, required ):
Bytes to validate
Returns:
is_ansible (bool):
True if data is ansible encryp... |
def _set_default_quality(subcategory_id: int) -> int:
"""Set the default quality for mechanical relays.
:param subcategory_id: the subcategory ID of the relay with missing defaults.
:return: _quality_id
:rtype: float
"""
return 5 if subcategory_id == 4 else 1 |
def validate_json(schema, doc):
"""
Validate that a json doesn't contains more elements that it should, raise
in case it does.
:return:
"""
is_invalid = set(doc).difference(set(schema))
if is_invalid:
return False
return True |
def _retrieve_bucket_name(bucket_url_or_name: str) -> str:
"""Returns bucket name retrieved from URL.
Args:
bucket_url_or_name: The name or url of the storage bucket.
"""
return bucket_url_or_name.split('/')[-1] |
def noam_decay(step, warmup_steps, d_model):
"""
Learning rate schedule described in
https://arxiv.org/pdf/1706.03762.pdf.
"""
return (
d_model ** (-0.5) * min(step ** (-0.5),
step * warmup_steps**(-1.5))) |
def merge_with_cache(cached_datapoints, start, step, values, func=None, raw_step=None):
"""Merge values with datapoints from a buffer/cache."""
consolidated = []
# Similar to the function in render/datalib:TimeSeries
def consolidate(func, values):
usable = [v for v in values if v is not None]
... |
def parse_egg_dirname(dn):
"""
Extrahiere die folgenden Informationen aus dem Namen:
- den Paketnamen
- die Versionsangabe
- das Python-Versionstupel
>>> parse_egg_dirname('visaplan.tools-1.0-py2.7.egg')
('visaplan.tools', '1.0', (2, 7))
Sonstige Namen werden nicht erkannt:
>>> pa... |
def flatten_lists(l):
"""
https://stackoverflow.com/questions/952914/how-to-make-a-flat-list-out-of-list-of-lists
"""
return [item for sublist in l for item in sublist] |
def _year2string(year):
"""
Helper function, takes a four digit integer year, makes a length-2 string.
Parameters
----------
year : int
The year.
Returns
-------
Length-2 string representation of ``year``
"""
return '{0:02}'.format(year % 100) |
def word_count_dict_to_tuples(counts, decrease=True):
"""
Given a dictionary of word counts (mapping words to counts of their
frequencies), convert this into an ordered list of tuples (word,
count). The list is ordered by decreasing count, unless increase is
True.
"""
return sorted(list(coun... |
def sort(array, reverse=True, sort_by_key=False):
"""Sort a simple 1-dimensional dictionary
"""
if isinstance(array, dict):
if not sort_by_key:
return sorted(array.items(), key=lambda x: x[1], reverse=reverse)
return sorted(array.items(), key=lambda x: str(x[0]).lower(), reverse=... |
def set_default_nside(nside=None):
"""
Utility function to set a default nside value across the scheduler.
XXX-there might be a better way to do this.
Parameters
----------
nside : int (None)
A valid healpixel nside.
"""
if not hasattr(set_default_nside, 'nside'):
if ns... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.