_id
stringlengths
5
9
text
stringlengths
5
385k
title
stringclasses
1 value
doc_27200
Many programs split up their functionality into a number of sub-commands, for example, the svn program can invoke sub-commands like svn checkout, svn update, and svn commit. Splitting up functionality this way can be a particularly good idea when a program performs several different functions which require different kinds of command-line arguments. ArgumentParser supports the creation of such sub-commands with the add_subparsers() method. The add_subparsers() method is normally called with no arguments and returns a special action object. This object has a single method, add_parser(), which takes a command name and any ArgumentParser constructor arguments, and returns an ArgumentParser object that can be modified as usual. Description of parameters: title - title for the sub-parser group in help output; by default “subcommands” if description is provided, otherwise uses title for positional arguments description - description for the sub-parser group in help output, by default None prog - usage information that will be displayed with sub-command help, by default the name of the program and any positional arguments before the subparser argument parser_class - class which will be used to create sub-parser instances, by default the class of the current parser (e.g. ArgumentParser) action - the basic type of action to be taken when this argument is encountered at the command line dest - name of the attribute under which sub-command name will be stored; by default None and no value is stored required - Whether or not a subcommand must be provided, by default False (added in 3.7) help - help for sub-parser group in help output, by default None metavar - string presenting available sub-commands in help; by default it is None and presents sub-commands in form {cmd1, cmd2, ..} Some example usage: >>> # create the top-level parser >>> parser = argparse.ArgumentParser(prog='PROG') >>> parser.add_argument('--foo', action='store_true', help='foo help') >>> subparsers = parser.add_subparsers(help='sub-command help') >>> >>> # create the parser for the "a" command >>> parser_a = subparsers.add_parser('a', help='a help') >>> parser_a.add_argument('bar', type=int, help='bar help') >>> >>> # create the parser for the "b" command >>> parser_b = subparsers.add_parser('b', help='b help') >>> parser_b.add_argument('--baz', choices='XYZ', help='baz help') >>> >>> # parse some argument lists >>> parser.parse_args(['a', '12']) Namespace(bar=12, foo=False) >>> parser.parse_args(['--foo', 'b', '--baz', 'Z']) Namespace(baz='Z', foo=True) Note that the object returned by parse_args() will only contain attributes for the main parser and the subparser that was selected by the command line (and not any other subparsers). So in the example above, when the a command is specified, only the foo and bar attributes are present, and when the b command is specified, only the foo and baz attributes are present. Similarly, when a help message is requested from a subparser, only the help for that particular parser will be printed. The help message will not include parent parser or sibling parser messages. (A help message for each subparser command, however, can be given by supplying the help= argument to add_parser() as above.) >>> parser.parse_args(['--help']) usage: PROG [-h] [--foo] {a,b} ... positional arguments: {a,b} sub-command help a a help b b help optional arguments: -h, --help show this help message and exit --foo foo help >>> parser.parse_args(['a', '--help']) usage: PROG a [-h] bar positional arguments: bar bar help optional arguments: -h, --help show this help message and exit >>> parser.parse_args(['b', '--help']) usage: PROG b [-h] [--baz {X,Y,Z}] optional arguments: -h, --help show this help message and exit --baz {X,Y,Z} baz help The add_subparsers() method also supports title and description keyword arguments. When either is present, the subparser’s commands will appear in their own group in the help output. For example: >>> parser = argparse.ArgumentParser() >>> subparsers = parser.add_subparsers(title='subcommands', ... description='valid subcommands', ... help='additional help') >>> subparsers.add_parser('foo') >>> subparsers.add_parser('bar') >>> parser.parse_args(['-h']) usage: [-h] {foo,bar} ... optional arguments: -h, --help show this help message and exit subcommands: valid subcommands {foo,bar} additional help Furthermore, add_parser supports an additional aliases argument, which allows multiple strings to refer to the same subparser. This example, like svn, aliases co as a shorthand for checkout: >>> parser = argparse.ArgumentParser() >>> subparsers = parser.add_subparsers() >>> checkout = subparsers.add_parser('checkout', aliases=['co']) >>> checkout.add_argument('foo') >>> parser.parse_args(['co', 'bar']) Namespace(foo='bar') One particularly effective way of handling sub-commands is to combine the use of the add_subparsers() method with calls to set_defaults() so that each subparser knows which Python function it should execute. For example: >>> # sub-command functions >>> def foo(args): ... print(args.x * args.y) ... >>> def bar(args): ... print('((%s))' % args.z) ... >>> # create the top-level parser >>> parser = argparse.ArgumentParser() >>> subparsers = parser.add_subparsers() >>> >>> # create the parser for the "foo" command >>> parser_foo = subparsers.add_parser('foo') >>> parser_foo.add_argument('-x', type=int, default=1) >>> parser_foo.add_argument('y', type=float) >>> parser_foo.set_defaults(func=foo) >>> >>> # create the parser for the "bar" command >>> parser_bar = subparsers.add_parser('bar') >>> parser_bar.add_argument('z') >>> parser_bar.set_defaults(func=bar) >>> >>> # parse the args and call whatever function was selected >>> args = parser.parse_args('foo 1 -x 2'.split()) >>> args.func(args) 2.0 >>> >>> # parse the args and call whatever function was selected >>> args = parser.parse_args('bar XYZYX'.split()) >>> args.func(args) ((XYZYX)) This way, you can let parse_args() do the job of calling the appropriate function after argument parsing is complete. Associating functions with actions like this is typically the easiest way to handle the different actions for each of your subparsers. However, if it is necessary to check the name of the subparser that was invoked, the dest keyword argument to the add_subparsers() call will work: >>> parser = argparse.ArgumentParser() >>> subparsers = parser.add_subparsers(dest='subparser_name') >>> subparser1 = subparsers.add_parser('1') >>> subparser1.add_argument('-x') >>> subparser2 = subparsers.add_parser('2') >>> subparser2.add_argument('y') >>> parser.parse_args(['2', 'frobble']) Namespace(subparser_name='2', y='frobble') Changed in version 3.7: New required keyword argument.
doc_27201
This signal is sent when the request is tearing down. This is always called, even if an exception is caused. Currently functions listening to this signal are called after the regular teardown handlers, but this is not something you can rely on. Example subscriber: def close_db_connection(sender, **extra): session.close() from flask import request_tearing_down request_tearing_down.connect(close_db_connection, app) As of Flask 0.9, this will also be passed an exc keyword argument that has a reference to the exception that caused the teardown if there was one.
doc_27202
The header to issue if the help output has a section for documented commands.
doc_27203
See Migration guide for more details. tf.compat.v1.raw_ops.CholeskyGrad tf.raw_ops.CholeskyGrad( l, grad, name=None ) For an explanation see "Differentiation of the Cholesky algorithm" by Iain Murray http://arxiv.org/abs/1602.07527 Args l A Tensor. Must be one of the following types: half, float32, float64. Output of batch Cholesky algorithm l = cholesky(A). Shape is [..., M, M]. Algorithm depends only on lower triangular part of the innermost matrices of this tensor. grad A Tensor. Must have the same type as l. df/dl where f is some scalar function. Shape is [..., M, M]. Algorithm depends only on lower triangular part of the innermost matrices of this tensor. name A name for the operation (optional). Returns A Tensor. Has the same type as l.
doc_27204
The number of days in the month.
doc_27205
sklearn.datasets.dump_svmlight_file(X, y, f, *, zero_based=True, comment=None, query_id=None, multilabel=False) [source] Dump the dataset in svmlight / libsvm file format. This format is a text-based format, with one sample per line. It does not store zero valued features hence is suitable for sparse dataset. The first element of each line can be used to store a target variable to predict. Parameters X{array-like, sparse matrix} of shape (n_samples, n_features) Training vectors, where n_samples is the number of samples and n_features is the number of features. y{array-like, sparse matrix}, shape = [n_samples (, n_labels)] Target values. Class labels must be an integer or float, or array-like objects of integer or float for multilabel classifications. fstring or file-like in binary mode If string, specifies the path that will contain the data. If file-like, data will be written to f. f should be opened in binary mode. zero_basedboolean, default=True Whether column indices should be written zero-based (True) or one-based (False). commentstring, default=None Comment to insert at the top of the file. This should be either a Unicode string, which will be encoded as UTF-8, or an ASCII byte string. If a comment is given, then it will be preceded by one that identifies the file as having been dumped by scikit-learn. Note that not all tools grok comments in SVMlight files. query_idarray-like of shape (n_samples,), default=None Array containing pairwise preference constraints (qid in svmlight format). multilabelboolean, default=False Samples may have several labels each (see https://www.csie.ntu.edu.tw/~cjlin/libsvmtools/datasets/multilabel.html) New in version 0.17: parameter multilabel to support multilabel datasets. Examples using sklearn.datasets.dump_svmlight_file Libsvm GUI
doc_27206
Draw Artist a only. This method can only be used after an initial draw of the figure, because that creates and caches the renderer needed here.
doc_27207
Isotonic regression model. Read more in the User Guide. New in version 0.13. Parameters y_minfloat, default=None Lower bound on the lowest predicted value (the minimum value may still be higher). If not set, defaults to -inf. y_maxfloat, default=None Upper bound on the highest predicted value (the maximum may still be lower). If not set, defaults to +inf. increasingbool or ‘auto’, default=True Determines whether the predictions should be constrained to increase or decrease with X. ‘auto’ will decide based on the Spearman correlation estimate’s sign. out_of_bounds{‘nan’, ‘clip’, ‘raise’}, default=’nan’ Handles how X values outside of the training domain are handled during prediction. ‘nan’, predictions will be NaN. ‘clip’, predictions will be set to the value corresponding to the nearest train interval endpoint. ‘raise’, a ValueError is raised. Attributes X_min_float Minimum value of input array X_ for left bound. X_max_float Maximum value of input array X_ for right bound. X_thresholds_ndarray of shape (n_thresholds,) Unique ascending X values used to interpolate the y = f(X) monotonic function. New in version 0.24. y_thresholds_ndarray of shape (n_thresholds,) De-duplicated y values suitable to interpolate the y = f(X) monotonic function. New in version 0.24. f_function The stepwise interpolating function that covers the input domain X. increasing_bool Inferred value for increasing. Notes Ties are broken using the secondary method from de Leeuw, 1977. References Isotonic Median Regression: A Linear Programming Approach Nilotpal Chakravarti Mathematics of Operations Research Vol. 14, No. 2 (May, 1989), pp. 303-308 Isotone Optimization in R : Pool-Adjacent-Violators Algorithm (PAVA) and Active Set Methods de Leeuw, Hornik, Mair Journal of Statistical Software 2009 Correctness of Kruskal’s algorithms for monotone regression with ties de Leeuw, Psychometrica, 1977 Examples >>> from sklearn.datasets import make_regression >>> from sklearn.isotonic import IsotonicRegression >>> X, y = make_regression(n_samples=10, n_features=1, random_state=41) >>> iso_reg = IsotonicRegression().fit(X, y) >>> iso_reg.predict([.1, .2]) array([1.8628..., 3.7256...]) Methods fit(X, y[, sample_weight]) Fit the model using X, y as training data. fit_transform(X[, y]) Fit to data, then transform it. get_params([deep]) Get parameters for this estimator. predict(T) Predict new data by linear interpolation. score(X, y[, sample_weight]) Return the coefficient of determination \(R^2\) of the prediction. set_params(**params) Set the parameters of this estimator. transform(T) Transform new data by linear interpolation fit(X, y, sample_weight=None) [source] Fit the model using X, y as training data. Parameters Xarray-like of shape (n_samples,) or (n_samples, 1) Training data. Changed in version 0.24: Also accepts 2d array with 1 feature. yarray-like of shape (n_samples,) Training target. sample_weightarray-like of shape (n_samples,), default=None Weights. If set to None, all weights will be set to 1 (equal weights). Returns selfobject Returns an instance of self. Notes X is stored for future use, as transform needs X to interpolate new input data. fit_transform(X, y=None, **fit_params) [source] Fit to data, then transform it. Fits transformer to X and y with optional parameters fit_params and returns a transformed version of X. Parameters Xarray-like of shape (n_samples, n_features) Input samples. yarray-like of shape (n_samples,) or (n_samples, n_outputs), default=None Target values (None for unsupervised transformations). **fit_paramsdict Additional fit parameters. Returns X_newndarray array of shape (n_samples, n_features_new) Transformed array. get_params(deep=True) [source] Get parameters for this estimator. Parameters deepbool, default=True If True, will return the parameters for this estimator and contained subobjects that are estimators. Returns paramsdict Parameter names mapped to their values. predict(T) [source] Predict new data by linear interpolation. Parameters Tarray-like of shape (n_samples,) or (n_samples, 1) Data to transform. Returns y_predndarray of shape (n_samples,) Transformed data. score(X, y, sample_weight=None) [source] Return the coefficient of determination \(R^2\) of the prediction. The coefficient \(R^2\) is defined as \((1 - \frac{u}{v})\), where \(u\) is the residual sum of squares ((y_true - y_pred) ** 2).sum() and \(v\) is the total sum of squares ((y_true - y_true.mean()) ** 2).sum(). The best possible score is 1.0 and it can be negative (because the model can be arbitrarily worse). A constant model that always predicts the expected value of y, disregarding the input features, would get a \(R^2\) score of 0.0. Parameters Xarray-like of shape (n_samples, n_features) Test samples. For some estimators this may be a precomputed kernel matrix or a list of generic objects instead with shape (n_samples, n_samples_fitted), where n_samples_fitted is the number of samples used in the fitting for the estimator. yarray-like of shape (n_samples,) or (n_samples, n_outputs) True values for X. sample_weightarray-like of shape (n_samples,), default=None Sample weights. Returns scorefloat \(R^2\) of self.predict(X) wrt. y. Notes The \(R^2\) score used when calling score on a regressor uses multioutput='uniform_average' from version 0.23 to keep consistent with default value of r2_score. This influences the score method of all the multioutput regressors (except for MultiOutputRegressor). set_params(**params) [source] Set the parameters of this estimator. The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object. Parameters **paramsdict Estimator parameters. Returns selfestimator instance Estimator instance. transform(T) [source] Transform new data by linear interpolation Parameters Tarray-like of shape (n_samples,) or (n_samples, 1) Data to transform. Changed in version 0.24: Also accepts 2d array with 1 feature. Returns y_predndarray of shape (n_samples,) The transformed data
doc_27208
Set the parameters of this estimator. The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object. Parameters **paramsdict Estimator parameters. Returns selfestimator instance Estimator instance.
doc_27209
See Migration guide for more details. tf.compat.v1.raw_ops.SerializeSparse tf.raw_ops.SerializeSparse( sparse_indices, sparse_values, sparse_shape, out_type=tf.dtypes.string, name=None ) Args sparse_indices A Tensor of type int64. 2-D. The indices of the SparseTensor. sparse_values A Tensor. 1-D. The values of the SparseTensor. sparse_shape A Tensor of type int64. 1-D. The shape of the SparseTensor. out_type An optional tf.DType from: tf.string, tf.variant. Defaults to tf.string. The dtype to use for serialization; the supported types are string (default) and variant. name A name for the operation (optional). Returns A Tensor of type out_type.
doc_27210
Similar to the max() method, but the comparison is done using the absolute values of the operands.
doc_27211
Count the non-masked elements of the array along the given axis. Parameters axisNone or int or tuple of ints, optional Axis or axes along which the count is performed. The default, None, performs the count over all the dimensions of the input array. axis may be negative, in which case it counts from the last to the first axis. New in version 1.10.0. If this is a tuple of ints, the count is performed on multiple axes, instead of a single axis or all the axes as before. keepdimsbool, optional If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the array. Returns resultndarray or scalar An array with the same shape as the input array, with the specified axis removed. If the array is a 0-d array, or if axis is None, a scalar is returned. See also ma.count_masked Count masked elements in array or along a given axis. Examples >>> import numpy.ma as ma >>> a = ma.arange(6).reshape((2, 3)) >>> a[1, :] = ma.masked >>> a masked_array( data=[[0, 1, 2], [--, --, --]], mask=[[False, False, False], [ True, True, True]], fill_value=999999) >>> a.count() 3 When the axis keyword is specified an array of appropriate size is returned. >>> a.count(axis=0) array([1, 1, 1]) >>> a.count(axis=1) array([3, 0])
doc_27212
Token value for "+=".
doc_27213
See Migration guide for more details. tf.compat.v1.raw_ops.SparseReduceMaxSparse tf.raw_ops.SparseReduceMaxSparse( input_indices, input_values, input_shape, reduction_axes, keep_dims=False, name=None ) This Op takes a SparseTensor and is the sparse counterpart to tf.reduce_max(). In contrast to SparseReduceMax, this Op returns a SparseTensor. Reduces sp_input along the dimensions given in reduction_axes. Unless keep_dims is true, the rank of the tensor is reduced by 1 for each entry in reduction_axes. If keep_dims is true, the reduced dimensions are retained with length 1. If reduction_axes has no entries, all dimensions are reduced, and a tensor with a single element is returned. Additionally, the axes can be negative, which are interpreted according to the indexing rules in Python. Args input_indices A Tensor of type int64. 2-D. N x R matrix with the indices of non-empty values in a SparseTensor, possibly not in canonical ordering. input_values A Tensor. Must be one of the following types: float32, float64, int32, uint8, int16, int8, int64, bfloat16, uint16, half, uint32, uint64. 1-D. N non-empty values corresponding to input_indices. input_shape A Tensor of type int64. 1-D. Shape of the input SparseTensor. reduction_axes A Tensor of type int32. 1-D. Length-K vector containing the reduction axes. keep_dims An optional bool. Defaults to False. If true, retain reduced dimensions with length 1. name A name for the operation (optional). Returns A tuple of Tensor objects (output_indices, output_values, output_shape). output_indices A Tensor of type int64. output_values A Tensor. Has the same type as input_values. output_shape A Tensor of type int64.
doc_27214
When used in combination with a with statement this opens a session transaction. This can be used to modify the session that the test client uses. Once the with block is left the session is stored back. with client.session_transaction() as session: session['value'] = 42 Internally this is implemented by going through a temporary test request context and since session handling could depend on request variables this function accepts the same arguments as test_request_context() which are directly passed through. Parameters args (Any) – kwargs (Any) – Return type Generator[flask.sessions.SessionMixin, None, None]
doc_27215
A memoryview and a PEP 3118 exporter are equal if their shapes are equivalent and if all corresponding values are equal when the operands’ respective format codes are interpreted using struct syntax. For the subset of struct format strings currently supported by tolist(), v and w are equal if v.tolist() == w.tolist(): >>> import array >>> a = array.array('I', [1, 2, 3, 4, 5]) >>> b = array.array('d', [1.0, 2.0, 3.0, 4.0, 5.0]) >>> c = array.array('b', [5, 3, 1]) >>> x = memoryview(a) >>> y = memoryview(b) >>> x == a == y == b True >>> x.tolist() == a.tolist() == y.tolist() == b.tolist() True >>> z = y[::-2] >>> z == c True >>> z.tolist() == c.tolist() True If either format string is not supported by the struct module, then the objects will always compare as unequal (even if the format strings and buffer contents are identical): >>> from ctypes import BigEndianStructure, c_long >>> class BEPoint(BigEndianStructure): ... _fields_ = [("x", c_long), ("y", c_long)] ... >>> point = BEPoint(100, 200) >>> a = memoryview(point) >>> b = memoryview(point) >>> a == point False >>> a == b False Note that, as with floating point numbers, v is w does not imply v == w for memoryview objects. Changed in version 3.3: Previous versions compared the raw memory disregarding the item format and the logical array structure.
doc_27216
Asserts that the strings html1 and html2 are not equal. The comparison is based on HTML semantics. See assertHTMLEqual() for details. html1 and html2 must contain HTML. An AssertionError will be raised if one of them cannot be parsed. Output in case of error can be customized with the msg argument.
doc_27217
draw an antialiased ellipse aaellipse(surface, x, y, rx, ry, color) -> None Draws an unfilled antialiased ellipse on the given surface. Parameters: surface (Surface) -- surface to draw on x (int) -- x coordinate of the center of the ellipse y (int) -- y coordinate of the center of the ellipse rx (int) -- horizontal radius of the ellipse ry (int) -- vertical radius of the ellipse color (Color or tuple(int, int, int, [int])) -- color to draw with, the alpha value is optional if using a tuple (RGB[A]) Returns: None Return type: NoneType
doc_27218
Return a with each element rounded to the given number of decimals. Refer to numpy.around for full documentation. See also numpy.around equivalent function
doc_27219
Applies a 1D max pooling over an input signal composed of several input planes. See MaxPool1d for details.
doc_27220
Moves all model parameters and buffers to the CPU. Returns self Return type Module
doc_27221
Clear the filecmp cache. This may be useful if a file is compared so quickly after it is modified that it is within the mtime resolution of the underlying filesystem. New in version 3.4.
doc_27222
re.MULTILINE When specified, the pattern character '^' matches at the beginning of the string and at the beginning of each line (immediately following each newline); and the pattern character '$' matches at the end of the string and at the end of each line (immediately preceding each newline). By default, '^' matches only at the beginning of the string, and '$' only at the end of the string and immediately before the newline (if any) at the end of the string. Corresponds to the inline flag (?m).
doc_27223
The path to the templates folder, relative to root_path, to add to the template loader. None if templates should not be added.
doc_27224
Roll provided date backward to next offset only if not on offset. Returns TimeStamp Rolled timestamp if not on offset, otherwise unchanged timestamp.
doc_27225
Repr.maxlist Repr.maxtuple Repr.maxset Repr.maxfrozenset Repr.maxdeque Repr.maxarray Limits on the number of entries represented for the named object type. The default is 4 for maxdict, 5 for maxarray, and 6 for the others.
doc_27226
Establish a network connection and return a pair of (reader, writer) objects. The returned reader and writer objects are instances of StreamReader and StreamWriter classes. The loop argument is optional and can always be determined automatically when this function is awaited from a coroutine. limit determines the buffer size limit used by the returned StreamReader instance. By default the limit is set to 64 KiB. The rest of the arguments are passed directly to loop.create_connection(). New in version 3.7: The ssl_handshake_timeout parameter.
doc_27227
Convert points to display units. You need to override this function (unless your backend doesn't have a dpi, e.g., postscript or svg). Some imaging systems assume some value for pixels per inch: points to pixels = points * pixels_per_inch/72 * dpi/72 Parameters pointsfloat or array-like a float or a numpy array of float Returns Points converted to pixels
doc_27228
Returns the population covariance as a float, or default if there aren’t any matching rows. Has one optional argument: sample By default CovarPop returns the general population covariance. However, if sample=True, the return value will be the sample population covariance.
doc_27229
Bases: matplotlib.offsetbox.OffsetBox The DrawingArea can contain any Artist as a child. The DrawingArea has a fixed width and height. The position of children relative to the parent is fixed. The children can be clipped at the boundaries of the parent. Parameters width, heightfloat Width and height of the container box. xdescent, ydescentfloat Descent of the box in x- and y-direction. clipbool Whether to clip the children to the box. add_artist(a)[source] Add an Artist to the container box. propertyclip_children If the children of this DrawingArea should be clipped by DrawingArea bounding box. draw(renderer)[source] Update the location of children if necessary and draw them to the given renderer. get_extent(renderer)[source] Return width, height, xdescent, ydescent of box. get_offset()[source] Return offset of the container. get_transform()[source] Return the Transform applied to the children. get_window_extent(renderer)[source] Get the artist's bounding box in display space. The bounding box' width and height are nonnegative. Subclasses should override for inclusion in the bounding box "tight" calculation. Default is to return an empty bounding box at 0, 0. Be careful when using this function, the results will not update if the artist window extent of the artist changes. The extent can change due to any changes in the transform stack, such as changing the axes limits, the figure size, or the canvas used (as is done when saving a figure). This can lead to unexpected behavior where interactive figures will look fine on the screen, but will save incorrectly. set(*, agg_filter=<UNSET>, alpha=<UNSET>, animated=<UNSET>, clip_box=<UNSET>, clip_on=<UNSET>, clip_path=<UNSET>, gid=<UNSET>, height=<UNSET>, in_layout=<UNSET>, label=<UNSET>, offset=<UNSET>, path_effects=<UNSET>, picker=<UNSET>, rasterized=<UNSET>, sketch_params=<UNSET>, snap=<UNSET>, transform=<UNSET>, url=<UNSET>, visible=<UNSET>, width=<UNSET>, zorder=<UNSET>)[source] Set multiple properties at once. Supported properties are Property Description agg_filter a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array alpha scalar or None animated bool clip_box Bbox clip_on bool clip_path Patch or (Path, Transform) or None figure Figure gid str height float in_layout bool label object offset (float, float) path_effects AbstractPathEffect picker None or bool or float or callable rasterized bool sketch_params (scale: float, length: float, randomness: float) snap bool or None transform unknown url str visible bool width float zorder float set_offset(xy)[source] Set the offset of the container. Parameters xy(float, float) The (x, y) coordinates of the offset in display units. set_transform(t)[source] set_transform is ignored.
doc_27230
See Migration guide for more details. tf.compat.v1.keras.layers.Add tf.keras.layers.Add( **kwargs ) It takes as input a list of tensors, all of the same shape, and returns a single tensor (also of the same shape). Examples: input_shape = (2, 3, 4) x1 = tf.random.normal(input_shape) x2 = tf.random.normal(input_shape) y = tf.keras.layers.Add()([x1, x2]) print(y.shape) (2, 3, 4) Used in a functional model: input1 = tf.keras.layers.Input(shape=(16,)) x1 = tf.keras.layers.Dense(8, activation='relu')(input1) input2 = tf.keras.layers.Input(shape=(32,)) x2 = tf.keras.layers.Dense(8, activation='relu')(input2) # equivalent to `added = tf.keras.layers.add([x1, x2])` added = tf.keras.layers.Add()([x1, x2]) out = tf.keras.layers.Dense(4)(added) model = tf.keras.models.Model(inputs=[input1, input2], outputs=out) Arguments **kwargs standard layer keyword arguments.
doc_27231
Constructs a ZoneInfo object from a file-like object returning bytes (e.g. a file opened in binary mode or an io.BytesIO object). Unlike the primary constructor, this always constructs a new object. The key parameter sets the name of the zone for the purposes of __str__() and __repr__(). Objects created via this constructor cannot be pickled (see pickling).
doc_27232
Draw a marker at each of path's vertices (excluding control points). This provides a fallback implementation of draw_markers that makes multiple calls to draw_path(). Some backends may want to override this method in order to draw the marker only once and reuse it multiple times. Parameters gcGraphicsContextBase The graphics context. marker_transmatplotlib.transforms.Transform An affine transform applied to the marker. transmatplotlib.transforms.Transform An affine transform applied to the path.
doc_27233
Returns a boolean indicating whether the geometry is three-dimensional.
doc_27234
Open FTP URLs.
doc_27235
Release the lock on the mailbox, if any.
doc_27236
Apply only the non-affine part of this transformation. transform(values) is always equivalent to transform_affine(transform_non_affine(values)). In non-affine transformations, this is generally equivalent to transform(values). In affine transformations, this is always a no-op. Parameters valuesarray The input values as NumPy array of length input_dims or shape (N x input_dims). Returns array The output values as NumPy array of length input_dims or shape (N x output_dims), depending on the input.
doc_27237
Applies the Softmax function to an n-dimensional input Tensor rescaling them so that the elements of the n-dimensional output Tensor lie in the range [0,1] and sum to 1. Softmax is defined as: Softmax(xi)=exp⁡(xi)∑jexp⁡(xj)\text{Softmax}(x_{i}) = \frac{\exp(x_i)}{\sum_j \exp(x_j)} When the input Tensor is a sparse tensor then the unspecifed values are treated as -inf. Shape: Input: (∗)(*) where * means, any number of additional dimensions Output: (∗)(*) , same shape as the input Returns a Tensor of the same dimension and shape as the input with values in the range [0, 1] Parameters dim (int) – A dimension along which Softmax will be computed (so every slice along dim will sum to 1). Note This module doesn’t work directly with NLLLoss, which expects the Log to be computed between the Softmax and itself. Use LogSoftmax instead (it’s faster and has better numerical properties). Examples: >>> m = nn.Softmax(dim=1) >>> input = torch.randn(2, 3) >>> output = m(input)
doc_27238
Bases: dict Register types with conversion interface. get_converter(x)[source] Get the converter interface instance for x, or None.
doc_27239
A tuple of line, column numbers, specifying where the error occurred.
doc_27240
Prevents an SSLv3 connection. This option is only applicable in conjunction with PROTOCOL_TLS. It prevents the peers from choosing SSLv3 as the protocol version. New in version 3.2. Deprecated since version 3.6: SSLv3 is deprecated
doc_27241
Indicate duplicate index values. Duplicated values are indicated as True values in the resulting array. Either all duplicates, all except the first, or all except the last occurrence of duplicates can be indicated. Parameters keep:{‘first’, ‘last’, False}, default ‘first’ The value or values in a set of duplicates to mark as missing. ‘first’ : Mark duplicates as True except for the first occurrence. ‘last’ : Mark duplicates as True except for the last occurrence. False : Mark all duplicates as True. Returns np.ndarray[bool] See also Series.duplicated Equivalent method on pandas.Series. DataFrame.duplicated Equivalent method on pandas.DataFrame. Index.drop_duplicates Remove duplicate values from Index. Examples By default, for each set of duplicated values, the first occurrence is set to False and all others to True: >>> idx = pd.Index(['lama', 'cow', 'lama', 'beetle', 'lama']) >>> idx.duplicated() array([False, False, True, False, True]) which is equivalent to >>> idx.duplicated(keep='first') array([False, False, True, False, True]) By using ‘last’, the last occurrence of each set of duplicated values is set on False and all others on True: >>> idx.duplicated(keep='last') array([ True, False, True, False, False]) By setting keep on False, all duplicates are True: >>> idx.duplicated(keep=False) array([ True, False, True, False, True])
doc_27242
Add a character set alias. alias is the alias name, e.g. latin-1. canonical is the character set’s canonical name, e.g. iso-8859-1. The global charset alias registry is kept in the module global dictionary ALIASES.
doc_27243
Call the set_content() method of the content_manager, passing self as the message object, and passing along any other arguments or keywords as additional arguments. If content_manager is not specified, use the content_manager specified by the current policy.
doc_27244
Returns a new tensor with the data in input fake quantized per channel using scale, zero_point, quant_min and quant_max, across the channel specified by axis. output=min(quant_max,max(quant_min,std::nearby_int(input/scale)+zero_point))\text{output} = min( \text{quant\_max}, max( \text{quant\_min}, \text{std::nearby\_int}(\text{input} / \text{scale}) + \text{zero\_point} ) ) Parameters input (Tensor) – the input value(s), in torch.float32. scale (Tensor) – quantization scale, per channel zero_point (Tensor) – quantization zero_point, per channel axis (int32) – channel axis quant_min (int64) – lower bound of the quantized domain quant_max (int64) – upper bound of the quantized domain Returns A newly fake_quantized per channel tensor Return type Tensor Example: >>> x = torch.randn(2, 2, 2) >>> x tensor([[[-0.2525, -0.0466], [ 0.3491, -0.2168]], [[-0.5906, 1.6258], [ 0.6444, -0.0542]]]) >>> scales = (torch.randn(2) + 1) * 0.05 >>> scales tensor([0.0475, 0.0486]) >>> zero_points = torch.zeros(2).to(torch.long) >>> zero_points tensor([0, 0]) >>> torch.fake_quantize_per_channel_affine(x, scales, zero_points, 1, 0, 255) tensor([[[0.0000, 0.0000], [0.3405, 0.0000]], [[0.0000, 1.6134], [0.6323, 0.0000]]])
doc_27245
lookup_name = 'time' output_field = TimeField() Changed in Django 3.2: The tzinfo parameter was added.
doc_27246
Create a new instance to handle XML-RPC requests in a CGI environment. The allow_none and encoding parameters are passed on to xmlrpc.client and control the XML-RPC responses that will be returned from the server. The use_builtin_types parameter is passed to the loads() function and controls which types are processed when date/times values or binary data are received; it defaults to false. Changed in version 3.3: The use_builtin_types flag was added.
doc_27247
Set multiple properties at once. Supported properties are Property Description agg_filter a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array alpha scalar or None animated bool clip_box Bbox clip_on bool clip_path Patch or (Path, Transform) or None figure Figure gid str height float in_layout bool label object offset (float, float) or callable path_effects AbstractPathEffect picker None or bool or float or callable rasterized bool sketch_params (scale: float, length: float, randomness: float) snap bool or None transform Transform url str visible bool width float zorder float
doc_27248
Copy the graph with its max node id. See also networkx.Graph.copy().
doc_27249
Return boolean flag, True if artist is included in layout calculations. E.g. Constrained Layout Guide, Figure.tight_layout(), and fig.savefig(fname, bbox_inches='tight').
doc_27250
Homogenize the input value for easy and efficient normalization. value can be a scalar or sequence. Returns resultmasked array Masked array with the same shape as value. is_scalarbool Whether value is a scalar. Notes Float dtypes are preserved; integer types with two bytes or smaller are converted to np.float32, and larger types are converted to np.float64. Preserving float32 when possible, and using in-place operations, greatly improves speed for large arrays.
doc_27251
x and y sticky edge lists for autoscaling. When performing autoscaling, if a data limit coincides with a value in the corresponding sticky_edges list, then no margin will be added--the view limit "sticks" to the edge. A typical use case is histograms, where one usually expects no margin on the bottom edge (0) of the histogram. Moreover, margin expansion "bumps" against sticky edges and cannot cross them. For example, if the upper data limit is 1.0, the upper view limit computed by simple margin application is 1.2, but there is a sticky edge at 1.1, then the actual upper view limit will be 1.1. This attribute cannot be assigned to; however, the x and y lists can be modified in place as needed. Examples >>> artist.sticky_edges.x[:] = (xmin, xmax) >>> artist.sticky_edges.y[:] = (ymin, ymax)
doc_27252
Parameters x – a number or a pair/vector of numbers or a turtle instance y – a number if x is a number, else None Return the distance from the turtle to (x,y), the given vector, or the given other turtle, in turtle step units. >>> turtle.home() >>> turtle.distance(30,40) 50.0 >>> turtle.distance((30,40)) 50.0 >>> joe = Turtle() >>> joe.forward(77) >>> turtle.distance(joe) 77.0
doc_27253
Return the clip path.
doc_27254
Shift the bits of an integer to the right. Bits are shifted to the right x2. Because the internal representation of numbers is in binary format, this operation is equivalent to dividing x1 by 2**x2. Parameters x1array_like, int Input values. x2array_like, int Number of bits to remove at the right of x1. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output). outndarray, None, or tuple of ndarray and None, optional A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned. A tuple (possible only as a keyword argument) must have length equal to the number of outputs. wherearray_like, optional This condition is broadcast over the input. At locations where the condition is True, the out array will be set to the ufunc result. Elsewhere, the out array will retain its original value. Note that if an uninitialized out array is created via the default out=None, locations within it where the condition is False will remain uninitialized. **kwargs For other keyword-only arguments, see the ufunc docs. Returns outndarray, int Return x1 with bits shifted x2 times to the right. This is a scalar if both x1 and x2 are scalars. See also left_shift Shift the bits of an integer to the left. binary_repr Return the binary representation of the input number as a string. Examples >>> np.binary_repr(10) '1010' >>> np.right_shift(10, 1) 5 >>> np.binary_repr(5) '101' >>> np.right_shift(10, [1,2,3]) array([5, 2, 1]) The >> operator can be used as a shorthand for np.right_shift on ndarrays. >>> x1 = 10 >>> x2 = np.array([1,2,3]) >>> x1 >> x2 array([5, 2, 1])
doc_27255
A boolean operation, ‘or’ or ‘and’. op is Or or And. values are the values involved. Consecutive operations with the same operator, such as a or b or c, are collapsed into one node with several values. This doesn’t include not, which is a UnaryOp. >>> print(ast.dump(ast.parse('x or y', mode='eval'), indent=4)) Expression( body=BoolOp( op=Or(), values=[ Name(id='x', ctx=Load()), Name(id='y', ctx=Load())]))
doc_27256
Called after the test case test has been executed, regardless of the outcome.
doc_27257
Cursor to use when the tool is active.
doc_27258
Random walker algorithm for segmentation from markers. Random walker algorithm is implemented for gray-level or multichannel images. Parameters dataarray_like Image to be segmented in phases. Gray-level data can be two- or three-dimensional; multichannel data can be three- or four- dimensional (multichannel=True) with the highest dimension denoting channels. Data spacing is assumed isotropic unless the spacing keyword argument is used. labelsarray of ints, of same shape as data without channels dimension Array of seed markers labeled with different positive integers for different phases. Zero-labeled pixels are unlabeled pixels. Negative labels correspond to inactive pixels that are not taken into account (they are removed from the graph). If labels are not consecutive integers, the labels array will be transformed so that labels are consecutive. In the multichannel case, labels should have the same shape as a single channel of data, i.e. without the final dimension denoting channels. betafloat, optional Penalization coefficient for the random walker motion (the greater beta, the more difficult the diffusion). modestring, available options {‘cg’, ‘cg_j’, ‘cg_mg’, ‘bf’} Mode for solving the linear system in the random walker algorithm. ‘bf’ (brute force): an LU factorization of the Laplacian is computed. This is fast for small images (<1024x1024), but very slow and memory-intensive for large images (e.g., 3-D volumes). ‘cg’ (conjugate gradient): the linear system is solved iteratively using the Conjugate Gradient method from scipy.sparse.linalg. This is less memory-consuming than the brute force method for large images, but it is quite slow. ‘cg_j’ (conjugate gradient with Jacobi preconditionner): the Jacobi preconditionner is applyed during the Conjugate gradient method iterations. This may accelerate the convergence of the ‘cg’ method. ‘cg_mg’ (conjugate gradient with multigrid preconditioner): a preconditioner is computed using a multigrid solver, then the solution is computed with the Conjugate Gradient method. This mode requires that the pyamg module is installed. tolfloat, optional Tolerance to achieve when solving the linear system using the conjugate gradient based modes (‘cg’, ‘cg_j’ and ‘cg_mg’). copybool, optional If copy is False, the labels array will be overwritten with the result of the segmentation. Use copy=False if you want to save on memory. multichannelbool, optional If True, input data is parsed as multichannel data (see ‘data’ above for proper input format in this case). return_full_probbool, optional If True, the probability that a pixel belongs to each of the labels will be returned, instead of only the most likely label. spacingiterable of floats, optional Spacing between voxels in each spatial dimension. If None, then the spacing between pixels/voxels in each dimension is assumed 1. prob_tolfloat, optional Tolerance on the resulting probability to be in the interval [0, 1]. If the tolerance is not satisfied, a warning is displayed. Returns outputndarray If return_full_prob is False, array of ints of same shape and data type as labels, in which each pixel has been labeled according to the marker that reached the pixel first by anisotropic diffusion. If return_full_prob is True, array of floats of shape (nlabels, labels.shape). output[label_nb, i, j] is the probability that label label_nb reaches the pixel (i, j) first. See also skimage.morphology.watershed watershed segmentation A segmentation algorithm based on mathematical morphology and “flooding” of regions from markers. Notes Multichannel inputs are scaled with all channel data combined. Ensure all channels are separately normalized prior to running this algorithm. The spacing argument is specifically for anisotropic datasets, where data points are spaced differently in one or more spatial dimensions. Anisotropic data is commonly encountered in medical imaging. The algorithm was first proposed in [1]. The algorithm solves the diffusion equation at infinite times for sources placed on markers of each phase in turn. A pixel is labeled with the phase that has the greatest probability to diffuse first to the pixel. The diffusion equation is solved by minimizing x.T L x for each phase, where L is the Laplacian of the weighted graph of the image, and x is the probability that a marker of the given phase arrives first at a pixel by diffusion (x=1 on markers of the phase, x=0 on the other markers, and the other coefficients are looked for). Each pixel is attributed the label for which it has a maximal value of x. The Laplacian L of the image is defined as: L_ii = d_i, the number of neighbors of pixel i (the degree of i) L_ij = -w_ij if i and j are adjacent pixels The weight w_ij is a decreasing function of the norm of the local gradient. This ensures that diffusion is easier between pixels of similar values. When the Laplacian is decomposed into blocks of marked and unmarked pixels: L = M B.T B A with first indices corresponding to marked pixels, and then to unmarked pixels, minimizing x.T L x for one phase amount to solving: A x = - B x_m where x_m = 1 on markers of the given phase, and 0 on other markers. This linear system is solved in the algorithm using a direct method for small images, and an iterative method for larger images. References 1 Leo Grady, Random walks for image segmentation, IEEE Trans Pattern Anal Mach Intell. 2006 Nov;28(11):1768-83. DOI:10.1109/TPAMI.2006.233. Examples >>> np.random.seed(0) >>> a = np.zeros((10, 10)) + 0.2 * np.random.rand(10, 10) >>> a[5:8, 5:8] += 1 >>> b = np.zeros_like(a, dtype=np.int32) >>> b[3, 3] = 1 # Marker for first phase >>> b[6, 6] = 2 # Marker for second phase >>> random_walker(a, b) array([[1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 2, 2, 2, 1, 1], [1, 1, 1, 1, 1, 2, 2, 2, 1, 1], [1, 1, 1, 1, 1, 2, 2, 2, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]], dtype=int32)
doc_27259
See Migration guide for more details. tf.compat.v1.truncatemod tf.truncatemod( x, y, name=None ) the result here is consistent with a truncating divide. E.g. truncate(x / y) * y + truncate_mod(x, y) = x. Note: truncatemod supports broadcasting. More about broadcasting here Args x A Tensor. Must be one of the following types: int32, int64, bfloat16, half, float32, float64. y A Tensor. Must have the same type as x. name A name for the operation (optional). Returns A Tensor. Has the same type as x.
doc_27260
Format a form in HTML.
doc_27261
Predict regression value for X. The predicted regression value of an input sample is computed as the weighted median prediction of the classifiers in the ensemble. Parameters X{array-like, sparse matrix} of shape (n_samples, n_features) The training input samples. Sparse matrix can be CSC, CSR, COO, DOK, or LIL. COO, DOK, and LIL are converted to CSR. Returns yndarray of shape (n_samples,) The predicted regression values.
doc_27262
Returns True if the distributed package is available. Otherwise, torch.distributed does not expose any other APIs. Currently, torch.distributed is available on Linux, MacOS and Windows. Set USE_DISTRIBUTED=1 to enable it when building PyTorch from source. Currently, the default value is USE_DISTRIBUTED=1 for Linux and Windows, USE_DISTRIBUTED=0 for MacOS.
doc_27263
Set if artist is to be included in layout calculations, E.g. Constrained Layout Guide, Figure.tight_layout(), and fig.savefig(fname, bbox_inches='tight'). Parameters in_layoutbool
doc_27264
Release the underlying lock. When invoked on an unlocked lock, a RuntimeError is raised.
doc_27265
Cookies that did not explicitly specify a domain cookie-attribute can only be returned to a domain equal to the domain that set the cookie (eg. spam.example.com won’t be returned cookies from example.com that had no domain cookie-attribute).
doc_27266
See Migration guide for more details. tf.compat.v1.image.generate_bounding_box_proposals tf.image.generate_bounding_box_proposals( scores, bbox_deltas, image_info, anchors, nms_threshold=0.7, pre_nms_topn=6000, min_size=16, post_nms_topn=300, name=None ) Args scores A 4-D float Tensor of shape [num_images, height, width, num_achors] containing scores of the boxes for given anchors, can be unsorted. bbox_deltas A 4-D float Tensor of shape [num_images, height, width, 4 x num_anchors] encoding boxes with respect to each anchor. Coordinates are given in the form [dy, dx, dh, dw]. image_info A 2-D float Tensor of shape [num_images, 5] containing image information Height, Width, Scale. anchors A 2-D float Tensor of shape [num_anchors, 4] describing the anchor boxes. Boxes are formatted in the form [y1, x1, y2, x2]. nms_threshold A scalar float Tensor for non-maximal-suppression threshold. Defaults to 0.7. pre_nms_topn A scalar int Tensor for the number of top scoring boxes to be used as input. Defaults to 6000. min_size A scalar float Tensor. Any box that has a smaller size than min_size will be discarded. Defaults to 16. post_nms_topn An integer. Maximum number of rois in the output. name A name for this operation (optional). Returns rois Region of interest boxes sorted by their scores. roi_probabilities scores of the ROI boxes in the ROIs' Tensor.
doc_27267
Return the greatest common divisor of the specified integer arguments. If any of the arguments is nonzero, then the returned value is the largest positive integer that is a divisor of all arguments. If all arguments are zero, then the returned value is 0. gcd() without arguments returns 0. New in version 3.5. Changed in version 3.9: Added support for an arbitrary number of arguments. Formerly, only two arguments were supported.
doc_27268
Remove categories which are not used. Parameters inplace:bool, default False Whether or not to drop unused categories inplace or return a copy of this categorical with unused categories dropped. Deprecated since version 1.2.0. Returns cat:Categorical or None Categorical with unused categories dropped or None if inplace=True. See also rename_categories Rename categories. reorder_categories Reorder categories. add_categories Add new categories. remove_categories Remove the specified categories. set_categories Set the categories to the specified ones. Examples >>> c = pd.Categorical(['a', 'c', 'b', 'c', 'd']) >>> c ['a', 'c', 'b', 'c', 'd'] Categories (4, object): ['a', 'b', 'c', 'd'] >>> c[2] = 'a' >>> c[4] = 'c' >>> c ['a', 'c', 'a', 'c', 'c'] Categories (4, object): ['a', 'b', 'c', 'd'] >>> c.remove_unused_categories() ['a', 'c', 'a', 'c', 'c'] Categories (2, object): ['a', 'c']
doc_27269
Autoscale the scalar limits on the norm instance using the current array, changing only limits that are None
doc_27270
Return the character at the given position in the window. The bottom 8 bits are the character proper, and upper bits are the attributes.
doc_27271
See Migration guide for more details. tf.compat.v1.strided_slice tf.strided_slice( input_, begin, end, strides=None, begin_mask=0, end_mask=0, ellipsis_mask=0, new_axis_mask=0, shrink_axis_mask=0, var=None, name=None ) See also tf.slice. Instead of calling this op directly most users will want to use the NumPy-style slicing syntax (e.g. tensor[..., 3:4:-1, tf.newaxis, 3]), which is supported via tf.Tensor.getitem and tf.Variable.getitem. The interface of this op is a low-level encoding of the slicing syntax. Roughly speaking, this op extracts a slice of size (end-begin)/stride from the given input_ tensor. Starting at the location specified by begin the slice continues by adding stride to the index until all dimensions are not less than end. Note that a stride can be negative, which causes a reverse slice. Given a Python slice input[spec0, spec1, ..., specn], this function will be called as follows. begin, end, and strides will be vectors of length n. n in general is not equal to the rank of the input_ tensor. In each mask field (begin_mask, end_mask, ellipsis_mask, new_axis_mask, shrink_axis_mask) the ith bit will correspond to the ith spec. If the ith bit of begin_mask is set, begin[i] is ignored and the fullest possible range in that dimension is used instead. end_mask works analogously, except with the end range. foo[5:,:,:3] on a 7x8x9 tensor is equivalent to foo[5:7,0:8,0:3]. foo[::-1] reverses a tensor with shape 8. If the ith bit of ellipsis_mask is set, as many unspecified dimensions as needed will be inserted between other dimensions. Only one non-zero bit is allowed in ellipsis_mask. For example foo[3:5,...,4:5] on a shape 10x3x3x10 tensor is equivalent to foo[3:5,:,:,4:5] and foo[3:5,...] is equivalent to foo[3:5,:,:,:]. If the ith bit of new_axis_mask is set, then begin, end, and stride are ignored and a new length 1 dimension is added at this point in the output tensor. For example, foo[:4, tf.newaxis, :2] would produce a shape (4, 1, 2) tensor. If the ith bit of shrink_axis_mask is set, it implies that the ith specification shrinks the dimensionality by 1, taking on the value at index begin[i]. end[i] and strides[i] are ignored in this case. For example in Python one might do foo[:, 3, :] which would result in shrink_axis_mask equal to 2. Note: begin and end are zero-indexed. strides entries must be non-zero. t = tf.constant([[[1, 1, 1], [2, 2, 2]], [[3, 3, 3], [4, 4, 4]], [[5, 5, 5], [6, 6, 6]]]) tf.strided_slice(t, [1, 0, 0], [2, 1, 3], [1, 1, 1]) # [[[3, 3, 3]]] tf.strided_slice(t, [1, 0, 0], [2, 2, 3], [1, 1, 1]) # [[[3, 3, 3], # [4, 4, 4]]] tf.strided_slice(t, [1, -1, 0], [2, -3, 3], [1, -1, 1]) # [[[4, 4, 4], # [3, 3, 3]]] Args input_ A Tensor. begin An int32 or int64 Tensor. end An int32 or int64 Tensor. strides An int32 or int64 Tensor. begin_mask An int32 mask. end_mask An int32 mask. ellipsis_mask An int32 mask. new_axis_mask An int32 mask. shrink_axis_mask An int32 mask. var The variable corresponding to input_ or None name A name for the operation (optional). Returns A Tensor the same type as input.
doc_27272
| NASNet-A (4 @ 1056) | 74.0 % | 91.6 % | 564 M | 5.3 | | NASNet-A (6 @ 4032) | 82.7 % | 96.2 % | 23.8 B | 88.9 | Reference: Learning Transferable Architectures for Scalable Image Recognition (CVPR 2018) Functions NASNetLarge(...): Instantiates a NASNet model in ImageNet mode. NASNetMobile(...): Instantiates a Mobile NASNet model in ImageNet mode. decode_predictions(...): Decodes the prediction of an ImageNet model. preprocess_input(...): Preprocesses a tensor or Numpy array encoding a batch of images.
doc_27273
Get parameters for this estimator. Parameters deepbool, default=True If True, will return the parameters for this estimator and contained subobjects that are estimators. Returns paramsdict Parameter names mapped to their values.
doc_27274
Sets whether to materialize output grad tensors. Default is true. This should be called only from inside the forward() method If true, undefined output grad tensors will be expanded to tensors full of zeros prior to calling the backward() method.
doc_27275
Optimize points for projection.
doc_27276
Prints the description for one or more registered options. Call with no arguments to get a listing for all registered options. Available options: compute.[use_bottleneck, use_numba, use_numexpr] display.[chop_threshold, colheader_justify, column_space, date_dayfirst, date_yearfirst, encoding, expand_frame_repr, float_format] display.html.[border, table_schema, use_mathjax] display.[large_repr] display.latex.[escape, longtable, multicolumn, multicolumn_format, multirow, repr] display.[max_categories, max_columns, max_colwidth, max_dir_items, max_info_columns, max_info_rows, max_rows, max_seq_items, memory_usage, min_rows, multi_sparse, notebook_repr_html, pprint_nest_depth, precision, show_dimensions] display.unicode.[ambiguous_as_wide, east_asian_width] display.[width] io.excel.ods.[reader, writer] io.excel.xls.[reader, writer] io.excel.xlsb.[reader] io.excel.xlsm.[reader, writer] io.excel.xlsx.[reader, writer] io.hdf.[default_format, dropna_table] io.parquet.[engine] io.sql.[engine] mode.[chained_assignment, data_manager, sim_interactive, string_storage, use_inf_as_na, use_inf_as_null] plotting.[backend] plotting.matplotlib.[register_converters] styler.format.[decimal, escape, formatter, na_rep, precision, thousands] styler.html.[mathjax] styler.latex.[environment, hrules, multicol_align, multirow_align] styler.render.[encoding, max_columns, max_elements, max_rows, repr] styler.sparse.[columns, index] Parameters pat:str Regexp pattern. All matching keys will have their description displayed. _print_desc:bool, default True If True (default) the description(s) will be printed to stdout. Otherwise, the description(s) will be returned as a unicode string (for testing). Returns None by default, the description(s) as a unicode string if _print_desc is False Notes The available options with its descriptions: compute.use_bottleneck:bool Use the bottleneck library to accelerate if it is installed, the default is True Valid values: False,True [default: True] [currently: True] compute.use_numba:bool Use the numba engine option for select operations if it is installed, the default is False Valid values: False,True [default: False] [currently: False] compute.use_numexpr:bool Use the numexpr library to accelerate computation if it is installed, the default is True Valid values: False,True [default: True] [currently: True] display.chop_threshold:float or None if set to a float value, all float values smaller then the given threshold will be displayed as exactly 0 by repr and friends. [default: None] [currently: None] display.colheader_justify:‘left’/’right’ Controls the justification of column headers. used by DataFrameFormatter. [default: right] [currently: right] display.column_space No description available. [default: 12] [currently: 12] display.date_dayfirst:boolean When True, prints and parses dates with the day first, eg 20/01/2005 [default: False] [currently: False] display.date_yearfirst:boolean When True, prints and parses dates with the year first, eg 2005/01/20 [default: False] [currently: False] display.encoding:str/unicode Defaults to the detected encoding of the console. Specifies the encoding to be used for strings returned by to_string, these are generally strings meant to be displayed on the console. [default: utf-8] [currently: utf-8] display.expand_frame_repr:boolean Whether to print out the full DataFrame repr for wide DataFrames across multiple lines, max_columns is still respected, but the output will wrap-around across multiple “pages” if its width exceeds display.width. [default: True] [currently: True] display.float_format:callable The callable should accept a floating point number and return a string with the desired format of the number. This is used in some places like SeriesFormatter. See formats.format.EngFormatter for an example. [default: None] [currently: None] display.html.border:int A border=value attribute is inserted in the <table> tag for the DataFrame HTML repr. [default: 1] [currently: 1] display.html.table_schema:boolean Whether to publish a Table Schema representation for frontends that support it. (default: False) [default: False] [currently: False] display.html.use_mathjax:boolean When True, Jupyter notebook will process table contents using MathJax, rendering mathematical expressions enclosed by the dollar symbol. (default: True) [default: True] [currently: True] display.large_repr:‘truncate’/’info’ For DataFrames exceeding max_rows/max_cols, the repr (and HTML repr) can show a truncated table (the default from 0.13), or switch to the view from df.info() (the behaviour in earlier versions of pandas). [default: truncate] [currently: truncate] display.latex.escape:bool This specifies if the to_latex method of a Dataframe uses escapes special characters. Valid values: False,True [default: True] [currently: True] display.latex.longtable :bool This specifies if the to_latex method of a Dataframe uses the longtable format. Valid values: False,True [default: False] [currently: False] display.latex.multicolumn:bool This specifies if the to_latex method of a Dataframe uses multicolumns to pretty-print MultiIndex columns. Valid values: False,True [default: True] [currently: True] display.latex.multicolumn_format:bool This specifies if the to_latex method of a Dataframe uses multicolumns to pretty-print MultiIndex columns. Valid values: False,True [default: l] [currently: l] display.latex.multirow:bool This specifies if the to_latex method of a Dataframe uses multirows to pretty-print MultiIndex rows. Valid values: False,True [default: False] [currently: False] display.latex.repr:boolean Whether to produce a latex DataFrame representation for jupyter environments that support it. (default: False) [default: False] [currently: False] display.max_categories:int This sets the maximum number of categories pandas should output when printing out a Categorical or a Series of dtype “category”. [default: 8] [currently: 8] display.max_columns:int If max_cols is exceeded, switch to truncate view. Depending on large_repr, objects are either centrally truncated or printed as a summary view. ‘None’ value means unlimited. In case python/IPython is running in a terminal and large_repr equals ‘truncate’ this can be set to 0 and pandas will auto-detect the width of the terminal and print a truncated object which fits the screen width. The IPython notebook, IPython qtconsole, or IDLE do not run in a terminal and hence it is not possible to do correct auto-detection. [default: 0] [currently: 0] display.max_colwidth:int or None The maximum width in characters of a column in the repr of a pandas data structure. When the column overflows, a “…” placeholder is embedded in the output. A ‘None’ value means unlimited. [default: 50] [currently: 50] display.max_dir_items:int The number of items that will be added to dir(…). ‘None’ value means unlimited. Because dir is cached, changing this option will not immediately affect already existing dataframes until a column is deleted or added. This is for instance used to suggest columns from a dataframe to tab completion. [default: 100] [currently: 100] display.max_info_columns:int max_info_columns is used in DataFrame.info method to decide if per column information will be printed. [default: 100] [currently: 100] display.max_info_rows:int or None df.info() will usually show null-counts for each column. For large frames this can be quite slow. max_info_rows and max_info_cols limit this null check only to frames with smaller dimensions than specified. [default: 1690785] [currently: 1690785] display.max_rows:int If max_rows is exceeded, switch to truncate view. Depending on large_repr, objects are either centrally truncated or printed as a summary view. ‘None’ value means unlimited. In case python/IPython is running in a terminal and large_repr equals ‘truncate’ this can be set to 0 and pandas will auto-detect the height of the terminal and print a truncated object which fits the screen height. The IPython notebook, IPython qtconsole, or IDLE do not run in a terminal and hence it is not possible to do correct auto-detection. [default: 60] [currently: 60] display.max_seq_items:int or None When pretty-printing a long sequence, no more then max_seq_items will be printed. If items are omitted, they will be denoted by the addition of “…” to the resulting string. If set to None, the number of items to be printed is unlimited. [default: 100] [currently: 100] display.memory_usage:bool, string or None This specifies if the memory usage of a DataFrame should be displayed when df.info() is called. Valid values True,False,’deep’ [default: True] [currently: True] display.min_rows:int The numbers of rows to show in a truncated view (when max_rows is exceeded). Ignored when max_rows is set to None or 0. When set to None, follows the value of max_rows. [default: 10] [currently: 10] display.multi_sparse:boolean “sparsify” MultiIndex display (don’t display repeated elements in outer levels within groups) [default: True] [currently: True] display.notebook_repr_html:boolean When True, IPython notebook will use html representation for pandas objects (if it is available). [default: True] [currently: True] display.pprint_nest_depth:int Controls the number of nested levels to process when pretty-printing [default: 3] [currently: 3] display.precision:int Floating point output precision in terms of number of places after the decimal, for regular formatting as well as scientific notation. Similar to precision in numpy.set_printoptions(). [default: 6] [currently: 6] display.show_dimensions:boolean or ‘truncate’ Whether to print out dimensions at the end of DataFrame repr. If ‘truncate’ is specified, only print out the dimensions if the frame is truncated (e.g. not display all rows and/or columns) [default: truncate] [currently: truncate] display.unicode.ambiguous_as_wide:boolean Whether to use the Unicode East Asian Width to calculate the display text width. Enabling this may affect to the performance (default: False) [default: False] [currently: False] display.unicode.east_asian_width:boolean Whether to use the Unicode East Asian Width to calculate the display text width. Enabling this may affect to the performance (default: False) [default: False] [currently: False] display.width:int Width of the display in characters. In case python/IPython is running in a terminal this can be set to None and pandas will correctly auto-detect the width. Note that the IPython notebook, IPython qtconsole, or IDLE do not run in a terminal and hence it is not possible to correctly detect the width. [default: 80] [currently: 80] io.excel.ods.reader:string The default Excel reader engine for ‘ods’ files. Available options: auto, odf. [default: auto] [currently: auto] io.excel.ods.writer:string The default Excel writer engine for ‘ods’ files. Available options: auto, odf. [default: auto] [currently: auto] io.excel.xls.reader:string The default Excel reader engine for ‘xls’ files. Available options: auto, xlrd. [default: auto] [currently: auto] io.excel.xls.writer:string The default Excel writer engine for ‘xls’ files. Available options: auto, xlwt. [default: auto] [currently: auto] (Deprecated, use `` instead.) io.excel.xlsb.reader:string The default Excel reader engine for ‘xlsb’ files. Available options: auto, pyxlsb. [default: auto] [currently: auto] io.excel.xlsm.reader:string The default Excel reader engine for ‘xlsm’ files. Available options: auto, xlrd, openpyxl. [default: auto] [currently: auto] io.excel.xlsm.writer:string The default Excel writer engine for ‘xlsm’ files. Available options: auto, openpyxl. [default: auto] [currently: auto] io.excel.xlsx.reader:string The default Excel reader engine for ‘xlsx’ files. Available options: auto, xlrd, openpyxl. [default: auto] [currently: auto] io.excel.xlsx.writer:string The default Excel writer engine for ‘xlsx’ files. Available options: auto, openpyxl, xlsxwriter. [default: auto] [currently: auto] io.hdf.default_format:format default format writing format, if None, then put will default to ‘fixed’ and append will default to ‘table’ [default: None] [currently: None] io.hdf.dropna_table:boolean drop ALL nan rows when appending to a table [default: False] [currently: False] io.parquet.engine:string The default parquet reader/writer engine. Available options: ‘auto’, ‘pyarrow’, ‘fastparquet’, the default is ‘auto’ [default: auto] [currently: auto] io.sql.engine:string The default sql reader/writer engine. Available options: ‘auto’, ‘sqlalchemy’, the default is ‘auto’ [default: auto] [currently: auto] mode.chained_assignment:string Raise an exception, warn, or no action if trying to use chained assignment, The default is warn [default: warn] [currently: warn] mode.data_manager:string Internal data manager type; can be “block” or “array”. Defaults to “block”, unless overridden by the ‘PANDAS_DATA_MANAGER’ environment variable (needs to be set before pandas is imported). [default: block] [currently: block] mode.sim_interactive:boolean Whether to simulate interactive mode for purposes of testing [default: False] [currently: False] mode.string_storage:string The default storage for StringDtype. [default: python] [currently: python] mode.use_inf_as_na:boolean True means treat None, NaN, INF, -INF as NA (old way), False means None and NaN are null, but INF, -INF are not NA (new way). [default: False] [currently: False] mode.use_inf_as_null:boolean use_inf_as_null had been deprecated and will be removed in a future version. Use use_inf_as_na instead. [default: False] [currently: False] (Deprecated, use mode.use_inf_as_na instead.) plotting.backend:str The plotting backend to use. The default value is “matplotlib”, the backend provided with pandas. Other backends can be specified by providing the name of the module that implements the backend. [default: matplotlib] [currently: matplotlib] plotting.matplotlib.register_converters:bool or ‘auto’. Whether to register converters with matplotlib’s units registry for dates, times, datetimes, and Periods. Toggling to False will remove the converters, restoring any converters that pandas overwrote. [default: auto] [currently: auto] styler.format.decimal:str The character representation for the decimal separator for floats and complex. [default: .] [currently: .] styler.format.escape:str, optional Whether to escape certain characters according to the given context; html or latex. [default: None] [currently: None] styler.format.formatter:str, callable, dict, optional A formatter object to be used as default within Styler.format. [default: None] [currently: None] styler.format.na_rep:str, optional The string representation for values identified as missing. [default: None] [currently: None] styler.format.precision:int The precision for floats and complex numbers. [default: 6] [currently: 6] styler.format.thousands:str, optional The character representation for thousands separator for floats, int and complex. [default: None] [currently: None] styler.html.mathjax:bool If False will render special CSS classes to table attributes that indicate Mathjax will not be used in Jupyter Notebook. [default: True] [currently: True] styler.latex.environment:str The environment to replace \begin{table}. If “longtable” is used results in a specific longtable environment format. [default: None] [currently: None] styler.latex.hrules:bool Whether to add horizontal rules on top and bottom and below the headers. [default: False] [currently: False] styler.latex.multicol_align:{“r”, “c”, “l”, “naive-l”, “naive-r”} The specifier for horizontal alignment of sparsified LaTeX multicolumns. Pipe decorators can also be added to non-naive values to draw vertical rules, e.g. “|r” will draw a rule on the left side of right aligned merged cells. [default: r] [currently: r] styler.latex.multirow_align:{“c”, “t”, “b”} The specifier for vertical alignment of sparsified LaTeX multirows. [default: c] [currently: c] styler.render.encoding:str The encoding used for output HTML and LaTeX files. [default: utf-8] [currently: utf-8] styler.render.max_columns:int, optional The maximum number of columns that will be rendered. May still be reduced to satsify max_elements, which takes precedence. [default: None] [currently: None] styler.render.max_elements:int The maximum number of data-cell (<td>) elements that will be rendered before trimming will occur over columns, rows or both if needed. [default: 262144] [currently: 262144] styler.render.max_rows:int, optional The maximum number of rows that will be rendered. May still be reduced to satsify max_elements, which takes precedence. [default: None] [currently: None] styler.render.repr:str Determine which output to use in Jupyter Notebook in {“html”, “latex”}. [default: html] [currently: html] styler.sparse.columns:bool Whether to sparsify the display of hierarchical columns. Setting to False will display each explicit level element in a hierarchical key for each column. [default: True] [currently: True] styler.sparse.index:bool Whether to sparsify the display of a hierarchical index. Setting to False will display each explicit level element in a hierarchical key for each row. [default: True] [currently: True]
doc_27277
Retrieve a module loader for the given fullname. This is a backwards compatibility wrapper around importlib.util.find_spec() that converts most failures to ImportError and only returns the loader rather than the full ModuleSpec. Changed in version 3.3: Updated to be based directly on importlib rather than relying on the package internal PEP 302 import emulation. Changed in version 3.4: Updated to be based on PEP 451
doc_27278
Join arrays r1 and r2 on key key. The key should be either a string or a sequence of string corresponding to the fields used to join the array. An exception is raised if the key field cannot be found in the two input arrays. Neither r1 nor r2 should have any duplicates along key: the presence of duplicates will make the output quite unreliable. Note that duplicates are not looked for by the algorithm. Parameters key{string, sequence} A string or a sequence of strings corresponding to the fields used for comparison. r1, r2arrays Structured arrays. jointype{‘inner’, ‘outer’, ‘leftouter’}, optional If ‘inner’, returns the elements common to both r1 and r2. If ‘outer’, returns the common elements as well as the elements of r1 not in r2 and the elements of not in r2. If ‘leftouter’, returns the common elements and the elements of r1 not in r2. r1postfixstring, optional String appended to the names of the fields of r1 that are present in r2 but absent of the key. r2postfixstring, optional String appended to the names of the fields of r2 that are present in r1 but absent of the key. defaults{dictionary}, optional Dictionary mapping field names to the corresponding default values. usemask{True, False}, optional Whether to return a MaskedArray (or MaskedRecords is asrecarray==True) or a ndarray. asrecarray{False, True}, optional Whether to return a recarray (or MaskedRecords if usemask==True) or just a flexible-type ndarray. Notes The output is sorted along the key. A temporary array is formed by dropping the fields not in the key for the two arrays and concatenating the result. This array is then sorted, and the common entries selected. The output is constructed by filling the fields with the selected entries. Matching is not preserved if there are some duplicates…
doc_27279
Return the Figure instance the artist belongs to.
doc_27280
turtle.setpos(x, y=None) turtle.setposition(x, y=None) Parameters x – a number or a pair/vector of numbers y – a number or None If y is None, x must be a pair of coordinates or a Vec2D (e.g. as returned by pos()). Move turtle to an absolute position. If the pen is down, draw line. Do not change the turtle’s orientation. >>> tp = turtle.pos() >>> tp (0.00,0.00) >>> turtle.setpos(60,30) >>> turtle.pos() (60.00,30.00) >>> turtle.setpos((20,80)) >>> turtle.pos() (20.00,80.00) >>> turtle.setpos(tp) >>> turtle.pos() (0.00,0.00)
doc_27281
gis_widget The widget class to be used for GeometryField. Defaults to OSMWidget. gis_widget_kwargs The keyword arguments that would be passed to the gis_widget. Defaults to an empty dictionary.
doc_27282
The reverse of escape(). This unescapes all the HTML entities, not only those inserted by escape. Deprecated since version 2.0: Will be removed in Werkzeug 2.1. Use MarkupSafe instead. Parameters s (str) – Return type str
doc_27283
heapq.heappush(heap, item) Push the value item onto the heap, maintaining the heap invariant. heapq.heappop(heap) Pop and return the smallest item from the heap, maintaining the heap invariant. If the heap is empty, IndexError is raised. To access the smallest item without popping it, use heap[0]. heapq.heappushpop(heap, item) Push item on the heap, then pop and return the smallest item from the heap. The combined action runs more efficiently than heappush() followed by a separate call to heappop(). heapq.heapify(x) Transform list x into a heap, in-place, in linear time. heapq.heapreplace(heap, item) Pop and return the smallest item from the heap, and also push the new item. The heap size doesn’t change. If the heap is empty, IndexError is raised. This one step operation is more efficient than a heappop() followed by heappush() and can be more appropriate when using a fixed-size heap. The pop/push combination always returns an element from the heap and replaces it with item. The value returned may be larger than the item added. If that isn’t desired, consider using heappushpop() instead. Its push/pop combination returns the smaller of the two values, leaving the larger value on the heap. The module also offers three general purpose functions based on heaps. heapq.merge(*iterables, key=None, reverse=False) Merge multiple sorted inputs into a single sorted output (for example, merge timestamped entries from multiple log files). Returns an iterator over the sorted values. Similar to sorted(itertools.chain(*iterables)) but returns an iterable, does not pull the data into memory all at once, and assumes that each of the input streams is already sorted (smallest to largest). Has two optional arguments which must be specified as keyword arguments. key specifies a key function of one argument that is used to extract a comparison key from each input element. The default value is None (compare the elements directly). reverse is a boolean value. If set to True, then the input elements are merged as if each comparison were reversed. To achieve behavior similar to sorted(itertools.chain(*iterables), reverse=True), all iterables must be sorted from largest to smallest. Changed in version 3.5: Added the optional key and reverse parameters. heapq.nlargest(n, iterable, key=None) Return a list with the n largest elements from the dataset defined by iterable. key, if provided, specifies a function of one argument that is used to extract a comparison key from each element in iterable (for example, key=str.lower). Equivalent to: sorted(iterable, key=key, reverse=True)[:n]. heapq.nsmallest(n, iterable, key=None) Return a list with the n smallest elements from the dataset defined by iterable. key, if provided, specifies a function of one argument that is used to extract a comparison key from each element in iterable (for example, key=str.lower). Equivalent to: sorted(iterable, key=key)[:n]. The latter two functions perform best for smaller values of n. For larger values, it is more efficient to use the sorted() function. Also, when n==1, it is more efficient to use the built-in min() and max() functions. If repeated usage of these functions is required, consider turning the iterable into an actual heap. Basic Examples A heapsort can be implemented by pushing all values onto a heap and then popping off the smallest values one at a time: >>> def heapsort(iterable): ... h = [] ... for value in iterable: ... heappush(h, value) ... return [heappop(h) for i in range(len(h))] ... >>> heapsort([1, 3, 5, 7, 9, 2, 4, 6, 8, 0]) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] This is similar to sorted(iterable), but unlike sorted(), this implementation is not stable. Heap elements can be tuples. This is useful for assigning comparison values (such as task priorities) alongside the main record being tracked: >>> h = [] >>> heappush(h, (5, 'write code')) >>> heappush(h, (7, 'release product')) >>> heappush(h, (1, 'write spec')) >>> heappush(h, (3, 'create tests')) >>> heappop(h) (1, 'write spec') Priority Queue Implementation Notes A priority queue is common use for a heap, and it presents several implementation challenges: Sort stability: how do you get two tasks with equal priorities to be returned in the order they were originally added? Tuple comparison breaks for (priority, task) pairs if the priorities are equal and the tasks do not have a default comparison order. If the priority of a task changes, how do you move it to a new position in the heap? Or if a pending task needs to be deleted, how do you find it and remove it from the queue? A solution to the first two challenges is to store entries as 3-element list including the priority, an entry count, and the task. The entry count serves as a tie-breaker so that two tasks with the same priority are returned in the order they were added. And since no two entry counts are the same, the tuple comparison will never attempt to directly compare two tasks. Another solution to the problem of non-comparable tasks is to create a wrapper class that ignores the task item and only compares the priority field: from dataclasses import dataclass, field from typing import Any @dataclass(order=True) class PrioritizedItem: priority: int item: Any=field(compare=False) The remaining challenges revolve around finding a pending task and making changes to its priority or removing it entirely. Finding a task can be done with a dictionary pointing to an entry in the queue. Removing the entry or changing its priority is more difficult because it would break the heap structure invariants. So, a possible solution is to mark the entry as removed and add a new entry with the revised priority: pq = [] # list of entries arranged in a heap entry_finder = {} # mapping of tasks to entries REMOVED = '<removed-task>' # placeholder for a removed task counter = itertools.count() # unique sequence count def add_task(task, priority=0): 'Add a new task or update the priority of an existing task' if task in entry_finder: remove_task(task) count = next(counter) entry = [priority, count, task] entry_finder[task] = entry heappush(pq, entry) def remove_task(task): 'Mark an existing task as REMOVED. Raise KeyError if not found.' entry = entry_finder.pop(task) entry[-1] = REMOVED def pop_task(): 'Remove and return the lowest priority task. Raise KeyError if empty.' while pq: priority, count, task = heappop(pq) if task is not REMOVED: del entry_finder[task] return task raise KeyError('pop from an empty priority queue') Theory Heaps are arrays for which a[k] <= a[2*k+1] and a[k] <= a[2*k+2] for all k, counting elements from 0. For the sake of comparison, non-existing elements are considered to be infinite. The interesting property of a heap is that a[0] is always its smallest element. The strange invariant above is meant to be an efficient memory representation for a tournament. The numbers below are k, not a[k]: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 In the tree above, each cell k is topping 2*k+1 and 2*k+2. In a usual binary tournament we see in sports, each cell is the winner over the two cells it tops, and we can trace the winner down the tree to see all opponents s/he had. However, in many computer applications of such tournaments, we do not need to trace the history of a winner. To be more memory efficient, when a winner is promoted, we try to replace it by something else at a lower level, and the rule becomes that a cell and the two cells it tops contain three different items, but the top cell “wins” over the two topped cells. If this heap invariant is protected at all time, index 0 is clearly the overall winner. The simplest algorithmic way to remove it and find the “next” winner is to move some loser (let’s say cell 30 in the diagram above) into the 0 position, and then percolate this new 0 down the tree, exchanging values, until the invariant is re-established. This is clearly logarithmic on the total number of items in the tree. By iterating over all items, you get an O(n log n) sort. A nice feature of this sort is that you can efficiently insert new items while the sort is going on, provided that the inserted items are not “better” than the last 0’th element you extracted. This is especially useful in simulation contexts, where the tree holds all incoming events, and the “win” condition means the smallest scheduled time. When an event schedules other events for execution, they are scheduled into the future, so they can easily go into the heap. So, a heap is a good structure for implementing schedulers (this is what I used for my MIDI sequencer :-). Various structures for implementing schedulers have been extensively studied, and heaps are good for this, as they are reasonably speedy, the speed is almost constant, and the worst case is not much different than the average case. However, there are other representations which are more efficient overall, yet the worst cases might be terrible. Heaps are also very useful in big disk sorts. You most probably all know that a big sort implies producing “runs” (which are pre-sorted sequences, whose size is usually related to the amount of CPU memory), followed by a merging passes for these runs, which merging is often very cleverly organised 1. It is very important that the initial sort produces the longest runs possible. Tournaments are a good way to achieve that. If, using all the memory available to hold a tournament, you replace and percolate items that happen to fit the current run, you’ll produce runs which are twice the size of the memory for random input, and much better for input fuzzily ordered. Moreover, if you output the 0’th item on disk and get an input which may not fit in the current tournament (because the value “wins” over the last output value), it cannot fit in the heap, so the size of the heap decreases. The freed memory could be cleverly reused immediately for progressively building a second heap, which grows at exactly the same rate the first heap is melting. When the first heap completely vanishes, you switch heaps and start a new run. Clever and quite effective! In a word, heaps are useful memory structures to know. I use them in a few applications, and I think it is good to keep a ‘heap’ module around. :-) Footnotes 1 The disk balancing algorithms which are current, nowadays, are more annoying than clever, and this is a consequence of the seeking capabilities of the disks. On devices which cannot seek, like big tape drives, the story was quite different, and one had to be very clever to ensure (far in advance) that each tape movement will be the most effective possible (that is, will best participate at “progressing” the merge). Some tapes were even able to read backwards, and this was also used to avoid the rewinding time. Believe me, real good tape sorts were quite spectacular to watch! From all times, sorting has always been a Great Art! :-)
doc_27284
window.vline(y, x, ch, n) Display a vertical line starting at (y, x) with length n consisting of the character ch.
doc_27285
Bases: matplotlib.offsetbox.PackerBase HPacker packs its children horizontally, automatically adjusting their relative positions at draw time. Parameters padfloat, optional The boundary padding in points. sepfloat, optional The spacing between items in points. width, heightfloat, optional Width and height of the container box in pixels, calculated if None. align{'top', 'bottom', 'left', 'right', 'center', 'baseline'}, default: 'baseline' Alignment of boxes. mode{'fixed', 'expand', 'equal'}, default: 'fixed' The packing mode. 'fixed' packs the given Artists tight with sep spacing. 'expand' uses the maximal available space to distribute the artists with equal spacing in between. 'equal': Each artist an equal fraction of the available space and is left-aligned (or top-aligned) therein. childrenlist of Artist The artists to pack. Notes pad and sep are in points and will be scaled with the renderer dpi, while width and height are in pixels. get_extent_offsets(renderer)[source] Update offset of the children and return the extent of the box. Parameters rendererRendererBase subclass Returns width height xdescent ydescent list of (xoffset, yoffset) pairs set(*, agg_filter=<UNSET>, alpha=<UNSET>, animated=<UNSET>, clip_box=<UNSET>, clip_on=<UNSET>, clip_path=<UNSET>, gid=<UNSET>, height=<UNSET>, in_layout=<UNSET>, label=<UNSET>, offset=<UNSET>, path_effects=<UNSET>, picker=<UNSET>, rasterized=<UNSET>, sketch_params=<UNSET>, snap=<UNSET>, transform=<UNSET>, url=<UNSET>, visible=<UNSET>, width=<UNSET>, zorder=<UNSET>)[source] Set multiple properties at once. Supported properties are Property Description agg_filter a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array alpha scalar or None animated bool clip_box Bbox clip_on bool clip_path Patch or (Path, Transform) or None figure Figure gid str height float in_layout bool label object offset (float, float) or callable path_effects AbstractPathEffect picker None or bool or float or callable rasterized bool sketch_params (scale: float, length: float, randomness: float) snap bool or None transform Transform url str visible bool width float zorder float
doc_27286
This signal is sent when a template was successfully rendered. The signal is invoked with the instance of the template as template and the context as dictionary (named context). Example subscriber: def log_template_renders(sender, template, context, **extra): sender.logger.debug('Rendering template "%s" with context %s', template.name or 'string template', context) from flask import template_rendered template_rendered.connect(log_template_renders, app)
doc_27287
This class is used to serve either files or output of CGI scripts from the current directory and below. Note that mapping HTTP hierarchic structure to local directory structure is exactly as in SimpleHTTPRequestHandler. Note CGI scripts run by the CGIHTTPRequestHandler class cannot execute redirects (HTTP code 302), because code 200 (script output follows) is sent prior to execution of the CGI script. This pre-empts the status code. The class will however, run the CGI script, instead of serving it as a file, if it guesses it to be a CGI script. Only directory-based CGI are used — the other common server configuration is to treat special extensions as denoting CGI scripts. The do_GET() and do_HEAD() functions are modified to run CGI scripts and serve the output, instead of serving files, if the request leads to somewhere below the cgi_directories path. The CGIHTTPRequestHandler defines the following data member: cgi_directories This defaults to ['/cgi-bin', '/htbin'] and describes directories to treat as containing CGI scripts. The CGIHTTPRequestHandler defines the following method: do_POST() This method serves the 'POST' request type, only allowed for CGI scripts. Error 501, “Can only POST to CGI scripts”, is output when trying to POST to a non-CGI url. Note that CGI scripts will be run with UID of user nobody, for security reasons. Problems with the CGI script will be translated to error 403.
doc_27288
Partition (split) each element around the right-most separator. Calls str.rpartition element-wise. For each element in a, split the element as the last occurrence of sep, and return 3 strings containing the part before the separator, the separator itself, and the part after the separator. If the separator is not found, return 3 strings containing the string itself, followed by two empty strings. Parameters aarray_like of str or unicode Input array sepstr or unicode Right-most separator to split each element in array. Returns outndarray Output array of string or unicode, depending on input type. The output array will have an extra dimension with 3 elements per input element. See also str.rpartition
doc_27289
A list of CSS classes used for weekday names in the header row. The default is the same as cssclasses. New in version 3.7.
doc_27290
Set the axis view limits. This method is for internal use; Matplotlib users should typically use e.g. set_xlim or set_ylim. If ignore is False (the default), this method will never reduce the preexisting view limits, only expand them if vmin or vmax are not within them. Moreover, the order of vmin and vmax does not matter; the orientation of the axis will not change. If ignore is True, the view limits will be set exactly to (vmin, vmax) in that order.
doc_27291
Casts all floating point parameters and buffers to double datatype. Returns self Return type Module
doc_27292
Pulls all flashed messages from the session and returns them. Further calls in the same request to the function will return the same messages. By default just the messages are returned, but when with_categories is set to True, the return value will be a list of tuples in the form (category, message) instead. Filter the flashed messages to one or more categories by providing those categories in category_filter. This allows rendering categories in separate html blocks. The with_categories and category_filter arguments are distinct: with_categories controls whether categories are returned with message text (True gives a tuple, where False gives just the message text). category_filter filters the messages down to only those matching the provided categories. See Message Flashing for examples. Changelog Changed in version 0.9: category_filter parameter added. Changed in version 0.3: with_categories parameter added. Parameters with_categories (bool) – set to True to also receive categories. category_filter (Iterable[str]) – filter of categories to limit return values. Only categories in the list will be returned. Return type Union[List[str], List[Tuple[str, str]]]
doc_27293
Re-initialize the major and minor Tick lists. Each list starts with a single fresh Tick.
doc_27294
Return a new string with backslashes in str replaced by two backslashes, and double quotes replaced by backslash-double quote.
doc_27295
Initialize the terminal. term is a string giving the terminal name, or None; if omitted or None, the value of the TERM environment variable will be used. fd is the file descriptor to which any initialization sequences will be sent; if not supplied or -1, the file descriptor for sys.stdout will be used.
doc_27296
Return the list of items for a given key. If that key is not in the MultiDict, the return value will be an empty list. Just like get, getlist accepts a type parameter. All items will be converted with the callable defined there. Parameters key – The key to be looked up. type – A callable that is used to cast the value in the MultiDict. If a ValueError is raised by this callable the value will be removed from the list. Returns a list of all the values for the key.
doc_27297
Convert Matplotlib dates to datetime objects. Parameters xfloat or sequence of floats Number of days (fraction part represents hours, minutes, seconds) since the epoch. See get_epoch for the epoch, which can be changed by rcParams["date.epoch"] (default: '1970-01-01T00:00:00') or set_epoch. tzstr, default: rcParams["timezone"] (default: 'UTC') Timezone of x. Returns datetime or sequence of datetime Dates are returned in timezone tz. If x is a sequence, a sequence of datetime objects will be returned. Notes The addition of one here is a historical artifact. Also, note that the Gregorian calendar is assumed; this is not universal practice. For details, see the module docstring.
doc_27298
Compares fromlines and tolines (lists of strings) and returns a string which is a complete HTML file containing a table showing line by line differences with inter-line and intra-line changes highlighted. fromdesc and todesc are optional keyword arguments to specify from/to file column header strings (both default to an empty string). context and numlines are both optional keyword arguments. Set context to True when contextual differences are to be shown, else the default is False to show the full files. numlines defaults to 5. When context is True numlines controls the number of context lines which surround the difference highlights. When context is False numlines controls the number of lines which are shown before a difference highlight when using the “next” hyperlinks (setting to zero would cause the “next” hyperlinks to place the next difference highlight at the top of the browser without any leading context). Note fromdesc and todesc are interpreted as unescaped HTML and should be properly escaped while receiving input from untrusted sources. Changed in version 3.5: charset keyword-only argument was added. The default charset of HTML document changed from 'ISO-8859-1' to 'utf-8'.
doc_27299
See Migration guide for more details. tf.compat.v1.truncatediv tf.truncatediv( x, y, name=None ) Truncation designates that negative numbers will round fractional quantities toward zero. I.e. -7 / 5 = -1. This matches C semantics but it is different than Python semantics. See FloorDiv for a division function that matches Python Semantics. Note: truncatediv supports broadcasting. More about broadcasting here Args x A Tensor. Must be one of the following types: bfloat16, half, float32, float64, uint8, int8, uint16, int16, int32, int64, complex64, complex128. y A Tensor. Must have the same type as x. name A name for the operation (optional). Returns A Tensor. Has the same type as x.