content stringlengths 42 6.51k |
|---|
def readable_duration(seconds: float, *, pad: str = "") -> str:
"""Produce human-readable duration."""
if seconds < 10:
return f"{seconds:.2g}s"
seconds = int(round(seconds))
parts = []
time_minute = 60
time_hour = 3600
time_day = 86400
time_week = 604800
weeks, seconds = ... |
def get_char_to_filter_by(shift_val: int, is_o2: bool = False) -> str:
"""Find out what character we should filter the lines with based on shift_val"""
if is_o2:
return "1" if shift_val >= 0 else "0"
return "0" if shift_val >= 0 else "1" |
def max_subarray(nums):
"""
Find the contiguous subarray within an array (containing at least one number) which has the largest sum.
For example, given the array [-2,1,-3,4,-1,2,1,-5,4],
the contiguous subarray [4,-1,2,1] has the largest sum = 6.
Args:
nums: list[int]
Returns:
... |
def RPL_CHANNELMODEIS(sender, receipient, message):
""" Reply Code 324 """
return "<" + sender + ">: " + message |
def clip_gradient(dx):
""" clip_gradient """
ret = dx
if ret > 1.0:
ret = 1.0
if ret < 0.2:
ret = 0.2
return ret |
def pad_data(d):
"""Pad data rows to the length of the longest row.
Args: d - list of lists
"""
max_len = set((len(i) for i in d))
if len(max_len) == 1:
return d
else:
max_len = max(max_len)
return [i + [""] * (max_len - len(i)) for i in d] |
def get_format_from_name(name: str) -> str:
"""
Function to infer the input format. Used when the input format is auto.
"""
try:
int(name)
src_format = "numeric"
except ValueError:
if len(name) == 2:
src_format = "alpha-2"
elif len(name) == 3:
... |
def dict_clean(d):
"""Remove None from dictionary"""
if not isinstance(d, dict):
return d
return dict((k, dict_clean(v)) for k, v in d.items() if v is not None) |
def sanitize_indexes(indexes: list, user_input: str) -> list:
"""
Given a list of valid indexes and a comma-separated
string of (supposedly) user-entered indexes,
it returns the list of indexes that are valid.
:param list indexes: list of permitted indexes
:param str user_input: comma-separated... |
def _wrapper(funct, *arg):
"""A function that returns the assumed function and arguments, this is used
for the print function so that a list of variables can be simply called.
"""
return funct(*arg) |
def vec2mat_index(N, I):
"""
Convert a vector index to a matrix index pair that is compatible with the
vector to matrix rearrangement done by the vec2mat function.
From Qutip.
"""
j = int(I / N)
i = I - N * j
return i, j |
def compute_top_k(models, k, tsvfile):
"""Compute top k models and record the scores of all of them"""
topk = []
with open(tsvfile, 'w') as tsv:
tsv.write("path\tscore\n")
for i, x in enumerate(sorted(models, key=lambda x:x['score'])):
path, score = x['path'], x['score']
... |
def serialize_value(value):
"""
Serialize a value in an DeepImageJ XML compatible manner.
:param value:
:return:
"""
if isinstance(value, bool):
return str(value).lower()
else:
return str(value) |
def rename_candidate_hugo(candidate, renamings):
"""Renames a candidate name according to a renaming map."""
name_expr = candidate.split(".")
base_name = name_expr[0]
if base_name in renamings:
base_name = renamings[base_name]
name_expr[0] = base_name
result = ".".join(name_expr)
return result |
def cindex_rlscore_reference(Y, P):
"""
Function taken from the rlscore package: https://github.com/aatapa/RLScore as reference.
"""
correct = Y
predictions = P
assert len(correct) == len(predictions)
disagreement = 0.
decisions = 0.
for i in range(len(correct)):
for j in ran... |
def greedy_partitioning(elems_dict, k, return_only_labels=False):
"""
Implementation of greed partitioning algorithm as explained `here <https://stackoverflow.com/a/6670011>`_ for a dict
`elems_dict` containing elements with label -> weight mapping. A weight can be a number in an arbitrary range. Since
... |
def get_user_name(user, full_name=True):
"""Return the user's name as a string.
:param user: `models.User` object. The user to get the name of.
:param full_name: (optional) Whether to return full user name, or just first name.
:return: The user's name.
""" # noqa
try:
if full_name:
... |
def sigmoidDerivative(x):
""" This function computes the sigmoid derivative of x for NeuralNetwork
(Note: Not Real Derivative)
"""
return x*(1.0-x) |
def construct_bbox(all_points):
"""
Construct the bounding box based on all points from the
road and buildings that were discretised.
"""
maximum = list(map(max, zip(*all_points)))
minimum = list(map(min, zip(*all_points)))
bbox = [(minimum[0], minimum[1]),
(minimum[0], maximum... |
def _get_intersection(cp1, cp2, s, e):
"""get intersection"""
dc = (cp1[0] - cp2[0], cp1[1] - cp2[1])
dp = (s[0] - e[0], s[1] - e[1])
n1 = cp1[0] * cp2[1] - cp1[1] * cp2[0]
n2 = s[0] * e[1] - s[1] * e[0]
n3 = 1.0 / (dc[0] * dp[1] - dc[1] * dp[0])
return ((n1*dp[0] - n2*dc[0]) * n3, (n1*dp[1]... |
def get_gpu_type(project, zone, gpu_model):
"""
Check the available gpu models for each zone
https://cloud.google.com/compute/docs/gpus/
"""
assert gpu_model in [
'nvidia-tesla-p4',
'nvidia-tesla-k80',
'nvidia-tesla-v100',
'nvidia-tesla-p100'
]
return (
... |
def get_display_name(username):
"""Return the username to display in the navbar. Shortens long usernames."""
if len(username) > 40:
return '%s...%s' % (username[:20].strip(), username[-15:].strip())
return username |
def intersection(a, b):
"""
Returns the intersection of sets a and b.
In plain english:
Returns all the items that are in both a and b.
"""
return a.intersection(b) |
def bin_to_nucleotide(bin_str):
"""
Convert binary bits to nucleotide
:param bin_str: pair of binary bits.
:return: nulceotide A, G, C, T
"""
if bin_str == '00':
return 'A'
elif bin_str == '01':
return 'C'
elif bin_str == '10':
return 'G'
elif bin_str == '11':... |
def ror (endv, iv):
""" This capital budgeting function computes the rate of
return on an investment for one period only.
iv = initial investment value
endv = total value at the end of the period
Example: ror(100000, 129,500)
"""
return (endv - iv)/iv |
def vpc_title(prefix):
"""
VPC title
"""
return "%sVPC" % prefix |
def drill_update(element, key=None, current_value=None, refactored_value=None):
"""Drill and refactor an element given its key, current_value and
refactored_value.
:element: structured data, either a list or dict
:key: key to be updated
:current_value: dictionary value of the key you're looking for... |
def _gen_intervals_dict(fun_dict):
"""
If there are consequent keys that map to the same value, we want to unite
them to intervals in order to have less conditional branches in code.
For example if fun_dict is something like:
{0:f1, 1:f1, 2:f2, 3:f2 , ...}
we will generate dict
{(0,1):f1, (2... |
def convert(number):
"""Convert a number to a series of rain tones.
Parameters
----------
arg1 : int
A number to convert to rain tones
Returns
------
string
A string containing rain tones or the number if it's not converted.
>>> convert(1)
"1"
>>> convert(3)
... |
def abbreviation(a, b):
"""
Your code goes here.
"""
# Cache for dynamic programming
cache = []
for _ in range(len(a) + 1):
cache.append([])
for _ in range(len(b) + 1):
cache[-1].append(None)
# We loop through a and b
# We are interested in ix and jx
#... |
def get_command_name(cmd, default=''):
"""Extracts command name."""
# Check if command object exists.
# Return the expected name property or replace with default.
if cmd:
return cmd.name
return default |
def precip_advice(precip_in):
"""Gives precipitation advice to the end user"""
precipitation_level = {0: "There is low to no precipitation.",
1: "There is a moderate amount of precipitation. Take necessary precautions.",
2: "There is a high amount of precipi... |
def get_table_name(dataset_name: str, scan_type: str,
base_table_name: str) -> str:
"""Construct a bigquery table name.
Args:
dataset_name: dataset name like 'base' or 'laplante'
scan_type: data type, one of 'echo', 'discard', 'http', 'https'
base_table_name: table name like 'scan'
... |
def bytearray_to_int(value: bytearray) -> int:
"""
Convert a 'bytearray' object to a long integer.
Args:
value: the 'bytearray' object to convert.
Returns:
Long integer value from 'bytearray' object.
"""
return int.from_bytes(value, byteorder='big') |
def secondsToUptime(seconds):
""" convert seconds to a pretty uptime output: 2 days, 19:45 """
days = int(seconds / (60 * 60 * 24))
hours = int((seconds - (days * 60 * 60 * 24)) / (60 * 60))
minutes = int((seconds - (days * 60 * 60 * 24) - (hours * 60 * 60)) / 60)
msg = ''
if days == 1:
... |
def transform_frame(val: str):
"""
Transforms a rating into numerical representation
"""
if val == 'very poor':
return 1
if val == 'poor':
return 2
if val == 'fair':
return 3
if val == 'good':
return 4
if val == 'very good':
return 5
else:
... |
def gem_cov(frags, weight_flag):
"""
GEM coverage.
Args:
frags (list of list): [chrom,start,end] for each fragment in a GEM
weight_flag (binary): True if weighted by fragment number; False otherwise
Returns:
gem_all (list of bed entries): bed entries in format [chrom,start,end]
... |
def array_strip_units(data):
"""strip the units of a quantity"""
try:
return data.magnitude
except AttributeError:
return data |
def paginated_body(results):
"""Just return a simple paginated result body based on results
this does not take next/previous into account - any tests using that should
specifically set values in the expected body
Args:
results (list): Expected results
Returns:
dict: previous/next ... |
def setBinningSingleImage(dataset_output, binning_array):
"""
It performs a binning in the given output steering data.
:param dataset_output: the (single) output to encode.
:param binning_array: the encoder.
:return: the encoded labels.
"""
label = 0
for j in rang... |
def _write_export(export, file_obj=None):
"""
Write a string to a file.
If file_obj isn't specified, return the string
Parameters
---------
export: a string of the export data
file_obj: a file-like object or a filename
"""
if file_obj is None:
return export
elif hasattr... |
def str_to_list(string, sep=',', options=None):
"""Convert string to list."""
res = string.split(sep)
options = options or {}
if 'len' in options and options['len'] != len(res):
raise ValueError(
'Length %s is must, got %s' % (options['len'], len(res)))
return res |
def get_power(x, y, serial_number):
"""
Simplify the power equation down to a single expression.
"""
return (((((x + 10)*y + serial_number) * (x+10)) // 100) % 10) - 5 |
def pass_inner(_, nodes):
"""
Pass inner value up, e.g. for stripping parentheses as in
`( <some expression> )`.
"""
n = nodes[1:-1]
try:
n, = n
except ValueError:
pass
return n |
def _fFlagsToSet(f_flags):
"""Transform an int f_flags parameter into a set of mount options.
Returns a set.
"""
# see /usr/include/sys/mount.h for the bitmask constants.
flags = set()
if f_flags & 0x1:
flags.add('read-only')
if f_flags & 0x1000:
flags.add('local')
if f_f... |
def create_filenames(no_of_files, prefix, suffix1, suffix2, label_name):
"""creates the names of the atlases enabling to return a list of filenames which may be used to coregister data"""
fID = []
for idx in range(1, no_of_files + 1, 1):
fID.append(tuple(('{}{}{}'.format(prefix, int(idx), suffix1),... |
def remap(value, input_min, input_max, output_min, output_max):
"""
Remap a value based on input minimum and maximum, the result is converted
to an integer since markers can only live as a whole frame.
:param float value: Value to remap
:param float input_min: Original minimum
:param float ... |
def distribute(available, weights):
"""distrubute some available fairly
across a list of numbers
:param available: the total
:type available: int
:param weights: numbers
:type weights: List[int]
"""
total = sum(weights)
if available < total:
while available != total:
... |
def rotate_slice(given_array, n):
"""rotate using 4 slices."""
# print(to_string(given_array))
for loop in range(n//2):
top = [x[loop:n-loop] for x in given_array[loop:loop+1]][0]
bottom = [x[loop:n-loop] for x in given_array[n-loop-1:n-loop]][0]
left = [x[loop] for x in reve... |
def format_cpnet_knowledge(input_json: dict) -> str:
"""
@param input_json: dictionary representing one datapoint in the openpi dataset
@return: knowledge from conceptnet formatted as a string
"""
knowledge = input_json["knowledge"]
knowledge = knowledge if len(knowledge) <= 10 else knowledge[:... |
def t_str(s, precision='2.1', ms=False):
"""Turn time delta in seconds into short string across time scales."""
fmt_str = '{: >' + precision + 'f}'
if s < 1 and ms:
return '{: >3.1f}'.format(s*1000) + ' ms'
if s < 60:
return fmt_str.format(s) + ' s'
m = s / 60
if m < 60:
... |
def _is_non_negative_int(item):
"""Verify that the value is a non-negative integer."""
if not isinstance(item, int):
return False
return item >= 0 |
def get_program_number(txt_row):
""" Checks if the current line of text contains a program
definition.
Args:
txt_row (string): text line to check.
Returns:
An integer number. If program number cannot be found, or is
invalid in some way, a large negative number is returned.
"""
... |
def import_string(modstr):
"""Resolve a package.module.variable string"""
module_name, module_var = modstr.rsplit('.', 1)
module = __import__(module_name)
for elt in module_name.split('.')[1:]:
module = getattr(module, elt)
return getattr(module, module_var) |
def valueFunction1(v,alpha,_lambda,beta):
"""
The value function used in prospect theory
:param v: Value
:param alpha:
:param _lambda:
:return:
"""
if v>=0:
return v**alpha
else:
return -_lambda*(-v)**beta |
def add_others_to_robots(robots, others_list):
"""Add others to robots set."""
for other in others_list:
robots.add(other)
return robots |
def line_strip(line):
"""
Remove comments and replace commas from input text
for a free formatted modflow input file
Parameters
----------
line : str
a line of text from a modflow input file
Returns
-------
str : line with comments removed and commas replaced
... |
def andop(funeval, *aa):
""" Lazy version of `and' """
for a in aa:
if not funeval(a): return False
return True |
def filter_pubs(pubs):
"""Remove publications without links, and merge
datasets and publications data together.
Also deduplicates publications based on pids.
Args:
pubs (dict): Publication data from OpenAIRE.
Returns:
_pubs (list): Flattened list of input data.
"""
_pub... |
def three_sum(array):
"""
:param array: List[int]
:return: Set[ Tuple[int, int, int] ]
"""
res = set()
array.sort()
for i in range(len(array) - 2):
if i > 0 and array[i] == array[i - 1]:
continue
l, r = i + 1, len(array) - 1
while l < r:
s = ar... |
def total_minutes_from(h, m):
"""Total Minutes from hour and minute."""
return h * 60 + m |
def dict_deep_overlay(defaults, params):
"""If defaults and params are both dictionaries, perform deep overlay (use params value for
keys defined in params, otherwise use defaults value)"""
if isinstance(defaults, dict) and isinstance(params, dict):
for key in params:
defaults[key] =... |
def recover_bitwise_flag_settings(flag, constants_dict) :
"""
@param flag : an integer value to be matched with bitwise OR options set
@param constants_dict : a dictionary containing each options' integer value
@rtype : a string summing up settings
"""
recover = ''
options = []
for option_value in consta... |
def calculate_center(S):
"""
Calculate the center of a list
of points, S
"""
cx = 0.
cy = 0.
n = len(S)
for p in S:
cx += p[0] / n
cy += p[1] / n
return (cx, cy) |
def get_kaalas(start_span, end_span, part_start, num_parts):
"""Compute kaalas in a given span with specified fractions
Args:
:param start_span float (jd)
:param end_span float (jd)
int part_start
int num_parts
Returns:
tuple (start_time_jd, end_time_jd)
Examples:
... |
def get_common_files(mediafile_list, srtfile_list):
"""
returns a list of filenames that are common in mediafile_list and
strfile_list. \n
While getting common filenames it ignores the extension.\n
Also the returned list will have the same file extension the mediafile_list
files have
"""
... |
def create_message(events):
"""
Build the message. The first event's timestamp is returned as the
overall event timestamp.
"""
messages = [event.get('description') for event in events]
return (events[0].get('timestamp'), '\n'.join(messages)) |
def histogram(vector):
"""Compute the histogram of a vector.
:param vector: a list of values
:type vector: list
:return: the histogram of values as a dictionnary
:rtype: dict
"""
return {k: vector.count(k) for k in set(vector)} |
def calculate_delta(num_attributes, sensitivity, epsilon):
"""Computing delta, which is a factor when applying differential privacy.
More info is in PrivBayes Section 4.2 "A First-Cut Solution".
Parameters
----------
num_attributes : int
Number of attributes in dataset.
sensitivity : flo... |
def format(number):
"""Reformat the number to the standard presentation format."""
if len(number) == 9:
number = number[:3] + '-' + number[3:5] + '-' + number[5:]
return number |
def _sanitize_name(node, prefix):
"""Sanitize name."""
return node.split('(')[0].strip().replace(prefix, '') |
def idecibel(x):
"""Calculates the inverse of input decibel values
:math:`z=10^{x \\over 10}`
Parameters
----------
x : a number or an array
Examples
--------
>>> from wradlib.trafo import idecibel
>>> print(idecibel(10.))
10.0
"""
return 10. ** (x / 10.) |
def ensure_required(rlist, required):
""" Check which keys aren't present. """
not_present = []
for k in required:
if k not in rlist:
not_present.append(k)
if len(not_present) != 0:
print(" Skipping: following required fields not present:")
for k in not_present:
... |
def resizeMasks(baseMasks, xRatio: float, yRatio: float):
"""
Resize mask's base points to fit the targeted size
:param baseMasks array of [x, y] coordinates which are all the polygon points representing the mask
:param xRatio width ratio that will be applied to coordinates
:param yRatio height rati... |
def ensure_ext(filepath, ext, case_sensitive=False):
"""
Return the path with the extension added if it is not already set.
:arg ext: The extension to check for, can be a compound extension. Should
start with a dot, such as '.blend' or '.tar.gz'.
:type ext: string
:arg case_sensitive:... |
def rm_last(*args):
"""
Remove the last index from each list
"""
if len(args) == 1:
return args[:-1]
else:
return [a[:-1] for a in args]
return |
def get_total_kernel_times(plugin):
""" This does extra processing on the plugin's results in order to get
"total kernel time", which doesn't correspond to a real JSON key. Instead,
it consists of the sum of actual kernel times, from launch to
after the synchronization, for each iteration of the plugin.... |
def notebook_header(text):
"""
Insert section header into a jinja file, formatted as notebook cell.
Leave 2 blank lines before the header.
"""
return f"""# # {text}
""" |
def clean_params(params, drop_nones=True, recursive=True):
"""Clean up a dict of API parameters to be sent to the Coinbase API."""
cleaned = {}
for key, value in params.items():
if drop_nones and value is None:
continue
if recursive and isinstance(value, dict):
value ... |
def greedyWrap(inString, width=80):
"""
Given a string and a column width, return a list of lines.
Caveat: I'm use a stupid greedy word-wrapping
algorythm. I won't put two spaces at the end
of a sentence. I don't do full justification.
And no, I've never even *heard* of hypenation.
"""
... |
def _normalize_response_tuple(tuple_):
"""
Helper function to normalize view return values .
It always returns (dict, status, headers). Missing values will be None.
For example in such cases when tuple_ is
(dict, status), (dict, headers), (dict, status, headers),
(dict, headers, status)
... |
def build_person(first_name, last_name, age=None):
"""Return a dictionary of information about a person."""
person = {'first': first_name.title(), 'last': last_name.title()}
if age:
person['age'] = age
return person |
def read_translated_file(filename, data):
"""Read a file inserting data.
Arguments:
filename (str): file to read
data (dict): dictionary with data to insert into file
Returns:
list of lines.
"""
if filename:
with open(filename) as f:
text = f.read().repl... |
def return_value(instring):
"""Function to convert a string to corresponding number format"""
from ast import literal_eval
try:
return literal_eval(instring)
except:
return instring |
def get_normalized_data(x, min_val, max_val):
"""
Normalizing the training and test dataset
"""
x_norm = (x - min_val) / (max_val - min_val)
return x_norm |
def is_fill_compute_el(obj):
"""Object contains executable methods 'fill' and 'compute'."""
return hasattr(obj, 'fill') and hasattr(obj, 'compute') \
and callable(obj.fill) and callable(obj.compute) |
def fibonacci_list(n):
"""
Return a list of n Fibonacci element
:param n: number of list element
:return: a list
"""
my_fib = [0, 1]
if n == 1:
return [0]
elif n == 2:
return my_fib
elif n <= 0:
pass
else:
for i in range(0, n - 2):
max... |
def translate_attribute(metasra_attribute: dict) -> dict:
"""Translate a MetaSRA attribute that looks like this:
{
"property_id": "EFO:0000246",
"unit_id": "missing",
"value": 31.0
}
into our representation documented here:
https://github.com/AlexsLemonade... |
def tamper(payload, **kwargs):
"""
Appends 'sp_password' to the end of the payload for automatic obfuscation from DBMS logs
Requirement:
* MSSQL
Notes:
* Appending sp_password to the end of the query will hide it from T-SQL logs as a security measure
* Reference: http://websec.... |
def reverse_words_in_string(text):
"""Reverse the words in a string."""
reversed_words = reversed([word for word in text.split('.')])
return '.'.join(reversed_words) |
def lNamesOfUndec(listOfStudents):
"""
return a list of the last names of students that have "UNDEC" as their major
>>> lNamesOfUndec([Student("MARY","KAY","MATH"), Student("FRED","CRUZ","HISTORY"), Student("CHRIS","GAUCHO","UNDEC")])
['GAUCHO']
>>>
"""
answerList = []
for student in ... |
def get_hash(obj: "(object | list | tuple)"):
"""Returns a hash of the given object or returns the hash of each object in a given collection.
Example:
>>> thelist = ["slowdown's",
... 'acrylic',
... 'tainting',
... 'Pruitt',
... 'pharmacopeias',
... 'bordell... |
def suma (a, b):
""" Suma de dos valores a y b
param int a cualquier entero
param int b cualquier entero
returns la sumatoria de a y b
"""
total = a + b
return total |
def remove_item(inventory, item):
"""
:param inventory: dict - inventory dictionary.
:param item: str - item to remove from the inventory.
:return: dict - updated inventory dictionary with item removed.
"""
inventory.pop(item, None)
return inventory |
def binary_search(input_array, value):
"""Your code goes here."""
N = len(input_array)
min = 0
max = N-1
mid = (N-1)/2
while mid >= 0 and mid < N-1:
if input_array[mid] == value:
return mid
elif input_array[mid] < value:
min = mid+1
mid = (m... |
def get_char_vocab(dataset):
"""
Args:
dataset: a iterator yielding tuples (sentence, tags)
Returns:
a set of all the characters in the dataset
"""
vocab_char = set()
for words, _ in dataset:
for word in words:
vocab_char.update(word)
return vocab_char |
def get_gamma_rate(bits):
"""Gamma rate calculations."""
return ''.join(
'1' if bits[position]['1'] > bits[position]['0'] else '0'
for position, _ in enumerate(bits)
) |
def transform_keyword(keywords):
"""
Transform each keyword into a query string compatible string
"""
keywordlist = []
for keyword in keywords:
keywordlist.append(keyword.lower().replace(" ", "+"))
return keywordlist |
def msg_text(message):
"""Remove postage stamp cutouts from an alert message.
"""
message_text = {k: message[k] for k in message
if k not in ['cutoutDifference', 'cutoutTemplate', 'cutoutScience']}
return message_text |
def human_size(nbytes):
"""Just a function to change sizes from MB to more readable for return values."""
suffixes = ['MB', 'GB', 'TB', 'PB']
i = 0
while nbytes >= 1024 and i < len(suffixes)-1:
nbytes /= 1024.
i += 1
f = ('%.2f' % nbytes).rstrip('0').rstrip('.')
return '%s %s' %... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.