_id
stringlengths
5
9
text
stringlengths
5
385k
title
stringclasses
1 value
doc_30100
Pytest specific decorator for parametrizing estimator checks. The id of each check is set to be a pprint version of the estimator and the name of the check with its keyword arguments. This allows to use pytest -k to specify which tests to run: pytest test_check_estimators.py -k check_estimators_fit_returns_self Parameters estimatorslist of estimators instances Estimators to generated checks for. Changed in version 0.24: Passing a class was deprecated in version 0.23, and support for classes was removed in 0.24. Pass an instance instead. New in version 0.24. Returns decoratorpytest.mark.parametrize Examples >>> from sklearn.utils.estimator_checks import parametrize_with_checks >>> from sklearn.linear_model import LogisticRegression >>> from sklearn.tree import DecisionTreeRegressor >>> @parametrize_with_checks([LogisticRegression(), ... DecisionTreeRegressor()]) ... def test_sklearn_compatible_estimator(estimator, check): ... check(estimator)
doc_30101
Computes the (weighted) graph of Neighbors for points in X Neighborhoods are restricted the points at a distance lower than radius. Parameters Xarray-like of shape (n_samples, n_features), default=None The query point or points. If not provided, neighbors of each indexed point are returned. In this case, the query point is not considered its own neighbor. radiusfloat, default=None Radius of neighborhoods. The default is the value passed to the constructor. mode{‘connectivity’, ‘distance’}, default=’connectivity’ Type of returned matrix: ‘connectivity’ will return the connectivity matrix with ones and zeros, in ‘distance’ the edges are Euclidean distance between points. sort_resultsbool, default=False If True, in each row of the result, the non-zero entries will be sorted by increasing distances. If False, the non-zero entries may not be sorted. Only used with mode=’distance’. New in version 0.22. Returns Asparse-matrix of shape (n_queries, n_samples_fit) n_samples_fit is the number of samples in the fitted data A[i, j] is assigned the weight of edge that connects i to j. The matrix if of format CSR. See also kneighbors_graph Examples >>> X = [[0], [3], [1]] >>> from sklearn.neighbors import NearestNeighbors >>> neigh = NearestNeighbors(radius=1.5) >>> neigh.fit(X) NearestNeighbors(radius=1.5) >>> A = neigh.radius_neighbors_graph(X) >>> A.toarray() array([[1., 0., 1.], [0., 1., 0.], [1., 0., 1.]])
doc_30102
shell Returns the shell or exterior ring of this polygon, as a LinearRing geometry. exterior_ring An alias for shell. centroid Returns a Point representing the centroid of this polygon.
doc_30103
Returns a list of ByteTensor representing the random number states of all devices.
doc_30104
Return the buffer size needed for recvmsg() to receive an ancillary data item with associated data of the given length, along with any trailing padding. The buffer space needed to receive multiple items is the sum of the CMSG_SPACE() values for their associated data lengths. Raises OverflowError if length is outside the permissible range of values. Note that some systems might support ancillary data without providing this function. Also note that setting the buffer size using the results of this function may not precisely limit the amount of ancillary data that can be received, since additional data may be able to fit into the padding area. Availability: most Unix platforms, possibly others. New in version 3.3.
doc_30105
Return True if it is a character device.
doc_30106
Applies a 2D convolution over a quantized 2D input composed of several input planes. See Conv2d for details and output shape. Parameters input – quantized input tensor of shape (minibatch,in_channels,iH,iW)(\text{minibatch} , \text{in\_channels} , iH , iW) weight – quantized filters of shape (out_channels,in_channelsgroups,kH,kW)(\text{out\_channels} , \frac{\text{in\_channels}}{\text{groups}} , kH , kW) bias – non-quantized bias tensor of shape (out_channels)(\text{out\_channels}) . The tensor type must be torch.float. stride – the stride of the convolving kernel. Can be a single number or a tuple (sH, sW). Default: 1 padding – implicit paddings on both sides of the input. Can be a single number or a tuple (padH, padW). Default: 0 dilation – the spacing between kernel elements. Can be a single number or a tuple (dH, dW). Default: 1 groups – split input into groups, in_channels\text{in\_channels} should be divisible by the number of groups. Default: 1 padding_mode – the padding mode to use. Only “zeros” is supported for quantized convolution at the moment. Default: “zeros” scale – quantization scale for the output. Default: 1.0 zero_point – quantization zero_point for the output. Default: 0 dtype – quantization data type to use. Default: torch.quint8 Examples: >>> from torch.nn.quantized import functional as qF >>> filters = torch.randn(8, 4, 3, 3, dtype=torch.float) >>> inputs = torch.randn(1, 4, 5, 5, dtype=torch.float) >>> bias = torch.randn(8, dtype=torch.float) >>> >>> scale, zero_point = 1.0, 0 >>> dtype_inputs = torch.quint8 >>> dtype_filters = torch.qint8 >>> >>> q_filters = torch.quantize_per_tensor(filters, scale, zero_point, dtype_filters) >>> q_inputs = torch.quantize_per_tensor(inputs, scale, zero_point, dtype_inputs) >>> qF.conv2d(q_inputs, q_filters, bias, padding=1, scale=scale, zero_point=zero_point)
doc_30107
Return the Transform applied to the children
doc_30108
GridSpec(nrows, ncols[, figure, left, ...]) A grid layout to place subplots within a figure. SubplotSpec(gridspec, num1[, num2]) The location of a subplot in a GridSpec. GridSpecBase(nrows, ncols[, height_ratios, ...]) A base class of GridSpec that specifies the geometry of the grid that a subplot will be placed. GridSpecFromSubplotSpec(nrows, ncols, ...[, ...]) GridSpec whose subplot layout parameters are inherited from the location specified by a given SubplotSpec.
doc_30109
Compute sum of group values. Parameters numeric_only:bool, default True Include only float, int, boolean columns. If None, will attempt to use everything, then use only numeric data. min_count:int, default 0 The required number of valid values to perform the operation. If fewer than min_count non-NA values are present the result will be NA. Returns Series or DataFrame Computed sum of values within each group.
doc_30110
Possible value for SSLContext.verify_flags. In this mode, certificate revocation lists (CRLs) are not checked. By default OpenSSL does neither require nor verify CRLs. New in version 3.4.
doc_30111
See Migration guide for more details. tf.compat.v1.quantization.quantized_concat, tf.compat.v1.quantized_concat tf.quantization.quantized_concat( concat_dim, values, input_mins, input_maxes, name=None ) Args concat_dim A Tensor of type int32. 0-D. The dimension along which to concatenate. Must be in the range [0, rank(values)). values A list of at least 2 Tensor objects with the same type. The N Tensors to concatenate. Their ranks and types must match, and their sizes must match in all dimensions except concat_dim. input_mins A list with the same length as values of Tensor objects with type float32. The minimum scalar values for each of the input tensors. input_maxes A list with the same length as values of Tensor objects with type float32. The maximum scalar values for each of the input tensors. name A name for the operation (optional). Returns A tuple of Tensor objects (output, output_min, output_max). output A Tensor. Has the same type as values. output_min A Tensor of type float32. output_max A Tensor of type float32.
doc_30112
DictFormatter(format_dict[, formatter]) format_dict : dictionary for format strings to be used. ExtremeFinderSimple(nx, ny) A helper class to figure out the range of grid lines that need to be drawn. FixedLocator(locs) FormatterPrettyPrint([useMathText]) GridFinder(transform[, extreme_finder, ...]) transform : transform from the image coordinate (which will be the transData of the axes to the world coordinate. MaxNLocator([nbins, steps, trim, integer, ...]) Parameters
doc_30113
tf.random.experimental.create_rng_state Compat aliases for migration See Migration guide for more details. tf.compat.v1.random.create_rng_state, tf.compat.v1.random.experimental.create_rng_state tf.random.create_rng_state( seed, alg ) Example: tf.random.create_rng_state( 1234, "philox") array([1234, 0, 0]) tf.random.create_rng_state( [12, 34], "threefry") array([12, 34]) Args seed an integer or 1-D numpy array. alg the RNG algorithm. Can be a string, an Algorithm or an integer. Returns a 1-D numpy array whose size depends on the algorithm.
doc_30114
Return the array with the same data viewed with a different byte order. Equivalent to: arr.view(arr.dtype.newbytorder(new_order)) Changes are also made in all fields and sub-arrays of the array data type. Parameters new_orderstring, optional Byte order to force; a value from the byte order specifications below. new_order codes can be any of: ‘S’ - swap dtype from current to opposite endian {‘<’, ‘little’} - little endian {‘>’, ‘big’} - big endian {‘=’, ‘native’} - native order, equivalent to sys.byteorder {‘|’, ‘I’} - ignore (no change to byte order) The default value (‘S’) results in swapping the current byte order. Returns new_arrarray New array object with the dtype reflecting given change to the byte order.
doc_30115
Token value for "<<=".
doc_30116
exception that pygame.midi functions and classes can raise MidiException(errno) -> None
doc_30117
Return the array with the same data viewed with a different byte order. Equivalent to: arr.view(arr.dtype.newbytorder(new_order)) Changes are also made in all fields and sub-arrays of the array data type. Parameters new_orderstring, optional Byte order to force; a value from the byte order specifications below. new_order codes can be any of: ‘S’ - swap dtype from current to opposite endian {‘<’, ‘little’} - little endian {‘>’, ‘big’} - big endian {‘=’, ‘native’} - native order, equivalent to sys.byteorder {‘|’, ‘I’} - ignore (no change to byte order) The default value (‘S’) results in swapping the current byte order. Returns new_arrarray New array object with the dtype reflecting given change to the byte order.
doc_30118
Add 2D bar(s). Parameters left1D array-like The x coordinates of the left sides of the bars. height1D array-like The height of the bars. zsfloat or 1D array-like Z coordinate of bars; if a single value is specified, it will be used for all bars. zdir{'x', 'y', 'z'}, default: 'z' When plotting 2D data, the direction to use as z ('x', 'y' or 'z'). dataindexable object, optional If given, all parameters also accept a string s, which is interpreted as data[s] (unless this raises an exception). **kwargs Other arguments are forwarded to matplotlib.axes.Axes.bar. Returns mpl_toolkits.mplot3d.art3d.Patch3DCollection
doc_30119
Alias for get_facecolor.
doc_30120
Returns whether or not the set of points in the geometry is empty.
doc_30121
Bases: matplotlib.patches.ArrowStyle._Curve An arrow with filled triangle head at the end. Parameters head_lengthfloat, default: 0.4 Length of the arrow head, relative to mutation_scale. head_widthfloat, default: 0.2 Width of the arrow head, relative to mutation_scale. widthAfloat, default: 1.0 Width of the bracket at the beginning of the arrow widthBfloat, default: 1.0 Width of the bracket at the end of the arrow lengthAfloat, default: 0.2 Length of the bracket at the beginning of the arrow lengthBfloat, default: 0.2 Length of the bracket at the end of the arrow angleAfloat, default 0 Orientation of the bracket at the beginning, as a counterclockwise angle. 0 degrees means perpendicular to the line. angleBfloat, default 0 Orientation of the bracket at the beginning, as a counterclockwise angle. 0 degrees means perpendicular to the line. scaleAfloat, default mutation_size The mutation_size for the beginning bracket scaleBfloat, default mutation_size The mutation_size for the end bracket arrow='-|>'
doc_30122
Bases: collections.abc.MutableMapping The container of all Spines in an Axes. The interface is dict-like mapping names (e.g. 'left') to Spine objects. Additionally it implements some pandas.Series-like features like accessing elements by attribute: spines['top'].set_visible(False) spines.top.set_visible(False) Multiple spines can be addressed simultaneously by passing a list: spines[['top', 'right']].set_visible(False) Use an open slice to address all spines: spines[:].set_visible(False) The latter two indexing methods will return a SpinesProxy that broadcasts all set_* calls to its members, but cannot be used for any other operation. classmethodfrom_dict(d)[source]
doc_30123
The maximum length (in bytes) of the field. The maximum length is enforced in Django’s validation using MaxLengthValidator.
doc_30124
Return the visibility.
doc_30125
When a BabylMessage instance’s original headers are modified, the visible headers are not automatically modified to correspond. This method updates the visible headers as follows: each visible header with a corresponding original header is set to the value of the original header, each visible header without a corresponding original header is removed, and any of Date, From, Reply-To, To, CC, and Subject that are present in the original headers but not the visible headers are added to the visible headers.
doc_30126
Acquire a semaphore. If the internal counter is greater than zero, decrement it by one and return True immediately. If it is zero, wait until a release() is called and return True.
doc_30127
Sums the product of the elements of the input operands along dimensions specified using a notation based on the Einstein summation convention. Einsum allows computing many common multi-dimensional linear algebraic array operations by representing them in a short-hand format based on the Einstein summation convention, given by equation. The details of this format are described below, but the general idea is to label every dimension of the input operands with some subscript and define which subscripts are part of the output. The output is then computed by summing the product of the elements of the operands along the dimensions whose subscripts are not part of the output. For example, matrix multiplication can be computed using einsum as torch.einsum(“ij,jk->ik”, A, B). Here, j is the summation subscript and i and k the output subscripts (see section below for more details on why). Equation: The equation string specifies the subscripts (lower case letters [‘a’, ‘z’]) for each dimension of the input operands in the same order as the dimensions, separating subcripts for each operand by a comma (‘,’), e.g. ‘ij,jk’ specify subscripts for two 2D operands. The dimensions labeled with the same subscript must be broadcastable, that is, their size must either match or be 1. The exception is if a subscript is repeated for the same input operand, in which case the dimensions labeled with this subscript for this operand must match in size and the operand will be replaced by its diagonal along these dimensions. The subscripts that appear exactly once in the equation will be part of the output, sorted in increasing alphabetical order. The output is computed by multiplying the input operands element-wise, with their dimensions aligned based on the subscripts, and then summing out the dimensions whose subscripts are not part of the output. Optionally, the output subscripts can be explicitly defined by adding an arrow (‘->’) at the end of the equation followed by the subscripts for the output. For instance, the following equation computes the transpose of a matrix multiplication: ‘ij,jk->ki’. The output subscripts must appear at least once for some input operand and at most once for the output. Ellipsis (‘…’) can be used in place of subscripts to broadcast the dimensions covered by the ellipsis. Each input operand may contain at most one ellipsis which will cover the dimensions not covered by subscripts, e.g. for an input operand with 5 dimensions, the ellipsis in the equation ‘ab…c’ cover the third and fourth dimensions. The ellipsis does not need to cover the same number of dimensions across the operands but the ‘shape’ of the ellipsis (the size of the dimensions covered by them) must broadcast together. If the output is not explicitly defined with the arrow (‘->’) notation, the ellipsis will come first in the output (left-most dimensions), before the subscript labels that appear exactly once for the input operands. e.g. the following equation implements batch matrix multiplication ‘…ij,…jk’. A few final notes: the equation may contain whitespaces between the different elements (subscripts, ellipsis, arrow and comma) but something like ‘…’ is not valid. An empty string ‘’ is valid for scalar operands. Note torch.einsum handles ellipsis (‘…’) differently from NumPy in that it allows dimensions covered by the ellipsis to be summed over, that is, ellipsis are not required to be part of the output. Note This function does not optimize the given expression, so a different formula for the same computation may run faster or consume less memory. Projects like opt_einsum (https://optimized-einsum.readthedocs.io/en/stable/) can optimize the formula for you. Parameters equation (string) – The subscripts for the Einstein summation. operands (Tensor) – The operands to compute the Einstein sum of. Examples: # trace >>> torch.einsum('ii', torch.randn(4, 4)) tensor(-1.2104) # diagonal >>> torch.einsum('ii->i', torch.randn(4, 4)) tensor([-0.1034, 0.7952, -0.2433, 0.4545]) # outer product >>> x = torch.randn(5) >>> y = torch.randn(4) >>> torch.einsum('i,j->ij', x, y) tensor([[ 0.1156, -0.2897, -0.3918, 0.4963], [-0.3744, 0.9381, 1.2685, -1.6070], [ 0.7208, -1.8058, -2.4419, 3.0936], [ 0.1713, -0.4291, -0.5802, 0.7350], [ 0.5704, -1.4290, -1.9323, 2.4480]]) # batch matrix multiplication >>> As = torch.randn(3,2,5) >>> Bs = torch.randn(3,5,4) >>> torch.einsum('bij,bjk->bik', As, Bs) tensor([[[-1.0564, -1.5904, 3.2023, 3.1271], [-1.6706, -0.8097, -0.8025, -2.1183]], [[ 4.2239, 0.3107, -0.5756, -0.2354], [-1.4558, -0.3460, 1.5087, -0.8530]], [[ 2.8153, 1.8787, -4.3839, -1.2112], [ 0.3728, -2.1131, 0.0921, 0.8305]]]) # batch permute >>> A = torch.randn(2, 3, 4, 5) >>> torch.einsum('...ij->...ji', A).shape torch.Size([2, 3, 5, 4]) # equivalent to torch.nn.functional.bilinear >>> A = torch.randn(3,5,4) >>> l = torch.randn(2,5) >>> r = torch.randn(2,4) >>> torch.einsum('bn,anm,bm->ba', l, A, r) tensor([[-0.3430, -5.2405, 0.4494], [ 0.3311, 5.5201, -3.0356]])
doc_30128
Return the square root of the argument to full precision.
doc_30129
See Migration guide for more details. tf.compat.v1.config.experimental.get_device_details tf.config.experimental.get_device_details( device ) This API takes in a tf.config.PhysicalDevice returned by tf.config.list_physical_devices. It returns a dict with string keys containing various details about the device. Each key is only supported by a subset of devices, so you should not assume the returned dict will have any particular key. gpu_devices = tf.config.list_physical_devices('GPU') if gpu_devices: details = tf.config.experimental.get_device_details(gpu_devices[0]) details.get('device_name', 'Unknown GPU') Currently, details are only returned for GPUs. This function returns an empty dict if passed a non-GPU device. The returned dict may have the following keys: 'device_name': A human-readable name of the device as a string, e.g. "Titan V". Unlike tf.config.PhysicalDevice.name, this will be the same for multiple devices if each device is the same model. Currently only available for GPUs. 'compute_capability': The compute capability of the device as a tuple of two ints, in the form (major_version, minor_version). Only available for NVIDIA GPUs Note: This is similar to tf.sysconfig.get_build_info in that both functions can return information relating to GPUs. However, this function returns run-time information about a specific device (such as a GPU's compute capability), while tf.sysconfig.get_build_info returns compile-time information about how TensorFlow was built (such as what version of CUDA TensorFlow was built for). Args device A tf.config.PhysicalDevice returned by tf.config.list_physical_devices or tf.config.get_visible_devices. Returns A dict with string keys.
doc_30130
Class to convert formats, names, titles description to a dtype. After constructing the format_parser object, the dtype attribute is the converted data-type: dtype = format_parser(formats, names, titles).dtype Parameters formatsstr or list of str The format description, either specified as a string with comma-separated format descriptions in the form 'f8, i4, a5', or a list of format description strings in the form ['f8', 'i4', 'a5']. namesstr or list/tuple of str The field names, either specified as a comma-separated string in the form 'col1, col2, col3', or as a list or tuple of strings in the form ['col1', 'col2', 'col3']. An empty list can be used, in that case default field names (‘f0’, ‘f1’, …) are used. titlessequence Sequence of title strings. An empty list can be used to leave titles out. alignedbool, optional If True, align the fields by padding as the C-compiler would. Default is False. byteorderstr, optional If specified, all the fields will be changed to the provided byte-order. Otherwise, the default byte-order is used. For all available string specifiers, see dtype.newbyteorder. See also dtype, typename, sctype2char Examples >>> np.format_parser(['<f8', '<i4', '<a5'], ['col1', 'col2', 'col3'], ... ['T1', 'T2', 'T3']).dtype dtype([(('T1', 'col1'), '<f8'), (('T2', 'col2'), '<i4'), (('T3', 'col3'), 'S5')]) names and/or titles can be empty lists. If titles is an empty list, titles will simply not appear. If names is empty, default field names will be used. >>> np.format_parser(['f8', 'i4', 'a5'], ['col1', 'col2', 'col3'], ... []).dtype dtype([('col1', '<f8'), ('col2', '<i4'), ('col3', '<S5')]) >>> np.format_parser(['<f8', '<i4', '<a5'], [], []).dtype dtype([('f0', '<f8'), ('f1', '<i4'), ('f2', 'S5')]) Attributes dtypedtype The converted data-type.
doc_30131
tf.compat.v1.nn.conv3d_transpose( value, filter=None, output_shape=None, strides=None, padding='SAME', data_format='NDHWC', name=None, input=None, filters=None, dilations=None ) This operation is sometimes called "deconvolution" after (Zeiler et al., 2010), but is really the transpose (gradient) of conv3d rather than an actual deconvolution. Args value A 5-D Tensor of type float and shape [batch, depth, height, width, in_channels]. filter A 5-D Tensor with the same type as value and shape [depth, height, width, output_channels, in_channels]. filter's in_channels dimension must match that of value. output_shape A 1-D Tensor representing the output shape of the deconvolution op. strides A list of ints. The stride of the sliding window for each dimension of the input tensor. padding A string, either 'VALID' or 'SAME'. The padding algorithm. See the "returns" section of tf.nn.convolution for details. data_format A string, either 'NDHWC' or 'NCDHW' specifying the layout of the input and output tensors. Defaults to 'NDHWC'. name Optional name for the returned tensor. input Alias of value. filters Alias of filter. dilations An int or list of ints that has length 1, 3 or 5, defaults to 1. The dilation factor for each dimension ofinput. If a single value is given it is replicated in the D, H and W dimension. By default the N and C dimensions are set to 1. If set to k > 1, there will be k-1 skipped cells between each filter element on that dimension. The dimension order is determined by the value of data_format, see above for details. Dilations in the batch and depth dimensions if a 5-d tensor must be 1. Returns A Tensor with the same type as value. Raises ValueError If input/output depth does not match filter's shape, or if padding is other than 'VALID' or 'SAME'. References: Deconvolutional Networks: Zeiler et al., 2010 (pdf)
doc_30132
Set the extra representation of the module To print customized extra information, you should re-implement this method in your own modules. Both single-line and multi-line strings are acceptable.
doc_30133
foo = Foo() app = Flask(__name__) app.config.update( FOO_BAR='baz', FOO_SPAM='eggs', ) foo.init_app(app) Building Extensions While the PyPI contains many Flask extensions, you may not find an extension that fits your need. If this is the case, you can create your own. Read Flask Extension Development to develop your own Flask extension.
doc_30134
See Migration guide for more details. tf.compat.v1.raw_ops.ResourceSparseApplyAdagrad tf.raw_ops.ResourceSparseApplyAdagrad( var, accum, lr, grad, indices, use_locking=False, update_slots=True, name=None ) That is for rows we have grad for, we update var and accum as follows: accum += grad * grad var -= lr * grad * (1 / sqrt(accum)) Args var A Tensor of type resource. Should be from a Variable(). accum A Tensor of type resource. Should be from a Variable(). lr A Tensor. Must be one of the following types: float32, float64, int32, uint8, int16, int8, complex64, int64, qint8, quint8, qint32, bfloat16, uint16, complex128, half, uint32, uint64. Learning rate. Must be a scalar. grad A Tensor. Must have the same type as lr. The gradient. indices A Tensor. Must be one of the following types: int32, int64. A vector of indices into the first dimension of var and accum. use_locking An optional bool. Defaults to False. If True, updating of the var and accum tensors will be protected by a lock; otherwise the behavior is undefined, but may exhibit less contention. update_slots An optional bool. Defaults to True. name A name for the operation (optional). Returns The created Operation.
doc_30135
Defines a formula for differentiating the operation. This function is to be overridden by all subclasses. It must accept a context ctx as the first argument, followed by as many outputs did forward() return, and it should return as many tensors, as there were inputs to forward(). Each argument is the gradient w.r.t the given output, and each returned value should be the gradient w.r.t. the corresponding input. The context can be used to retrieve tensors saved during the forward pass. It also has an attribute ctx.needs_input_grad as a tuple of booleans representing whether each input needs gradient. E.g., backward() will have ctx.needs_input_grad[0] = True if the first input to forward() needs gradient computated w.r.t. the output.
doc_30136
Soft Voting/Majority Rule classifier for unfitted estimators. Read more in the User Guide. New in version 0.17. Parameters estimatorslist of (str, estimator) tuples Invoking the fit method on the VotingClassifier will fit clones of those original estimators that will be stored in the class attribute self.estimators_. An estimator can be set to 'drop' using set_params. Changed in version 0.21: 'drop' is accepted. Using None was deprecated in 0.22 and support was removed in 0.24. voting{‘hard’, ‘soft’}, default=’hard’ If ‘hard’, uses predicted class labels for majority rule voting. Else if ‘soft’, predicts the class label based on the argmax of the sums of the predicted probabilities, which is recommended for an ensemble of well-calibrated classifiers. weightsarray-like of shape (n_classifiers,), default=None Sequence of weights (float or int) to weight the occurrences of predicted class labels (hard voting) or class probabilities before averaging (soft voting). Uses uniform weights if None. n_jobsint, default=None The number of jobs to run in parallel for fit. None means 1 unless in a joblib.parallel_backend context. -1 means using all processors. See Glossary for more details. New in version 0.18. flatten_transformbool, default=True Affects shape of transform output only when voting=’soft’ If voting=’soft’ and flatten_transform=True, transform method returns matrix with shape (n_samples, n_classifiers * n_classes). If flatten_transform=False, it returns (n_classifiers, n_samples, n_classes). verbosebool, default=False If True, the time elapsed while fitting will be printed as it is completed. New in version 0.23. Attributes estimators_list of classifiers The collection of fitted sub-estimators as defined in estimators that are not ‘drop’. named_estimators_Bunch Attribute to access any fitted sub-estimators by name. New in version 0.20. classes_array-like of shape (n_predictions,) The classes labels. See also VotingRegressor Prediction voting regressor. Examples >>> import numpy as np >>> from sklearn.linear_model import LogisticRegression >>> from sklearn.naive_bayes import GaussianNB >>> from sklearn.ensemble import RandomForestClassifier, VotingClassifier >>> clf1 = LogisticRegression(multi_class='multinomial', random_state=1) >>> clf2 = RandomForestClassifier(n_estimators=50, random_state=1) >>> clf3 = GaussianNB() >>> X = np.array([[-1, -1], [-2, -1], [-3, -2], [1, 1], [2, 1], [3, 2]]) >>> y = np.array([1, 1, 1, 2, 2, 2]) >>> eclf1 = VotingClassifier(estimators=[ ... ('lr', clf1), ('rf', clf2), ('gnb', clf3)], voting='hard') >>> eclf1 = eclf1.fit(X, y) >>> print(eclf1.predict(X)) [1 1 1 2 2 2] >>> np.array_equal(eclf1.named_estimators_.lr.predict(X), ... eclf1.named_estimators_['lr'].predict(X)) True >>> eclf2 = VotingClassifier(estimators=[ ... ('lr', clf1), ('rf', clf2), ('gnb', clf3)], ... voting='soft') >>> eclf2 = eclf2.fit(X, y) >>> print(eclf2.predict(X)) [1 1 1 2 2 2] >>> eclf3 = VotingClassifier(estimators=[ ... ('lr', clf1), ('rf', clf2), ('gnb', clf3)], ... voting='soft', weights=[2,1,1], ... flatten_transform=True) >>> eclf3 = eclf3.fit(X, y) >>> print(eclf3.predict(X)) [1 1 1 2 2 2] >>> print(eclf3.transform(X).shape) (6, 6) Methods fit(X, y[, sample_weight]) Fit the estimators. fit_transform(X[, y]) Return class labels or probabilities for each estimator. get_params([deep]) Get the parameters of an estimator from the ensemble. predict(X) Predict class labels for X. score(X, y[, sample_weight]) Return the mean accuracy on the given test data and labels. set_params(**params) Set the parameters of an estimator from the ensemble. transform(X) Return class labels or probabilities for X for each estimator. fit(X, y, sample_weight=None) [source] Fit the estimators. 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. yarray-like of shape (n_samples,) Target values. sample_weightarray-like of shape (n_samples,), default=None Sample weights. If None, then samples are equally weighted. Note that this is supported only if all underlying estimators support sample weights. New in version 0.18. Returns selfobject fit_transform(X, y=None, **fit_params) [source] Return class labels or probabilities for each estimator. Return predictions for X for each estimator. Parameters X{array-like, sparse matrix, dataframe} of shape (n_samples, n_features) Input samples yndarray of shape (n_samples,), 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 the parameters of an estimator from the ensemble. Returns the parameters given in the constructor as well as the estimators contained within the estimators parameter. Parameters deepbool, default=True Setting it to True gets the various estimators and the parameters of the estimators as well. predict(X) [source] Predict class labels for X. Parameters X{array-like, sparse matrix} of shape (n_samples, n_features) The input samples. Returns majarray-like of shape (n_samples,) Predicted class labels. property predict_proba Compute probabilities of possible outcomes for samples in X. Parameters X{array-like, sparse matrix} of shape (n_samples, n_features) The input samples. Returns avgarray-like of shape (n_samples, n_classes) Weighted average probability for each class per sample. score(X, y, sample_weight=None) [source] Return the mean accuracy on the given test data and labels. In multi-label classification, this is the subset accuracy which is a harsh metric since you require for each sample that each label set be correctly predicted. Parameters Xarray-like of shape (n_samples, n_features) Test samples. yarray-like of shape (n_samples,) or (n_samples, n_outputs) True labels for X. sample_weightarray-like of shape (n_samples,), default=None Sample weights. Returns scorefloat Mean accuracy of self.predict(X) wrt. y. set_params(**params) [source] Set the parameters of an estimator from the ensemble. Valid parameter keys can be listed with get_params(). Note that you can directly set the parameters of the estimators contained in estimators. Parameters **paramskeyword arguments Specific parameters using e.g. set_params(parameter_name=new_value). In addition, to setting the parameters of the estimator, the individual estimator of the estimators can also be set, or can be removed by setting them to ‘drop’. transform(X) [source] Return class labels or probabilities for X for each estimator. 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. Returns probabilities_or_labels If voting='soft' and flatten_transform=True: returns ndarray of shape (n_classifiers, n_samples * n_classes), being class probabilities calculated by each classifier. If voting='soft' and `flatten_transform=False: ndarray of shape (n_classifiers, n_samples, n_classes) If voting='hard': ndarray of shape (n_samples, n_classifiers), being class labels predicted by each classifier.
doc_30137
Alias for set_linestyle.
doc_30138
See Migration guide for more details. tf.compat.v1.group tf.group( *inputs, **kwargs ) When this op finishes, all ops in inputs have finished. This op has no output. Note: In TensorFlow 2 with eager and/or Autograph, you should not require this method, as code executes in your expected order. Only use tf.group when working with v1-style code or in a graph context such as inside Dataset.map. When operating in a v1-style graph context, ops are not executed in the same order as specified in the code; TensorFlow will attempt to execute ops in parallel or in an order convienient to the result it is computing. tf.group allows you to request that one or more results finish before execution continues. tf.group creates a single op (of type NoOp), and then adds appropriate control dependencies. Thus, c = tf.group(a, b) will compute the same graph as this: with tf.control_dependencies([a, b]): c = tf.no_op() See also tf.tuple and tf.control_dependencies. Args *inputs Zero or more tensors to group. name A name for this operation (optional). Returns An Operation that executes all its inputs. Raises ValueError If an unknown keyword argument is provided.
doc_30139
Returns whether the kernel is stationary.
doc_30140
See Migration guide for more details. tf.compat.v1.random.stateless_poisson tf.random.stateless_poisson( shape, seed, lam, dtype=tf.dtypes.int32, name=None ) The generated values follow a Poisson distribution with specified rate parameter. This is a stateless version of tf.random.poisson: if run twice with the same seeds and shapes, it will produce the same pseudorandom numbers. The output is consistent across multiple runs on the same hardware, but may change between versions of TensorFlow or on non-CPU/GPU hardware. A slight difference exists in the interpretation of the shape parameter between stateless_poisson and poisson: in poisson, the shape is always prepended to the shape of lam; whereas in stateless_poisson the shape of lam must match the trailing dimensions of shape. Example: samples = tf.random.stateless_poisson([10, 2], seed=[12, 34], lam=[5, 15]) # samples has shape [10, 2], where each slice [:, 0] and [:, 1] represents # the samples drawn from each distribution samples = tf.random.stateless_poisson([7, 5, 2], seed=[12, 34], lam=[5, 15]) # samples has shape [7, 5, 2], where each slice [:, :, 0] and [:, :, 1] # represents the 7x5 samples drawn from each of the two distributions rate = tf.constant([[1.], [3.], [5.]]) samples = tf.random.stateless_poisson([30, 3, 1], seed=[12, 34], lam=rate) # samples has shape [30, 3, 1], with 30 samples each of 3x1 distributions. Args shape A 1-D integer Tensor or Python array. The shape of the output tensor. seed A shape [2] Tensor, the seed to the random number generator. Must have dtype int32 or int64. (When using XLA, only int32 is allowed.) lam Tensor. The rate parameter "lambda" of the Poisson distribution. Shape must match the rightmost dimensions of shape. dtype Dtype of the samples (int or float dtypes are permissible, as samples are discrete). Default: int32. name A name for the operation (optional). Returns samples A Tensor of the specified shape filled with random Poisson values. For each i, each samples[..., i] is an independent draw from the Poisson distribution with rate lam[i].
doc_30141
class sklearn.feature_extraction.image.PatchExtractor(*, patch_size=None, max_patches=None, random_state=None) [source] Extracts patches from a collection of images Read more in the User Guide. New in version 0.9. Parameters patch_sizetuple of int (patch_height, patch_width), default=None The dimensions of one patch. max_patchesint or float, default=None The maximum number of patches per image to extract. If max_patches is a float in (0, 1), it is taken to mean a proportion of the total number of patches. random_stateint, RandomState instance, default=None Determines the random number generator used for random sampling when max_patches is not None. Use an int to make the randomness deterministic. See Glossary. Examples >>> from sklearn.datasets import load_sample_images >>> from sklearn.feature_extraction import image >>> # Use the array data from the second image in this dataset: >>> X = load_sample_images().images[1] >>> print('Image shape: {}'.format(X.shape)) Image shape: (427, 640, 3) >>> pe = image.PatchExtractor(patch_size=(2, 2)) >>> pe_fit = pe.fit(X) >>> pe_trans = pe.transform(X) >>> print('Patches shape: {}'.format(pe_trans.shape)) Patches shape: (545706, 2, 2) Methods fit(X[, y]) Do nothing and return the estimator unchanged. get_params([deep]) Get parameters for this estimator. set_params(**params) Set the parameters of this estimator. transform(X) Transforms the image samples in X into a matrix of patch data. fit(X, y=None) [source] Do nothing and return the estimator unchanged. This method is just there to implement the usual API and hence work in pipelines. Parameters Xarray-like of shape (n_samples, n_features) Training data. 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. 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(X) [source] Transforms the image samples in X into a matrix of patch data. Parameters Xndarray of shape (n_samples, image_height, image_width) or (n_samples, image_height, image_width, n_channels) Array of images from which to extract patches. For color images, the last dimension specifies the channel: a RGB image would have n_channels=3. Returns patchesarray of shape (n_patches, patch_height, patch_width) or (n_patches, patch_height, patch_width, n_channels) The collection of patches extracted from the images, where n_patches is either n_samples * max_patches or the total number of patches that can be extracted.
doc_30142
Get a resource from a package. This is a wrapper for the loader get_data API. The package argument should be the name of a package, in standard module format (foo.bar). The resource argument should be in the form of a relative filename, using / as the path separator. The parent directory name .. is not allowed, and nor is a rooted name (starting with a /). The function returns a binary string that is the contents of the specified resource. For packages located in the filesystem, which have already been imported, this is the rough equivalent of: d = os.path.dirname(sys.modules[package].__file__) data = open(os.path.join(d, resource), 'rb').read() If the package cannot be located or loaded, or it uses a loader which does not support get_data, then None is returned. In particular, the loader for namespace packages does not support get_data.
doc_30143
Roll provided date backward to next offset only if not on offset. Returns TimeStamp Rolled timestamp if not on offset, otherwise unchanged timestamp.
doc_30144
Draw samples from a Gamma distribution. Samples are drawn from a Gamma distribution with specified parameters, shape (sometimes designated “k”) and scale (sometimes designated “theta”), where both parameters are > 0. Note New code should use the gamma method of a default_rng() instance instead; please see the Quick Start. Parameters shapefloat or array_like of floats The shape of the gamma distribution. Must be non-negative. scalefloat or array_like of floats, optional The scale of the gamma distribution. Must be non-negative. Default is equal to 1. sizeint or tuple of ints, optional Output shape. If the given shape is, e.g., (m, n, k), then m * n * k samples are drawn. If size is None (default), a single value is returned if shape and scale are both scalars. Otherwise, np.broadcast(shape, scale).size samples are drawn. Returns outndarray or scalar Drawn samples from the parameterized gamma distribution. See also scipy.stats.gamma probability density function, distribution or cumulative density function, etc. Generator.gamma which should be used for new code. Notes The probability density for the Gamma distribution is \[p(x) = x^{k-1}\frac{e^{-x/\theta}}{\theta^k\Gamma(k)},\] where \(k\) is the shape and \(\theta\) the scale, and \(\Gamma\) is the Gamma function. The Gamma distribution is often used to model the times to failure of electronic components, and arises naturally in processes for which the waiting times between Poisson distributed events are relevant. References 1 Weisstein, Eric W. “Gamma Distribution.” From MathWorld–A Wolfram Web Resource. http://mathworld.wolfram.com/GammaDistribution.html 2 Wikipedia, “Gamma distribution”, https://en.wikipedia.org/wiki/Gamma_distribution Examples Draw samples from the distribution: >>> shape, scale = 2., 2. # mean=4, std=2*sqrt(2) >>> s = np.random.gamma(shape, scale, 1000) Display the histogram of the samples, along with the probability density function: >>> import matplotlib.pyplot as plt >>> import scipy.special as sps >>> count, bins, ignored = plt.hist(s, 50, density=True) >>> y = bins**(shape-1)*(np.exp(-bins/scale) / ... (sps.gamma(shape)*scale**shape)) >>> plt.plot(bins, y, linewidth=2, color='r') >>> plt.show()
doc_30145
Return the encoding of the message catalog file.
doc_30146
See torch.mm()
doc_30147
This exception is raised if source and destination in copyfile() are the same file. New in version 3.4.
doc_30148
Check if coefficients match. New in version 1.6.0. Parameters otherclass instance The other class must have the coef attribute. Returns boolboolean True if the coefficients are the same, False otherwise.
doc_30149
tf.nn.batch_norm_with_global_normalization( input, mean, variance, beta, gamma, variance_epsilon, scale_after_normalization, name=None ) This op is deprecated. See tf.nn.batch_normalization. Args input A 4D input Tensor. mean A 1D mean Tensor with size matching the last dimension of t. This is the first output from tf.nn.moments, or a saved moving average thereof. variance A 1D variance Tensor with size matching the last dimension of t. This is the second output from tf.nn.moments, or a saved moving average thereof. beta A 1D beta Tensor with size matching the last dimension of t. An offset to be added to the normalized tensor. gamma A 1D gamma Tensor with size matching the last dimension of t. If "scale_after_normalization" is true, this tensor will be multiplied with the normalized tensor. variance_epsilon A small float number to avoid dividing by 0. scale_after_normalization A bool indicating whether the resulted tensor needs to be multiplied with gamma. name A name for this operation (optional). Returns A batch-normalized t. References: Batch Normalization - Accelerating Deep Network Training by Reducing Internal Covariate Shift: Ioffe et al., 2015 (pdf)
doc_30150
tf.compat.v1.scatter_sub( ref, indices, updates, use_locking=False, name=None ) # Scalar indices ref[indices, ...] -= updates[...] # Vector indices (for each i) ref[indices[i], ...] -= updates[i, ...] # High rank indices (for each i, ..., j) ref[indices[i, ..., j], ...] -= updates[i, ..., j, ...] This operation outputs ref after the update is done. This makes it easier to chain operations that need to use the reset value. Duplicate entries are handled correctly: if multiple indices reference the same location, their (negated) contributions add. Requires updates.shape = indices.shape + ref.shape[1:] or updates.shape = []. Args ref A mutable Tensor. Must be one of the following types: float32, float64, int32, uint8, int16, int8, complex64, int64, qint8, quint8, qint32, bfloat16, uint16, complex128, half, uint32, uint64. Should be from a Variable node. indices A Tensor. Must be one of the following types: int32, int64. A tensor of indices into the first dimension of ref. updates A Tensor. Must have the same type as ref. A tensor of updated values to subtract from ref. use_locking An optional bool. Defaults to False. If True, the subtraction will be protected by a lock; otherwise the behavior is undefined, but may exhibit less contention. name A name for the operation (optional). Returns A mutable Tensor. Has the same type as ref.
doc_30151
The bytes which represent the bytecode version number. If you need help with loading/writing bytecode then consider importlib.abc.SourceLoader. New in version 3.4.
doc_30152
Represents the C signed long long datatype. The constructor accepts an optional integer initializer; no overflow checking is done.
doc_30153
See Migration guide for more details. tf.compat.v1.signal.vorbis_window tf.signal.vorbis_window( window_length, dtype=tf.dtypes.float32, name=None ) Args window_length A scalar Tensor indicating the window length to generate. dtype The data type to produce. Must be a floating point type. name An optional name for the operation. Returns A Tensor of shape [window_length] of type dtype.
doc_30154
Enter echo mode. In echo mode, each character input is echoed to the screen as it is entered.
doc_30155
See Migration guide for more details. tf.compat.v1.cholesky_solve, tf.compat.v1.linalg.cholesky_solve tf.linalg.cholesky_solve( chol, rhs, name=None ) Specifically, returns X from A X = RHS, where A = L L^T, L is the chol arg and RHS is the rhs arg. # Solve 10 separate 2x2 linear systems: A = ... # shape 10 x 2 x 2 RHS = ... # shape 10 x 2 x 1 chol = tf.linalg.cholesky(A) # shape 10 x 2 x 2 X = tf.linalg.cholesky_solve(chol, RHS) # shape 10 x 2 x 1 # tf.matmul(A, X) ~ RHS X[3, :, 0] # Solution to the linear system A[3, :, :] x = RHS[3, :, 0] # Solve five linear systems (K = 5) for every member of the length 10 batch. A = ... # shape 10 x 2 x 2 RHS = ... # shape 10 x 2 x 5 ... X[3, :, 2] # Solution to the linear system A[3, :, :] x = RHS[3, :, 2] Args chol A Tensor. Must be float32 or float64, shape is [..., M, M]. Cholesky factorization of A, e.g. chol = tf.linalg.cholesky(A). For that reason, only the lower triangular parts (including the diagonal) of the last two dimensions of chol are used. The strictly upper part is assumed to be zero and not accessed. rhs A Tensor, same type as chol, shape is [..., M, K]. name A name to give this Op. Defaults to cholesky_solve. Returns Solution to A x = rhs, shape [..., M, K].
doc_30156
Subclass of unittest.SkipTest. Raised when a resource (such as a network connection) is not available. Raised by the requires() function.
doc_30157
See Migration guide for more details. tf.compat.v1.keras.backend.set_floatx tf.keras.backend.set_floatx( value ) Note: It is not recommended to set this to float16 for training, as this will likely cause numeric stability issues. Instead, mixed precision, which is using a mix of float16 and float32, can be used by calling tf.keras.mixed_precision.experimental.set_policy('mixed_float16'). See the mixed precision guide for details. Arguments value String; 'float16', 'float32', or 'float64'. Example: tf.keras.backend.floatx() 'float32' tf.keras.backend.set_floatx('float64') tf.keras.backend.floatx() 'float64' tf.keras.backend.set_floatx('float32') Raises ValueError In case of invalid value.
doc_30158
Getter for the precision matrix. Returns precision_array-like of shape (n_features, n_features) The precision matrix associated to the current covariance object.
doc_30159
alias of werkzeug.formparser.FormDataParser
doc_30160
Standardize a dataset along any axis Center to the median and component wise scale according to the interquartile range. Read more in the User Guide. Parameters X{array-like, sparse matrix} of shape (n_sample, n_features) The data to center and scale. axisint, default=0 axis used to compute the medians and IQR along. If 0, independently scale each feature, otherwise (if 1) scale each sample. with_centeringbool, default=True If True, center the data before scaling. with_scalingbool, default=True If True, scale the data to unit variance (or equivalently, unit standard deviation). quantile_rangetuple (q_min, q_max), 0.0 < q_min < q_max < 100.0 default=(25.0, 75.0), == (1st quantile, 3rd quantile), == IQR Quantile range used to calculate scale_. New in version 0.18. copybool, default=True set to False to perform inplace row normalization and avoid a copy (if the input is already a numpy array or a scipy.sparse CSR matrix and if axis is 1). unit_variancebool, default=False If True, scale data so that normally distributed features have a variance of 1. In general, if the difference between the x-values of q_max and q_min for a standard normal distribution is greater than 1, the dataset will be scaled down. If less than 1, the dataset will be scaled up. New in version 0.24. Returns X_tr{ndarray, sparse matrix} of shape (n_samples, n_features) The transformed data. See also RobustScaler Performs centering and scaling using the Transformer API (e.g. as part of a preprocessing Pipeline). Notes This implementation will refuse to center scipy.sparse matrices since it would make them non-sparse and would potentially crash the program with memory exhaustion problems. Instead the caller is expected to either set explicitly with_centering=False (in that case, only variance scaling will be performed on the features of the CSR matrix) or to call X.toarray() if he/she expects the materialized dense array to fit in memory. To avoid memory copy the caller should pass a CSR matrix. For a comparison of the different scalers, transformers, and normalizers, see examples/preprocessing/plot_all_scaling.py. Warning Risk of data leak Do not use robust_scale unless you know what you are doing. A common mistake is to apply it to the entire data before splitting into training and test sets. This will bias the model evaluation because information would have leaked from the test set to the training set. In general, we recommend using RobustScaler within a Pipeline in order to prevent most risks of data leaking: pipe = make_pipeline(RobustScaler(), LogisticRegression()).
doc_30161
Django view for the model instance addition page. See note below.
doc_30162
Set a label that will be displayed in the legend. Parameters sobject s will be converted to a string by calling str.
doc_30163
os.RTLD_NOW os.RTLD_GLOBAL os.RTLD_LOCAL os.RTLD_NODELETE os.RTLD_NOLOAD os.RTLD_DEEPBIND Flags for use with the setdlopenflags() and getdlopenflags() functions. See the Unix manual page dlopen(3) for what the different flags mean. New in version 3.3.
doc_30164
Similar to add_library, but the specified library is installed. Most C libraries used with distutils are only used to build python extensions, but libraries built through this method will be installed so that they can be reused by third-party packages. Parameters namestr Name of the installed library. sourcessequence List of the library’s source files. See add_library for details. install_dirstr Path to install the library, relative to the current sub-package. build_infodict, optional The following keys are allowed: depends macros include_dirs extra_compiler_args extra_f77_compile_args extra_f90_compile_args f2py_options language Returns None See also add_library, add_npy_pkg_config, get_info Notes The best way to encode the options required to link against the specified C libraries is to use a “libname.ini” file, and use get_info to retrieve the required options (see add_npy_pkg_config for more information).
doc_30165
Return a context manager for temporarily changing rcParams. Parameters rcdict The rcParams to temporarily set. fnamestr or path-like A file with Matplotlib rc settings. If both fname and rc are given, settings from rc take precedence. See also The matplotlibrc file Examples Passing explicit values via a dict: with mpl.rc_context({'interactive': False}): fig, ax = plt.subplots() ax.plot(range(3), range(3)) fig.savefig('example.png') plt.close(fig) Loading settings from a file: with mpl.rc_context(fname='print.rc'): plt.plot(x, y) # uses 'print.rc'
doc_30166
Return whether image composition by Matplotlib should be skipped. Raster backends should usually return False (letting the C-level rasterizer take care of image composition); vector backends should usually return not rcParams["image.composite_image"].
doc_30167
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_30168
Concrete implementation of importlib.abc.Loader.load_module() where specifying the name of the module to load is optional. Deprecated since version 3.6: Use importlib.abc.Loader.exec_module() instead.
doc_30169
See Migration guide for more details. tf.compat.v1.raw_ops.BoostedTreesCalculateBestFeatureSplit tf.raw_ops.BoostedTreesCalculateBestFeatureSplit( node_id_range, stats_summary, l1, l2, tree_complexity, min_node_weight, logits_dimension, split_type='inequality', name=None ) The split information is the best threshold (bucket id), gains and left/right node contributions per node for each feature. It is possible that not all nodes can be split on each feature. Hence, the list of possible nodes can differ between the features. Therefore, we return node_ids_list for each feature, containing the list of nodes that this feature can be used to split. In this manner, the output is the best split per features and per node, so that it needs to be combined later to produce the best split for each node (among all possible features). The output shapes are compatible in a way that the first dimension of all tensors are the same and equal to the number of possible split nodes for each feature. Args node_id_range A Tensor of type int32. A Rank 1 tensor (shape=[2]) to specify the range [first, last) of node ids to process within stats_summary_list. The nodes are iterated between the two nodes specified by the tensor, as like for node_id in range(node_id_range[0], node_id_range[1]) (Note that the last index node_id_range[1] is exclusive). stats_summary A Tensor of type float32. A Rank 4 tensor (#shape=[max_splits, feature_dims, bucket, stats_dims]) for accumulated stats summary (gradient/hessian) per node, per dimension, per buckets for each feature. The first dimension of the tensor is the maximum number of splits, and thus not all elements of it will be used, but only the indexes specified by node_ids will be used. l1 A Tensor of type float32. l1 regularization factor on leaf weights, per instance based. l2 A Tensor of type float32. l2 regularization factor on leaf weights, per instance based. tree_complexity A Tensor of type float32. adjustment to the gain, per leaf based. min_node_weight A Tensor of type float32. minimum avg of hessians in a node before required for the node to be considered for splitting. logits_dimension An int that is >= 1. The dimension of logit, i.e., number of classes. split_type An optional string from: "inequality", "equality". Defaults to "inequality". A string indicating if this Op should perform inequality split or equality split. name A name for the operation (optional). Returns A tuple of Tensor objects (node_ids, gains, feature_dimensions, thresholds, left_node_contribs, right_node_contribs, split_with_default_directions). node_ids A Tensor of type int32. gains A Tensor of type float32. feature_dimensions A Tensor of type int32. thresholds A Tensor of type int32. left_node_contribs A Tensor of type float32. right_node_contribs A Tensor of type float32. split_with_default_directions A Tensor of type string.
doc_30170
The PopupMenu widget can be used as a replacement of the tk_popup command. The advantage of the Tix PopupMenu widget is it requires less application code to manipulate.
doc_30171
tkinter.messagebox.showerror(title=None, message=None, **options)
doc_30172
The get_exclude method is given the HttpRequest and the obj being edited (or None on an add form) and is expected to return a list of fields, as described in ModelAdmin.exclude.
doc_30173
draw a Bezier curve bezier(surface, points, steps, color) -> None Draws a Bézier curve on the given surface. Parameters: surface (Surface) -- surface to draw on points (tuple(coordinate) or list(coordinate)) -- a sequence of 3 or more (x, y) coordinates used to form a curve, where each coordinate in the sequence must be a tuple/list/pygame.math.Vector2 of 2 ints/floats (float values will be truncated) steps (int) -- number of steps for the interpolation, the minimum is 2 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 Raises: ValueError -- if steps < 2 ValueError -- if len(points) < 3 (must have at least 3 points) IndexError -- if len(coordinate) < 2 (each coordinate must have at least 2 items)
doc_30174
Aggregate using one or more operations over the specified axis. Parameters func:function, str, list or dict Function to use for aggregating the data. If a function, must either work when passed a Series/Dataframe or when passed to Series/Dataframe.apply. Accepted combinations are: function string function name list of functions and/or function names, e.g. [np.sum, 'mean'] dict of axis labels -> functions, function names or list of such. *args Positional arguments to pass to func. **kwargs Keyword arguments to pass to func. Returns scalar, Series or DataFrame The return can be: scalar : when Series.agg is called with single function Series : when DataFrame.agg is called with a single function DataFrame : when DataFrame.agg is called with several functions Return scalar, Series or DataFrame. See also pandas.Series.rolling Calling object with Series data. pandas.DataFrame.rolling Calling object with DataFrame data. Notes agg is an alias for aggregate. Use the alias. Functions that mutate the passed object can produce unexpected behavior or errors and are not supported. See Mutating with User Defined Function (UDF) methods for more details. A passed user-defined-function will be passed a Series for evaluation. Examples >>> df = pd.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6], "C": [7, 8, 9]}) >>> df A B C 0 1 4 7 1 2 5 8 2 3 6 9 >>> df.rolling(2).sum() A B C 0 NaN NaN NaN 1 3.0 9.0 15.0 2 5.0 11.0 17.0 >>> df.rolling(2).agg({"A": "sum", "B": "min"}) A B 0 NaN NaN 1 3.0 4.0 2 5.0 5.0
doc_30175
if set to False accessing properties on the response object will not try to consume the response iterator and convert it into a list. Changelog New in version 0.6.2: That attribute was previously called implicit_seqence_conversion. (Notice the typo). If you did use this feature, you have to adapt your code to the name change.
doc_30176
Imputation transformer for completing missing values. Read more in the User Guide. New in version 0.20: SimpleImputer replaces the previous sklearn.preprocessing.Imputer estimator which is now removed. Parameters missing_valuesint, float, str, np.nan or None, default=np.nan The placeholder for the missing values. All occurrences of missing_values will be imputed. For pandas’ dataframes with nullable integer dtypes with missing values, missing_values should be set to np.nan, since pd.NA will be converted to np.nan. strategystring, default=’mean’ The imputation strategy. If “mean”, then replace missing values using the mean along each column. Can only be used with numeric data. If “median”, then replace missing values using the median along each column. Can only be used with numeric data. If “most_frequent”, then replace missing using the most frequent value along each column. Can be used with strings or numeric data. If there is more than one such value, only the smallest is returned. If “constant”, then replace missing values with fill_value. Can be used with strings or numeric data. New in version 0.20: strategy=”constant” for fixed value imputation. fill_valuestring or numerical value, default=None When strategy == “constant”, fill_value is used to replace all occurrences of missing_values. If left to the default, fill_value will be 0 when imputing numerical data and “missing_value” for strings or object data types. verboseinteger, default=0 Controls the verbosity of the imputer. copyboolean, default=True If True, a copy of X will be created. If False, imputation will be done in-place whenever possible. Note that, in the following cases, a new copy will always be made, even if copy=False: If X is not an array of floating values; If X is encoded as a CSR matrix; If add_indicator=True. add_indicatorboolean, default=False If True, a MissingIndicator transform will stack onto output of the imputer’s transform. This allows a predictive estimator to account for missingness despite imputation. If a feature has no missing values at fit/train time, the feature won’t appear on the missing indicator even if there are missing values at transform/test time. Attributes statistics_array of shape (n_features,) The imputation fill value for each feature. Computing statistics can result in np.nan values. During transform, features corresponding to np.nan statistics will be discarded. indicator_MissingIndicator Indicator used to add binary indicators for missing values. None if add_indicator is False. See also IterativeImputer Multivariate imputation of missing values. Notes Columns which only contained missing values at fit are discarded upon transform if strategy is not “constant”. Examples >>> import numpy as np >>> from sklearn.impute import SimpleImputer >>> imp_mean = SimpleImputer(missing_values=np.nan, strategy='mean') >>> imp_mean.fit([[7, 2, 3], [4, np.nan, 6], [10, 5, 9]]) SimpleImputer() >>> X = [[np.nan, 2, 3], [4, np.nan, 6], [10, np.nan, 9]] >>> print(imp_mean.transform(X)) [[ 7. 2. 3. ] [ 4. 3.5 6. ] [10. 3.5 9. ]] Methods fit(X[, y]) Fit the imputer on X. fit_transform(X[, y]) Fit to data, then transform it. get_params([deep]) Get parameters for this estimator. inverse_transform(X) Convert the data back to the original representation. set_params(**params) Set the parameters of this estimator. transform(X) Impute all missing values in X. fit(X, y=None) [source] Fit the imputer on X. Parameters X{array-like, sparse matrix}, shape (n_samples, n_features) Input data, where n_samples is the number of samples and n_features is the number of features. Returns selfSimpleImputer 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. inverse_transform(X) [source] Convert the data back to the original representation. Inverts the transform operation performed on an array. This operation can only be performed after SimpleImputer is instantiated with add_indicator=True. Note that inverse_transform can only invert the transform in features that have binary indicators for missing values. If a feature has no missing values at fit time, the feature won’t have a binary indicator, and the imputation done at transform time won’t be inverted. New in version 0.24. Parameters Xarray-like of shape (n_samples, n_features + n_features_missing_indicator) The imputed data to be reverted to original data. It has to be an augmented array of imputed data and the missing indicator mask. Returns X_originalndarray of shape (n_samples, n_features) The original X with missing values as it was prior to imputation. 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(X) [source] Impute all missing values in X. Parameters X{array-like, sparse matrix}, shape (n_samples, n_features) The input data to complete.
doc_30177
Receive normal data (up to bufsize bytes) and ancillary data from the socket. The ancbufsize argument sets the size in bytes of the internal buffer used to receive the ancillary data; it defaults to 0, meaning that no ancillary data will be received. Appropriate buffer sizes for ancillary data can be calculated using CMSG_SPACE() or CMSG_LEN(), and items which do not fit into the buffer might be truncated or discarded. The flags argument defaults to 0 and has the same meaning as for recv(). The return value is a 4-tuple: (data, ancdata, msg_flags, address). The data item is a bytes object holding the non-ancillary data received. The ancdata item is a list of zero or more tuples (cmsg_level, cmsg_type, cmsg_data) representing the ancillary data (control messages) received: cmsg_level and cmsg_type are integers specifying the protocol level and protocol-specific type respectively, and cmsg_data is a bytes object holding the associated data. The msg_flags item is the bitwise OR of various flags indicating conditions on the received message; see your system documentation for details. If the receiving socket is unconnected, address is the address of the sending socket, if available; otherwise, its value is unspecified. On some systems, sendmsg() and recvmsg() can be used to pass file descriptors between processes over an AF_UNIX socket. When this facility is used (it is often restricted to SOCK_STREAM sockets), recvmsg() will return, in its ancillary data, items of the form (socket.SOL_SOCKET, socket.SCM_RIGHTS, fds), where fds is a bytes object representing the new file descriptors as a binary array of the native C int type. If recvmsg() raises an exception after the system call returns, it will first attempt to close any file descriptors received via this mechanism. Some systems do not indicate the truncated length of ancillary data items which have been only partially received. If an item appears to extend beyond the end of the buffer, recvmsg() will issue a RuntimeWarning, and will return the part of it which is inside the buffer provided it has not been truncated before the start of its associated data. On systems which support the SCM_RIGHTS mechanism, the following function will receive up to maxfds file descriptors, returning the message data and a list containing the descriptors (while ignoring unexpected conditions such as unrelated control messages being received). See also sendmsg(). import socket, array def recv_fds(sock, msglen, maxfds): fds = array.array("i") # Array of ints msg, ancdata, flags, addr = sock.recvmsg(msglen, socket.CMSG_LEN(maxfds * fds.itemsize)) for cmsg_level, cmsg_type, cmsg_data in ancdata: if cmsg_level == socket.SOL_SOCKET and cmsg_type == socket.SCM_RIGHTS: # Append data, ignoring any truncated integers at the end. fds.frombytes(cmsg_data[:len(cmsg_data) - (len(cmsg_data) % fds.itemsize)]) return msg, list(fds) Availability: most Unix platforms, possibly others. New in version 3.3. Changed in version 3.5: If the system call is interrupted and the signal handler does not raise an exception, the method now retries the system call instead of raising an InterruptedError exception (see PEP 475 for the rationale).
doc_30178
See Migration guide for more details. tf.compat.v1.OptionalSpec, tf.compat.v1.data.experimental.OptionalStructure tf.OptionalSpec( element_spec ) For instance, tf.OptionalSpec can be used to define a tf.function that takes tf.experimental.Optional as an input argument: @tf.function(input_signature=[tf.OptionalSpec( tf.TensorSpec(shape=(), dtype=tf.int32, name=None))]) def maybe_square(optional): if optional.has_value(): x = optional.get_value() return x * x return -1 optional = tf.experimental.Optional.from_value(5) print(maybe_square(optional)) tf.Tensor(25, shape=(), dtype=int32) Attributes element_spec A nested structure of TypeSpec objects that represents the type specification of the optional element. value_type The Python type for values that are compatible with this TypeSpec. In particular, all values that are compatible with this TypeSpec must be an instance of this type. Methods from_value View source @staticmethod from_value( value ) is_compatible_with View source is_compatible_with( spec_or_value ) Returns true if spec_or_value is compatible with this TypeSpec. most_specific_compatible_type View source most_specific_compatible_type( other ) Returns the most specific TypeSpec compatible with self and other. Args other A TypeSpec. Raises ValueError If there is no TypeSpec that is compatible with both self and other. __eq__ View source __eq__( other ) Return self==value. __ne__ View source __ne__( other ) Return self!=value.
doc_30179
This closes the database connection. Note that this does not automatically call commit(). If you just close your database connection without calling commit() first, your changes will be lost!
doc_30180
A class attribute describing the function that will be generated. Specifically, the function will be interpolated as the function placeholder within template. Defaults to None.
doc_30181
Return system configuration information relevant to an open file. name specifies the configuration value to retrieve; it may be a string which is the name of a defined system value; these names are specified in a number of standards (POSIX.1, Unix 95, Unix 98, and others). Some platforms define additional names as well. The names known to the host operating system are given in the pathconf_names dictionary. For configuration variables not included in that mapping, passing an integer for name is also accepted. If name is a string and is not known, ValueError is raised. If a specific value for name is not supported by the host system, even if it is included in pathconf_names, an OSError is raised with errno.EINVAL for the error number. As of Python 3.3, this is equivalent to os.pathconf(fd, name). Availability: Unix.
doc_30182
A custom setuptools build extension . This setuptools.build_ext subclass takes care of passing the minimum required compiler flags (e.g. -std=c++14) as well as mixed C++/CUDA compilation (and support for CUDA files in general). When using BuildExtension, it is allowed to supply a dictionary for extra_compile_args (rather than the usual list) that maps from languages (cxx or nvcc) to a list of additional compiler flags to supply to the compiler. This makes it possible to supply different flags to the C++ and CUDA compiler during mixed compilation. use_ninja (bool): If use_ninja is True (default), then we attempt to build using the Ninja backend. Ninja greatly speeds up compilation compared to the standard setuptools.build_ext. Fallbacks to the standard distutils backend if Ninja is not available. Note By default, the Ninja backend uses #CPUS + 2 workers to build the extension. This may use up too many resources on some systems. One can control the number of workers by setting the MAX_JOBS environment variable to a non-negative number.
doc_30183
Return the visibility.
doc_30184
display video captured live from an attached camera camera.main() -> None A simple live video player, it uses the first available camera it finds on the system.
doc_30185
Return the clip rectangle as a Bbox instance.
doc_30186
Context manager for global scikit-learn configuration Parameters assume_finitebool, default=False If True, validation for finiteness will be skipped, saving time, but leading to potential crashes. If False, validation for finiteness will be performed, avoiding error. Global default: False. working_memoryint, default=1024 If set, scikit-learn will attempt to limit the size of temporary arrays to this number of MiB (per job when parallelised), often saving both computation time and memory on expensive operations that can be performed in chunks. Global default: 1024. print_changed_onlybool, default=True If True, only the parameters that were set to non-default values will be printed when printing an estimator. For example, print(SVC()) while True will only print ‘SVC()’, but would print ‘SVC(C=1.0, cache_size=200, …)’ with all the non-changed parameters when False. Default is True. Changed in version 0.23: Default changed from False to True. display{‘text’, ‘diagram’}, default=’text’ If ‘diagram’, estimators will be displayed as a diagram in a Jupyter lab or notebook context. If ‘text’, estimators will be displayed as text. Default is ‘text’. New in version 0.23. See also set_config Set global scikit-learn configuration. get_config Retrieve current values of the global configuration. Notes All settings, not just those presently modified, will be returned to their previous values when the context manager is exited. This is not thread-safe. Examples >>> import sklearn >>> from sklearn.utils.validation import assert_all_finite >>> with sklearn.config_context(assume_finite=True): ... assert_all_finite([float('nan')]) >>> with sklearn.config_context(assume_finite=True): ... with sklearn.config_context(assume_finite=False): ... assert_all_finite([float('nan')]) Traceback (most recent call last): ... ValueError: Input contains NaN, ...
doc_30187
Set the sketch parameters. Parameters scalefloat, optional The amplitude of the wiggle perpendicular to the source line, in pixels. If scale is None, or not provided, no sketch filter will be provided. lengthfloat, optional The length of the wiggle along the line, in pixels (default 128.0) randomnessfloat, optional The scale factor by which the length is shrunken or expanded (default 16.0) The PGF backend uses this argument as an RNG seed and not as described above. Using the same seed yields the same random shape.
doc_30188
See Migration guide for more details. tf.compat.v1.raw_ops.Cumprod tf.raw_ops.Cumprod( x, axis, exclusive=False, reverse=False, name=None ) By default, this op performs an inclusive cumprod, which means that the first element of the input is identical to the first element of the output: tf.cumprod([a, b, c]) # => [a, a * b, a * b * c] By setting the exclusive kwarg to True, an exclusive cumprod is performed instead: tf.cumprod([a, b, c], exclusive=True) # => [1, a, a * b] By setting the reverse kwarg to True, the cumprod is performed in the opposite direction: tf.cumprod([a, b, c], reverse=True) # => [a * b * c, b * c, c] This is more efficient than using separate tf.reverse ops. The reverse and exclusive kwargs can also be combined: tf.cumprod([a, b, c], exclusive=True, reverse=True) # => [b * c, c, 1] Args x A Tensor. Must be one of the following types: float32, float64, int32, uint8, int16, int8, complex64, int64, qint8, quint8, qint32, bfloat16, uint16, complex128, half, uint32, uint64. A Tensor. Must be one of the following types: float32, float64, int64, int32, uint8, uint16, int16, int8, complex64, complex128, qint8, quint8, qint32, half. axis A Tensor. Must be one of the following types: int32, int64. A Tensor of type int32 (default: 0). Must be in the range [-rank(x), rank(x)). exclusive An optional bool. Defaults to False. If True, perform exclusive cumprod. reverse An optional bool. Defaults to False. A bool (default: False). name A name for the operation (optional). Returns A Tensor. Has the same type as x.
doc_30189
Select a scale for the range from vmin to vmax. Subclasses should override this method to change locator behaviour.
doc_30190
tf.compat.v1.batch_to_space( input, crops, block_size, name=None, block_shape=None ) This is a legacy version of the more general BatchToSpaceND. Rearranges (permutes) data from batch into blocks of spatial data, followed by cropping. This is the reverse transformation of SpaceToBatch. More specifically, this op outputs a copy of the input tensor where values from the batch dimension are moved in spatial blocks to the height and width dimensions, followed by cropping along the height and width dimensions. Args input A Tensor. 4-D tensor with shape [batch*block_size*block_size, height_pad/block_size, width_pad/block_size, depth]. Note that the batch size of the input tensor must be divisible by block_size * block_size. crops A Tensor. Must be one of the following types: int32, int64. 2-D tensor of non-negative integers with shape [2, 2]. It specifies how many elements to crop from the intermediate result across the spatial dimensions as follows: crops = [[crop_top, crop_bottom], [crop_left, crop_right]] block_size An int that is >= 2. name A name for the operation (optional). Returns A Tensor. Has the same type as input.
doc_30191
Fit the hierarchical clustering from features or distance matrix, and return cluster labels. Parameters Xarray-like of shape (n_samples, n_features) or (n_samples, n_samples) Training instances to cluster, or distances between instances if affinity='precomputed'. yIgnored Not used, present here for API consistency by convention. Returns labelsndarray of shape (n_samples,) Cluster labels.
doc_30192
Turn on attribute A_STANDOUT.
doc_30193
Convert y using the unit type of the yaxis. If the artist is not in contained in an Axes or if the yaxis does not have units, y itself is returned.
doc_30194
Module email Represent and manipulate messages. Mailbox objects class mailbox.Mailbox A mailbox, which may be inspected and modified. The Mailbox class defines an interface and is not intended to be instantiated. Instead, format-specific subclasses should inherit from Mailbox and your code should instantiate a particular subclass. The Mailbox interface is dictionary-like, with small keys corresponding to messages. Keys are issued by the Mailbox instance with which they will be used and are only meaningful to that Mailbox instance. A key continues to identify a message even if the corresponding message is modified, such as by replacing it with another message. Messages may be added to a Mailbox instance using the set-like method add() and removed using a del statement or the set-like methods remove() and discard(). Mailbox interface semantics differ from dictionary semantics in some noteworthy ways. Each time a message is requested, a new representation (typically a Message instance) is generated based upon the current state of the mailbox. Similarly, when a message is added to a Mailbox instance, the provided message representation’s contents are copied. In neither case is a reference to the message representation kept by the Mailbox instance. The default Mailbox iterator iterates over message representations, not keys as the default dictionary iterator does. Moreover, modification of a mailbox during iteration is safe and well-defined. Messages added to the mailbox after an iterator is created will not be seen by the iterator. Messages removed from the mailbox before the iterator yields them will be silently skipped, though using a key from an iterator may result in a KeyError exception if the corresponding message is subsequently removed. Warning Be very cautious when modifying mailboxes that might be simultaneously changed by some other process. The safest mailbox format to use for such tasks is Maildir; try to avoid using single-file formats such as mbox for concurrent writing. If you’re modifying a mailbox, you must lock it by calling the lock() and unlock() methods before reading any messages in the file or making any changes by adding or deleting a message. Failing to lock the mailbox runs the risk of losing messages or corrupting the entire mailbox. Mailbox instances have the following methods: add(message) Add message to the mailbox and return the key that has been assigned to it. Parameter message may be a Message instance, an email.message.Message instance, a string, a byte string, or a file-like object (which should be open in binary mode). If message is an instance of the appropriate format-specific Message subclass (e.g., if it’s an mboxMessage instance and this is an mbox instance), its format-specific information is used. Otherwise, reasonable defaults for format-specific information are used. Changed in version 3.2: Support for binary input was added. remove(key) __delitem__(key) discard(key) Delete the message corresponding to key from the mailbox. If no such message exists, a KeyError exception is raised if the method was called as remove() or __delitem__() but no exception is raised if the method was called as discard(). The behavior of discard() may be preferred if the underlying mailbox format supports concurrent modification by other processes. __setitem__(key, message) Replace the message corresponding to key with message. Raise a KeyError exception if no message already corresponds to key. As with add(), parameter message may be a Message instance, an email.message.Message instance, a string, a byte string, or a file-like object (which should be open in binary mode). If message is an instance of the appropriate format-specific Message subclass (e.g., if it’s an mboxMessage instance and this is an mbox instance), its format-specific information is used. Otherwise, the format-specific information of the message that currently corresponds to key is left unchanged. iterkeys() keys() Return an iterator over all keys if called as iterkeys() or return a list of keys if called as keys(). itervalues() __iter__() values() Return an iterator over representations of all messages if called as itervalues() or __iter__() or return a list of such representations if called as values(). The messages are represented as instances of the appropriate format-specific Message subclass unless a custom message factory was specified when the Mailbox instance was initialized. Note The behavior of __iter__() is unlike that of dictionaries, which iterate over keys. iteritems() items() Return an iterator over (key, message) pairs, where key is a key and message is a message representation, if called as iteritems() or return a list of such pairs if called as items(). The messages are represented as instances of the appropriate format-specific Message subclass unless a custom message factory was specified when the Mailbox instance was initialized. get(key, default=None) __getitem__(key) Return a representation of the message corresponding to key. If no such message exists, default is returned if the method was called as get() and a KeyError exception is raised if the method was called as __getitem__(). The message is represented as an instance of the appropriate format-specific Message subclass unless a custom message factory was specified when the Mailbox instance was initialized. get_message(key) Return a representation of the message corresponding to key as an instance of the appropriate format-specific Message subclass, or raise a KeyError exception if no such message exists. get_bytes(key) Return a byte representation of the message corresponding to key, or raise a KeyError exception if no such message exists. New in version 3.2. get_string(key) Return a string representation of the message corresponding to key, or raise a KeyError exception if no such message exists. The message is processed through email.message.Message to convert it to a 7bit clean representation. get_file(key) Return a file-like representation of the message corresponding to key, or raise a KeyError exception if no such message exists. The file-like object behaves as if open in binary mode. This file should be closed once it is no longer needed. Changed in version 3.2: The file object really is a binary file; previously it was incorrectly returned in text mode. Also, the file-like object now supports the context management protocol: you can use a with statement to automatically close it. Note Unlike other representations of messages, file-like representations are not necessarily independent of the Mailbox instance that created them or of the underlying mailbox. More specific documentation is provided by each subclass. __contains__(key) Return True if key corresponds to a message, False otherwise. __len__() Return a count of messages in the mailbox. clear() Delete all messages from the mailbox. pop(key, default=None) Return a representation of the message corresponding to key and delete the message. If no such message exists, return default. The message is represented as an instance of the appropriate format-specific Message subclass unless a custom message factory was specified when the Mailbox instance was initialized. popitem() Return an arbitrary (key, message) pair, where key is a key and message is a message representation, and delete the corresponding message. If the mailbox is empty, raise a KeyError exception. The message is represented as an instance of the appropriate format-specific Message subclass unless a custom message factory was specified when the Mailbox instance was initialized. update(arg) Parameter arg should be a key-to-message mapping or an iterable of (key, message) pairs. Updates the mailbox so that, for each given key and message, the message corresponding to key is set to message as if by using __setitem__(). As with __setitem__(), each key must already correspond to a message in the mailbox or else a KeyError exception will be raised, so in general it is incorrect for arg to be a Mailbox instance. Note Unlike with dictionaries, keyword arguments are not supported. flush() Write any pending changes to the filesystem. For some Mailbox subclasses, changes are always written immediately and flush() does nothing, but you should still make a habit of calling this method. lock() Acquire an exclusive advisory lock on the mailbox so that other processes know not to modify it. An ExternalClashError is raised if the lock is not available. The particular locking mechanisms used depend upon the mailbox format. You should always lock the mailbox before making any modifications to its contents. unlock() Release the lock on the mailbox, if any. close() Flush the mailbox, unlock it if necessary, and close any open files. For some Mailbox subclasses, this method does nothing. Maildir class mailbox.Maildir(dirname, factory=None, create=True) A subclass of Mailbox for mailboxes in Maildir format. Parameter factory is a callable object that accepts a file-like message representation (which behaves as if opened in binary mode) and returns a custom representation. If factory is None, MaildirMessage is used as the default message representation. If create is True, the mailbox is created if it does not exist. If create is True and the dirname path exists, it will be treated as an existing maildir without attempting to verify its directory layout. It is for historical reasons that dirname is named as such rather than path. Maildir is a directory-based mailbox format invented for the qmail mail transfer agent and now widely supported by other programs. Messages in a Maildir mailbox are stored in separate files within a common directory structure. This design allows Maildir mailboxes to be accessed and modified by multiple unrelated programs without data corruption, so file locking is unnecessary. Maildir mailboxes contain three subdirectories, namely: tmp, new, and cur. Messages are created momentarily in the tmp subdirectory and then moved to the new subdirectory to finalize delivery. A mail user agent may subsequently move the message to the cur subdirectory and store information about the state of the message in a special “info” section appended to its file name. Folders of the style introduced by the Courier mail transfer agent are also supported. Any subdirectory of the main mailbox is considered a folder if '.' is the first character in its name. Folder names are represented by Maildir without the leading '.'. Each folder is itself a Maildir mailbox but should not contain other folders. Instead, a logical nesting is indicated using '.' to delimit levels, e.g., “Archived.2005.07”. Note The Maildir specification requires the use of a colon (':') in certain message file names. However, some operating systems do not permit this character in file names, If you wish to use a Maildir-like format on such an operating system, you should specify another character to use instead. The exclamation point ('!') is a popular choice. For example: import mailbox mailbox.Maildir.colon = '!' The colon attribute may also be set on a per-instance basis. Maildir instances have all of the methods of Mailbox in addition to the following: list_folders() Return a list of the names of all folders. get_folder(folder) Return a Maildir instance representing the folder whose name is folder. A NoSuchMailboxError exception is raised if the folder does not exist. add_folder(folder) Create a folder whose name is folder and return a Maildir instance representing it. remove_folder(folder) Delete the folder whose name is folder. If the folder contains any messages, a NotEmptyError exception will be raised and the folder will not be deleted. clean() Delete temporary files from the mailbox that have not been accessed in the last 36 hours. The Maildir specification says that mail-reading programs should do this occasionally. Some Mailbox methods implemented by Maildir deserve special remarks: add(message) __setitem__(key, message) update(arg) Warning These methods generate unique file names based upon the current process ID. When using multiple threads, undetected name clashes may occur and cause corruption of the mailbox unless threads are coordinated to avoid using these methods to manipulate the same mailbox simultaneously. flush() All changes to Maildir mailboxes are immediately applied, so this method does nothing. lock() unlock() Maildir mailboxes do not support (or require) locking, so these methods do nothing. close() Maildir instances do not keep any open files and the underlying mailboxes do not support locking, so this method does nothing. get_file(key) Depending upon the host platform, it may not be possible to modify or remove the underlying message while the returned file remains open. See also maildir man page from Courier A specification of the format. Describes a common extension for supporting folders. Using maildir format Notes on Maildir by its inventor. Includes an updated name-creation scheme and details on “info” semantics. mbox class mailbox.mbox(path, factory=None, create=True) A subclass of Mailbox for mailboxes in mbox format. Parameter factory is a callable object that accepts a file-like message representation (which behaves as if opened in binary mode) and returns a custom representation. If factory is None, mboxMessage is used as the default message representation. If create is True, the mailbox is created if it does not exist. The mbox format is the classic format for storing mail on Unix systems. All messages in an mbox mailbox are stored in a single file with the beginning of each message indicated by a line whose first five characters are “From “. Several variations of the mbox format exist to address perceived shortcomings in the original. In the interest of compatibility, mbox implements the original format, which is sometimes referred to as mboxo. This means that the Content-Length header, if present, is ignored and that any occurrences of “From ” at the beginning of a line in a message body are transformed to “>From ” when storing the message, although occurrences of “>From ” are not transformed to “From ” when reading the message. Some Mailbox methods implemented by mbox deserve special remarks: get_file(key) Using the file after calling flush() or close() on the mbox instance may yield unpredictable results or raise an exception. lock() unlock() Three locking mechanisms are used—dot locking and, if available, the flock() and lockf() system calls. See also mbox man page from tin A specification of the format, with details on locking. Configuring Netscape Mail on Unix: Why The Content-Length Format is Bad An argument for using the original mbox format rather than a variation. “mbox” is a family of several mutually incompatible mailbox formats A history of mbox variations. MH class mailbox.MH(path, factory=None, create=True) A subclass of Mailbox for mailboxes in MH format. Parameter factory is a callable object that accepts a file-like message representation (which behaves as if opened in binary mode) and returns a custom representation. If factory is None, MHMessage is used as the default message representation. If create is True, the mailbox is created if it does not exist. MH is a directory-based mailbox format invented for the MH Message Handling System, a mail user agent. Each message in an MH mailbox resides in its own file. An MH mailbox may contain other MH mailboxes (called folders) in addition to messages. Folders may be nested indefinitely. MH mailboxes also support sequences, which are named lists used to logically group messages without moving them to sub-folders. Sequences are defined in a file called .mh_sequences in each folder. The MH class manipulates MH mailboxes, but it does not attempt to emulate all of mh’s behaviors. In particular, it does not modify and is not affected by the context or .mh_profile files that are used by mh to store its state and configuration. MH instances have all of the methods of Mailbox in addition to the following: list_folders() Return a list of the names of all folders. get_folder(folder) Return an MH instance representing the folder whose name is folder. A NoSuchMailboxError exception is raised if the folder does not exist. add_folder(folder) Create a folder whose name is folder and return an MH instance representing it. remove_folder(folder) Delete the folder whose name is folder. If the folder contains any messages, a NotEmptyError exception will be raised and the folder will not be deleted. get_sequences() Return a dictionary of sequence names mapped to key lists. If there are no sequences, the empty dictionary is returned. set_sequences(sequences) Re-define the sequences that exist in the mailbox based upon sequences, a dictionary of names mapped to key lists, like returned by get_sequences(). pack() Rename messages in the mailbox as necessary to eliminate gaps in numbering. Entries in the sequences list are updated correspondingly. Note Already-issued keys are invalidated by this operation and should not be subsequently used. Some Mailbox methods implemented by MH deserve special remarks: remove(key) __delitem__(key) discard(key) These methods immediately delete the message. The MH convention of marking a message for deletion by prepending a comma to its name is not used. lock() unlock() Three locking mechanisms are used—dot locking and, if available, the flock() and lockf() system calls. For MH mailboxes, locking the mailbox means locking the .mh_sequences file and, only for the duration of any operations that affect them, locking individual message files. get_file(key) Depending upon the host platform, it may not be possible to remove the underlying message while the returned file remains open. flush() All changes to MH mailboxes are immediately applied, so this method does nothing. close() MH instances do not keep any open files, so this method is equivalent to unlock(). See also nmh - Message Handling System Home page of nmh, an updated version of the original mh. MH & nmh: Email for Users & Programmers A GPL-licensed book on mh and nmh, with some information on the mailbox format. Babyl class mailbox.Babyl(path, factory=None, create=True) A subclass of Mailbox for mailboxes in Babyl format. Parameter factory is a callable object that accepts a file-like message representation (which behaves as if opened in binary mode) and returns a custom representation. If factory is None, BabylMessage is used as the default message representation. If create is True, the mailbox is created if it does not exist. Babyl is a single-file mailbox format used by the Rmail mail user agent included with Emacs. The beginning of a message is indicated by a line containing the two characters Control-Underscore ('\037') and Control-L ('\014'). The end of a message is indicated by the start of the next message or, in the case of the last message, a line containing a Control-Underscore ('\037') character. Messages in a Babyl mailbox have two sets of headers, original headers and so-called visible headers. Visible headers are typically a subset of the original headers that have been reformatted or abridged to be more attractive. Each message in a Babyl mailbox also has an accompanying list of labels, or short strings that record extra information about the message, and a list of all user-defined labels found in the mailbox is kept in the Babyl options section. Babyl instances have all of the methods of Mailbox in addition to the following: get_labels() Return a list of the names of all user-defined labels used in the mailbox. Note The actual messages are inspected to determine which labels exist in the mailbox rather than consulting the list of labels in the Babyl options section, but the Babyl section is updated whenever the mailbox is modified. Some Mailbox methods implemented by Babyl deserve special remarks: get_file(key) In Babyl mailboxes, the headers of a message are not stored contiguously with the body of the message. To generate a file-like representation, the headers and body are copied together into an io.BytesIO instance, which has an API identical to that of a file. As a result, the file-like object is truly independent of the underlying mailbox but does not save memory compared to a string representation. lock() unlock() Three locking mechanisms are used—dot locking and, if available, the flock() and lockf() system calls. See also Format of Version 5 Babyl Files A specification of the Babyl format. Reading Mail with Rmail The Rmail manual, with some information on Babyl semantics. MMDF class mailbox.MMDF(path, factory=None, create=True) A subclass of Mailbox for mailboxes in MMDF format. Parameter factory is a callable object that accepts a file-like message representation (which behaves as if opened in binary mode) and returns a custom representation. If factory is None, MMDFMessage is used as the default message representation. If create is True, the mailbox is created if it does not exist. MMDF is a single-file mailbox format invented for the Multichannel Memorandum Distribution Facility, a mail transfer agent. Each message is in the same form as an mbox message but is bracketed before and after by lines containing four Control-A ('\001') characters. As with the mbox format, the beginning of each message is indicated by a line whose first five characters are “From “, but additional occurrences of “From ” are not transformed to “>From ” when storing messages because the extra message separator lines prevent mistaking such occurrences for the starts of subsequent messages. Some Mailbox methods implemented by MMDF deserve special remarks: get_file(key) Using the file after calling flush() or close() on the MMDF instance may yield unpredictable results or raise an exception. lock() unlock() Three locking mechanisms are used—dot locking and, if available, the flock() and lockf() system calls. See also mmdf man page from tin A specification of MMDF format from the documentation of tin, a newsreader. MMDF A Wikipedia article describing the Multichannel Memorandum Distribution Facility. Message objects class mailbox.Message(message=None) A subclass of the email.message module’s Message. Subclasses of mailbox.Message add mailbox-format-specific state and behavior. If message is omitted, the new instance is created in a default, empty state. If message is an email.message.Message instance, its contents are copied; furthermore, any format-specific information is converted insofar as possible if message is a Message instance. If message is a string, a byte string, or a file, it should contain an RFC 2822-compliant message, which is read and parsed. Files should be open in binary mode, but text mode files are accepted for backward compatibility. The format-specific state and behaviors offered by subclasses vary, but in general it is only the properties that are not specific to a particular mailbox that are supported (although presumably the properties are specific to a particular mailbox format). For example, file offsets for single-file mailbox formats and file names for directory-based mailbox formats are not retained, because they are only applicable to the original mailbox. But state such as whether a message has been read by the user or marked as important is retained, because it applies to the message itself. There is no requirement that Message instances be used to represent messages retrieved using Mailbox instances. In some situations, the time and memory required to generate Message representations might not be acceptable. For such situations, Mailbox instances also offer string and file-like representations, and a custom message factory may be specified when a Mailbox instance is initialized. MaildirMessage class mailbox.MaildirMessage(message=None) A message with Maildir-specific behaviors. Parameter message has the same meaning as with the Message constructor. Typically, a mail user agent application moves all of the messages in the new subdirectory to the cur subdirectory after the first time the user opens and closes the mailbox, recording that the messages are old whether or not they’ve actually been read. Each message in cur has an “info” section added to its file name to store information about its state. (Some mail readers may also add an “info” section to messages in new.) The “info” section may take one of two forms: it may contain “2,” followed by a list of standardized flags (e.g., “2,FR”) or it may contain “1,” followed by so-called experimental information. Standard flags for Maildir messages are as follows: Flag Meaning Explanation D Draft Under composition F Flagged Marked as important P Passed Forwarded, resent, or bounced R Replied Replied to S Seen Read T Trashed Marked for subsequent deletion MaildirMessage instances offer the following methods: get_subdir() Return either “new” (if the message should be stored in the new subdirectory) or “cur” (if the message should be stored in the cur subdirectory). Note A message is typically moved from new to cur after its mailbox has been accessed, whether or not the message is has been read. A message msg has been read if "S" in msg.get_flags() is True. set_subdir(subdir) Set the subdirectory the message should be stored in. Parameter subdir must be either “new” or “cur”. get_flags() Return a string specifying the flags that are currently set. If the message complies with the standard Maildir format, the result is the concatenation in alphabetical order of zero or one occurrence of each of 'D', 'F', 'P', 'R', 'S', and 'T'. The empty string is returned if no flags are set or if “info” contains experimental semantics. set_flags(flags) Set the flags specified by flags and unset all others. add_flag(flag) Set the flag(s) specified by flag without changing other flags. To add more than one flag at a time, flag may be a string of more than one character. The current “info” is overwritten whether or not it contains experimental information rather than flags. remove_flag(flag) Unset the flag(s) specified by flag without changing other flags. To remove more than one flag at a time, flag maybe a string of more than one character. If “info” contains experimental information rather than flags, the current “info” is not modified. get_date() Return the delivery date of the message as a floating-point number representing seconds since the epoch. set_date(date) Set the delivery date of the message to date, a floating-point number representing seconds since the epoch. get_info() Return a string containing the “info” for a message. This is useful for accessing and modifying “info” that is experimental (i.e., not a list of flags). set_info(info) Set “info” to info, which should be a string. When a MaildirMessage instance is created based upon an mboxMessage or MMDFMessage instance, the Status and X-Status headers are omitted and the following conversions take place: Resulting state mboxMessage or MMDFMessage state “cur” subdirectory O flag F flag F flag R flag A flag S flag R flag T flag D flag When a MaildirMessage instance is created based upon an MHMessage instance, the following conversions take place: Resulting state MHMessage state “cur” subdirectory “unseen” sequence “cur” subdirectory and S flag no “unseen” sequence F flag “flagged” sequence R flag “replied” sequence When a MaildirMessage instance is created based upon a BabylMessage instance, the following conversions take place: Resulting state BabylMessage state “cur” subdirectory “unseen” label “cur” subdirectory and S flag no “unseen” label P flag “forwarded” or “resent” label R flag “answered” label T flag “deleted” label mboxMessage class mailbox.mboxMessage(message=None) A message with mbox-specific behaviors. Parameter message has the same meaning as with the Message constructor. Messages in an mbox mailbox are stored together in a single file. The sender’s envelope address and the time of delivery are typically stored in a line beginning with “From ” that is used to indicate the start of a message, though there is considerable variation in the exact format of this data among mbox implementations. Flags that indicate the state of the message, such as whether it has been read or marked as important, are typically stored in Status and X-Status headers. Conventional flags for mbox messages are as follows: Flag Meaning Explanation R Read Read O Old Previously detected by MUA D Deleted Marked for subsequent deletion F Flagged Marked as important A Answered Replied to The “R” and “O” flags are stored in the Status header, and the “D”, “F”, and “A” flags are stored in the X-Status header. The flags and headers typically appear in the order mentioned. mboxMessage instances offer the following methods: get_from() Return a string representing the “From ” line that marks the start of the message in an mbox mailbox. The leading “From ” and the trailing newline are excluded. set_from(from_, time_=None) Set the “From ” line to from_, which should be specified without a leading “From ” or trailing newline. For convenience, time_ may be specified and will be formatted appropriately and appended to from_. If time_ is specified, it should be a time.struct_time instance, a tuple suitable for passing to time.strftime(), or True (to use time.gmtime()). get_flags() Return a string specifying the flags that are currently set. If the message complies with the conventional format, the result is the concatenation in the following order of zero or one occurrence of each of 'R', 'O', 'D', 'F', and 'A'. set_flags(flags) Set the flags specified by flags and unset all others. Parameter flags should be the concatenation in any order of zero or more occurrences of each of 'R', 'O', 'D', 'F', and 'A'. add_flag(flag) Set the flag(s) specified by flag without changing other flags. To add more than one flag at a time, flag may be a string of more than one character. remove_flag(flag) Unset the flag(s) specified by flag without changing other flags. To remove more than one flag at a time, flag maybe a string of more than one character. When an mboxMessage instance is created based upon a MaildirMessage instance, a “From ” line is generated based upon the MaildirMessage instance’s delivery date, and the following conversions take place: Resulting state MaildirMessage state R flag S flag O flag “cur” subdirectory D flag T flag F flag F flag A flag R flag When an mboxMessage instance is created based upon an MHMessage instance, the following conversions take place: Resulting state MHMessage state R flag and O flag no “unseen” sequence O flag “unseen” sequence F flag “flagged” sequence A flag “replied” sequence When an mboxMessage instance is created based upon a BabylMessage instance, the following conversions take place: Resulting state BabylMessage state R flag and O flag no “unseen” label O flag “unseen” label D flag “deleted” label A flag “answered” label When a Message instance is created based upon an MMDFMessage instance, the “From ” line is copied and all flags directly correspond: Resulting state MMDFMessage state R flag R flag O flag O flag D flag D flag F flag F flag A flag A flag MHMessage class mailbox.MHMessage(message=None) A message with MH-specific behaviors. Parameter message has the same meaning as with the Message constructor. MH messages do not support marks or flags in the traditional sense, but they do support sequences, which are logical groupings of arbitrary messages. Some mail reading programs (although not the standard mh and nmh) use sequences in much the same way flags are used with other formats, as follows: Sequence Explanation unseen Not read, but previously detected by MUA replied Replied to flagged Marked as important MHMessage instances offer the following methods: get_sequences() Return a list of the names of sequences that include this message. set_sequences(sequences) Set the list of sequences that include this message. add_sequence(sequence) Add sequence to the list of sequences that include this message. remove_sequence(sequence) Remove sequence from the list of sequences that include this message. When an MHMessage instance is created based upon a MaildirMessage instance, the following conversions take place: Resulting state MaildirMessage state “unseen” sequence no S flag “replied” sequence R flag “flagged” sequence F flag When an MHMessage instance is created based upon an mboxMessage or MMDFMessage instance, the Status and X-Status headers are omitted and the following conversions take place: Resulting state mboxMessage or MMDFMessage state “unseen” sequence no R flag “replied” sequence A flag “flagged” sequence F flag When an MHMessage instance is created based upon a BabylMessage instance, the following conversions take place: Resulting state BabylMessage state “unseen” sequence “unseen” label “replied” sequence “answered” label BabylMessage class mailbox.BabylMessage(message=None) A message with Babyl-specific behaviors. Parameter message has the same meaning as with the Message constructor. Certain message labels, called attributes, are defined by convention to have special meanings. The attributes are as follows: Label Explanation unseen Not read, but previously detected by MUA deleted Marked for subsequent deletion filed Copied to another file or mailbox answered Replied to forwarded Forwarded edited Modified by the user resent Resent By default, Rmail displays only visible headers. The BabylMessage class, though, uses the original headers because they are more complete. Visible headers may be accessed explicitly if desired. BabylMessage instances offer the following methods: get_labels() Return a list of labels on the message. set_labels(labels) Set the list of labels on the message to labels. add_label(label) Add label to the list of labels on the message. remove_label(label) Remove label from the list of labels on the message. get_visible() Return an Message instance whose headers are the message’s visible headers and whose body is empty. set_visible(visible) Set the message’s visible headers to be the same as the headers in message. Parameter visible should be a Message instance, an email.message.Message instance, a string, or a file-like object (which should be open in text mode). update_visible() When a BabylMessage instance’s original headers are modified, the visible headers are not automatically modified to correspond. This method updates the visible headers as follows: each visible header with a corresponding original header is set to the value of the original header, each visible header without a corresponding original header is removed, and any of Date, From, Reply-To, To, CC, and Subject that are present in the original headers but not the visible headers are added to the visible headers. When a BabylMessage instance is created based upon a MaildirMessage instance, the following conversions take place: Resulting state MaildirMessage state “unseen” label no S flag “deleted” label T flag “answered” label R flag “forwarded” label P flag When a BabylMessage instance is created based upon an mboxMessage or MMDFMessage instance, the Status and X-Status headers are omitted and the following conversions take place: Resulting state mboxMessage or MMDFMessage state “unseen” label no R flag “deleted” label D flag “answered” label A flag When a BabylMessage instance is created based upon an MHMessage instance, the following conversions take place: Resulting state MHMessage state “unseen” label “unseen” sequence “answered” label “replied” sequence MMDFMessage class mailbox.MMDFMessage(message=None) A message with MMDF-specific behaviors. Parameter message has the same meaning as with the Message constructor. As with message in an mbox mailbox, MMDF messages are stored with the sender’s address and the delivery date in an initial line beginning with “From “. Likewise, flags that indicate the state of the message are typically stored in Status and X-Status headers. Conventional flags for MMDF messages are identical to those of mbox message and are as follows: Flag Meaning Explanation R Read Read O Old Previously detected by MUA D Deleted Marked for subsequent deletion F Flagged Marked as important A Answered Replied to The “R” and “O” flags are stored in the Status header, and the “D”, “F”, and “A” flags are stored in the X-Status header. The flags and headers typically appear in the order mentioned. MMDFMessage instances offer the following methods, which are identical to those offered by mboxMessage: get_from() Return a string representing the “From ” line that marks the start of the message in an mbox mailbox. The leading “From ” and the trailing newline are excluded. set_from(from_, time_=None) Set the “From ” line to from_, which should be specified without a leading “From ” or trailing newline. For convenience, time_ may be specified and will be formatted appropriately and appended to from_. If time_ is specified, it should be a time.struct_time instance, a tuple suitable for passing to time.strftime(), or True (to use time.gmtime()). get_flags() Return a string specifying the flags that are currently set. If the message complies with the conventional format, the result is the concatenation in the following order of zero or one occurrence of each of 'R', 'O', 'D', 'F', and 'A'. set_flags(flags) Set the flags specified by flags and unset all others. Parameter flags should be the concatenation in any order of zero or more occurrences of each of 'R', 'O', 'D', 'F', and 'A'. add_flag(flag) Set the flag(s) specified by flag without changing other flags. To add more than one flag at a time, flag may be a string of more than one character. remove_flag(flag) Unset the flag(s) specified by flag without changing other flags. To remove more than one flag at a time, flag maybe a string of more than one character. When an MMDFMessage instance is created based upon a MaildirMessage instance, a “From ” line is generated based upon the MaildirMessage instance’s delivery date, and the following conversions take place: Resulting state MaildirMessage state R flag S flag O flag “cur” subdirectory D flag T flag F flag F flag A flag R flag When an MMDFMessage instance is created based upon an MHMessage instance, the following conversions take place: Resulting state MHMessage state R flag and O flag no “unseen” sequence O flag “unseen” sequence F flag “flagged” sequence A flag “replied” sequence When an MMDFMessage instance is created based upon a BabylMessage instance, the following conversions take place: Resulting state BabylMessage state R flag and O flag no “unseen” label O flag “unseen” label D flag “deleted” label A flag “answered” label When an MMDFMessage instance is created based upon an mboxMessage instance, the “From ” line is copied and all flags directly correspond: Resulting state mboxMessage state R flag R flag O flag O flag D flag D flag F flag F flag A flag A flag Exceptions The following exception classes are defined in the mailbox module: exception mailbox.Error The based class for all other module-specific exceptions. exception mailbox.NoSuchMailboxError Raised when a mailbox is expected but is not found, such as when instantiating a Mailbox subclass with a path that does not exist (and with the create parameter set to False), or when opening a folder that does not exist. exception mailbox.NotEmptyError Raised when a mailbox is not empty but is expected to be, such as when deleting a folder that contains messages. exception mailbox.ExternalClashError Raised when some mailbox-related condition beyond the control of the program causes it to be unable to proceed, such as when failing to acquire a lock that another program already holds a lock, or when a uniquely-generated file name already exists. exception mailbox.FormatError Raised when the data in a file cannot be parsed, such as when an MH instance attempts to read a corrupted .mh_sequences file. Examples A simple example of printing the subjects of all messages in a mailbox that seem interesting: import mailbox for message in mailbox.mbox('~/mbox'): subject = message['subject'] # Could possibly be None. if subject and 'python' in subject.lower(): print(subject) To copy all mail from a Babyl mailbox to an MH mailbox, converting all of the format-specific information that can be converted: import mailbox destination = mailbox.MH('~/Mail') destination.lock() for message in mailbox.Babyl('~/RMAIL'): destination.add(mailbox.MHMessage(message)) destination.flush() destination.unlock() This example sorts mail from several mailing lists into different mailboxes, being careful to avoid mail corruption due to concurrent modification by other programs, mail loss due to interruption of the program, or premature termination due to malformed messages in the mailbox: import mailbox import email.errors list_names = ('python-list', 'python-dev', 'python-bugs') boxes = {name: mailbox.mbox('~/email/%s' % name) for name in list_names} inbox = mailbox.Maildir('~/Maildir', factory=None) for key in inbox.iterkeys(): try: message = inbox[key] except email.errors.MessageParseError: continue # The message is malformed. Just leave it. for name in list_names: list_id = message['list-id'] if list_id and name in list_id: # Get mailbox to use box = boxes[name] # Write copy to disk before removing original. # If there's a crash, you might duplicate a message, but # that's better than losing a message completely. box.lock() box.add(message) box.flush() box.unlock() # Remove original message inbox.lock() inbox.discard(key) inbox.flush() inbox.unlock() break # Found destination, so stop looking. for box in boxes.itervalues(): box.close()
doc_30195
Uses Pillow to ensure that value.name (value is a File) has a valid image extension.
doc_30196
A callable object or function. Calls to the partial object will be forwarded to func with new arguments and keywords.
doc_30197
tf.initializers.serialize Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.initializers.serialize tf.keras.initializers.serialize( initializer )
doc_30198
tf.compat.v1.metrics.true_positives_at_thresholds( labels, predictions, thresholds, weights=None, metrics_collections=None, updates_collections=None, name=None ) If weights is None, weights default to 1. Use weights of 0 to mask values. Args labels A Tensor whose shape matches predictions. Will be cast to bool. predictions A floating point Tensor of arbitrary shape and whose values are in the range [0, 1]. thresholds A python list or tuple of float thresholds in [0, 1]. weights Optional Tensor whose rank is either 0, or the same rank as labels, and must be broadcastable to labels (i.e., all dimensions must be either 1, or the same as the corresponding labels dimension). metrics_collections An optional list of collections that true_positives should be added to. updates_collections An optional list of collections that update_op should be added to. name An optional variable_scope name. Returns true_positives A float Tensor of shape [len(thresholds)]. update_op An operation that updates the true_positives variable and returns its current value. Raises ValueError If predictions and labels have mismatched shapes, or if weights is not None and its shape doesn't match predictions, or if either metrics_collections or updates_collections are not a list or tuple. RuntimeError If eager execution is enabled.
doc_30199
Starts the listener. This starts up a background thread to monitor the queue for LogRecords to process.