INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Floor function ( round towards negative infinity ) | def floor(x):
"""
Floor function (round towards negative infinity)
"""
if isinstance(x, UncertainFunction):
mcpts = np.floor(x._mcpts)
return UncertainFunction(mcpts)
else:
return np.floor(x) |
Calculate the hypotenuse given two legs of a right triangle | def hypot(x, y):
"""
Calculate the hypotenuse given two "legs" of a right triangle
"""
if isinstance(x, UncertainFunction) or isinstance(x, UncertainFunction):
ufx = to_uncertain_func(x)
ufy = to_uncertain_func(y)
mcpts = np.hypot(ufx._mcpts, ufy._mcpts)
return UncertainF... |
Natural logarithm | def log(x):
"""
Natural logarithm
"""
if isinstance(x, UncertainFunction):
mcpts = np.log(x._mcpts)
return UncertainFunction(mcpts)
else:
return np.log(x) |
Base - 10 logarithm | def log10(x):
"""
Base-10 logarithm
"""
if isinstance(x, UncertainFunction):
mcpts = np.log10(x._mcpts)
return UncertainFunction(mcpts)
else:
return np.log10(x) |
Natural logarithm of ( 1 + x ) | def log1p(x):
"""
Natural logarithm of (1 + x)
"""
if isinstance(x, UncertainFunction):
mcpts = np.log1p(x._mcpts)
return UncertainFunction(mcpts)
else:
return np.log1p(x) |
Convert degrees to radians | def radians(x):
"""
Convert degrees to radians
"""
if isinstance(x, UncertainFunction):
mcpts = np.radians(x._mcpts)
return UncertainFunction(mcpts)
else:
return np.radians(x) |
Sine | def sin(x):
"""
Sine
"""
if isinstance(x, UncertainFunction):
mcpts = np.sin(x._mcpts)
return UncertainFunction(mcpts)
else:
return np.sin(x) |
Hyperbolic sine | def sinh(x):
"""
Hyperbolic sine
"""
if isinstance(x, UncertainFunction):
mcpts = np.sinh(x._mcpts)
return UncertainFunction(mcpts)
else:
return np.sinh(x) |
Square - root function | def sqrt(x):
"""
Square-root function
"""
if isinstance(x, UncertainFunction):
mcpts = np.sqrt(x._mcpts)
return UncertainFunction(mcpts)
else:
return np.sqrt(x) |
Tangent | def tan(x):
"""
Tangent
"""
if isinstance(x, UncertainFunction):
mcpts = np.tan(x._mcpts)
return UncertainFunction(mcpts)
else:
return np.tan(x) |
Hyperbolic tangent | def tanh(x):
"""
Hyperbolic tangent
"""
if isinstance(x, UncertainFunction):
mcpts = np.tanh(x._mcpts)
return UncertainFunction(mcpts)
else:
return np.tanh(x) |
Truncate the values to the integer value without rounding | def trunc(x):
"""
Truncate the values to the integer value without rounding
"""
if isinstance(x, UncertainFunction):
mcpts = np.trunc(x._mcpts)
return UncertainFunction(mcpts)
else:
return np.trunc(x) |
Create a Latin - Hypercube sample design based on distributions defined in the scipy. stats module Parameters ---------- dist: array_like frozen scipy. stats. rv_continuous or rv_discrete distribution objects that are defined previous to calling LHD | def lhd(
dist=None,
size=None,
dims=1,
form="randomized",
iterations=100,
showcorrelations=False,
):
"""
Create a Latin-Hypercube sample design based on distributions defined in the
`scipy.stats` module
Parameters
----------
dist: array_like
frozen scipy.stat... |
Transforms x into an UncertainFunction - compatible object unless it is already an UncertainFunction ( in which case x is returned unchanged ). | def to_uncertain_func(x):
"""
Transforms x into an UncertainFunction-compatible object,
unless it is already an UncertainFunction (in which case x is returned
unchanged).
Raises an exception unless 'x' belongs to some specific classes of
objects that are known not to depend on UncertainFunctio... |
A Beta random variate Parameters ---------- alpha: scalar The first shape parameter beta: scalar The second shape parameter Optional -------- low: scalar Lower bound of the distribution support ( default = 0 ) high: scalar Upper bound of the distribution support ( default = 1 ) | def Beta(alpha, beta, low=0, high=1, tag=None):
"""
A Beta random variate
Parameters
----------
alpha : scalar
The first shape parameter
beta : scalar
The second shape parameter
Optional
--------
low : scalar
Lower bound of the distribution support (... |
A BetaPrime random variate Parameters ---------- alpha: scalar The first shape parameter beta: scalar The second shape parameter | def BetaPrime(alpha, beta, tag=None):
"""
A BetaPrime random variate
Parameters
----------
alpha : scalar
The first shape parameter
beta : scalar
The second shape parameter
"""
assert (
alpha > 0 and beta > 0
), 'BetaPrime "alpha" and "beta" paramete... |
A Bradford random variate Parameters ---------- q: scalar The shape parameter low: scalar The lower bound of the distribution ( default = 0 ) high: scalar The upper bound of the distribution ( default = 1 ) | def Bradford(q, low=0, high=1, tag=None):
"""
A Bradford random variate
Parameters
----------
q : scalar
The shape parameter
low : scalar
The lower bound of the distribution (default=0)
high : scalar
The upper bound of the distribution (default=1)
"""
ass... |
A Burr random variate Parameters ---------- c: scalar The first shape parameter k: scalar The second shape parameter | def Burr(c, k, tag=None):
"""
A Burr random variate
Parameters
----------
c : scalar
The first shape parameter
k : scalar
The second shape parameter
"""
assert c > 0 and k > 0, 'Burr "c" and "k" parameters must be greater than zero'
return uv(ss.burr(c, k), ... |
A Chi - Squared random variate Parameters ---------- k: int The degrees of freedom of the distribution ( must be greater than one ) | def ChiSquared(k, tag=None):
"""
A Chi-Squared random variate
Parameters
----------
k : int
The degrees of freedom of the distribution (must be greater than one)
"""
assert int(k) == k and k >= 1, 'Chi-Squared "k" must be an integer greater than 0'
return uv(ss.chi2(k), tag=... |
An Erlang random variate. This distribution is the same as a Gamma ( k theta ) distribution but with the restriction that k must be a positive integer. This is provided for greater compatibility with other simulation tools but provides no advantage over the Gamma distribution in its applications. Parameters ---------- ... | def Erlang(k, lamda, tag=None):
"""
An Erlang random variate.
This distribution is the same as a Gamma(k, theta) distribution, but
with the restriction that k must be a positive integer. This
is provided for greater compatibility with other simulation tools, but
provides no advantage over ... |
An Exponential random variate Parameters ---------- lamda: scalar The inverse scale ( as shown on Wikipedia ). ( FYI: mu = 1/ lamda. ) | def Exponential(lamda, tag=None):
"""
An Exponential random variate
Parameters
----------
lamda : scalar
The inverse scale (as shown on Wikipedia). (FYI: mu = 1/lamda.)
"""
assert lamda > 0, 'Exponential "lamda" must be greater than zero'
return uv(ss.expon(scale=1.0 / lamda... |
An Extreme Value Maximum random variate. Parameters ---------- mu: scalar The location parameter sigma: scalar The scale parameter ( must be greater than zero ) | def ExtValueMax(mu, sigma, tag=None):
"""
An Extreme Value Maximum random variate.
Parameters
----------
mu : scalar
The location parameter
sigma : scalar
The scale parameter (must be greater than zero)
"""
assert sigma > 0, 'ExtremeValueMax "sigma" must be greater t... |
An F ( fisher ) random variate Parameters ---------- d1: int Numerator degrees of freedom d2: int Denominator degrees of freedom | def Fisher(d1, d2, tag=None):
"""
An F (fisher) random variate
Parameters
----------
d1 : int
Numerator degrees of freedom
d2 : int
Denominator degrees of freedom
"""
assert (
int(d1) == d1 and d1 >= 1
), 'Fisher (F) "d1" must be an integer greater than 0... |
A Gamma random variate Parameters ---------- k: scalar The shape parameter ( must be positive and non - zero ) theta: scalar The scale parameter ( must be positive and non - zero ) | def Gamma(k, theta, tag=None):
"""
A Gamma random variate
Parameters
----------
k : scalar
The shape parameter (must be positive and non-zero)
theta : scalar
The scale parameter (must be positive and non-zero)
"""
assert (
k > 0 and theta > 0
), 'Gamma "k... |
A Log - Normal random variate Parameters ---------- mu: scalar The location parameter sigma: scalar The scale parameter ( must be positive and non - zero ) | def LogNormal(mu, sigma, tag=None):
"""
A Log-Normal random variate
Parameters
----------
mu : scalar
The location parameter
sigma : scalar
The scale parameter (must be positive and non-zero)
"""
assert sigma > 0, 'Log-Normal "sigma" must be positive'
return uv(s... |
A Normal ( or Gaussian ) random variate Parameters ---------- mu: scalar The mean value of the distribution sigma: scalar The standard deviation ( must be positive and non - zero ) | def Normal(mu, sigma, tag=None):
"""
A Normal (or Gaussian) random variate
Parameters
----------
mu : scalar
The mean value of the distribution
sigma : scalar
The standard deviation (must be positive and non-zero)
"""
assert sigma > 0, 'Normal "sigma" must be greater... |
A Pareto random variate ( first kind ) Parameters ---------- q: scalar The scale parameter a: scalar The shape parameter ( the minimum possible value ) | def Pareto(q, a, tag=None):
"""
A Pareto random variate (first kind)
Parameters
----------
q : scalar
The scale parameter
a : scalar
The shape parameter (the minimum possible value)
"""
assert q > 0 and a > 0, 'Pareto "q" and "a" must be positive scalars'
p = Uni... |
A Pareto random variate ( second kind ). This form always starts at the origin. Parameters ---------- q: scalar The scale parameter b: scalar The shape parameter | def Pareto2(q, b, tag=None):
"""
A Pareto random variate (second kind). This form always starts at the
origin.
Parameters
----------
q : scalar
The scale parameter
b : scalar
The shape parameter
"""
assert q > 0 and b > 0, 'Pareto2 "q" and "b" must be positive sc... |
A PERT random variate Parameters ---------- low: scalar Lower bound of the distribution support peak: scalar The location of the distribution s peak ( low < = peak < = high ) high: scalar Upper bound of the distribution support Optional -------- g: scalar Controls the uncertainty of the distribution around the peak. Sm... | def PERT(low, peak, high, g=4.0, tag=None):
"""
A PERT random variate
Parameters
----------
low : scalar
Lower bound of the distribution support
peak : scalar
The location of the distribution's peak (low <= peak <= high)
high : scalar
Upper bound of the distribut... |
A Student - T random variate Parameters ---------- v: int The degrees of freedom of the distribution ( must be greater than one ) | def StudentT(v, tag=None):
"""
A Student-T random variate
Parameters
----------
v : int
The degrees of freedom of the distribution (must be greater than one)
"""
assert int(v) == v and v >= 1, 'Student-T "v" must be an integer greater than 0'
return uv(ss.t(v), tag=tag) |
A triangular random variate Parameters ---------- low: scalar Lower bound of the distribution support peak: scalar The location of the triangle s peak ( low < = peak < = high ) high: scalar Upper bound of the distribution support | def Triangular(low, peak, high, tag=None):
"""
A triangular random variate
Parameters
----------
low : scalar
Lower bound of the distribution support
peak : scalar
The location of the triangle's peak (low <= peak <= high)
high : scalar
Upper bound of the distribu... |
A Uniform random variate Parameters ---------- low: scalar Lower bound of the distribution support. high: scalar Upper bound of the distribution support. | def Uniform(low, high, tag=None):
"""
A Uniform random variate
Parameters
----------
low : scalar
Lower bound of the distribution support.
high : scalar
Upper bound of the distribution support.
"""
assert low < high, 'Uniform "low" must be less than "high"'
retur... |
A Weibull random variate Parameters ---------- lamda: scalar The scale parameter k: scalar The shape parameter | def Weibull(lamda, k, tag=None):
"""
A Weibull random variate
Parameters
----------
lamda : scalar
The scale parameter
k : scalar
The shape parameter
"""
assert (
lamda > 0 and k > 0
), 'Weibull "lamda" and "k" parameters must be greater than zero'
re... |
A Bernoulli random variate Parameters ---------- p: scalar The probability of success | def Bernoulli(p, tag=None):
"""
A Bernoulli random variate
Parameters
----------
p : scalar
The probability of success
"""
assert (
0 < p < 1
), 'Bernoulli probability "p" must be between zero and one, non-inclusive'
return uv(ss.bernoulli(p), tag=tag) |
A Binomial random variate Parameters ---------- n: int The number of trials p: scalar The probability of success | def Binomial(n, p, tag=None):
"""
A Binomial random variate
Parameters
----------
n : int
The number of trials
p : scalar
The probability of success
"""
assert (
int(n) == n and n > 0
), 'Binomial number of trials "n" must be an integer greater than zero'... |
A Geometric random variate Parameters ---------- p: scalar The probability of success | def Geometric(p, tag=None):
"""
A Geometric random variate
Parameters
----------
p : scalar
The probability of success
"""
assert (
0 < p < 1
), 'Geometric probability "p" must be between zero and one, non-inclusive'
return uv(ss.geom(p), tag=tag) |
A Hypergeometric random variate Parameters ---------- N: int The total population size n: int The number of individuals of interest in the population K: int The number of individuals that will be chosen from the population Example ------- ( Taken from the wikipedia page ) Assume we have an urn with two types of marbles... | def Hypergeometric(N, n, K, tag=None):
"""
A Hypergeometric random variate
Parameters
----------
N : int
The total population size
n : int
The number of individuals of interest in the population
K : int
The number of individuals that will be chosen from the popul... |
A Poisson random variate Parameters ---------- lamda: scalar The rate of an occurance within a specified interval of time or space. | def Poisson(lamda, tag=None):
"""
A Poisson random variate
Parameters
----------
lamda : scalar
The rate of an occurance within a specified interval of time or space.
"""
assert lamda > 0, 'Poisson "lamda" must be greater than zero.'
return uv(ss.poisson(lamda), tag=tag) |
Calculate the covariance matrix of uncertain variables oriented by the order of the inputs Parameters ---------- nums_with_uncert: array - like A list of variables that have an associated uncertainty Returns ------- cov_matrix: 2d - array - like A nested list containing covariance values Example ------- >>> x = N ( 1 0... | def covariance_matrix(nums_with_uncert):
"""
Calculate the covariance matrix of uncertain variables, oriented by the
order of the inputs
Parameters
----------
nums_with_uncert : array-like
A list of variables that have an associated uncertainty
Returns
-------
cov_m... |
Calculate the correlation matrix of uncertain variables oriented by the order of the inputs Parameters ---------- nums_with_uncert: array - like A list of variables that have an associated uncertainty Returns ------- corr_matrix: 2d - array - like A nested list containing covariance values Example ------- >>> x = N ( 1... | def correlation_matrix(nums_with_uncert):
"""
Calculate the correlation matrix of uncertain variables, oriented by the
order of the inputs
Parameters
----------
nums_with_uncert : array-like
A list of variables that have an associated uncertainty
Returns
-------
cor... |
Variance value as a result of an uncertainty calculation | def var(self):
"""
Variance value as a result of an uncertainty calculation
"""
mn = self.mean
vr = np.mean((self._mcpts - mn) ** 2)
return vr |
r Skewness coefficient value as a result of an uncertainty calculation defined as:: _____ m3 \/ beta1 = ------ std ** 3 where m3 is the third central moment and std is the standard deviation | def skew(self):
r"""
Skewness coefficient value as a result of an uncertainty calculation,
defined as::
_____ m3
\/beta1 = ------
std**3
where m3 is the third central moment and std is the standard deviation
... |
Kurtosis coefficient value as a result of an uncertainty calculation defined as:: m4 beta2 = ------ std ** 4 | def kurt(self):
"""
Kurtosis coefficient value as a result of an uncertainty calculation,
defined as::
m4
beta2 = ------
std**4
where m4 is the fourth central moment and std is the standard deviation
"""
... |
The first four standard moments of a distribution: mean variance and standardized skewness and kurtosis coefficients. | def stats(self):
"""
The first four standard moments of a distribution: mean, variance, and
standardized skewness and kurtosis coefficients.
"""
mn = self.mean
vr = self.var
sk = self.skew
kt = self.kurt
return [mn, vr, sk, kt] |
Get the distribution value at a given percentile or set of percentiles. This follows the NIST method for calculating percentiles. Parameters ---------- val: scalar or array Either a single value or an array of values between 0 and 1. Returns ------- out: scalar or array The actual distribution value that appears at the... | def percentile(self, val):
"""
Get the distribution value at a given percentile or set of percentiles.
This follows the NIST method for calculating percentiles.
Parameters
----------
val : scalar or array
Either a single value or an array of values be... |
Cleanly show what the four displayed distribution moments are: - Mean - Variance - Standardized Skewness Coefficient - Standardized Kurtosis Coefficient For a standard Normal distribution these are [ 0 1 0 3 ]. If the object has an associated tag this is presented. If the optional name kwarg is utilized this is present... | def describe(self, name=None):
"""
Cleanly show what the four displayed distribution moments are:
- Mean
- Variance
- Standardized Skewness Coefficient
- Standardized Kurtosis Coefficient
For a standard Normal distribution, these are [0, 1... |
Plot the distribution of the UncertainFunction. By default the distribution is shown with a kernel density estimate ( kde ). Optional -------- hist: bool If true a density histogram is displayed ( histtype = stepfilled ) show: bool If True the figure will be displayed after plotting the distribution. If False an explic... | def plot(self, hist=False, show=False, **kwargs):
"""
Plot the distribution of the UncertainFunction. By default, the
distribution is shown with a kernel density estimate (kde).
Optional
--------
hist : bool
If true, a density histogram is displayed (... |
Plot the distribution of the UncertainVariable. Continuous distributions are plotted with a line plot and discrete distributions are plotted with discrete circles. Optional -------- hist: bool If true a histogram is displayed show: bool If True the figure will be displayed after plotting the distribution. If False an e... | def plot(self, hist=False, show=False, **kwargs):
"""
Plot the distribution of the UncertainVariable. Continuous
distributions are plotted with a line plot and discrete distributions
are plotted with discrete circles.
Optional
--------
hist : bool
... |
Loads the hat from a picture at path. | def load_hat(self, path): # pylint: disable=no-self-use
"""Loads the hat from a picture at path.
Args:
path: The path to load from
Returns:
The hat data.
"""
hat = cv2.imread(path, cv2.IMREAD_UNCHANGED)
if hat is None:
raise ValueErr... |
Uses a haarcascade to detect faces inside an image. | def find_faces(self, image, draw_box=False):
"""Uses a haarcascade to detect faces inside an image.
Args:
image: The image.
draw_box: If True, the image will be marked with a rectangle.
Return:
The faces as returned by OpenCV's detectMultiScale method for
... |
Find instances of rsrc_type that match the filter in ** kwargs | def find_resources(self, rsrc_type, sort=None, yield_pages=False, **kwargs):
"""Find instances of `rsrc_type` that match the filter in `**kwargs`"""
return rsrc_type.find(self, sort=sort, yield_pages=yield_pages, **kwargs) |
Marks the object as changed. | def changed(self, message=None, *args):
"""Marks the object as changed.
If a `parent` attribute is set, the `changed()` method on the parent
will be called, propagating the change notification up the chain.
The message (if provided) will be debug logged.
"""
if message ... |
Decorator for mutation tracker registration. | def register(cls, origin_type):
"""Decorator for mutation tracker registration.
The provided `origin_type` is mapped to the decorated class such that
future calls to `convert()` will convert the object of `origin_type`
to an instance of the decorated class.
"""
def decor... |
Converts objects to registered tracked types | def convert(cls, obj, parent):
"""Converts objects to registered tracked types
This checks the type of the given object against the registered tracked
types. When a match is found, the given object will be converted to the
tracked type, its parent set to the provided parent, and returne... |
Generator like convert_iterable but for 2 - tuple iterators. | def convert_items(self, items):
"""Generator like `convert_iterable`, but for 2-tuple iterators."""
return ((key, self.convert(value, self)) for key, value in items) |
Convenience method to track either a dict or a 2 - tuple iterator. | def convert_mapping(self, mapping):
"""Convenience method to track either a dict or a 2-tuple iterator."""
if isinstance(mapping, dict):
return self.convert_items(iteritems(mapping))
return self.convert_items(mapping) |
If we only have a single preference object redirect to it otherwise display listing. | def changelist_view(self, request, extra_context=None):
"""
If we only have a single preference object redirect to it,
otherwise display listing.
"""
model = self.model
if model.objects.all().count() > 1:
return super(PreferencesAdmin, self).changelist_view(re... |
Only converts headers | def md2rst(md_lines):
'Only converts headers'
lvl2header_char = {1: '=', 2: '-', 3: '~'}
for md_line in md_lines:
if md_line.startswith('#'):
header_indent, header_text = md_line.split(' ', 1)
yield header_text
header_char = lvl2header_char[len(header_indent)]
... |
Function decorator to transform a generator into a list | def aslist(generator):
'Function decorator to transform a generator into a list'
def wrapper(*args, **kwargs):
return list(generator(*args, **kwargs))
return wrapper |
No classifier - based selection of Python packages is currently implemented: for now we don t fetch any. whl or. egg Eventually we should select the best release available based on the classifier & PEP 425: https:// www. python. org/ dev/ peps/ pep - 0425/ E. g. a wheel when available but NOT for tornado 4. 3 for examp... | def get_package_release_from_pypi(pkg_name, version, pypi_json_api_url, allowed_classifiers):
"""
No classifier-based selection of Python packages is currently implemented: for now we don't fetch any .whl or .egg
Eventually, we should select the best release available, based on the classifier & PEP 425: htt... |
Returns a PEP425 - compliant classifier ( or py2. py3 - none - any if it cannot be extracted ) and the file extension TODO: return a classifier 3 - members namedtuple instead of a single string | def extract_classifier_and_extension(pkg_name, filename):
"""
Returns a PEP425-compliant classifier (or 'py2.py3-none-any' if it cannot be extracted),
and the file extension
TODO: return a classifier 3-members namedtuple instead of a single string
"""
basename, _, extension = filename.rpartition... |
Convert plain dictionary to NestedMutable. | def coerce(cls, key, value):
"""Convert plain dictionary to NestedMutable."""
if value is None:
return value
if isinstance(value, cls):
return value
if isinstance(value, dict):
return NestedMutableDict.coerce(key, value)
if isinstance(value, li... |
Checks if a function in a module was declared in that module. | def is_mod_function(mod, fun):
"""Checks if a function in a module was declared in that module.
http://stackoverflow.com/a/1107150/3004221
Args:
mod: the module
fun: the function
"""
return inspect.isfunction(fun) and inspect.getmodule(fun) == mod |
Checks if a class in a module was declared in that module. | def is_mod_class(mod, cls):
"""Checks if a class in a module was declared in that module.
Args:
mod: the module
cls: the class
"""
return inspect.isclass(cls) and inspect.getmodule(cls) == mod |
Lists all functions declared in a module. | def list_functions(mod_name):
"""Lists all functions declared in a module.
http://stackoverflow.com/a/1107150/3004221
Args:
mod_name: the module name
Returns:
A list of functions declared in that module.
"""
mod = sys.modules[mod_name]
return [func.__name__ for func in mod.... |
Lists all classes declared in a module. | def list_classes(mod_name):
"""Lists all classes declared in a module.
Args:
mod_name: the module name
Returns:
A list of functions declared in that module.
"""
mod = sys.modules[mod_name]
return [cls.__name__ for cls in mod.__dict__.values()
if is_mod_class(mod, cls... |
Returns a dictionary which maps function names to line numbers. | def get_linenumbers(functions, module, searchstr='def {}(image):\n'):
"""Returns a dictionary which maps function names to line numbers.
Args:
functions: a list of function names
module: the module to look the functions up
searchstr: the string to search for
Returns:
A di... |
Formats the documentation in a nicer way and for notebook cells. | def format_doc(fun):
"""Formats the documentation in a nicer way and for notebook cells."""
SEPARATOR = '============================='
func = cvloop.functions.__dict__[fun]
doc_lines = ['{}'.format(l).strip() for l in func.__doc__.split('\n')]
if hasattr(func, '__init__'):
doc_lines.append... |
Main function creates the cvloop. functions example notebook. | def main():
"""Main function creates the cvloop.functions example notebook."""
notebook = {
'cells': [
{
'cell_type': 'markdown',
'metadata': {},
'source': [
'# cvloop functions\n\n',
'This notebook shows... |
Prepares an axes object for clean plotting. | def prepare_axes(axes, title, size, cmap=None):
"""Prepares an axes object for clean plotting.
Removes x and y axes labels and ticks, sets the aspect ratio to be
equal, uses the size to determine the drawing area and fills the image
with random colors as visual feedback.
Creates an AxesImage to be... |
Connects event handlers to the figure. | def connect_event_handlers(self):
"""Connects event handlers to the figure."""
self.figure.canvas.mpl_connect('close_event', self.evt_release)
self.figure.canvas.mpl_connect('pause_event', self.evt_toggle_pause) |
Pauses and resumes the video source. | def evt_toggle_pause(self, *args): # pylint: disable=unused-argument
"""Pauses and resumes the video source."""
if self.event_source._timer is None: # noqa: e501 pylint: disable=protected-access
self.event_source.start()
else:
self.event_source.stop() |
Prints information about the unprocessed image. | def print_info(self, capture):
"""Prints information about the unprocessed image.
Reads one frame from the source to determine image colors, dimensions
and data types.
Args:
capture: the source to read from.
"""
self.frame_offset += 1
ret, frame = ca... |
Determines the height and width of the image source. | def determine_size(self, capture):
"""Determines the height and width of the image source.
If no dimensions are available, this method defaults to a resolution of
640x480, thus returns (480, 640).
If capture has a get method it is assumed to understand
`cv2.CAP_PROP_FRAME_WIDTH`... |
Initializes the drawing of the frames by setting the images to random colors. | def _init_draw(self):
"""Initializes the drawing of the frames by setting the images to
random colors.
This function is called by TimedAnimation.
"""
if self.original is not None:
self.original.set_data(np.random.random((10, 10, 3)))
self.processed.set_data(n... |
Reads a frame and converts the color if needed. | def read_frame(self):
"""Reads a frame and converts the color if needed.
In case no frame is available, i.e. self.capture.read() returns False
as the first return value, the event_source of the TimedAnimation is
stopped, and if possible the capture source released.
Returns:
... |
Annotates the processed axis with given annotations for the provided framedata. | def annotate(self, framedata):
"""Annotates the processed axis with given annotations for
the provided framedata.
Args:
framedata: The current frame number.
"""
for artist in self.annotation_artists:
artist.remove()
self.annotation_artists = []
... |
Reads processes and draws the frames. | def _draw_frame(self, framedata):
"""Reads, processes and draws the frames.
If needed for color maps, conversions to gray scale are performed. In
case the images are no color images and no custom color maps are
defined, the colormap `gray` is applied.
This function is called by... |
Updates the figure s suptitle. | def update_info(self, custom=None):
"""Updates the figure's suptitle.
Calls self.info_string() unless custom is provided.
Args:
custom: Overwrite it with this string, unless None.
"""
self.figure.suptitle(self.info_string() if custom is None else custom) |
Returns information about the stream. | def info_string(self, size=None, message='', frame=-1):
"""Returns information about the stream.
Generates a string containing size, frame number, and info messages.
Omits unnecessary information (e.g. empty messages and frame -1).
This method is primarily used to update the suptitle o... |
Sanitizes the loaded *. ipynb. | def main():
"""Sanitizes the loaded *.ipynb."""
with open(sys.argv[1], 'r') as nbfile:
notebook = json.load(nbfile)
# remove kernelspec (venvs)
try:
del notebook['metadata']['kernelspec']
except KeyError:
pass
# remove outputs and metadata, set execution counts to None
... |
create comment: param comment:: param mentions: list of pair of code and type ( USER GROUP and so on ): return: | def create(self, comment, mentions=()):
"""
create comment
:param comment:
:param mentions: list of pair of code and type("USER", "GROUP", and so on)
:return:
"""
data = {
"app": self.app_id,
"record": self.record_id,
"comment"... |
Advance the iterator n - steps ahead. If n is none consume entirely. | def _consume(iterator, n=None):
"""Advance the iterator n-steps ahead. If n is none, consume entirely."""
# Use functions that consume iterators at C speed.
if n is None:
# feed the entire iterator into a zero-length deque
collections.deque(iterator, maxlen=0)
else:
# advance to ... |
Calculate how many items must be in the collection to satisfy this slice | def _slice_required_len(slice_obj):
"""
Calculate how many items must be in the collection to satisfy this slice
returns `None` for slices may vary based on the length of the underlying collection
such as `lst[-1]` or `lst[::]`
"""
if slice_obj.step and slice_obj.step != 1:
return None
... |
conveniently styles your text as and resets ANSI codes at its end. | def stylize(text, styles, reset=True):
"""conveniently styles your text as and resets ANSI codes at its end."""
terminator = attr("reset") if reset else ""
return "{}{}{}".format("".join(styles), text, terminator) |
stylize () variant that adds C0 control codes ( SOH/ STX ) for readline safety. | def stylize_interactive(text, styles, reset=True):
"""stylize() variant that adds C0 control codes (SOH/STX) for readline
safety."""
# problem: readline includes bare ANSI codes in width calculations.
# solution: wrap nonprinting codes in SOH/STX when necessary.
# see: https://github.com/dslackw/col... |
Set or reset attributes | def attribute(self):
"""Set or reset attributes"""
paint = {
"bold": self.ESC + "1" + self.END,
1: self.ESC + "1" + self.END,
"dim": self.ESC + "2" + self.END,
2: self.ESC + "2" + self.END,
"underlined": self.ESC + "4" + self.END,
... |
Print 256 foreground colors | def foreground(self):
"""Print 256 foreground colors"""
code = self.ESC + "38;5;"
if str(self.color).isdigit():
self.reverse_dict()
color = self.reserve_paint[str(self.color)]
return code + self.paint[color] + self.END
elif self.color.startswith("#"):
... |
reverse dictionary | def reverse_dict(self):
"""reverse dictionary"""
self.reserve_paint = dict(zip(self.paint.values(), self.paint.keys())) |
Perform a reset and check for presence pulse. | def reset(self, required=False):
"""
Perform a reset and check for presence pulse.
:param bool required: require presence pulse
"""
reset = self._ow.reset()
if required and reset:
raise OneWireError("No presence pulse found. Check devices and wiring.")
... |
Read into buf from the device. The number of bytes read will be the length of buf. | def readinto(self, buf, *, start=0, end=None):
"""
Read into ``buf`` from the device. The number of bytes read will be the
length of ``buf``.
If ``start`` or ``end`` is provided, then the buffer will be sliced
as if ``buf[start:end]``. This will not cause an allocation like
... |
Write the bytes from buf to the device. | def write(self, buf, *, start=0, end=None):
"""
Write the bytes from ``buf`` to the device.
If ``start`` or ``end`` is provided, then the buffer will be sliced
as if ``buffer[start:end]``. This will not cause an allocation like
``buffer[start:end]`` will so it saves memory.
... |
Scan for devices on the bus and return a list of addresses. | def scan(self):
"""Scan for devices on the bus and return a list of addresses."""
devices = []
diff = 65
rom = False
count = 0
for _ in range(0xff):
rom, diff = self._search_rom(rom, diff)
if rom:
count += 1
if count... |
Perform the 1 - Wire CRC check on the provided data. | def crc8(data):
"""
Perform the 1-Wire CRC check on the provided data.
:param bytearray data: 8 byte array representing 64 bit ROM code
"""
crc = 0
for byte in data:
crc ^= byte
for _ in range(8):
if crc & 0x01:
... |
deserialize json to model: param json_body: json data: param get_value_and_type: function ( f: json_field ) - > value field_type_string ( see FieldType ): return: | def _deserialize(cls, json_body, get_value_and_type):
"""
deserialize json to model
:param json_body: json data
:param get_value_and_type: function(f: json_field) -> value, field_type_string(see FieldType)
:return:
"""
instance = cls()
is_set = False
... |
serialize model object to dictionary: param convert_to_key_and_value: function ( field_name value property_detail ) - > key value: return: | def _serialize(self, convert_to_key_and_value, ignore_missing=False):
"""
serialize model object to dictionary
:param convert_to_key_and_value: function(field_name, value, property_detail) -> key, value
:return:
"""
serialized = {}
properties = self._get_property... |
Read into buf from the device. The number of bytes read will be the length of buf. | def readinto(self, buf, *, start=0, end=None):
"""
Read into ``buf`` from the device. The number of bytes read will be the
length of ``buf``.
If ``start`` or ``end`` is provided, then the buffer will be sliced
as if ``buf[start:end]``. This will not cause an allocation like
... |
Write the bytes from buf to the device. | def write(self, buf, *, start=0, end=None):
"""
Write the bytes from ``buf`` to the device.
If ``start`` or ``end`` is provided, then the buffer will be sliced
as if ``buffer[start:end]``. This will not cause an allocation like
``buffer[start:end]`` will so it saves memory.
... |
Adds various preferences members to preferences. preferences thus enabling easy access from code. | def preferences_class_prepared(sender, *args, **kwargs):
"""
Adds various preferences members to preferences.preferences,
thus enabling easy access from code.
"""
cls = sender
if issubclass(cls, Preferences):
# Add singleton manager to subclasses.
cls.add_to_class('singleton', Si... |
Make sure there is only a single preferences object per site. So remove sites from pre - existing preferences objects. | def site_cleanup(sender, action, instance, **kwargs):
"""
Make sure there is only a single preferences object per site.
So remove sites from pre-existing preferences objects.
"""
if action == 'post_add':
if isinstance(instance, Preferences) \
and hasattr(instance.__class__, 'obje... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.