content stringlengths 42 6.51k |
|---|
def calculate_command_processor_snapshot_difference(client, snapshot_old, snapshot_new):
"""
Calculates the difference between two command processor snapshots.
Parameters
----------
client : ``Client``
The respective client.
snapshot_old : `None` or `tuple` of (`None` or `set` of ``... |
def square_loss(labels, predictions):
""" Square loss function
Args:
labels (array[float]): 1-d array of labels
predictions (array[float]): 1-d array of predictions
Returns:
float: square loss
"""
loss = 0
for l, p in zip(labels, predictions):
loss = loss + (l - ... |
def escapeCharsForCDATA(obj):
"""Escape [,],>, and < for CDATA section. Needed since some browsers (Firefox)
crap out on them."""
return obj.replace('>', '>').replace('<', '<').replace('[', '[').replace(']', ']') |
def data_battery_vt(module, voltage, temperature):
"""Battery V/T data format"""
return 'C{}: {:.1f}mV aux {:.1f}mV'.format(module, voltage / 10, temperature / 10) |
def until(n, filter_func, v):
"""Build a list: list( filter( filter_func, range(n) ) )
>>> list( filter( lambda x: x%3==0 or x%5==0, range(10) ) )
[0, 3, 5, 6, 9]
>>> until(10, lambda x: x%3==0 or x%5==0, 0)
[0, 3, 5, 6, 9]
"""
if v == n:
return []
if filter_func(v):
ret... |
def Prefix(prefix = None):
"""
Returns the current installation prefix. If an argument is supplied, the
prefix is changed to the supplied value and then returned.
"""
global _prefix
# Change the prefix if requested
if prefix != None:
_prefix = prefix
# Return the current prefix
return... |
def get_xml(xml, value):
"""operate xml"""
tempxml = xml % value
return tempxml |
def check_inside_circle(x, y, x_c, y_c, r):
"""
check if point inside of circle
"""
return (x - x_c) * (x - x_c) + (y - y_c) * (y - y_c) < r * r |
def _SplitLabels(labels):
"""Parse the 'labels' key from a PerfKitBenchmarker record.
Labels are recorded in '|key:value|,|key:value|' form.
This function transforms them to a dict.
Args:
labels: string. labels to parse.
Returns:
dict. Parsed 'labels'.
"""
result = {}
for item in labels.strip... |
def uniform_profile(ind, num, start, end):
"""Return uniformly spaced mesh corners"""
delta = (end - start) / num
return start + ind * delta, delta |
def gas_fvf(z, temp, pressure):
"""
Calculate Gas FVF
For range: this is not a correlation, so valid for infinite intervals
"""
temp = temp + 459.67
Bg = 0.0282793 * z * temp / pressure
return(Bg) |
def within_time_period(t, time_period):
"""
Check if time is in the time period
Argument:
t = given time in format (half, min, sec)
time_period = tuple of (start_time, end_time) in format (half, min, sec)
Return:
boolean
"""
start_time = time_period[0]
end_time = t... |
def make_axes_from_spec(fig, gs, axesspec):
"""Generate 2D array of subplot axes from an irregular axes specification
Args:
- fig(matplotlib.figure.Figure): a matplotlib figure handle
- gs(matplotlib.gridspec.GridSpec): the gridspec
- axesspec(list): list of gridspec slices
Returns:
- ... |
def echo(word:str, n:int, toupper:bool=False) -> str:
"""
Repeat a given word some number of times.
:param word: word to repeat
:type word: str
:param n: number of repeats
:type n: int
:param toupper: return in all caps?
:type toupper: bool
:return: result
:return type: str
... |
def top_sentences(query, sentences, idfs, n):
"""
Given a `query` (a set of words), `sentences` (a dictionary mapping
sentences to a list of their words), and `idfs` (a dictionary mapping words
to their IDF values), return a list of the `n` top sentences that match
the query, ranked according to idf... |
def get_distance_to(position, to_position):
"""Get distance from position to to_position."""
return sum(abs(pos_coord - to_coord)
for pos_coord, to_coord in zip(position, to_position)) |
def calculate_pv(a, int_, n_term):
""" Private function """
return a / int_ * (1 - 1 / (1 + int_) ** n_term) |
def fermat_little_test( p, a ):
""" Fermat Little Test. Included as a curiosity, not useful for cryptographic use.
p -> possiblePrime, a -> any integer
"""
if pow(a,p-1,p) == 1 :
return 1 # could be prime
else:
return 0 |
def get_pad_tuple3d(padding, kernel):
"""Common code to get the pad option
Parameters
----------
padding : int or str
Padding size, or ['VALID', 'SAME']
kernel : tuple of int
Conv kernel size
Returns
-------
pad_front : int
Padding size on front.
pad_top : int... |
def calculate_perf_100nsec_timer(previous, current, property_name):
"""
PERF_100NSEC_TIMER
https://technet.microsoft.com/en-us/library/cc728274(v=ws.10).aspx
"""
n0 = previous[property_name]
n1 = current[property_name]
d0 = previous["Timestamp_Sys100NS"]
d1 = current["Timestamp_Sys100NS... |
def _calculate_for(tn, fn):
"""Calculate for."""
return fn, (fn + tn) |
def guess_display_type(track_type):
"""
Returns the possible display type to use for a given track type.
:param str track_type: the type of the track
:return: the type of the display to use for the given track type
:rtype: str
"""
displays = {
"AlignmentsTrack": "LinearAlignmentsDis... |
def _calculate_ppv(tp, fp):
"""Calculate ppv."""
return tp, (tp + fp) |
def sorted_smartly(to_sort):
"""
Sorts the given list of strings alphabetically, but with
extra smarts to handle simple numbers. It effectly sorts them
as if they had been 0 padded so all numbers were the same
length; this makes them sort numerically.
"""
def split_digits(text):
"""
... |
def _parse_cmdstr(cmdstr):
"""
Parse cmdstr to dict.
@param cmdstr: str
@return: dict, dictionary representation of input
example:
cmdstr "picturedir: | title:demo | thumb_size:300x200"
result {'picturedir': '', 'thumb_size': '300x200', 'title': 'demo'}
"""
pars = {}
fo... |
def parse_attribute(attStr, default="*",
ID_tags="ID,gene_id,transcript_id,mRNA_id",
Name_tags="Name,gene_name,transcript_name,mRNA_name",
Type_tags="Type,gene_type,gene_biotype,biotype",
Parent_tags="Parent"):
"""
Parse attributes ... |
def probable_prime(n):
"""Return True if n is a probable prime according to Fermat's theorem."""
return pow(2, n-1, n) == 1 |
def validate_rule(rule):
""" Validator for checking rules """
if rule not in ('simple', 'strict'):
return {'error': 'check_rule in not present in Post data'} |
def _gen_returns_section(cfattrs):
"""Generate the "Returns" section of an indicator's docstring.
Parameters
----------
cfattrs : Sequence[Dict[str, Any]]
The list of cf attributes, usually Indicator.cf_attrs.
"""
section = "Returns\n-------\n"
for attrs in cfattrs:
section +=... |
def get_result_template_from_user(request, search_type="prestataire"):
"""
Retrieve the template name to display the
search results from the request. It will
depend on the user right to see some / all
parts of the results.
:param request: an HTTP request
:param search_type: fa... |
def convert_uint32_to_array(value):
""" Convert a number into an array of 4 bytes (LSB). """
return [(value >> 0 & 0xFF), (value >> 8 & 0xFF),
(value >> 16 & 0xFF), (value >> 24 & 0xFF)] |
def max_sub_array(nums):
""" Returns the max subarray of the given list of numbers.
Returns 0 if nums is None or an empty list.
Time Complexity: ?
Space Complexity: ?
"""
if nums == None:
return 0
if len(nums) == 0:
return 0
max_so_far = nums[0]
max_... |
def outer_parenthesis(expr):
"""
identifies the first parenthesis expression
(may have nested parentheses inside it)
rerurns the content, or just the string if ther are no parentheses
may consider returning NONE then (if no?)
"""
start_pos=expr.find('(')
if start_pos == -1:
between = expr
else... |
def filter_cam_lists(cam_list):
""" function intended to ensure DLC has been run on each session
Attributes
---------------
cam_list: list containing each camera file
Returns
-----------
cu: bool , 0 if ok 1 if not ok
"""
cu = 0
c1 = cam_list[0]
c2 = cam_list[1]
c3 = cam... |
def get_field_value(instance, field_name):
"""
Returns verbose_name for a field.
"""
return getattr(instance, field_name) |
def calculate_NDSI_TOA(rho_green_TOA, rho_SWIR1_TOA):
"""Normalized-Difference Snow Index"""
rho_NDSI_TOA=(rho_green_TOA-rho_SWIR1_TOA)/(rho_green_TOA+rho_SWIR1_TOA)
return rho_NDSI_TOA |
def get_simple_moi(panel_app_moi: str) -> str:
"""
takes the vast range of PanelApp MOIs, and reduces to a reduced
range of cases which can be easily implemented in RD analysis
This is required to reduce the complexity of an MVP
Could become a strict enumeration
{
Biallelic: [all, panel... |
def RGB( nRed, nGreen, nBlue ):
"""Return an integer which repsents a color.
The color is specified in RGB notation.
Each of nRed, nGreen and nBlue must be a number from 0 to 255.
"""
return (int( nRed ) & 255) << 16 | (int( nGreen ) & 255) << 8 | (int( nBlue ) & 255) |
def _is_path_within_scope(scope, fullpath):
"""Check whether the given `fullpath` is within the given `scope`"""
if scope == '/':
return fullpath is not None
fullpath = fullpath.lstrip('/') if fullpath else ''
scope = scope.strip('/')
return (fullpath + '/').startswith(scope + '/') |
def generate_node_index_dict(node_list):
"""Returns a dict of node -> position in node_list
Can be used for creation of links between nodes in d3 force layout
"""
node_index_dict = {}
for node in node_list:
node_index_dict[node["course_id"]] = node_list.index(node)
return node_index_di... |
def sensible_title_caps(title):
"""Capitalize the title of a movie
This function capitalizes the first character in movie titles while
leaving out certain words to not be capitalized
:param title: string of the movie title name
:return: string containing the movie title with capitalized first
... |
def flag_decomposer(flags: int) -> dict:
"""
Make font flags human readable.
:param flags: integer indicating binary encoded font attributes
:return: dictionary of attributes names and their activation state
"""
# defaults
tmp = {"superscript": 0, "italic": 0, "serifed": 0, "monospaced": 0... |
def prid(obj, show_cls=False):
"""Get the id of an object as a hex string, optionally with its class/type."""
if obj is None:
s = 'None'
else:
s = hex(id(obj))
if show_cls:
s += str(type(obj))
return s |
def binaryalert_yara_match(rec):
"""
author: Austin Byers (Airbnb CSIRT)
description: BinaryAlert found a binary matching a YARA rule
reference: https://binaryalert.io
"""
return rec['NumMatchedRules'] > 0 |
def rel_ref(from_path: str, to_path: str) -> str:
"""
Calculate related reference
:param from_path:
:param to_path:
:return:
"""
path1 = from_path.split("/")[:-1]
path2 = to_path.split("/")
fn = path2.pop(-1)
common = 0
for x, y in zip(path1, path2):
if x != y:
... |
def use_func_quantize(x, lim, n_levels='128', return_varname = 'qx'):
""" Quantize x with the given number of levels
parameters:
1. x: the name of vector or string of R vector
2. lim: the name of a vector of lower and upper limits or R vector
3. n_levels: the name of variable of the number of l... |
def color_rgb(red, green, blue):
""" Given three intensities red, green, blue, all from 0 to 255,
returns the corresponding CSS color string e.g. '#ff00cc' """
return f"#{red*256**2 + green*256 + blue:06x}" |
def autocomplete(input_, dictionary):
"""
Check if all the letters in the input are alphabetic, remove all letters in input that are not alphabetic
:param input_: word 'user' is typing
:param dictionary: dictionary to evaluate
:return: list of possible matches based on first characters of word, rest... |
def isbytelen(value, minimum, maximum):
"""
Return whether or not given value's length (in bytes) falls in a range.
If the value's length (in bytes) falls in a range, this function returns ``True``, otherwise ``False``.
Examples::
>>> isbytelen('123456', 0, 100)
True
>>> isbyt... |
def _to_loc(ll):
"""Check if location exists."""
if isinstance(ll, (int, float)) or len(ll) > 0:
return ll
else:
return 0. |
def project_name(configuration):
"""
We need unique project names, as docker resource names are derived from them, and
those need to be unique for the whole host OS. Currently, we rely on the configuration
generator to provide these.
"""
return configuration["project_name"] |
def map_coords2(func, obj):
"""
Returns the mapped coordinates from a Geometry after applying the provided
function to each dimension in tuples list (ie, linear scaling).
:param func: Function to apply to tuples
:type func: function
:param obj: A geometry or feature to extract the coordinates f... |
def update_total(flags, isbuildingflags):
""" The update_total function iterates over all the flag types and increments the total number of reads it has
encountered by 1.
:param flags: a 2d list containing all the flag information.
:param isbuildingflags: a list indicating which flags are currently bei... |
def is_balanced_parentheses(string):
"""returns whether parantheses are balanced"""
par = '()'
for i in range(len(string)):
if string[i] not in par:
string = string[:i] + '%' + string[i+1:]
s = string.replace('%', '')
count = 0
for i in range(len(s)):
if s[i] == '(':
... |
def _get_min(lhs, rhs):
"""Get min value"""
if lhs < 0:
return rhs
if rhs < 0:
return lhs
return min(lhs, rhs) |
def max_and_min(lst):
"""Returns max and min of given list."""
#return tuple containing max and min of list
return (max(lst), min(lst)) |
def trysplit(x, delimiter):
"""
Function to split only if string, otherwise return x
Parameters
----------
x: anything, hopefully string
delimiter: string
Returns
-------
x: same type as parameter x
"""
if isinstance(x, str):
return(x.split(delimiter))
else:
... |
def isInt(string):
""" is the given string an interger? """
try: int(string)
except ValueError: return 0
else: return 1 |
def scale_confidence(confidence):
"""
Hack so that 95% confidence doesn't look like basically 100%
"""
if confidence is None:
return 0
assert confidence <= 1
confidence_scaled = min(1, max(0, confidence-.05))
# confidence_scaled = confidence_scaled**2 # arbitrary fudge factor
... |
def ds_zip_in_list_of_files(xml_file, file_list):
"""
Given an XML file and a list of files
check the list of files contains a ds zip file that matches the xml file
"""
doi_id = xml_file.split("-")[-1].split(".")[0]
for file in file_list:
if str(doi_id) in file and file.endswith("ds.zip"... |
def compareConfigs(name, c1, c2, shortcut=True, rtol=1E-8, atol=1E-8, output=None):
"""Compare two `lsst.pex.config.Config` instances for equality.
This function is a helper for `lsst.pex.config.Config.compare`.
Parameters
----------
name : `str`
Name to use when reporting differences, typ... |
def count_increases(depths: list):
"""
Count the number of times a value is greater than the previous value.
:param depths: list of depths
:return: number of times depth increased
:rtype: int
"""
increases = 0
previous = None
for depth in depths:
depth = int(depth)
... |
def replace_linebr(value):
"""
Replaces all values of line break from the given string
with a line space.
Args:
value: string in template
"""
value = value.replace("\n", ' ')
while value.find(' ') >= 0:
value = value.replace(' ', ' ')
value = value.replace(' >', '>')
... |
def _fmt_metric(value, show_stdv=True):
"""format metric string"""
if len(value) == 2:
return '%s:%g' % (value[0], value[1])
elif len(value) == 3:
if show_stdv:
return '%s:%g+%g' % (value[0], value[1], value[2])
else:
return '%s:%g' % (value[0], value[1])
... |
def get_line_coords(img_shape, p1, p2):
"""
returns the coordinates of a line passing through two specified points
"""
x1, y1 = [int(p) for p in p1]
x2, y2 = [int(p) for p in p2]
div = 1.0 * (x2 - x1) if x2 != x1 else .00001
a = (1.0 * (y2 - y1)) / div
b = -a * x1 + y1
y1_, y2_ = 0, ... |
def subset (matrix, indices):
"""Returns a subset of `matrix` rows that correspond to `indices`."""
return [ matrix[index] for index in indices ] |
def parse_edges_and_weights(
data: str, start_string: str = "Distance", end_string: str = "# Source",
) -> list:
"""Return a list of edges with weights.
This function will parse through the read-in input data between strings ''start_string'' and ''end_string''
to return the filtered text in-between... |
def diff(a, b):
"""
Returns a list of strings describing differences between objects 'a' and 'b'.
If types are compatible (one is a subtype of the other) and either has a
_diff_ method, the _diff_ method of the subtype will be called (or the diff
method of 'a' if they're the same type, or 'b' if they're the s... |
def straight(ranks):
"""Return True if there is a straight"""
return (max(ranks) - min(ranks) == 4) and len(set(ranks)) == 5 |
def wall_mono_to_string(mono, latex=False):
"""
String representation of element of Wall's basis.
This is used by the _repr_ and _latex_ methods.
INPUT:
- ``mono`` - tuple of pairs of non-negative integers (m,k) with `m
>= k`
- ``latex`` - boolean (optional, default False), if true, ou... |
def prefix_sums(A):
"""
This function calculate of sums of eements in given slice (contiguous segments of array).
Its main idea uses prefix sums which
are defined as the consecutive totals of the first 0, 1, 2, . . . , n elements of an array.
Args:
A: an array represents number of mushroom... |
def verify(items, check=lambda x: x == 0):
"""Verify that all elements of items are equal to correct_answer."""
return check(items[0]) and len(set(items)) == 1 |
def maybe_get(obj, i):
"""
:param obj: object
:param i: the index
:return: the i-th item if the `obj` instantiates the __getitem__ function
"""
return obj[i] if hasattr(obj, "__getitem__") else obj |
def trim(docstring):
"""from https://www.python.org/dev/peps/pep-0257/"""
if not docstring:
return ''
# Convert tabs to spaces (following the normal Python rules)
# and split into a list of lines:
lines = docstring.expandtabs().splitlines()
# Determine minimum indentation (first line doe... |
def floatformatter(*args, sig: int=6, **kwargs) -> str:
"""
Returns a formatter, which essantially a string temapate
ready to be formatted.
Parameters
----------
sig : int, Optional
Number of significant digits. Default is 6.
Returns
-------
string
The s... |
def normalize_preferences(choices):
"""Removes duplicates and drops falsy values from a single preference order."""
new_choices = []
for choice in choices:
if choice and (choice not in new_choices):
new_choices.append(choice)
return new_choices |
def check_alt(h):
"""
Checks whether the input altitude is within range and correct type
Parameters
----------
h : float or int
altitude (0 to 24k) in meters
Returns
-------
None. Raises an exception in case
"""
if isinstance(h, (int, float)):
if ((h < 0) or (h ... |
def loop_condition(first_count, second_count, third_count):
"""
Custom function used to break out of while loop
:first_count: number of syllables in first line
:second_count: number of syllables in second line
:third_count: number of syllables in third line
"""
return first_count <= 5 and s... |
def simple_fibonacci(n):
"""Compute the nth Fibonacci number."""
a, b = 1, 1
for _ in range(n - 1):
a, b = a + b, a
return a |
def _add_left_zeros(number, iteration_digits):
"""Add zeros to the left side of the experiment run number.
Zeros will be added according to missing spaces until iterations_digits are
reached.
"""
number = str(number)
return f'{"0" * (iteration_digits - len(number))}{number}' |
def _cmplx_rsub_ ( s , o ) :
"""subtract complex values
>>> r = other - v
"""
return o - complex ( s ) |
def extract_name(module_name):
"""
extracts the module name.
:param module_name:
:return: <str> the module name without the version.
"""
return module_name.split('_v')[0] |
def insertion_sort(lst):
"""Implement insertion sorting algorithm."""
if len(lst) < 2:
return lst
for i in range(1, len(lst)):
while lst[i] < lst[i-1]:
lst[i], lst[i - 1] = lst[i - 1], lst[i]
if (i - 1) == 0:
break
i -= 1
return lst |
def _FormatFloat(number):
"""Formats float with two decimal points."""
if number:
return '%.2f' % number
else:
return '0.00' |
def q_mult(q1, q2):
"""Quaternion multiplication"""
w1, x1, y1, z1 = q1
w2, x2, y2, z2 = q2
w = w1 * w2 - x1 * x2 - y1 * y2 - z1 * z2
x = w1 * x2 + x1 * w2 + y1 * z2 - z1 * y2
y = w1 * y2 + y1 * w2 + z1 * x2 - x1 * z2
z = w1 * z2 + z1 * w2 + x1 * y2 - y1 * x2
return w, x, y, z |
def class_(obj) :
"""Return a class from an object
Often in itk, the __class__ is not what the user is expecting.
class_() should do a better job
"""
import inspect
if inspect.isclass(obj) :
# obj is already a class !
return obj
else :
# First, drop the smart pointer
try:
obj = ob... |
def change_Nfutures(left_path):
"""
:param left_path: image path
:return: number of matches lines we want to compare between the two images
"""
if (left_path[0] =='5') :
return 6000
return 500 |
def puedo_cambiar(cambiar,event,lugares_usados_temp,lugares_usados_total):
"""Verifica que el evento reciente sea un click en el tablero para ingresar una letra"""
# Se chequea si no es integer para que no cambie las letras.
return cambiar and isinstance(event, int) == False and event != '__TIMEOUT__' and... |
def change_state(current_state, neighbor_states):
"""
If a cube is active and exactly 2 or 3 of its neighbors are also active,
the cube remains active. Otherwise, the cube becomes inactive.
If a cube is inactive but exactly 3 of its neighbors are active,
the cube becomes active. Otherwise, the cube ... |
def get_split(partition_rank, training=0.7, dev=0.2, test=0.1):
"""
This function partitions the data into training, dev, and test sets
The partitioning algorithm is as follows:
1. anything less than 0.7 goes into training and receives an appropiate label
2. If not less than 0.7 subtract 0.7... |
def file_precursor(kwargs, psr):
"""
Creates a common precursor string for files and directories
using kwargs from observation_processing_pipeline.py and a pulsar name
"""
label = kwargs["label"]
if label:
label = f"_{kwargs['label']}"
return f"{kwargs['obsid']}{label}_{psr}" |
def _find_longest_strs_form_results(long_strs, r):
"""Find various longest strings from a general list of extracted
strings and text values assigned to object names.
@param long_strs (list) A list of pretty long strings encountered
during processing.
@param r (list) A list of 2 element tuples wher... |
def subcopy(self, subitems):
"""
This method is here mainly for overriding
"""
return self.__class__(subitems) |
def human_hz(v):
"""Returns a number of Hz autoselected for Hz, kHz, MHz, and GHz
"""
if v < 1e3:
return (v, 'Hz')
if v < 1e6:
return (v/1.0e3, 'kHz')
if v < 1e9:
return (v/1.0e6, 'MHz')
return (v/1.0e9, 'GHz') |
def c3d(coord):
""" Convert coordinate to 3D. """
pp = [coord[i]*1e+6 for i in range(len(list(coord)))]
return pp |
def ir(x):
"""
Rounds floating point to thew nearest integer ans returns integer
:param x: {float} num to round
:return:
"""
return int(round(x)) |
def zeller(config, n):
"""
Splits up the input config into n pieces as used by Zeller in the original
reference implementation. The approach works iteratively in n steps, first
slicing off a chunk sized 1/n-th of the original config, then slicing off
1/(n-1)-th of the remainder, and so on, until the... |
def clean_background_command(command):
"""Cleans a command containing background &.
:param command: Converted command e.g. ['bash', '$PWD/c1 &']."""
return [x.replace(" &", "") for x in command] |
def lower_case_underscore_to_camel_case(string):
"""Convert string or unicode from lower-case underscore to camel-case"""
splitted_string = string.split('_')
# use string's class to work on the string to keep its type
class_ = string.__class__
return class_.join('', map(class_.capitalize, splitted_s... |
def _collect_classes(user_annotations, class_dict):
"""Collect classes from chosen presets."""
result = {}
for annotation in user_annotations:
result.update(class_dict.get(annotation, {}))
return result |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.