content stringlengths 42 6.51k |
|---|
def mu2hms(musecond):
"""convert microsecond to hours:min:second (string)."""
m1, s1 = divmod(int(musecond / 1e6), 60)
h1, m1 = divmod(m1, 60)
return "{:d}:{:02d}:{:02d}".format(h1, m1, s1) |
def get_people_ids_based_on_role(assignee_role,
default_role,
template_settings,
acl_dict):
"""Get people_ids base on role and template settings."""
if not template_settings.get(assignee_role):
return []
templat... |
def parse_responsive_length(responsive_length):
"""
Takes a string containing a length definition in pixels or percent and parses it to obtain
a computational length. It returns a tuple where the first element is the length in pixels and
the second element is its length in percent divided by 100.
No... |
def int_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:
An int that results ... |
def _update_dict_defaults(values, defaults):
"""Helper to handle dict updates"""
out = {k: v for k, v in defaults.items()}
if isinstance(values, dict):
out.update(values)
return out |
def _str_len_check(text, min_len, max_len):
"""
Validate string type, max and min length.
"""
if not isinstance(text, str):
raise ValueError("expected string type")
if not (min_len <= len(text) <= max_len):
raise ValueError(f"length should be between {min_len} and {max_len} character... |
def get_const_diff_ints(ints, length):
"""f(n) = an + b"""
first = ints[0]
diff = ints[1] - ints[0]
return [first + diff * n for n in range(length)] |
def summarize_data(state2state_id, state_id_2_policy_counts, state_2_case_counts):
"""Returns a list of dictionaries that contain four key-value pairs: US state, US state id, the total number of state-level policies, and the total number of COVID-19 cases.
Keys are state, state_id, total_policies, and total_ca... |
def keyparams(**kwargs):
"""callDebug helper, generating kwargs signature"""
return f"{', ' if len(kwargs) != 0 else ''}{', '.join([f'{k}={v}' for k,v in kwargs.items()])}" |
def check_form_access(sender, account, form, **kwargs):
"""Check if form must be used for account."""
if form["id"] != "resources":
return True
if account.role not in ["Resellers", "DomainAdmins"]:
return False
return True |
def is_tool(name: str) -> bool:
"""Check whether `name` is on PATH and marked as executable."""
from shutil import which
return which(name) is not None |
def is_transformer(pipe):
"""
Determine if a pipe is a transformer.
"""
if hasattr(pipe, 'transform'):
return True
else:
return False |
def make_divisible(v, divisor, min_val=None):
"""
This function is taken from the original tf repo.
It ensures that all layers have a channel number that is divisible by 8
It can be seen here:
https://github.com/tensorflow/models/blob/master/research/slim/nets/mobilenet/mobilenet.py
"""
if m... |
def get_object_properties(object, properties):
"""Returns first non empty property of given object."""
properties = properties.split(',')
for property in properties:
attribute = getattr(object, property, '')
if attribute:
return attribute
return '' |
def _shape_setup(shape):
"""Array shape preprocessing, return (shape,) if shape is an integer."""
return (shape,) if isinstance(shape, int) else shape |
def part1(data):
"""
>>> part1(('A', 6, {
... ('A', 0): (1, 1, 'B'),
... ('A', 1): (0, -1, 'B'),
... ('B', 0): (1, -1, 'A'),
... ('B', 1): (1, 1, 'A')
... }))
3
>>> part1(read_input())
3145
"""
state, max_steps, rules = data
tape = {}
cursor = 0
... |
def _test_gif(h):
"""GIF ('87 and '89 variants)"""
if h[:6] in (b'GIF87a', b'GIF89a'):
return 'gif' |
def isprime(n):
"""memorized prime evaluation, 2x more faster on that algorithm"""
for p in range(2, int(abs(n) ** 0.5) + 1):
if n % p == 0:
return False
return True |
def summe_vektoren (vec1, vec2):
"""addiert zwei Vektoren
Vektor (Eingabe + Ausgabe): Liste der Form [x1, x2, x3]"""
r1 = vec1[0] + vec2[0]
r2 = vec1[1] + vec2[1]
r3 = vec1[2] + vec2[2]
result = [r1, r2, r3]
return result |
def caffeineBuzz(n):
"""
caffeineBuzz() takes a non-zero integer as it's sole argument.
If the integer is divisible by 3, return the string "Java".
If the integer is divisible by 3 and 4, return the string "Coffee"
If the integer is one of the above and is even, add "Script" to the end of
t... |
def _env_sh(_dict, path_append=True):
"""
Parameters
----------
_dict : dict
Returns
-------
str
"""
text = ""
for k, v in _dict.items():
if path_append and k == "PATH":
text += k + "=\"" + "$PATH:" + v + "\"\n"
else:
text += k + "=\"" + v... |
def get_converter_type_uuid(*args, **kwargs):
"""
Handle converter type "uuid"
:param args:
:param kwargs:
:return: return schema dict
"""
schema = {
'type': 'string',
'format': 'uuid',
}
return schema |
def checksum(command):
"""Function to calculate checksum as per Satel manual."""
crc = 0x147A
for b in command:
# rotate (crc 1 bit left)
crc = ((crc << 1) & 0xFFFF) | (crc & 0x8000) >> 15
crc = crc ^ 0xFFFF
crc = (crc + (crc >> 8) + b) & 0xFFFF
return crc |
def _from_bool(s: str) -> bool:
"""Convert a string into a boolean."""
if s.lower() == 'true':
return True
if s.lower() == 'false':
return False
raise ValueError('String cannot be converted to bool') |
def in_list(input_list):
"""
"""
return ",".join(str(x) for x in input_list) |
def trips_to_response(location, trips):
"""
Formulates a response to be read by Google Assistant
location The location where the trips depart from
trips The trips departing from the location of interest
"""
# Sort the trip on departure order, first ones to leave first
trips = sorte... |
def constructor_class_name_is_false_positive(constructor: str, line: str) -> bool:
"""Decides whether given class name constructor is false positive.
Class name constructor must be in the format `new constructor` (for example `new KeyPair`)
"""
return f"new {constructor}" not in line |
def prob4(dig=3):
"""
A palindromic number reads the same both ways. The largest palindrome made
from the product of two 2-digit numbers is 9009 = 91 * 99.
Find the largest palindrome made from the product of two 3-digit numbers.
"""
limit = 10 ** dig - 1
a = []
for i in range(limit, ... |
def func_x_p(x, *, p="p"):
"""func.
Parameters
----------
x: float
p: str, optional
Returns
-------
x: float
p: str
"""
return x, None, None, None, None, p, None, None |
def parse_line_number(line_str):
"""
In a line of the format "<line_num>: <text>"or "<line_num> <text>"
this grabs line_num.
>>> parse_line_number('5: def parse_line_number(line_str):')
'5'
>>> parse_line_number('43 line = view.line(s)')
'43'
>>> parse_line_number('13... |
def _MachineTypeMemoryToCell(machine_type):
"""Returns the memory of the given machine type in GB."""
memory = machine_type.get('memoryMb')
if memory:
return '{0:5.2f}'.format(memory / 2.0 ** 10)
else:
return '' |
def should_export_checkpoint(strategy):
"""Returns whether the checkpoint should be exported given current strategy"""
return (not strategy) or strategy.extended.should_checkpoint |
def duplicate_data(data, nbr):
"""
Duplicate a single list (data) into identical sublists a given number of times (nbr)
"""
out = []
for i in range (nbr):
out.append(data)
return out |
def uni(value):
"""
Create unicode from raw string with unicode escapes
:Parameters:
`value` : ``str``
String, which encodes to ascii and decodes as unicode_escape
:Return: The decoded string
:Rtype: ``unicode``
"""
return value.encode('ascii').decode('unicode_escape') |
def pack_stringlist(stringlist):
"""formats a stringlist to pass on command-line"""
if stringlist is None or stringlist == '':
return None
if isinstance(stringlist,list):
stringlist = '__delim__'.join(stringlist)
return "'" + stringlist.replace("'","__squote__") + "'" |
def split_type_entity_id(eid, default_type_id=None):
"""
Returns (type_id,entyity_id) pair for supplied string "type_id/entity_id".
The supplied `eid` may be a bare "entity_id" then the supplied default
type_id is used.
>>> split_type_entity_id("type_id/entity_id") == ('type_id', 'entity_id')
... |
def comac(Psi_1, Psi_2, dof):
"""Co-modal assurance criterion
"""
comac = 1
return comac |
def go_right(x: int, y: int) -> tuple:
"""
Go 1 unit in positive x-direction
:param x: x-coordinate of the node
:param y: y-coordinate of the node
:return: new coordinates of the node after moving a unit in the positive x-direction
"""
return x + 1, y |
def select_csv_columns(line: str, ncols: int = 8) -> str:
"""Select first ncols in a line from a csv.
Parameters
----------
ncols: int
Number of column to select.
Returns
-------
selected_cols: str
Selected ncols of csv.
"""
return ",".join(line.split(",")[:ncols]) |
def clues_login(text):
""" Check for any "failed login" clues in the response code """
text = text.lower()
for clue in ('username', 'password', 'invalid', 'authen', 'access denied'):
if clue in text:
return True
return False |
def compute_frequency2_from_frequency1(frequency1):
"""Compute the second frequency from the first one.
Parameters
----------
frequency1: int, float
Returns
-------
frequency2: int, float
"""
prefactor = 1.2
return prefactor * frequency1 |
def max(a,b):
"""Return the maximum of a and b."""
if a >= b:
r = a
else:
r = b
return r |
def number_to_lower_endian(n, base):
"""Helper function: convert a number to a list of digits in the given base."""
if n < base:
return [n]
return [n % base] + number_to_lower_endian(n // base, base) |
def get_marker_size(val, verbose=False, getscale=False):
"""
Get the size of the marker based on val
:param val: the value to test
:param verbose: more output
:param getscale: return the marker sizes regardless of val
:return: the size of the marker in pixels
"""
# these are the sizes o... |
def col_names_conn_matrix(n: int,
preprocessing_type: str = 'conn'):
"""
creates the column names for the flattened connectivity matrix
Args:
n: number of columns in connectivity matrix
preprocessing_type: conn for connectivity matrix,
"aggregation" fo... |
def _chunk_iterable(_iterable, chunk_size):
"""Split an iterable into chunk_sized parts"""
chunks = [_iterable[index:index + chunk_size] for index in range(0, len(_iterable), chunk_size)]
return chunks |
def task3(s1, s2):
"""
Functions which accepts two numbers as string (separated by comma) and generates a string with the result of
their addition.
Input: n,m -> strings
Output: string
"""
liczba_1 = int(s1)
liczba_2 = int(s2)
wynik = liczba_1 + liczba_2
wynik_str = str(wynik)
... |
def strip_string_literals(code, prefix='__Pyx_L'):
"""
Normalizes every string literal to be of the form '__Pyx_Lxxx',
returning the normalized code and a mapping of labels to
string literals.
"""
new_code = []
literals = {}
counter = 0
start = q = 0
in_quote = False
raw = Fa... |
def validation_metrics_v2(ground_truth, bowtie2_prediction):
"""Calculates the recall and specificity
Find list instersection!!
parameters
----------
ground_truth
dict, contains the ground truth as obtained from the sim reads
bowtie2_prediction
dict, contains the predicted read m... |
def _ValidateComponentClassifierConfig(component_classifier_config):
"""Checks that a component_classifier_config dict is properly formatted.
Args:
commponent_classifier_config (dict): A dictionary that provides component to
its function and path patterns, and some other settings.
For example:
... |
def union(regions):
"""
Returns union of all regions
:param regions: list of region as an array [xmin, ymin, xmax, ymax]
:type regions: list of list of four float
:returns: xmin, ymin, xmax, ymax
:rtype: list of 4 float
"""
xmin = min([r[0] for r in regions])
xmax = max([r[2] for r... |
def is_not_abs_blank(str):
"""
To check out whether str is not NONE nor empty nor blank.
"""
if str and str.strip():
return True
return False |
def format_data(x_data=None,y_data=None):
"""
=============================================================================
Function converts a list of separate x and y coordinates to a format suitable
for plotting in ReportLab
Arguments:
x_data - a list of x coordinates (or any object that can be indexe... |
def _sort_list_digital_PCR(elem):
"""Get the first column of the list as int. for sorting.
Args:
elem: The list
Returns:
The a int value of the first list element.
"""
arr = elem.split("\t")
return int(arr[0]), arr[4] |
def ppdistance(a,b):
"""Returns the squared distance between the two 2D points.
a - [float,float], b - [float,float]
return - (float)
"""
return (b[0]-a[0])**2+(b[1]-a[1])**2 |
def dc_weighted_average_from_dc_values(
dc_electrical_value: float,
dc_thermal_value: float,
electrical_demand: float,
thermal_demand: float,
) -> float:
"""
Determines weighted-average demand covered over both electrical and thermal outputs.
:param dc_electrical_value:
The value fo... |
def convert_to_int(s):
"""
Convert string to integer
:param s: Input string
:return: Interpreted value if successful, 0 otherwise
"""
try:
nr = int(s)
except (ValueError, TypeError):
nr = 0
return nr |
def sub2ind(matrixSize, rowSub, colSub):
"""Convert row, col matrix subscripts to linear indices
"""
m, n = matrixSize
return rowSub * (n-1) + colSub - 1 |
def pythagorean_triples(n):
"""
Return list of pythagorean triples as non-descending tuples
of ints from 1 to n.
Assume n is positive.
@param int n: upper bound of pythagorean triples
>>> pythagorean_triples(5)
[(3, 4, 5)]
"""
# helper to check whether a triple is pythagorean and ... |
def binary_find(N, x, array):
"""
Binary search
:param N: size of the array
:param x: value
:param array: array
:return: position where it is found. -1 if it is not found
"""
lower = 0
upper = N
while (lower + 1) < upper:
mid = int((lower + upper) / 2)
if x < arr... |
def VG_conductivity(x, h, ksat, a, n):
""" Hydraulic conductivity function
Unsaturated hydraulic conductivity function as described by
:cite:`VanGenuchten1980`.
Parameters
----------
x : `float`
Positional argument :math:`\\left(length\\right)`.
h : `float`
Soil water poten... |
def make_shape_channels_last(shape):
"""Makes a (N, C, ...) shape into (N, ..., C)."""
return shape[:1] + shape[1:-1] + shape[1:2] |
def has_header(headers, name):
"""
Is header named ``name`` present in headers?
"""
name = name.lower()
for header, value in headers:
if header.lower() == name:
return True
return False |
def interval_is_subset(bounds1, bounds2):
"""
Checks if the interval specified in bounds1 is a subset of the interval
specified in bounds2. If this is not the case but the intervals are not
disjoint either, an error is thrown.
Args:
bounds1: the interval which is checked to being a subset o... |
def strftime(value, arg):
"""
Calls an object's strftime function.
"""
if value:
return value.strftime(arg)
else:
return None |
def d_r_to_rq(r):
"""
derivative of inverse coordinate transformation
Hernquist & Ostriker 1992 eq. 2.17
"""
fac = r + 1.0;
return 2.0/(fac*fac); |
def safeStr(string):
"""
_safeStr_
Cast simple data (int, float, basestring) to string.
"""
if not isinstance(string, (tuple, list, set, dict)):
return str(string)
raise ValueError("We're not supposed to convert %s to string." % string) |
def prettify_url(url):
"""Return a URL without its schema
"""
if not url:
return url
split = url.split('//', 1)
if len(split) == 2:
schema, path = split
else:
path = url
return path |
def handle_echo(event):
"""Optional implementation of the evt.EVT_C_ECHO handler."""
# Return a Success response to the peer
# We could also return a pydicom Dataset with a (0000, 0900) Status
# element
return 0x0000 |
def clamp(x, lower=float('-inf'), upper=float('inf')):
"""Limit a value to a given range.
Args:
x (int or float): Number to be clamped.
lower (int or float): Minimum value for x.
upper (int or float): Maximum value for x.
The returned value is guaranteed to be between *lower* and
... |
def p(n):
"""Return the nth pentagonal number."""
return n * (3 * n - 1) // 2 |
def get_image_value(x, y, img):
"""Get pixel value at specified x-y coordinate of image.
Args:
x (int): horizontal pixel coordinate
y (int): vertical pixel coordinate
img (numpy.ndarray): image from which to get get pixel value
Returns:
float: pixel value at specified coord... |
def format_user(user_id):
"""
Formats a user id so it appears as @user in the slack
"""
return "<@" + user_id + ">" |
def validate_runtime_environment(runtime_environment):
"""
Validate RuntimeEnvironment for Application
Property: Application.RuntimeEnvironment
"""
VALID_RUNTIME_ENVIRONMENTS = ("SQL-1_0", "FLINK-1_6", "FLINK-1_8", "FLINK-1_11")
if runtime_environment not in VALID_RUNTIME_ENVIRONMENTS:
... |
def get_file_list_based_on_suffix(file_list, suffix):
"""
Get filenames endinge with "suffix"
:param file_list:
:param suffix:
:return:
"""
match_list = []
for fid in file_list:
if '~$' in fid:
# memory prefix when a file is open
continue
elif fid... |
def convert_value(value_obj):
""" Convert the SPARQL json object dictionary into a Fuse type.
"""
valuetype = value_obj['type']
value = value_obj['value']
if valuetype == 'typed-literal':
typ = value_obj['datatype']
if typ == 'http://www.w3.org/2001/XMLSchema#integer':
va... |
def dc_host_list(hostdclist, dc):
"""Split the two data center server list.
accepts: host dictionary, data center list.
returns: single data center server dictionary.
"""
host_grp = []
for i in hostdclist:
d = {'id': i['id'], dc: i[dc]}
host_grp.append(d)
return host_grp |
def process_issue_info(issues):
""" Creates a dict where issue id is the key and issue_type the value
Args:
issues (list): a list of issue data
"""
col_names = {'issue_id': None, 'issue_type': None}
for cn in col_names:
col_names[cn] = None if not cn in issues[0] else issu... |
def flip(lines):
"""
Reverses the order of the lines.
Args:
lines (list[str])
Returns:
list[str]:
The flipped lines.
"""
return tuple(reversed(lines)) |
def subset(obj, keys):
"""Returns subset of the dictionary object with only the specified keys (as comma separated list)"""
return [obj[key] for key in keys.split(',')] |
def briconToScaleOffset(brightness, contrast, drange):
"""Used by the :func:`briconToDisplayRange` and the :func:`applyBricon`
functions.
Calculates a scale and offset which can be used to transform a display
range of the given size so that the given brightness/contrast settings
are applied.
:... |
def format_num(num, unit='bytes'):
"""
Returns a human readable string of a byte-value.
If 'num' is bits, set unit='bits'.
"""
if unit == 'bytes':
extension = 'B'
else:
# if it's not bytes, it's bits
extension = 'Bit'
for dimension in (unit, 'K', 'M', 'G', 'T'):
... |
def split_object_name_type(full_name):
"""
Split the name and type into their separate parts.
:param full_name: The full name of the ObjectType.
:type full_name: str
:returns: list of [<name>, <type>]
"""
split_name = full_name.split(" - ")
# if len(split_name) == 1, name and type are ... |
def get_proxy_image_url(
server_id: str,
media_content_id: str,
) -> str:
"""Generate an url for a Plex media browser image."""
return f"/api/plex_image_proxy/{server_id}/{media_content_id}" |
def build_filter_query(key, values):
"""Create a text query that matches a union of all values for a key
build_filter_query("foo", ["x", "y"])
=> foo = |("x"c, "y"c)
build_filter_query("~#foo", ["1"])
=> #(foo = 1)
"""
if not values:
return u""
if key.startswith("~#"):
... |
def msb_size(data, offset=0):
"""
:return: tuple(read_bytes, size) read the msb size from the given random
access data starting at the given byte offset"""
size = 0
i = 0
l = len(data)
hit_msb = False
while i < l:
c = data[i + offset]
size |= (c & 0x7F) << i * 7
... |
def pingpong(n):
"""Return the nth element of the ping-pong sequence.
>>> pingpong(8)
8
>>> pingpong(10)
6
>>> pingpong(15)
1
>>> pingpong(21)
-1
>>> pingpong(22)
-2
>>> pingpong(30)
-2
>>> pingpong(68)
0
>>> pingpong(69)
-1
>>> pingpong(80)
0... |
def is_in_path(file_path, find_str):
"""
check if find_str is in filename given file path
"""
file_path = file_path.lower()
find_str = find_str.lower()
return file_path.split('/')[-1].find(find_str) >= 0 |
def sum_time_spent(dictionary,incoming_number, duration):
"""calculate total time spent for each telephone number"""
dictionary[incoming_number] = dictionary.get(incoming_number, 0) + int(duration)
return dictionary |
def electrostatic_potentials(file_name):
"""
Returns the dielectic constant for the various solvents within the
database. If a solvent is not in the list will return 1. Takes a
string and returns a double
Sources:
acetic acid to water (pH 7):
https://www.organicdivision.org/wp-con... |
def border_mode_to_pad(mode, convdim, kshp):
"""
Computes a tuple for padding given the border_mode parameter
Parameters
----------
mode : int or tuple
One of "valid", "full", "half", an integer, or a tuple where each
member is either an integer or a tuple of 2 positive integers.
... |
def size_encode(size, dst=None):
"""
Encodes the given size in little-endian variable-length encoding.
The dst argument can be an existing bytearray to append the size. If it's
omitted (or None), a new bytearray is created and used.
Returns the destination bytearray.
"""
if dst is None:
... |
def wait_until_complete(cond):
"""
Wait until condition is satisfied
"""
return "while %s; do sleep 0.2; done" % cond |
def sample_width_to_string(sample_width):
"""Convert sample width (bytes) to ALSA format string."""
return {1: 's8', 2: 's16', 4: 's32'}[sample_width] |
def get_parallel_sequential_module_list(module_list):
"""
Functions segregate parallel & sequential modules
:param module_list: Complete list of modules
:return: parallel & sequential module lists
"""
# list of files consisting tests that needs to be
# executed sequentially
sequential_te... |
def count_nucleotides(dna, nucleotide):
""" (str, str) -> int
Return the number of occurrences of nucleotide in the DNA sequence dna.
>>> count_nucleotides('ATCGGC', 'G')
2
>>> count_nucleotides('ATCTA', 'G')
0
"""
chars = 0
for char in dna:
if char in nucleotide:
... |
def filter(iterable, filter_function):
"""
Filter an iterable object(e.g a list) by a user supplied function
Example:
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
def filter_function(x):
return x % 2 == 0 # all even numbers
numbers = filter(numbers, filter_function)
... |
def bin2byte(data):
"""
bin2byte: Converts a string of 1s and 0s to python byte data
Takes:
data: string of1s and 0s
Returns:
python byte data
"""
v = int(data, 2)
b = bytearray()
while v:
b.append(v & 0xff)
v >>= 8
return bytes(b[::-1]) |
def format_influx_measurement_record(record):
"""Format the record from Influx in proper manner for the insertion in Kafka bus
Args:
record (dict): The measurement record after query in influxDB
Returns:
dict: OSM-related information
"""
flavor = {
"vcpus": record.get("vdu_... |
def _indentation(line):
"""Returns the length of the line's leading whitespace, treating tab stops
as being spaced 8 characters apart."""
line = line.expandtabs()
return len(line) - len(line.lstrip()) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.