content stringlengths 42 6.51k |
|---|
def n_complete(n, d):
"""
Return the number of terms in a complete polynomial of degree d in n
variables
Parameters
----------
n : int
The number of parameters in the polynomial
d : int
The degree of the complete polynomials
Returns
-------
m : int
The ... |
def apply(function, args=(), kwds={}):
"""call a function (or other callable object) and return its result"""
return function(*args, **kwds) |
def get_palette(num_cls):
""" Returns the color map for visualizing the segmentation mask.
Args:
num_cls: Number of classes
Returns:
The color map
"""
n = num_cls
palette = [0] * (n * 3)
for j in range(0, n):
lab = j
palette[j * 3 + 0] = 0
palette[j * ... |
def station_id(mqtt_topic: str) -> str:
"""
Returns the id of the weather station based on mqtt topic.
The id is for the database location tag.
Parameters:
mqtt_topic (str): weather station mqtt topic
Returns:
weather station id
"""
# Topic is a string like "ws/esp0", the ... |
def enumerate_flags(flag, f_map):
"""
Iterate through record flag mappings and enumerate.
"""
# Reset string based flags to null
f_type = ''
f_flag = ''
# Iterate through flags
for i in f_map:
if i & flag:
if f_map[i] == 'FolderEvent;' or \
... |
def set_worst(old_worst, new_worst):
"""
Pad new_worst with zeroes to prevent it being shorter than old_worst.
>>> set_worst(311920, '48-49')
'48-490'
>>> set_worst(98, -2)
-20
"""
if isinstance(new_worst, bool):
return new_worst
# Negative numbers confuse the lengt... |
def parse_url_query(query):
"""Parse url query string.
Returns a dictionary of field names and their values.
Args:
query (str): url query string
Returns:
Dict[str,str]
"""
ret = {}
for i in query.split('&'):
if not i:
continue
temp = i.split('=... |
def encode_value(value, col_sep, encl='"'):
""" convert a value to string and enclose with `encl`
if it contains ','
"""
if not isinstance(value, str):
value = str(value)
if col_sep in value:
value = '{encl}{value}{encl}'.format(encl=encl, value=value)
return value |
def get_fsname_from_service_name(service_name):
"""
Extract fsname from the volume name
"""
fields = service_name.split('-')
if len(fields) != 2:
return None
return fields[0] |
def clean_label(label: str) -> str:
"""
Return a label without spaces or parenthesis
"""
for c in "()":
label = label.replace(c, "")
for c in " ":
label = label.replace(c, "_")
return label.strip("_") |
def long_repeat(line: str) -> int:
"""
length the longest substring that consists of the same char
"""
if len(line) == 0:
return 0
if len(set(list(line))) == 1:
return len(line)
ans = 1
count = 1
for i in range(len(line)-1):
if line[i] == line[i+1]:
... |
def _snake_to_camel_case(original_text: str) -> str:
"""Converts attribute name from snake to camel case."""
if original_text:
original_text = original_text[0].lower() + original_text[1:]
components = original_text.replace(' ', '_').split('_')
if len(components) > 1:
return (components[0].lower() +
... |
def bam_index(input_bam):
"""make the bam index"""
return ["samtools", "index", input_bam] |
def _bytes_to_http_headers(data):
"""Parses a byte string into a HTTP headers dict.
Not using the standard functions here because the RP control interface is
limited in what it supports.
"""
out = {}
for line in data.split(b'\r\n'):
if not line:
continue
k, v = line.... |
def get_block_coords(row_num, col_num):
""" returns the upper left coordinates of the block in which the input coords exist """
return [row_num - (row_num % 3), col_num - (col_num % 3)] |
def compression_type_of_files(files):
"""Return GZIP or None for the compression type of the files."""
return 'GZIP' if all(f.endswith('.gz') for f in files) else None |
def spremeni_v_apostrof(seznam):
"""nekatere nagrade imajo v imenu apostrof, ki je v html oblike '
ta zapis spremenimo v ' """
sez = []
for i in seznam:
i = i.replace("'", "'")
sez.append(i)
return sez |
def fuel_used(pos, list_):
"""gives the fuel amount for a specific position"""
return sum([abs(pos - i) for i in list_]) |
def clean_name(name):
"""
Clean a name for the node, edge...
Because every name we use is double quoted,
then we just have to convert double quotes to html special char
See https://www.graphviz.org/doc/info/lang.html on the bottom.
:param name: pretty name of the object
:return: string with... |
def process_services(services, enterprise):
"""Converts services to a format Couchbase understands"""
sep = ","
if services.find(sep) < 0:
# backward compatible when using ";" as separator
sep = ";"
svc_set = set([w.strip() for w in services.split(sep)])
svc_candidate = ["data", "ind... |
def intsign(n):
"""Return the sign of an integer."""
if n == 0:
return n
elif n < 0:
return -1
else:
return 1 |
def is_url(value: str):
""" Return True if value is an url. False otherwise. """
return value.startswith("http") or value.startswith("icecast") |
def check_bitwidth_opt(msgs):
# type: (str) -> bool
# pylint: disable=unused-argument
"""
Check if memory coalescing is enabled as expected
FIXME Now we cannot judge if the memory coalescing
failure is due to incorrect pragmas, since it may
be caused by the kernel program characters
"""
... |
def kernel(r, h):
"""
Compute the cubic spline softened kernel
Arguments:
-r : Radial distance [FLOAT]
-h : Gravitational softening length [FLOAT]
Returns:
Kernel value
"""
if h == 0.0:
return -1.0 / r
hinv = 1.0 / h
q = r * hinv
if q <= 0.5:
ret... |
def is_power_of_two(n):
"""
:type n: int
:rtype: bool
"""
# 00..010000 minus 1
# 00..001111
return False if n <= 0 else (n & (n - 1)) == 0 |
def chunks(l, n):
"""Partitions the list l into disjoint sub-lists of length n."""
if len(l) % n != 0:
raise Exception('List length is not a multiple on %s', n)
return [l[i:i+n] for i in range(0, len(l), n)] |
def ARGMIN(agg_column,out_column):
"""
Builtin arg minimum aggregator for groupby
Example: Get the movie with minimum rating per user.
>>> sf.groupby("user",
... {'best_movie':tc.aggregate.ARGMIN('rating','movie')})
"""
return ("__builtin__argmin__",[agg_column,out_column]) |
def sec2hms(seconds):
"""Converts seconds to hours, minutes, seconds
:param int seconds: number of seconds
:return: (*tuple*) -- first element is number of hour(s), second is number
of minutes(s) and third is number of second(s)
:raises TypeError: if argument is not an integer.
"""
if n... |
def get_icon_name(x):
"""Returns the icon name from a CDragon path"""
return x.split('/')[-1] |
def dfs_filter(dfs, df_names, column_list):
"""Filter out all pandas.DataFrame without required columns
:param dfs: list of pandas.DataFrame objects to draw on the subplot
:type dfs: list[pandas.DataFrame]
:param df_names: a list of human readable descriptions for dfs
:type df_names: list[str]
... |
def get_line(start, end):
# http://www.roguebasin.com/index.php?title=Bresenham%27s_Line_Algorithm#Python
"""Bresenham's Line Algorithm
Produces a list of tuples from start and end
"""
# Setup initial conditions
x1, y1 = start
x2, y2 = end
dx = x2 - x1
dy = y2 - y1
# Determine how... |
def faster(b: int) -> int:
"""2**b via faster divide-and-conquer recursion.
>>> faster(17)-1
131071
"""
if b == 0:
return 1
if b%2 == 1:
return 2*faster(b-1)
t = faster(b//2)
return t*t |
def split_context(method, args, kwargs):
""" Extract the context from a pair of positional and keyword arguments.
Return a triple ``context, args, kwargs``.
"""
return kwargs.pop('context', None), args, kwargs |
def argmin2(l):
"""Return the indexes of the smalles two items in l."""
(j1, m1) = (-1, float('inf'))
(j2, m2) = (-1, float('inf'))
for ix, x in enumerate(l):
if x <= m1:
(j2, m2) = (j1, m1)
(j1, m1) = (ix, x)
elif x < m2:
(j2, m2) = (ix, x)
return... |
def get_channel_value(channel):
"""Helper to calculate luminance."""
channel = channel / 255.0
if channel <= 0.03928:
channel = channel / 12.92
else:
channel = ((channel + 0.055) / 1.055) ** 2.4
return channel |
def _add_value(interface, value, chosen_values, total_chosen_values, interface_to_value, value_to_implementation):
"""
Add a given value and a corresponding container (if it can be found) to a chosen value set.
:param interface: Interface identifier.
:param value: Provided implementation of an interfac... |
def crop_window(window, cropper_window):
"""Returns a version of window cropped against cropper_window.
Also returns a tuple containing two bools: (cropped_rows, cropped_cols)"""
(changed_rows, changed_cols) = (False, False)
((row_start,row_end),(col_start, col_end)) = window
if row_start < cropper... |
def slice_sum(lst, begin, end):
"""
This takes am iterable object and does recursive sum between begin and end.
:param lst: iterable object
:param begin: beginning index
:param end: ending index
:return: begin index for list + recursive call
"""
if begin > end or begin > len(lst) - 1 or ... |
def make_gram(summary: str, n: int) -> set:
"""
Extracts the ngrams of a text
Args:
summary: A `str` corresponding to a summary we want the ngrams from.
n: An `int` giving the length of the ngrams.
Returns:
A `set` of `str` corresponding to the ngrams of the summary.
"""
... |
def get_gui_widgets(gui, **kwargs):
""" Returns the GUI widget objects specified in kwargs
:param gui: (Window) main window gui object containing other widgets
:param kwargs: keyword arguments with argument name being the name
of the widget (str, widget_name) and argument value an integer specifyin... |
def filter_none_steps(steps):
"""Filters out pipeline steps whose estimators are None"""
return [(step_name, transform) for step_name, transform in steps if transform is not None] |
def process_ps_stdout(stdout):
""" Process the stdout of the ps command """
return [i.split()[0] for i in filter(lambda x: x, stdout.decode("utf-8").split("\n")[1:])] |
def parse_readable_time_str(time_str):
"""Parses a time string in the format N, Nus, Nms, Ns.
Args:
time_str: (`str`) string consisting of an integer time value optionally
followed by 'us', 'ms', or 's' suffix. If suffix is not specified,
value is assumed to be in microseconds. (e.g. 100u... |
def makeGoals(tokens):
"""Formats a token stream and creates a new goal
Keyword arguments:
tokens -- Collection of tokens
"""
aux = []
tAux = ()
for i in range(len (tokens)):
tokens[i][0] = tokens[i][0].upper()
tAux = tuple(tokens[i])
aux.append(tAux)
return aux |
def build_slice_path( data_root, data_suffix, experiment_name, variable_name, time_index, xy_slice_index, index_precision=3 ):
"""
Returns the on-disk path to a specific slice. The path generated has the following
form:
<root>/<variable>/<experiment>-<variable>-z=<slice>-Nt=<time><suffix>
<sli... |
def _replace_10(y):
"""
Return the numpy array as is, but all 10s are replaced by 0.
Parameters
----------
y : numpy array
Returns
-------
numpy array
"""
for i, el in enumerate(y):
if el == 10:
y[i] = 0
return y |
def _count0Bits(num):
"""Find the highest bit set to 0 in an integer."""
# this could be so easy if _count1Bits(~int(num)) would work as excepted
num = int(num)
if num < 0:
raise ValueError("Only positive Numbers please: %s" % (num))
ret = 0
while num > 0:
if num & 1 == 1:
... |
def binary_search_2(arr, elem, start, end):
"""
A method to perform binary search on a sorted array.
:param arr: The array to search
:param elem: The element to search
:param start: start position from where to start searching
:param end: start position till where to search
:return: The in... |
def is_reduced(obj):
"""A simple predicate to test whether an object has a reduced structure.
If `obj` does not have a `reducing_end` attribute, this will return :const:`False`
Parameters
----------
obj : object
The object to check
Returns
-------
bool
"""
try:
... |
def per_iteration(pars, iter, resid, *args, **kws):
"""iteration callback, will abort at iteration 23
"""
# print( iter, ', '.join(["%s=%.4f" % (p.name, p.value) for p in pars.values()]))
return iter == 23 |
def prepare_params_yaml(param_dic):
"""This function takes a single parameter dictionary and transforms it for
the standard use in the network model.
Parameters:
----------
param_dic: dict, dictionary with params.
"""
new_params = {}
# init dictionaries in the main dictioarny
for i... |
def _replace_oov(original_vocab, line):
"""Replace out-of-vocab words with "UNK".
This maintains compatability with published results.
Args:
original_vocab: a set of strings (The standard vocabulary for the dataset)
line: a unicode string - a space-delimited sequence of words.
Returns:
a unicode ... |
def vel_final_time_helper(initial_velocity, acceleration, time):
"""
Calculates the final velocity given the initial velocity, acceleration, and time traveled. This is a helper function
for the vel_final_time function.
:param initial_velocity: Integer initial velocity
:param acceleration: Integ... |
def map_num(x, in_min, in_max, out_min, out_max):
"""Will map a value x, bounded by in_min and in_max,
from out_min to out_max"""
ret_val = (x - in_min) * (out_max - out_min) // (in_max - in_min) + out_min
return ret_val |
def one_of_k_encoding_unk(x, allowable_set):
"""Maps inputs not in the allowable set to the last element."""
if x not in allowable_set:
x = allowable_set[-1]
return list(map(lambda s: float(x == s), allowable_set)) |
def get_char_set(char_dict, max_val):
"""Generate a list of characters from a dictionary."""
char_set = []
i = 0
while i < max_val + 1:
char_set.append([])
i += 1
for letter, thickness in char_dict.items():
char_set[thickness].append(letter)
return char_set |
def b_count(pattern):
"""
Count the number of B's that occur in a site pattern
Input:
pattern --- a site pattern
Output:
num_b --- the number of B's in the site pattern
"""
num_b = 0
for char in pattern:
if char == "B":
num_b += 1
return num_b |
def turning_radius(speed):
"""Minimum turning radius given speed."""
return -6.901E-11 * speed**4 + 2.1815E-07 * speed**3 - 5.4437E-06 * speed**2 + 0.12496671 * speed + 157 |
def flatten_list(nested_list):
"""
Given a list of lists, it flattens it to a single list.
:param nested_list: list of lists
:return: Single list containing flattened list.
"""
return [item for sub_list in nested_list for item in sub_list] |
def rotate_tour(tour):
"""Rotate a given tour to start at the final city."""
i = tour.index(max(tour))
return tour[i:] + tour[:i] |
def clean_code(code):
""" Remove duplicate declarations of std function definitions.
Use this if you build a JS source file from multiple snippets and
want to get rid of the function declarations like ``_truthy`` and
``sum``.
Parameters:
code (str): the complete source code.
... |
def surround_by_tag_name(line: str, tag_name: str) -> str:
"""
:param line:
:param tag_name:
:return:
"""
return f'<{tag_name}>{line}</{tag_name}>' |
def smart_int(s, fallback=0):
"""Convert a string to int, with fallback for invalid strings or types."""
try:
return int(float(s))
except (ValueError, TypeError, OverflowError):
return fallback |
def compute_present_value(j,I,p):
""" Computes Present Value (PV) of an ordinary annuity """
# NOTES:
# Any ONE of the input arguments can be an array, but the others
# must be scalar.
# INPUTS:
# p -> Periodic payment amount
# I -> Interest, as annual rate. If 9%, enter 0.09... |
def question_save_feedback(question_stored):
"""
Sends a immediate feedback, explaining, if the question was saved or not.
:return: Feedback message
"""
if question_stored:
response = "Your question has been saved. " \
"I will get back to you with an expert's answer. " \
... |
def lambda_tokenize(string):
""" Tokenizes a lambda-calculus statement into tokens.
Args:
string(`str`): a lambda-calculus string
Outputs:
`list`: a list of tokens.
"""
space_separated = string.split(" ")
new_tokens = []
# Separate the string by spaces, then separate based... |
def show_types(obj):
"""Recursively show dict types."""
# convert associative array
if isinstance(obj, dict):
obj = {
f"{type(str(k))}:{str(k)}": show_types(v)
for k, v in obj.items()
}
# convert list
elif isinstance(obj, list):
obj = [show_types(x) f... |
def point_to_range(point_location):
"""
Convert a point location to a range location.
:param point_location: A point location model complying object.
:return: A range location model complying object.
"""
if point_location.get("uncertain"):
location = {
"type": "range",
... |
def differences(scansion: str, candidate: str) -> list:
""""Given two strings, return a list of index positions where the contents differ.
>>> differences("abc", "abz")
[2]
"""
before = scansion.replace(" ", "")
after = candidate.replace(" ", "")
diffs = []
for idx, tmp in enumerate(befo... |
def get_dbf_from_config(config: dict) -> str:
"""Find the DBF file specified in a config.
Must return a string, not a Path, in case there's a protocol.
"""
shp_path = config['SHAPEFILE']
dbf_path = shp_path.replace('shp', 'dbf')
return dbf_path |
def rshift_zero_padded(val, n):
"""Zero-padded right shift"""
return (val % 0x100000000) >> n |
def __get_average_defective_rate__(qars: list):
"""
Get the average of defective rate in the benin republic area
"""
total = 0
count = len(qars)
if count == 0:
count = 1
for i, x in enumerate(qars):
total += x.defective_rate
result = total / count
return "{:.2f}".form... |
def is_number(s):
"""
Checks for number
"""
try:
float(s)
return True
except ValueError:
pass
try:
import unicodedata
unicodedata.numeric(s)
return True
except (TypeError, ValueError):
pass
return False |
def escape(s):
"""Escapes a string to make it HTML-safe"""
s = str(s)
s = s.replace('"', """)
s = s.replace(">", ">")
s = s.replace("<", "<")
return s |
def _is_public(ident_name):
"""
Returns `True` if `ident_name` matches the export criteria for an
identifier name.
"""
return not ident_name.startswith("_") |
def get_path_to_energy_density_dir(name: str, data_directory: str) -> str:
"""Get the path to the directory where the star formation data should be stored
Args:
name (str): Name of the galaxy
data_directory (str): dr2 data directory
Returns:
str: Path to energy_density dir
"""
... |
def parse_play_sentences(sentences):
"""
Return sentences from the play tagged with act, scene, and speaker.
"""
act = 0
scene = 0
speaker = ""
parsed_sentences = []
for sentence in sentences:
if "ACT" in sentence:
act += 1
if "SCENE" in sentence:
... |
def is_valid_source(src, fulls, prefixes):
"""Return True if the source is valid.
A source is valid if it is in the list of valid full sources or prefixed by
a prefix in the list of valid prefix sources.
"""
return src in fulls or any(p in src for p in prefixes) |
def fibonacci(n):
"""Return Fibonacci sequence of n.
Args:
n (int): An integer
Returns:
sum of nth term in fibonacci
"""
if n == 0:
return 0
elif n == 1:
return 1
else:
return fibonacci(n - 1) + fibonacci(n - 2) |
def points_from_xywh(box):
"""
Constructs a polygon representation from a rectangle described as a dict with keys x, y, w, h.
"""
x, y, w, h = box['x'], box['y'], box['w'], box['h']
# tesseract uses a different region representation format
return "%i,%i %i,%i %i,%i %i,%i" % (
x, y,
... |
def decode_ay(ay):
"""Convert binary blob from DBus queries to strings."""
if ay is None:
return ''
elif isinstance(ay, str):
return ay
elif isinstance(ay, bytes):
return ay.decode('utf-8')
else:
# dbus.Array([dbus.Byte]) or any similar sequence type:
return b... |
def inverse_of_relation(r):
"""
Function to determine the inverse of a relation
:param r: a relation
:return: inverse of the relation
"""
return [(y, x) for (x, y) in r] |
def list_duplicates(cells):
"""Find duplicates in list for detailed reporting
"""
# reference https://stackoverflow.com/questions/9835762
seen = set()
# save add function to avoid repeated lookups
seen_add = seen.add
# list comprehension below chosen for computational efficiency
# adds a... |
def _abbrev_n_shots(n_shots: int) -> str:
"""Shorter n_shots component of a filename"""
if n_shots % 1000 == 0:
return f'{n_shots // 1000}k'
return str(n_shots) |
def darcy_s(x, s, gradient, kfun=lambda x, s: 1):
""" Flux function for saturated flow
Flow equation as first described by :cite:`Darcy1856` which
is altered to include a state dependency.
Parameters
----------
x : `float`
Positional argument :math:`\\left(length\\right)`.
s : `flo... |
def rk(main, pattern, multi=False):
"""
@param:
main: str, input string
pattern: str, pattern string
multi: bool, multi position searching
@return:
idxs: list, idxs of where pattern string match with main string
"""
n, m = len(main), len(patt... |
def submodular_pick(scores, knobs, n_pick, knob_weight=1.0):
"""Run greedy optimization to pick points with regard to both score and diversity.
DiversityScore = knob_weight * number of unique knobs in the selected set
Obj = sum(scores[i] for i in pick) + DiversityScore
Note that this objective function... |
def shellsort(a):
"""Shellsort
Time complexity: Between O(nlogn) and O(nlog^2n) ?
Space complexity: O(1)
:param a: A list to be sorted
:type a: list
:return: A new sorted list
:rtype: list
"""
b = [*a]
n = len(b)
gap = n // 2
while gap > 0:
for i in range(n):
... |
def format_desktop_command( command, filename):
"""
Formats a command template from the "Exec=" line of a .desktop
file to a string that can be invoked in a shell.
Handled format strings: %U, %u, %F, %f and a fallback that
appends the filename as first parameter of the command.
See http://stan... |
def f_score(r: float, p: float, b: int = 1):
"""
Calculate f-measure from recall and precision.
Args:
r: recall score
p: precision score
b: weight of precision in harmonic mean
Returns:
val: value of f-measure
"""
try:
val = (1 + b ** 2) * (p * r) / (b *... |
def recursive_any_to_dict(anyElement):
"""
Recursive any nested type into a dict (so that it can be JSON'able).
:param anyElement: Just about any 'attrs-ized' instance variable type in Python.
:return: A dict structure
"""
if isinstance(anyElement, dict):
simple_dict = {}
for key... |
def nameLength(name):
"""
Remove the '~' from strings and count the letters.
:param name: String to count
:return: length of name without '~'
"""
return len(name) - name.count('~') |
def data_prepare(raw_data: list, headers_list: tuple) -> list:
""" Returns only the necessary data for a given subject. """
prepared_data = []
for raw_item in raw_data:
prepared_item = {}
for key in headers_list:
prepared_item[key] = raw_item[key]
prepared_data.append(pre... |
def get_content(obj):
""" Works arround (sometimes) non predictible results of pythonzimbra
Sometime, the content of an XML tag is wrapped in {'_content': foo},
sometime it is accessible directly.
"""
if isinstance(obj, dict):
return obj['_content']
else:
return obj |
def determineLeadValidity(playedCards, card, hand):
"""
Given the cards that have been played so far, as well as the player's hand,
determine whether the card they have attempted to lead is valid.
"""
# must lead 2C if have it for first trick
if "01c" in hand and card != "01c":
return [F... |
def get_schema(schema_in):
"""returns schema dictionary from json"""
if type(schema_in) is list:
return schema_in[0]
else:
return schema_in |
def user_dict(user, base64_file=None):
"""Convert the user object to a result dict"""
if user:
return {
'username': user.id,
'accesskey': user.access,
'secretkey': user.secret,
'file': base64_file}
else:
return {} |
def integer_sqrt(n: int) -> int:
"""
Returns the integer square root of n >= 0 - the integer m satisfying
m**2 <= n < (m + 1)**2.
Parameters:
n: int (n >= 0)
Examples:
>>> integer_sqrt(10)
3
>>> integer_sqrt(121)
11
"""
if n < 0:
rais... |
def delete_key_from_dict(dictionary, key):
"""Loop recursively over nested dictionaries."""
for v in dictionary.values():
if key in v:
del v[key]
if isinstance(v, dict):
delete_key_from_dict(v, key)
return dictionary |
def get_timestamp(imu_dict):
"""The timestamp of a message does not necessarily equal
the timestamp in the message's header. The header timestamp
is more accurate and the timestamp of the message just corresponds
to whenever the bag received the message and saved it.
Args:
imu_dict (dict): ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.