_id
stringlengths
5
9
text
stringlengths
5
385k
title
stringclasses
1 value
doc_25700
See Migration guide for more details. tf.compat.v1.app.flags.DEFINE_float tf.compat.v1.flags.DEFINE_float( name, default, help, lower_bound=None, upper_bound=None, flag_values=_flagvalues.FLAGS, **args ) If lower_bound or upper_bound are set, then this flag must be within the given range. Args name str, the flag name. default float|str|None, the default value of the flag. help str, the help message. lower_bound float, min value of the flag. upper_bound float, max value of the flag. flag_values FlagValues, the FlagValues instance with which the flag will be registered. This should almost never need to be overridden. **args dict, the extra keyword args that are passed to DEFINE. Returns a handle to defined flag.
doc_25701
from django.shortcuts import get_object_or_404 from myapps.serializers import UserSerializer from rest_framework import viewsets from rest_framework.response import Response class UserViewSet(viewsets.ViewSet): """ A simple ViewSet for listing or retrieving users. """ def list(self, request): queryset = User.objects.all() serializer = UserSerializer(queryset, many=True) return Response(serializer.data) def retrieve(self, request, pk=None): queryset = User.objects.all() user = get_object_or_404(queryset, pk=pk) serializer = UserSerializer(user) return Response(serializer.data) If we need to, we can bind this viewset into two separate views, like so: user_list = UserViewSet.as_view({'get': 'list'}) user_detail = UserViewSet.as_view({'get': 'retrieve'}) Typically we wouldn't do this, but would instead register the viewset with a router, and allow the urlconf to be automatically generated. from myapp.views import UserViewSet from rest_framework.routers import DefaultRouter router = DefaultRouter() router.register(r'users', UserViewSet, basename='user') urlpatterns = router.urls Rather than writing your own viewsets, you'll often want to use the existing base classes that provide a default set of behavior. For example: class UserViewSet(viewsets.ModelViewSet): """ A viewset for viewing and editing user instances. """ serializer_class = UserSerializer queryset = User.objects.all() There are two main advantages of using a ViewSet class over using a View class. Repeated logic can be combined into a single class. In the above example, we only need to specify the queryset once, and it'll be used across multiple views. By using routers, we no longer need to deal with wiring up the URL conf ourselves. Both of these come with a trade-off. Using regular views and URL confs is more explicit and gives you more control. ViewSets are helpful if you want to get up and running quickly, or when you have a large API and you want to enforce a consistent URL configuration throughout. ViewSet actions The default routers included with REST framework will provide routes for a standard set of create/retrieve/update/destroy style actions, as shown below: class UserViewSet(viewsets.ViewSet): """ Example empty viewset demonstrating the standard actions that will be handled by a router class. If you're using format suffixes, make sure to also include the `format=None` keyword argument for each action. """ def list(self, request): pass def create(self, request): pass def retrieve(self, request, pk=None): pass def update(self, request, pk=None): pass def partial_update(self, request, pk=None): pass def destroy(self, request, pk=None): pass Introspecting ViewSet actions During dispatch, the following attributes are available on the ViewSet. basename - the base to use for the URL names that are created. action - the name of the current action (e.g., list, create). detail - boolean indicating if the current action is configured for a list or detail view. suffix - the display suffix for the viewset type - mirrors the detail attribute. name - the display name for the viewset. This argument is mutually exclusive to suffix. description - the display description for the individual view of a viewset. You may inspect these attributes to adjust behaviour based on the current action. For example, you could restrict permissions to everything except the list action similar to this: def get_permissions(self): """ Instantiates and returns the list of permissions that this view requires. """ if self.action == 'list': permission_classes = [IsAuthenticated] else: permission_classes = [IsAdmin] return [permission() for permission in permission_classes] Marking extra actions for routing If you have ad-hoc methods that should be routable, you can mark them as such with the @action decorator. Like regular actions, extra actions may be intended for either a single object, or an entire collection. To indicate this, set the detail argument to True or False. The router will configure its URL patterns accordingly. e.g., the DefaultRouter will configure detail actions to contain pk in their URL patterns. A more complete example of extra actions: from django.contrib.auth.models import User from rest_framework import status, viewsets from rest_framework.decorators import action from rest_framework.response import Response from myapp.serializers import UserSerializer, PasswordSerializer class UserViewSet(viewsets.ModelViewSet): """ A viewset that provides the standard actions """ queryset = User.objects.all() serializer_class = UserSerializer @action(detail=True, methods=['post']) def set_password(self, request, pk=None): user = self.get_object() serializer = PasswordSerializer(data=request.data) if serializer.is_valid(): user.set_password(serializer.validated_data['password']) user.save() return Response({'status': 'password set'}) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) @action(detail=False) def recent_users(self, request): recent_users = User.objects.all().order_by('-last_login') page = self.paginate_queryset(recent_users) if page is not None: serializer = self.get_serializer(page, many=True) return self.get_paginated_response(serializer.data) serializer = self.get_serializer(recent_users, many=True) return Response(serializer.data) The action decorator will route GET requests by default, but may also accept other HTTP methods by setting the methods argument. For example: @action(detail=True, methods=['post', 'delete']) def unset_password(self, request, pk=None): ... The decorator allows you to override any viewset-level configuration such as permission_classes, serializer_class, filter_backends...: @action(detail=True, methods=['post'], permission_classes=[IsAdminOrIsSelf]) def set_password(self, request, pk=None): ... The two new actions will then be available at the urls ^users/{pk}/set_password/$ and ^users/{pk}/unset_password/$. Use the url_path and url_name parameters to change the URL segment and the reverse URL name of the action. To view all extra actions, call the .get_extra_actions() method. Routing additional HTTP methods for extra actions Extra actions can map additional HTTP methods to separate ViewSet methods. For example, the above password set/unset methods could be consolidated into a single route. Note that additional mappings do not accept arguments. @action(detail=True, methods=['put'], name='Change Password') def password(self, request, pk=None): """Update the user's password.""" ... @password.mapping.delete def delete_password(self, request, pk=None): """Delete the user's password.""" ... Reversing action URLs If you need to get the URL of an action, use the .reverse_action() method. This is a convenience wrapper for reverse(), automatically passing the view's request object and prepending the url_name with the .basename attribute. Note that the basename is provided by the router during ViewSet registration. If you are not using a router, then you must provide the basename argument to the .as_view() method. Using the example from the previous section: >>> view.reverse_action('set-password', args=['1']) 'http://localhost:8000/api/users/1/set_password' Alternatively, you can use the url_name attribute set by the @action decorator. >>> view.reverse_action(view.set_password.url_name, args=['1']) 'http://localhost:8000/api/users/1/set_password' The url_name argument for .reverse_action() should match the same argument to the @action decorator. Additionally, this method can be used to reverse the default actions, such as list and create. API Reference ViewSet The ViewSet class inherits from APIView. You can use any of the standard attributes such as permission_classes, authentication_classes in order to control the API policy on the viewset. The ViewSet class does not provide any implementations of actions. In order to use a ViewSet class you'll override the class and define the action implementations explicitly. GenericViewSet The GenericViewSet class inherits from GenericAPIView, and provides the default set of get_object, get_queryset methods and other generic view base behavior, but does not include any actions by default. In order to use a GenericViewSet class you'll override the class and either mixin the required mixin classes, or define the action implementations explicitly. ModelViewSet The ModelViewSet class inherits from GenericAPIView and includes implementations for various actions, by mixing in the behavior of the various mixin classes. The actions provided by the ModelViewSet class are .list(), .retrieve(), .create(), .update(), .partial_update(), and .destroy(). Example Because ModelViewSet extends GenericAPIView, you'll normally need to provide at least the queryset and serializer_class attributes. For example: class AccountViewSet(viewsets.ModelViewSet): """ A simple ViewSet for viewing and editing accounts. """ queryset = Account.objects.all() serializer_class = AccountSerializer permission_classes = [IsAccountAdminOrReadOnly] Note that you can use any of the standard attributes or method overrides provided by GenericAPIView. For example, to use a ViewSet that dynamically determines the queryset it should operate on, you might do something like this: class AccountViewSet(viewsets.ModelViewSet): """ A simple ViewSet for viewing and editing the accounts associated with the user. """ serializer_class = AccountSerializer permission_classes = [IsAccountAdminOrReadOnly] def get_queryset(self): return self.request.user.accounts.all() Note however that upon removal of the queryset property from your ViewSet, any associated router will be unable to derive the basename of your Model automatically, and so you will have to specify the basename kwarg as part of your router registration. Also note that although this class provides the complete set of create/list/retrieve/update/destroy actions by default, you can restrict the available operations by using the standard permission classes. ReadOnlyModelViewSet The ReadOnlyModelViewSet class also inherits from GenericAPIView. As with ModelViewSet it also includes implementations for various actions, but unlike ModelViewSet only provides the 'read-only' actions, .list() and .retrieve(). Example As with ModelViewSet, you'll normally need to provide at least the queryset and serializer_class attributes. For example: class AccountViewSet(viewsets.ReadOnlyModelViewSet): """ A simple ViewSet for viewing accounts. """ queryset = Account.objects.all() serializer_class = AccountSerializer Again, as with ModelViewSet, you can use any of the standard attributes and method overrides available to GenericAPIView. Custom ViewSet base classes You may need to provide custom ViewSet classes that do not have the full set of ModelViewSet actions, or that customize the behavior in some other way. Example To create a base viewset class that provides create, list and retrieve operations, inherit from GenericViewSet, and mixin the required actions: from rest_framework import mixins class CreateListRetrieveViewSet(mixins.CreateModelMixin, mixins.ListModelMixin, mixins.RetrieveModelMixin, viewsets.GenericViewSet): """ A viewset that provides `retrieve`, `create`, and `list` actions. To use it, override the class and set the `.queryset` and `.serializer_class` attributes. """ pass By creating your own base ViewSet classes, you can provide common behavior that can be reused in multiple viewsets across your API. viewsets.py
doc_25702
A subclass of ConnectionResetError and BadStatusLine. Raised by HTTPConnection.getresponse() when the attempt to read the response results in no data read from the connection, indicating that the remote end has closed the connection. New in version 3.5: Previously, BadStatusLine('') was raised.
doc_25703
Returns the diagonal of the kernel k(X, X). The result of this method is identical to np.diag(self(X)); however, it can be evaluated more efficiently since only the diagonal is evaluated. Parameters Xarray-like of shape (n_samples_X, n_features) or list of object Argument to the kernel. Returns K_diagndarray of shape (n_samples_X,) Diagonal of kernel k(X, X)
doc_25704
Return 'PROPNAME or alias' if s has an alias, else return 'PROPNAME', formatted for reST. e.g., for the line markerfacecolor property, which has an alias, return 'markerfacecolor or mfc' and for the transform property, which does not, return 'transform'.
doc_25705
Add one polynomial to another. Returns the sum of two polynomials c1 + c2. The arguments are sequences of coefficients from lowest order term to highest, i.e., [1,2,3] represents the polynomial 1 + 2*x + 3*x**2. Parameters c1, c2array_like 1-D arrays of polynomial coefficients ordered from low to high. Returns outndarray The coefficient array representing their sum. See also polysub, polymulx, polymul, polydiv, polypow Examples >>> from numpy.polynomial import polynomial as P >>> c1 = (1,2,3) >>> c2 = (3,2,1) >>> sum = P.polyadd(c1,c2); sum array([4., 4., 4.]) >>> P.polyval(2, sum) # 4 + 4(2) + 4(2**2) 28.0
doc_25706
Return the file system representation of the path. If str or bytes is passed in, it is returned unchanged. Otherwise __fspath__() is called and its value is returned as long as it is a str or bytes object. In all other cases, TypeError is raised. New in version 3.6.
doc_25707
True if the address is allocated for public networks. See iana-ipv4-special-registry (for IPv4) or iana-ipv6-special-registry (for IPv6). New in version 3.4.
doc_25708
Return the values (min, max) that are mapped to the colormap limits.
doc_25709
Roll provided date forward to next offset only if not on offset. Returns TimeStamp Rolled timestamp if not on offset, otherwise unchanged timestamp.
doc_25710
tf.compat.v1.train.Supervisor( graph=None, ready_op=USE_DEFAULT, ready_for_local_init_op=USE_DEFAULT, is_chief=True, init_op=USE_DEFAULT, init_feed_dict=None, local_init_op=USE_DEFAULT, logdir=None, summary_op=USE_DEFAULT, saver=USE_DEFAULT, global_step=USE_DEFAULT, save_summaries_secs=120, save_model_secs=600, recovery_wait_secs=30, stop_grace_secs=120, checkpoint_basename='model.ckpt', session_manager=None, summary_writer=USE_DEFAULT, init_fn=None, local_init_run_options=None ) This class is deprecated. Please use tf.compat.v1.train.MonitoredTrainingSession instead. The Supervisor is a small wrapper around a Coordinator, a Saver, and a SessionManager that takes care of common needs of TensorFlow training programs. Use for a single program with tf.Graph().as_default(): ...add operations to the graph... # Create a Supervisor that will checkpoint the model in '/tmp/mydir'. sv = Supervisor(logdir='/tmp/mydir') # Get a TensorFlow session managed by the supervisor. with sv.managed_session(FLAGS.master) as sess: # Use the session to train the graph. while not sv.should_stop(): sess.run(<my_train_op>) Within the with sv.managed_session() block all variables in the graph have been initialized. In addition, a few services have been started to checkpoint the model and add summaries to the event log. If the program crashes and is restarted, the managed session automatically reinitialize variables from the most recent checkpoint. The supervisor is notified of any exception raised by one of the services. After an exception is raised, should_stop() returns True. In that case the training loop should also stop. This is why the training loop has to check for sv.should_stop(). Exceptions that indicate that the training inputs have been exhausted, tf.errors.OutOfRangeError, also cause sv.should_stop() to return True but are not re-raised from the with block: they indicate a normal termination. Use for multiple replicas To train with replicas you deploy the same program in a Cluster. One of the tasks must be identified as the chief: the task that handles initialization, checkpoints, summaries, and recovery. The other tasks depend on the chief for these services. The only change you have to do to the single program code is to indicate if the program is running as the chief. # Choose a task as the chief. This could be based on server_def.task_index, # or job_def.name, or job_def.tasks. It's entirely up to the end user. # But there can be only one *chief*. is_chief = (server_def.task_index == 0) server = tf.distribute.Server(server_def) with tf.Graph().as_default(): ...add operations to the graph... # Create a Supervisor that uses log directory on a shared file system. # Indicate if you are the 'chief' sv = Supervisor(logdir='/shared_directory/...', is_chief=is_chief) # Get a Session in a TensorFlow server on the cluster. with sv.managed_session(server.target) as sess: # Use the session to train the graph. while not sv.should_stop(): sess.run(<my_train_op>) In the chief task, the Supervisor works exactly as in the first example above. In the other tasks sv.managed_session() waits for the Model to have been initialized before returning a session to the training code. The non-chief tasks depend on the chief task for initializing the model. If one of the tasks crashes and restarts, managed_session() checks if the Model is initialized. If yes, it just creates a session and returns it to the training code that proceeds normally. If the model needs to be initialized, the chief task takes care of reinitializing it; the other tasks just wait for the model to have been initialized. Note: This modified program still works fine as a single program. The single program marks itself as the chief. What master string to use Whether you are running on your machine or in the cluster you can use the following values for the --master flag: Specifying '' requests an in-process session that does not use RPC. Specifying 'local' requests a session that uses the RPC-based "Master interface" to run TensorFlow programs. See tf.train.Server.create_local_server for details. Specifying 'grpc://hostname:port' requests a session that uses the RPC interface to a specific host, and also allows the in-process master to access remote tensorflow workers. Often, it is appropriate to pass server.target (for some tf.distribute.Server named `server). Advanced use Launching additional services managed_session() launches the Checkpoint and Summary services (threads). If you need more services to run you can simply launch them in the block controlled by managed_session(). Example: Start a thread to print losses. We want this thread to run every 60 seconds, so we launch it with sv.loop(). ... sv = Supervisor(logdir='/tmp/mydir') with sv.managed_session(FLAGS.master) as sess: sv.loop(60, print_loss, (sess, )) while not sv.should_stop(): sess.run(my_train_op) Launching fewer services managed_session() launches the "summary" and "checkpoint" threads which use either the optionally summary_op and saver passed to the constructor, or default ones created automatically by the supervisor. If you want to run your own summary and checkpointing logic, disable these services by passing None to the summary_op and saver parameters. Example: Create summaries manually every 100 steps in the chief. # Create a Supervisor with no automatic summaries. sv = Supervisor(logdir='/tmp/mydir', is_chief=is_chief, summary_op=None) # As summary_op was None, managed_session() does not start the # summary thread. with sv.managed_session(FLAGS.master) as sess: for step in xrange(1000000): if sv.should_stop(): break if is_chief and step % 100 == 0: # Create the summary every 100 chief steps. sv.summary_computed(sess, sess.run(my_summary_op)) else: # Train normally sess.run(my_train_op) Custom model initialization managed_session() only supports initializing the model by running an init_op or restoring from the latest checkpoint. If you have special initialization needs, see how to specify a local_init_op when creating the supervisor. You can also use the SessionManager directly to create a session and check if it could be initialized automatically. Args graph A Graph. The graph that the model will use. Defaults to the default Graph. The supervisor may add operations to the graph before creating a session, but the graph should not be modified by the caller after passing it to the supervisor. ready_op 1-D string Tensor. This tensor is evaluated by supervisors in prepare_or_wait_for_session() to check if the model is ready to use. The model is considered ready if it returns an empty array. Defaults to the tensor returned from tf.compat.v1.report_uninitialized_variables() If None, the model is not checked for readiness. ready_for_local_init_op 1-D string Tensor. This tensor is evaluated by supervisors in prepare_or_wait_for_session() to check if the model is ready to run the local_init_op. The model is considered ready if it returns an empty array. Defaults to None. If None, the model is not checked for readiness before running local_init_op. is_chief If True, create a chief supervisor in charge of initializing and restoring the model. If False, create a supervisor that relies on a chief supervisor for inits and restore. init_op Operation. Used by chief supervisors to initialize the model when it can not be recovered. Defaults to an Operation that initializes all global variables. If None, no initialization is done automatically unless you pass a value for init_fn, see below. init_feed_dict A dictionary that maps Tensor objects to feed values. This feed dictionary will be used when init_op is evaluated. local_init_op Operation. Used by all supervisors to run initializations that should run for every new supervisor instance. By default these are table initializers and initializers for local variables. If None, no further per supervisor-instance initialization is done automatically. logdir A string. Optional path to a directory where to checkpoint the model and log events for the visualizer. Used by chief supervisors. The directory will be created if it does not exist. summary_op An Operation that returns a Summary for the event logs. Used by chief supervisors if a logdir was specified. Defaults to the operation returned from summary.merge_all(). If None, summaries are not computed automatically. saver A Saver object. Used by chief supervisors if a logdir was specified. Defaults to the saved returned by Saver(). If None, the model is not saved automatically. global_step An integer Tensor of size 1 that counts steps. The value from 'global_step' is used in summaries and checkpoint filenames. Default to the op named 'global_step' in the graph if it exists, is of rank 1, size 1, and of type tf.int32 or tf.int64. If None the global step is not recorded in summaries and checkpoint files. Used by chief supervisors if a logdir was specified. save_summaries_secs Number of seconds between the computation of summaries for the event log. Defaults to 120 seconds. Pass 0 to disable summaries. save_model_secs Number of seconds between the creation of model checkpoints. Defaults to 600 seconds. Pass 0 to disable checkpoints. recovery_wait_secs Number of seconds between checks that the model is ready. Used by supervisors when waiting for a chief supervisor to initialize or restore the model. Defaults to 30 seconds. stop_grace_secs Grace period, in seconds, given to running threads to stop when stop() is called. Defaults to 120 seconds. checkpoint_basename The basename for checkpoint saving. session_manager SessionManager, which manages Session creation and recovery. If it is None, a default SessionManager will be created with the set of arguments passed in for backwards compatibility. summary_writer SummaryWriter to use or USE_DEFAULT. Can be None to indicate that no summaries should be written. init_fn Optional callable used to initialize the model. Called after the optional init_op is called. The callable must accept one argument, the session being initialized. local_init_run_options RunOptions to be passed as the SessionManager local_init_run_options parameter. Raises RuntimeError If called with eager execution enabled. Attributes coord Return the Coordinator used by the Supervisor. The Coordinator can be useful if you want to run multiple threads during your training. global_step Return the global_step Tensor used by the supervisor. init_feed_dict Return the feed dictionary used when evaluating the init_op. init_op Return the Init Op used by the supervisor. is_chief Return True if this is a chief supervisor. ready_for_local_init_op ready_op Return the Ready Op used by the supervisor. save_model_secs Return the delay between checkpoints. save_path Return the save path used by the supervisor. save_summaries_secs Return the delay between summary computations. saver Return the Saver used by the supervisor. session_manager Return the SessionManager used by the Supervisor. summary_op Return the Summary Tensor used by the chief supervisor. summary_writer Return the SummaryWriter used by the chief supervisor. Methods Loop View source Loop( timer_interval_secs, target, args=None, kwargs=None ) Start a LooperThread that calls a function periodically. If timer_interval_secs is None the thread calls target(*args, **kwargs) repeatedly. Otherwise it calls it every timer_interval_secs seconds. The thread terminates when a stop is requested. The started thread is added to the list of threads managed by the supervisor so it does not need to be passed to the stop() method. Args timer_interval_secs Number. Time boundaries at which to call target. target A callable object. args Optional arguments to pass to target when calling it. kwargs Optional keyword arguments to pass to target when calling it. Returns The started thread. PrepareSession View source PrepareSession( master='', config=None, wait_for_checkpoint=False, max_wait_secs=7200, start_standard_services=True ) Make sure the model is ready to be used. Create a session on 'master', recovering or initializing the model as needed, or wait for a session to be ready. If running as the chief and start_standard_service is set to True, also call the session manager to start the standard services. Args master name of the TensorFlow master to use. See the tf.compat.v1.Session constructor for how this is interpreted. config Optional ConfigProto proto used to configure the session, which is passed as-is to create the session. wait_for_checkpoint Whether we should wait for the availability of a checkpoint before creating Session. Defaults to False. max_wait_secs Maximum time to wait for the session to become available. start_standard_services Whether to start the standard services and the queue runners. Returns A Session object that can be used to drive the model. RequestStop View source RequestStop( ex=None ) Request that the coordinator stop the threads. See Coordinator.request_stop(). Args ex Optional Exception, or Python exc_info tuple as returned by sys.exc_info(). If this is the first call to request_stop() the corresponding exception is recorded and re-raised from join(). ShouldStop View source ShouldStop() Check if the coordinator was told to stop. See Coordinator.should_stop(). Returns True if the coordinator was told to stop, False otherwise. StartQueueRunners View source StartQueueRunners( sess, queue_runners=None ) Start threads for QueueRunners. Note that the queue runners collected in the graph key QUEUE_RUNNERS are already started automatically when you create a session with the supervisor, so unless you have non-collected queue runners to start you do not need to call this explicitly. Args sess A Session. queue_runners A list of QueueRunners. If not specified, we'll use the list of queue runners gathered in the graph under the key GraphKeys.QUEUE_RUNNERS. Returns The list of threads started for the QueueRunners. Raises RuntimeError If called with eager execution enabled. Eager Compatibility Queues are not compatible with eager execution. To ingest data when eager execution is enabled, use the tf.data API. StartStandardServices View source StartStandardServices( sess ) Start the standard services for 'sess'. This starts services in the background. The services started depend on the parameters to the constructor and may include: A Summary thread computing summaries every save_summaries_secs. A Checkpoint thread saving the model every save_model_secs. A StepCounter thread measure step time. Args sess A Session. Returns A list of threads that are running the standard services. You can use the Supervisor's Coordinator to join these threads with: sv.coord.Join() Raises RuntimeError If called with a non-chief Supervisor. ValueError If not logdir was passed to the constructor as the services need a log directory. Stop View source Stop( threads=None, close_summary_writer=True, ignore_live_threads=False ) Stop the services and the coordinator. This does not close the session. Args threads Optional list of threads to join with the coordinator. If None, defaults to the threads running the standard services, the threads started for QueueRunners, and the threads started by the loop() method. To wait on additional threads, pass the list in this parameter. close_summary_writer Whether to close the summary_writer. Defaults to True if the summary writer was created by the supervisor, False otherwise. ignore_live_threads If True ignores threads that remain running after a grace period when joining threads via the coordinator, instead of raising a RuntimeError. StopOnException View source StopOnException() Context handler to stop the supervisor when an exception is raised. See Coordinator.stop_on_exception(). Returns A context handler. SummaryComputed View source SummaryComputed( sess, summary, global_step=None ) Indicate that a summary was computed. Args sess A Session object. summary A Summary proto, or a string holding a serialized summary proto. global_step Int. global step this summary is associated with. If None, it will try to fetch the current step. Raises TypeError if 'summary' is not a Summary proto or a string. RuntimeError if the Supervisor was created without a logdir. WaitForStop View source WaitForStop() Block waiting for the coordinator to stop. loop View source loop( timer_interval_secs, target, args=None, kwargs=None ) Start a LooperThread that calls a function periodically. If timer_interval_secs is None the thread calls target(*args, **kwargs) repeatedly. Otherwise it calls it every timer_interval_secs seconds. The thread terminates when a stop is requested. The started thread is added to the list of threads managed by the supervisor so it does not need to be passed to the stop() method. Args timer_interval_secs Number. Time boundaries at which to call target. target A callable object. args Optional arguments to pass to target when calling it. kwargs Optional keyword arguments to pass to target when calling it. Returns The started thread. managed_session View source @contextlib.contextmanager managed_session( master='', config=None, start_standard_services=True, close_summary_writer=True ) Returns a context manager for a managed session. This context manager creates and automatically recovers a session. It optionally starts the standard services that handle checkpoints and summaries. It monitors exceptions raised from the with block or from the services and stops the supervisor as needed. The context manager is typically used as follows: def train(): sv = tf.compat.v1.train.Supervisor(...) with sv.managed_session(<master>) as sess: for step in xrange(..): if sv.should_stop(): break sess.run(<my training op>) ...do other things needed at each training step... An exception raised from the with block or one of the service threads is raised again when the block exits. This is done after stopping all threads and closing the session. For example, an AbortedError exception, raised in case of preemption of one of the workers in a distributed model, is raised again when the block exits. If you want to retry the training loop in case of preemption you can do it as follows: def main(...): while True try: train() except tf.errors.Aborted: pass As a special case, exceptions used for control flow, such as OutOfRangeError which reports that input queues are exhausted, are not raised again from the with block: they indicate a clean termination of the training loop and are considered normal termination. Args master name of the TensorFlow master to use. See the tf.compat.v1.Session constructor for how this is interpreted. config Optional ConfigProto proto used to configure the session. Passed as-is to create the session. start_standard_services Whether to start the standard services, such as checkpoint, summary and step counter. close_summary_writer Whether to close the summary writer when closing the session. Defaults to True. Returns A context manager that yields a Session restored from the latest checkpoint or initialized from scratch if not checkpoint exists. The session is closed when the with block exits. prepare_or_wait_for_session View source prepare_or_wait_for_session( master='', config=None, wait_for_checkpoint=False, max_wait_secs=7200, start_standard_services=True ) Make sure the model is ready to be used. Create a session on 'master', recovering or initializing the model as needed, or wait for a session to be ready. If running as the chief and start_standard_service is set to True, also call the session manager to start the standard services. Args master name of the TensorFlow master to use. See the tf.compat.v1.Session constructor for how this is interpreted. config Optional ConfigProto proto used to configure the session, which is passed as-is to create the session. wait_for_checkpoint Whether we should wait for the availability of a checkpoint before creating Session. Defaults to False. max_wait_secs Maximum time to wait for the session to become available. start_standard_services Whether to start the standard services and the queue runners. Returns A Session object that can be used to drive the model. request_stop View source request_stop( ex=None ) Request that the coordinator stop the threads. See Coordinator.request_stop(). Args ex Optional Exception, or Python exc_info tuple as returned by sys.exc_info(). If this is the first call to request_stop() the corresponding exception is recorded and re-raised from join(). should_stop View source should_stop() Check if the coordinator was told to stop. See Coordinator.should_stop(). Returns True if the coordinator was told to stop, False otherwise. start_queue_runners View source start_queue_runners( sess, queue_runners=None ) Start threads for QueueRunners. Note that the queue runners collected in the graph key QUEUE_RUNNERS are already started automatically when you create a session with the supervisor, so unless you have non-collected queue runners to start you do not need to call this explicitly. Args sess A Session. queue_runners A list of QueueRunners. If not specified, we'll use the list of queue runners gathered in the graph under the key GraphKeys.QUEUE_RUNNERS. Returns The list of threads started for the QueueRunners. Raises RuntimeError If called with eager execution enabled. Eager Compatibility Queues are not compatible with eager execution. To ingest data when eager execution is enabled, use the tf.data API. start_standard_services View source start_standard_services( sess ) Start the standard services for 'sess'. This starts services in the background. The services started depend on the parameters to the constructor and may include: A Summary thread computing summaries every save_summaries_secs. A Checkpoint thread saving the model every save_model_secs. A StepCounter thread measure step time. Args sess A Session. Returns A list of threads that are running the standard services. You can use the Supervisor's Coordinator to join these threads with: sv.coord.Join() Raises RuntimeError If called with a non-chief Supervisor. ValueError If not logdir was passed to the constructor as the services need a log directory. stop View source stop( threads=None, close_summary_writer=True, ignore_live_threads=False ) Stop the services and the coordinator. This does not close the session. Args threads Optional list of threads to join with the coordinator. If None, defaults to the threads running the standard services, the threads started for QueueRunners, and the threads started by the loop() method. To wait on additional threads, pass the list in this parameter. close_summary_writer Whether to close the summary_writer. Defaults to True if the summary writer was created by the supervisor, False otherwise. ignore_live_threads If True ignores threads that remain running after a grace period when joining threads via the coordinator, instead of raising a RuntimeError. stop_on_exception View source stop_on_exception() Context handler to stop the supervisor when an exception is raised. See Coordinator.stop_on_exception(). Returns A context handler. summary_computed View source summary_computed( sess, summary, global_step=None ) Indicate that a summary was computed. Args sess A Session object. summary A Summary proto, or a string holding a serialized summary proto. global_step Int. global step this summary is associated with. If None, it will try to fetch the current step. Raises TypeError if 'summary' is not a Summary proto or a string. RuntimeError if the Supervisor was created without a logdir. wait_for_stop View source wait_for_stop() Block waiting for the coordinator to stop. Class Variables USE_DEFAULT 0
doc_25711
See Migration guide for more details. tf.compat.v1.raw_ops.BoostedTreesDeserializeEnsemble tf.raw_ops.BoostedTreesDeserializeEnsemble( tree_ensemble_handle, stamp_token, tree_ensemble_serialized, name=None ) ensemble. Args tree_ensemble_handle A Tensor of type resource. Handle to the tree ensemble. stamp_token A Tensor of type int64. Token to use as the new value of the resource stamp. tree_ensemble_serialized A Tensor of type string. Serialized proto of the ensemble. name A name for the operation (optional). Returns The created Operation.
doc_25712
Schedule the callback callback to be called with args arguments at the next iteration of the event loop. Callbacks are called in the order in which they are registered. Each callback will be called exactly once. An optional keyword-only context argument allows specifying a custom contextvars.Context for the callback to run in. The current context is used when no context is provided. An instance of asyncio.Handle is returned, which can be used later to cancel the callback. This method is not thread-safe.
doc_25713
See Migration guide for more details. tf.compat.v1.image.yuv_to_rgb tf.image.yuv_to_rgb( images ) Outputs a tensor of the same shape as the images tensor, containing the RGB value of the pixels. The output is only well defined if the Y value in images are in [0,1], U and V value are in [-0.5,0.5]. As per the above description, you need to scale your YUV images if their pixel values are not in the required range. Below given example illustrates preprocessing of each channel of images before feeding them to yuv_to_rgb. yuv_images = tf.random.uniform(shape=[100, 64, 64, 3], maxval=255) last_dimension_axis = len(yuv_images.shape) - 1 yuv_tensor_images = tf.truediv( tf.subtract( yuv_images, tf.reduce_min(yuv_images) ), tf.subtract( tf.reduce_max(yuv_images), tf.reduce_min(yuv_images) ) ) y, u, v = tf.split(yuv_tensor_images, 3, axis=last_dimension_axis) target_uv_min, target_uv_max = -0.5, 0.5 u = u * (target_uv_max - target_uv_min) + target_uv_min v = v * (target_uv_max - target_uv_min) + target_uv_min preprocessed_yuv_images = tf.concat([y, u, v], axis=last_dimension_axis) rgb_tensor_images = tf.image.yuv_to_rgb(preprocessed_yuv_images) Args images 2-D or higher rank. Image data to convert. Last dimension must be size 3. Returns images tensor with the same shape as images.
doc_25714
Least Squares projection of the data onto the sparse components. To avoid instability issues in case the system is under-determined, regularization can be applied (Ridge regression) via the ridge_alpha parameter. Note that Sparse PCA components orthogonality is not enforced as in PCA hence one cannot use a simple linear projection. Parameters Xndarray of shape (n_samples, n_features) Test data to be transformed, must have the same number of features as the data used to train the model. Returns X_newndarray of shape (n_samples, n_components) Transformed data.
doc_25715
See Migration guide for more details. tf.compat.v1.raw_ops.InfeedEnqueue tf.raw_ops.InfeedEnqueue( input, shape=[], layout=[], device_ordinal=-1, name=None ) Args input A Tensor. A tensor that will be provided using the infeed mechanism. shape An optional tf.TensorShape or list of ints. Defaults to []. The shape of the tensor. layout An optional list of ints. Defaults to []. A vector holding the requested layout in minor-to-major sequence. If a layout attribute is passed, but its values are all -1, the layout will be computed by the infeed operation. device_ordinal An optional int. Defaults to -1. The TPU device to use. This should be -1 when the Op is running on a TPU device, and >= 0 when the Op is running on the CPU device. name A name for the operation (optional). Returns The created Operation.
doc_25716
Draw samples from Gaussian process and evaluate at X. Parameters Xarray-like of shape (n_samples, n_features) or list of object Query points where the GP is evaluated. n_samplesint, default=1 The number of samples drawn from the Gaussian process random_stateint, RandomState instance or None, default=0 Determines random number generation to randomly draw samples. Pass an int for reproducible results across multiple function calls. See :term: Glossary <random_state>. Returns y_samplesndarray of shape (n_samples_X, [n_output_dims], n_samples) Values of n_samples samples drawn from Gaussian process and evaluated at query points.
doc_25717
Same as equivalent method in the Document class.
doc_25718
See Migration guide for more details. tf.compat.v1.sparse.transpose, tf.compat.v1.sparse_transpose tf.sparse.transpose( sp_input, perm=None, name=None ) The returned tensor's dimension i will correspond to the input dimension perm[i]. If perm is not given, it is set to (n-1...0), where n is the rank of the input tensor. Hence by default, this operation performs a regular matrix transpose on 2-D input Tensors. For example, if sp_input has shape [4, 5] and indices / values: [0, 3]: b [0, 1]: a [3, 1]: d [2, 0]: c then the output will be a SparseTensor of shape [5, 4] and indices / values: [0, 2]: c [1, 0]: a [1, 3]: d [3, 0]: b Args sp_input The input SparseTensor. perm A permutation of the dimensions of sp_input. name A name prefix for the returned tensors (optional) Returns A transposed SparseTensor. Raises TypeError If sp_input is not a SparseTensor.
doc_25719
Return the label used for this artist in the legend.
doc_25720
A regular expression specified either as a string or a compiled regular expression object.
doc_25721
A class attribute, as a format string, that describes the SQL that is generated for this aggregate. Defaults to '%(function)s(%(distinct)s%(expressions)s)'.
doc_25722
See Migration guide for more details. tf.compat.v1.raw_ops.SymbolicGradient tf.raw_ops.SymbolicGradient( input, Tout, f, name=None ) Args input A list of Tensor objects. a list of input tensors of size N + M; Tout A list of tf.DTypes that has length >= 1. the type list for the input list. f A function decorated with @Defun. The function we want to compute the gradient for. The function 'f' must be a numerical function which takes N inputs and produces M outputs. Its gradient function 'g', which is computed by this SymbolicGradient op is a function taking N + M inputs and produces N outputs. I.e. if we have (y1, y2, ..., y_M) = f(x1, x2, ..., x_N), then, g is (dL/dx1, dL/dx2, ..., dL/dx_N) = g(x1, x2, ..., x_N, dL/dy1, dL/dy2, ..., dL/dy_M), where L is a scalar-value function of (x1, x2, ..., xN) (e.g., the loss function). dL/dx_i is the partial derivative of L with respect to x_i. (Needs some math expert to say the comment above better.) name A name for the operation (optional). Returns A list of Tensor objects of type Tout.
doc_25723
default_lon The default center longitude. default_lat The default center latitude. default_zoom The default zoom level to use. Defaults to 4. extra_js Sequence of URLs to any extra JavaScript to include. map_template Override the template used to generate the JavaScript slippy map. Default is 'gis/admin/openlayers.html'. map_width Width of the map, in pixels. Defaults to 600. map_height Height of the map, in pixels. Defaults to 400. openlayers_url Link to the URL of the OpenLayers JavaScript. Defaults to 'https://cdnjs.cloudflare.com/ajax/libs/openlayers/2.13.1/OpenLayers.js'. modifiable Defaults to True. When set to False, disables editing of existing geometry fields in the admin. Note This is different from adding the geometry field to readonly_fields, which will only display the WKT of the geometry. Setting modifiable=False, actually displays the geometry in a map, but disables the ability to edit its vertices. Deprecated since version 4.0: This class is deprecated. Use ModelAdmin instead.
doc_25724
Removes a key or index and returns a (key, value) item.
doc_25725
Draw a stacked area plot. An area plot displays quantitative data visually. This function wraps the matplotlib area function. Parameters x:label or position, optional Coordinates for the X axis. By default uses the index. y:label or position, optional Column to plot. By default uses all columns. stacked:bool, default True Area plots are stacked by default. Set to False to create a unstacked plot. **kwargs Additional keyword arguments are documented in DataFrame.plot(). Returns matplotlib.axes.Axes or numpy.ndarray Area plot, or array of area plots if subplots is True. See also DataFrame.plot Make plots of DataFrame using matplotlib / pylab. Examples Draw an area plot based on basic business metrics: >>> df = pd.DataFrame({ ... 'sales': [3, 2, 3, 9, 10, 6], ... 'signups': [5, 5, 6, 12, 14, 13], ... 'visits': [20, 42, 28, 62, 81, 50], ... }, index=pd.date_range(start='2018/01/01', end='2018/07/01', ... freq='M')) >>> ax = df.plot.area() Area plots are stacked by default. To produce an unstacked plot, pass stacked=False: >>> ax = df.plot.area(stacked=False) Draw an area plot for a single column: >>> ax = df.plot.area(y='sales') Draw with a different x: >>> df = pd.DataFrame({ ... 'sales': [3, 2, 3], ... 'visits': [20, 42, 28], ... 'day': [1, 2, 3], ... }) >>> ax = df.plot.area(x='day')
doc_25726
Directory.
doc_25727
Which headers can be sent with the cross origin request.
doc_25728
The set of all exceptions (as a tuple) that methods of FTP instances may raise as a result of problems with the FTP connection (as opposed to programming errors made by the caller). This set includes the four exceptions listed above as well as OSError and EOFError.
doc_25729
Resets parameter data pointer so that they can use faster code paths. Right now, this works only if the module is on the GPU and cuDNN is enabled. Otherwise, it’s a no-op.
doc_25730
tf.nn.depthwise_conv2d( input, filter, strides, padding, data_format=None, dilations=None, name=None ) Given a 4D input tensor ('NHWC' or 'NCHW' data formats) and a filter tensor of shape [filter_height, filter_width, in_channels, channel_multiplier] containing in_channels convolutional filters of depth 1, depthwise_conv2d applies a different filter to each input channel (expanding from 1 channel to channel_multiplier channels for each), then concatenates the results together. The output has in_channels * channel_multiplier channels. In detail, with the default NHWC format, output[b, i, j, k * channel_multiplier + q] = sum_{di, dj} filter[di, dj, k, q] * input[b, strides[1] * i + rate[0] * di, strides[2] * j + rate[1] * dj, k] Must have strides[0] = strides[3] = 1. For the most common case of the same horizontal and vertical strides, strides = [1, stride, stride, 1]. If any value in rate is greater than 1, we perform atrous depthwise convolution, in which case all values in the strides tensor must be equal to 1. Usage Example: x = np.array([ [1., 2.], [3., 4.], [5., 6.] ], dtype=np.float32).reshape((1, 3, 2, 1)) kernel = np.array([ [1., 2.], [3., 4] ], dtype=np.float32).reshape((2, 1, 1, 2)) tf.nn.depthwise_conv2d(x, kernel, strides=[1, 1, 1, 1], padding='VALID').numpy() array([[[[10., 14.], [14., 20.]], [[18., 26.], [22., 32.]]]], dtype=float32) tf.nn.depthwise_conv2d(x, kernel, strides=[1, 1, 1, 1], padding=[[0, 0], [1, 0], [1, 0], [0, 0]]).numpy() array([[[[ 0., 0.], [ 3., 4.], [ 6., 8.]], [[ 0., 0.], [10., 14.], [14., 20.]], [[ 0., 0.], [18., 26.], [22., 32.]]]], dtype=float32) Args input 4-D with shape according to data_format. filter 4-D with shape [filter_height, filter_width, in_channels, channel_multiplier]. strides 1-D of size 4. The stride of the sliding window for each dimension of input. padding Controls how to pad the image before applying the convolution. Can be the string "SAME" or "VALID" indicating the type of padding algorithm to use, or a list indicating the explicit paddings at the start and end of each dimension. When explicit padding is used and data_format is "NHWC", this should be in the form [[0, 0], [pad_top, pad_bottom], [pad_left, pad_right], [0, 0]]. When explicit padding used and data_format is "NCHW", this should be in the form [[0, 0], [0, 0], [pad_top, pad_bottom], [pad_left, pad_right]]. data_format The data format for input. Either "NHWC" (default) or "NCHW". dilations 1-D of size 2. The dilation rate in which we sample input values across the height and width dimensions in atrous convolution. If it is greater than 1, then all values of strides must be 1. name A name for this operation (optional). Returns A 4-D Tensor with shape according to data_format. E.g., for "NHWC" format, shape is [batch, out_height, out_width, in_channels * channel_multiplier].
doc_25731
class ast.Sub class ast.Mult class ast.Div class ast.FloorDiv class ast.Mod class ast.Pow class ast.LShift class ast.RShift class ast.BitOr class ast.BitXor class ast.BitAnd class ast.MatMult Binary operator tokens.
doc_25732
sklearn.decomposition.dict_learning(X, n_components, *, alpha, max_iter=100, tol=1e-08, method='lars', n_jobs=None, dict_init=None, code_init=None, callback=None, verbose=False, random_state=None, return_n_iter=False, positive_dict=False, positive_code=False, method_max_iter=1000) [source] Solves a dictionary learning matrix factorization problem. Finds the best dictionary and the corresponding sparse code for approximating the data matrix X by solving: (U^*, V^*) = argmin 0.5 || X - U V ||_2^2 + alpha * || U ||_1 (U,V) with || V_k ||_2 = 1 for all 0 <= k < n_components where V is the dictionary and U is the sparse code. Read more in the User Guide. Parameters Xndarray of shape (n_samples, n_features) Data matrix. n_componentsint Number of dictionary atoms to extract. alphaint Sparsity controlling parameter. max_iterint, default=100 Maximum number of iterations to perform. tolfloat, default=1e-8 Tolerance for the stopping condition. method{‘lars’, ‘cd’}, default=’lars’ The method used: 'lars': uses the least angle regression method to solve the lasso problem (linear_model.lars_path); 'cd': uses the coordinate descent method to compute the Lasso solution (linear_model.Lasso). Lars will be faster if the estimated components are sparse. n_jobsint, default=None Number of parallel jobs to run. None means 1 unless in a joblib.parallel_backend context. -1 means using all processors. See Glossary for more details. dict_initndarray of shape (n_components, n_features), default=None Initial value for the dictionary for warm restart scenarios. code_initndarray of shape (n_samples, n_components), default=None Initial value for the sparse code for warm restart scenarios. callbackcallable, default=None Callable that gets invoked every five iterations verbosebool, default=False To control the verbosity of the procedure. random_stateint, RandomState instance or None, default=None Used for randomly initializing the dictionary. Pass an int for reproducible results across multiple function calls. See Glossary. return_n_iterbool, default=False Whether or not to return the number of iterations. positive_dictbool, default=False Whether to enforce positivity when finding the dictionary. New in version 0.20. positive_codebool, default=False Whether to enforce positivity when finding the code. New in version 0.20. method_max_iterint, default=1000 Maximum number of iterations to perform. New in version 0.22. Returns codendarray of shape (n_samples, n_components) The sparse code factor in the matrix factorization. dictionaryndarray of shape (n_components, n_features), The dictionary factor in the matrix factorization. errorsarray Vector of errors at each iteration. n_iterint Number of iterations run. Returned only if return_n_iter is set to True. See also dict_learning_online DictionaryLearning MiniBatchDictionaryLearning SparsePCA MiniBatchSparsePCA
doc_25733
A ParameterizedMIMEHeader class that handles the Content-Disposition header. content_disposition inline and attachment are the only valid values in common use.
doc_25734
Set a title for the Axes. Set one of the three available Axes titles. The available titles are positioned above the Axes in the center, flush with the left edge, and flush with the right edge. Parameters labelstr Text to use for the title fontdictdict A dictionary controlling the appearance of the title text, the default fontdict is: {'fontsize': rcParams['axes.titlesize'], 'fontweight': rcParams['axes.titleweight'], 'color': rcParams['axes.titlecolor'], 'verticalalignment': 'baseline', 'horizontalalignment': loc} loc{'center', 'left', 'right'}, default: rcParams["axes.titlelocation"] (default: 'center') Which title to set. yfloat, default: rcParams["axes.titley"] (default: None) Vertical Axes loation for the title (1.0 is the top). If None (the default), y is determined automatically to avoid decorators on the Axes. padfloat, default: rcParams["axes.titlepad"] (default: 6.0) The offset of the title from the top of the Axes, in points. Returns Text The matplotlib text instance representing the title Other Parameters **kwargsText properties Other keyword arguments are text properties, see Text for a list of valid text properties. Examples using matplotlib.axes.Axes.set_title Bar Label Demo Stacked bar chart Grouped bar chart with labels Horizontal bar chart Errorbar subsampling EventCollection Demo Fill Between and Alpha Filling the area between lines Fill Betweenx Demo Hat graph Markevery Demo Psd Demo Scatter Demo2 Using span_where Stackplots and streamgraphs hlines and vlines Contour Corner Mask Contour Demo Contour Label Demo Contourf Demo Creating annotated heatmaps Image antialiasing Image Demo Image Masked Image Nonuniform Interpolations for imshow Contour plot of irregularly spaced data Pcolor Demo pcolormesh grids and shading pcolormesh Streamplot Advanced quiver and quiverkey functions Tricontour Demo Tricontour Smooth Delaunay Tricontour Smooth User Trigradient Demo Tripcolor Demo Triplot Demo Axes Demo Controlling view limits using margins and sticky_edges Resizing axes with constrained layout Resizing axes with tight layout Figure labels: suptitle, supxlabel, supylabel Invert Axes Secondary Axis Figure subfigures Creating multiple subplots using plt.subplots Box plots with custom fill colors Plot a confidence ellipse of a two-dimensional dataset Violin plot customization Different ways of specifying error bars Including upper and lower limits in error bars Hexagonal binned plot Using histograms to plot a cumulative distribution Some features of the histogram (hist) function The histogram (hist) function with multiple data sets Bar of pie Labeling a pie and a donut Polar plot Using accented text in matplotlib Scale invariant angle label Date tick labels Custom tick formatter for time series Labeling ticks using engineering notation Using a ttf font file in Matplotlib Labelling subplots Legend Demo Mathtext Math fontfamily Multiline Rendering math equations using TeX Title positioning Boxplot Demo Simple axes labels Text Commands Color Demo Creating a colormap from a list of colors Line, Poly and RegularPoly Collection with autoscaling Compound path Mmh Donuts!!! Line Collection Bezier Curve Bayesian Methods for Hackers style sheet Dark background style sheet FiveThirtyEight style sheet Make Room For Ylabel Using Axesgrid Axis Direction Anatomy of a figure XKCD pyplot animation Data Browser Image Slices Viewer Keypress event Lasso Demo Legend Picking Looking Glass Path Editor Pick Event Demo2 Poly Editor Trifinder Event Demo Viewlims Cross hair cursor Packed-bubble chart Pythonic Matplotlib Rasterization for vector graphics Zorder Demo Demo of 3D bar charts Lorenz Attractor 3D wireframe plots in one direction Loglog Aspect Exploring normalizations Scales Radar chart (aka spider or star chart) Topographic hillshading Spine Placement Spines Dropped spines Colorbar Tick Labelling Date Precision and Epochs Set default x-axis tick labels on the top Artist tests Group barchart with units Evans test Interactive Adjustment of Colormap Range Annotated Cursor Rectangle and ellipse selectors Span Selector Basic Usage Image tutorial Artist tutorial Styling with cycler Constrained Layout Guide Tight Layout guide Transformations Tutorial Specifying Colors Colormap Normalization Text in Matplotlib Plots
doc_25735
Parameters urlslist of str or None Notes URLs are currently only implemented by the SVG backend. They are ignored by all other backends.
doc_25736
Determines the HttpResponse for the delete_view() stage. response_delete is called after the object has been deleted. You can override it to change the default behavior after the object has been deleted. obj_display is a string with the name of the deleted object. obj_id is the serialized identifier used to retrieve the object to be deleted.
doc_25737
A possible value for the how parameter to pthread_sigmask() indicating that signals are to be unblocked. New in version 3.3.
doc_25738
Set how to draw endpoints of lines. Parameters csCapStyle or {'butt', 'projecting', 'round'}
doc_25739
tf.negative Compat aliases for migration See Migration guide for more details. tf.compat.v1.math.negative, tf.compat.v1.negative tf.math.negative( x, name=None ) I.e., \(y = -x\). Args x A Tensor. Must be one of the following types: bfloat16, half, float32, float64, int8, int16, int32, int64, complex64, complex128. name A name for the operation (optional). Returns A Tensor. Has the same type as x. If x is a SparseTensor, returns SparseTensor(x.indices, tf.math.negative(x.values, ...), x.dense_shape)
doc_25740
Calculate the expanding standard error of mean. Parameters ddof:int, default 1 Delta Degrees of Freedom. The divisor used in calculations is N - ddof, where N represents the number of elements. *args For NumPy compatibility and will not have an effect on the result. **kwargs For NumPy compatibility and will not have an effect on the result. Returns Series or DataFrame Return type is the same as the original object with np.float64 dtype. See also pandas.Series.expanding Calling expanding with Series data. pandas.DataFrame.expanding Calling expanding with DataFrames. pandas.Series.sem Aggregating sem for Series. pandas.DataFrame.sem Aggregating sem for DataFrame. Notes A minimum of one period is required for the calculation. Examples >>> s = pd.Series([0, 1, 2, 3]) >>> s.expanding().sem() 0 NaN 1 0.707107 2 0.707107 3 0.745356 dtype: float64
doc_25741
Return a deep copy of x.
doc_25742
Return random bytes. Note New code should use the bytes method of a default_rng() instance instead; please see the Quick Start. Parameters lengthint Number of random bytes. Returns outbytes String of length length. See also Generator.bytes which should be used for new code. Examples >>> np.random.bytes(10) b' eh\x85\x022SZ\xbf\xa4' #random
doc_25743
A set object indicating which functions in the os module accept an open file descriptor for their dir_fd parameter. Different platforms provide different features, and the underlying functionality Python uses to implement the dir_fd parameter is not available on all platforms Python supports. For consistency’s sake, functions that may support dir_fd always allow specifying the parameter, but will throw an exception if the functionality is used when it’s not locally available. (Specifying None for dir_fd is always supported on all platforms.) To check whether a particular function accepts an open file descriptor for its dir_fd parameter, use the in operator on supports_dir_fd. As an example, this expression evaluates to True if os.stat() accepts open file descriptors for dir_fd on the local platform: os.stat in os.supports_dir_fd Currently dir_fd parameters only work on Unix platforms; none of them work on Windows. New in version 3.3.
doc_25744
Return the getters and actual values as list of strings.
doc_25745
Process a pick event. Each child artist will fire a pick event if mouseevent is over the artist and the artist has picker set. See also set_picker, get_picker, pickable
doc_25746
Delete the ACLs (remove any rights) set for who on mailbox.
doc_25747
Make a 2D histogram plot. Parameters x, yarray-like, shape (n, ) Input values binsNone or int or [int, int] or array-like or [array, array] The bin specification: If int, the number of bins for the two dimensions (nx=ny=bins). If [int, int], the number of bins in each dimension (nx, ny = bins). If array-like, the bin edges for the two dimensions (x_edges=y_edges=bins). If [array, array], the bin edges in each dimension (x_edges, y_edges = bins). The default value is 10. rangearray-like shape(2, 2), optional The leftmost and rightmost edges of the bins along each dimension (if not specified explicitly in the bins parameters): [[xmin, xmax], [ymin, ymax]]. All values outside of this range will be considered outliers and not tallied in the histogram. densitybool, default: False Normalize histogram. See the documentation for the density parameter of hist for more details. weightsarray-like, shape (n, ), optional An array of values w_i weighing each sample (x_i, y_i). cmin, cmaxfloat, default: None All bins that has count less than cmin or more than cmax will not be displayed (set to NaN before passing to imshow) and these count values in the return value count histogram will also be set to nan upon return. Returns h2D array The bi-dimensional histogram of samples x and y. Values in x are histogrammed along the first dimension and values in y are histogrammed along the second dimension. xedges1D array The bin edges along the x axis. yedges1D array The bin edges along the y axis. imageQuadMesh Other Parameters cmapColormap or str, optional A colors.Colormap instance. If not set, use rc settings. normNormalize, optional A colors.Normalize instance is used to scale luminance data to [0, 1]. If not set, defaults to colors.Normalize(). vmin/vmaxNone or scalar, optional Arguments passed to the Normalize instance. alpha0 <= scalar <= 1 or None, optional The alpha blending value. dataindexable object, optional If given, the following parameters also accept a string s, which is interpreted as data[s] (unless this raises an exception): x, y, weights **kwargs Additional parameters are passed along to the pcolormesh method and QuadMesh constructor. See also hist 1D histogram plotting hexbin 2D histogram with hexagonal bins Notes Currently hist2d calculates its own axis limits, and any limits previously set are ignored. Rendering the histogram with a logarithmic color scale is accomplished by passing a colors.LogNorm instance to the norm keyword argument. Likewise, power-law normalization (similar in effect to gamma correction) can be accomplished with colors.PowerNorm.
doc_25748
See Migration guide for more details. tf.compat.v1.raw_ops.QuantizeAndDequantizeV3 tf.raw_ops.QuantizeAndDequantizeV3( input, input_min, input_max, num_bits, signed_input=True, range_given=True, narrow_range=False, axis=-1, name=None ) This is almost identical to QuantizeAndDequantizeV2, except that num_bits is a tensor, so its value can change during training. Args input A Tensor. Must be one of the following types: bfloat16, half, float32, float64. input_min A Tensor. Must have the same type as input. input_max A Tensor. Must have the same type as input. num_bits A Tensor of type int32. signed_input An optional bool. Defaults to True. range_given An optional bool. Defaults to True. narrow_range An optional bool. Defaults to False. axis An optional int. Defaults to -1. name A name for the operation (optional). Returns A Tensor. Has the same type as input.
doc_25749
Align two objects on their axes with the specified join method. Join method is specified for each axis Index. Parameters other:DataFrame or Series join:{‘outer’, ‘inner’, ‘left’, ‘right’}, default ‘outer’ axis:allowed axis of the other object, default None Align on index (0), columns (1), or both (None). level:int or level name, default None Broadcast across a level, matching Index values on the passed MultiIndex level. copy:bool, default True Always returns new objects. If copy=False and no reindexing is required then original objects are returned. fill_value:scalar, default np.NaN Value to use for missing values. Defaults to NaN, but can be any “compatible” value. method:{‘backfill’, ‘bfill’, ‘pad’, ‘ffill’, None}, default None Method to use for filling holes in reindexed Series: pad / ffill: propagate last valid observation forward to next valid. backfill / bfill: use NEXT valid observation to fill gap. limit:int, default None If method is specified, this is the maximum number of consecutive NaN values to forward/backward fill. In other words, if there is a gap with more than this number of consecutive NaNs, it will only be partially filled. If method is not specified, this is the maximum number of entries along the entire axis where NaNs will be filled. Must be greater than 0 if not None. fill_axis:{0 or ‘index’, 1 or ‘columns’}, default 0 Filling axis, method and limit. broadcast_axis:{0 or ‘index’, 1 or ‘columns’}, default None Broadcast values along this axis, if aligning two objects of different dimensions. Returns (left, right):(DataFrame, type of other) Aligned objects. Examples >>> df = pd.DataFrame( ... [[1, 2, 3, 4], [6, 7, 8, 9]], columns=["D", "B", "E", "A"], index=[1, 2] ... ) >>> other = pd.DataFrame( ... [[10, 20, 30, 40], [60, 70, 80, 90], [600, 700, 800, 900]], ... columns=["A", "B", "C", "D"], ... index=[2, 3, 4], ... ) >>> df D B E A 1 1 2 3 4 2 6 7 8 9 >>> other A B C D 2 10 20 30 40 3 60 70 80 90 4 600 700 800 900 Align on columns: >>> left, right = df.align(other, join="outer", axis=1) >>> left A B C D E 1 4 2 NaN 1 3 2 9 7 NaN 6 8 >>> right A B C D E 2 10 20 30 40 NaN 3 60 70 80 90 NaN 4 600 700 800 900 NaN We can also align on the index: >>> left, right = df.align(other, join="outer", axis=0) >>> left D B E A 1 1.0 2.0 3.0 4.0 2 6.0 7.0 8.0 9.0 3 NaN NaN NaN NaN 4 NaN NaN NaN NaN >>> right A B C D 1 NaN NaN NaN NaN 2 10.0 20.0 30.0 40.0 3 60.0 70.0 80.0 90.0 4 600.0 700.0 800.0 900.0 Finally, the default axis=None will align on both index and columns: >>> left, right = df.align(other, join="outer", axis=None) >>> left A B C D E 1 4.0 2.0 NaN 1.0 3.0 2 9.0 7.0 NaN 6.0 8.0 3 NaN NaN NaN NaN NaN 4 NaN NaN NaN NaN NaN >>> right A B C D E 1 NaN NaN NaN NaN NaN 2 10.0 20.0 30.0 40.0 NaN 3 60.0 70.0 80.0 90.0 NaN 4 600.0 700.0 800.0 900.0 NaN
doc_25750
Return True if path refers to an existing path. Returns True for broken symbolic links. Equivalent to exists() on platforms lacking os.lstat(). Changed in version 3.6: Accepts a path-like object.
doc_25751
Generates the SQL fragment for the expression. Returns a tuple (sql, params), where sql is the SQL string, and params is the list or tuple of query parameters. The compiler is an SQLCompiler object, which has a compile() method that can be used to compile other expressions. The connection is the connection used to execute the query. Calling expression.as_sql() is usually incorrect - instead compiler.compile(expression) should be used. The compiler.compile() method will take care of calling vendor-specific methods of the expression. Custom keyword arguments may be defined on this method if it’s likely that as_vendorname() methods or subclasses will need to supply data to override the generation of the SQL string. See Func.as_sql() for example usage.
doc_25752
See Migration guide for more details. tf.compat.v1.raw_ops.ResourceScatterDiv tf.raw_ops.ResourceScatterDiv( resource, indices, updates, name=None ) This operation computes # 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, ...] Duplicate entries are handled correctly: if multiple indices reference the same location, their contributions multiply. Requires updates.shape = indices.shape + ref.shape[1:] or updates.shape = []. Args resource A Tensor of type resource. 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 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 of updated values to add to ref. name A name for the operation (optional). Returns The created Operation.
doc_25753
tf.metrics.Metric Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.metrics.Metric tf.keras.metrics.Metric( name=None, dtype=None, **kwargs ) Args name (Optional) string name of the metric instance. dtype (Optional) data type of the metric result. **kwargs Additional layer keywords arguments. Standalone usage: m = SomeMetric(...) for input in ...: m.update_state(input) print('Final result: ', m.result().numpy()) Usage with compile() API: model = tf.keras.Sequential() model.add(tf.keras.layers.Dense(64, activation='relu')) model.add(tf.keras.layers.Dense(64, activation='relu')) model.add(tf.keras.layers.Dense(10, activation='softmax')) model.compile(optimizer=tf.keras.optimizers.RMSprop(0.01), loss=tf.keras.losses.CategoricalCrossentropy(), metrics=[tf.keras.metrics.CategoricalAccuracy()]) data = np.random.random((1000, 32)) labels = np.random.random((1000, 10)) dataset = tf.data.Dataset.from_tensor_slices((data, labels)) dataset = dataset.batch(32) model.fit(dataset, epochs=10) To be implemented by subclasses: __init__(): All state variables should be created in this method by calling self.add_weight() like: self.var = self.add_weight(...) update_state(): Has all updates to the state variables like: self.var.assign_add(...). result(): Computes and returns a value for the metric from the state variables. Example subclass implementation: class BinaryTruePositives(tf.keras.metrics.Metric): def __init__(self, name='binary_true_positives', **kwargs): super(BinaryTruePositives, self).__init__(name=name, **kwargs) self.true_positives = self.add_weight(name='tp', initializer='zeros') def update_state(self, y_true, y_pred, sample_weight=None): y_true = tf.cast(y_true, tf.bool) y_pred = tf.cast(y_pred, tf.bool) values = tf.logical_and(tf.equal(y_true, True), tf.equal(y_pred, True)) values = tf.cast(values, self.dtype) if sample_weight is not None: sample_weight = tf.cast(sample_weight, self.dtype) sample_weight = tf.broadcast_to(sample_weight, values.shape) values = tf.multiply(values, sample_weight) self.true_positives.assign_add(tf.reduce_sum(values)) def result(self): return self.true_positives Methods add_weight View source add_weight( name, shape=(), aggregation=tf.compat.v1.VariableAggregation.SUM, synchronization=tf.VariableSynchronization.ON_READ, initializer=None, dtype=None ) Adds state variable. Only for use by subclasses. reset_states View source reset_states() Resets all of the metric state variables. This function is called between epochs/steps, when a metric is evaluated during training. result View source @abc.abstractmethod result() Computes and returns the metric value tensor. Result computation is an idempotent operation that simply calculates the metric value using the state variables. update_state View source @abc.abstractmethod update_state( *args, **kwargs ) Accumulates statistics for the metric. Note: This function is executed as a graph function in graph mode. This means: a) Operations on the same resource are executed in textual order. This should make it easier to do things like add the updated value of a variable to another, for example. b) You don't need to worry about collecting the update ops to execute. All update ops added to the graph by this function will be executed. As a result, code should generally work the same way with graph or eager execution. Args *args **kwargs A mini-batch of inputs to the Metric.
doc_25754
sklearn.metrics.rand_score(labels_true, labels_pred) [source] Rand index. The Rand Index computes a similarity measure between two clusterings by considering all pairs of samples and counting pairs that are assigned in the same or different clusters in the predicted and true clusterings. The raw RI score is: RI = (number of agreeing pairs) / (number of pairs) Read more in the User Guide. Parameters labels_truearray-like of shape (n_samples,), dtype=integral Ground truth class labels to be used as a reference. labels_predarray-like of shape (n_samples,), dtype=integral Cluster labels to evaluate. Returns RIfloat Similarity score between 0.0 and 1.0, inclusive, 1.0 stands for perfect match. See also adjusted_rand_score Adjusted Rand Score adjusted_mutual_info_score Adjusted Mutual Information References Examples Perfectly matching labelings have a score of 1 even >>> from sklearn.metrics.cluster import rand_score >>> rand_score([0, 0, 1, 1], [1, 1, 0, 0]) 1.0 Labelings that assign all classes members to the same clusters are complete but may not always be pure, hence penalized: >>> rand_score([0, 0, 1, 2], [0, 0, 1, 1]) 0.83...
doc_25755
See Migration guide for more details. tf.compat.v1.train.Feature Attributes bytes_list BytesList bytes_list float_list FloatList float_list int64_list Int64List int64_list
doc_25756
See Migration guide for more details. tf.compat.v1.raw_ops.QuantizedConv2DAndReluAndRequantize tf.raw_ops.QuantizedConv2DAndReluAndRequantize( input, filter, min_input, max_input, min_filter, max_filter, min_freezed_output, max_freezed_output, strides, padding, out_type=tf.dtypes.quint8, dilations=[1, 1, 1, 1], padding_list=[], name=None ) Args input A Tensor. Must be one of the following types: qint8, quint8, qint32, qint16, quint16. filter A Tensor. Must be one of the following types: qint8, quint8, qint32, qint16, quint16. min_input A Tensor of type float32. max_input A Tensor of type float32. min_filter A Tensor of type float32. max_filter A Tensor of type float32. min_freezed_output A Tensor of type float32. max_freezed_output A Tensor of type float32. strides A list of ints. padding A string from: "SAME", "VALID". out_type An optional tf.DType from: tf.qint8, tf.quint8, tf.qint32, tf.qint16, tf.quint16. Defaults to tf.quint8. dilations An optional list of ints. Defaults to [1, 1, 1, 1]. padding_list An optional list of ints. Defaults to []. name A name for the operation (optional). Returns A tuple of Tensor objects (output, min_output, max_output). output A Tensor of type out_type. min_output A Tensor of type float32. max_output A Tensor of type float32.
doc_25757
Return an array with the elements of self left-justified in a string of length width. See also char.ljust
doc_25758
Create an object with a writable value attribute and return a proxy for it.
doc_25759
Set the value array from array-like A. Parameters Aarray-like or None The values that are mapped to colors. The base class ScalarMappable does not make any assumptions on the dimensionality and shape of the value array A.
doc_25760
See Migration guide for more details. tf.compat.v1.linalg.lu_solve tf.linalg.lu_solve( lower_upper, perm, rhs, validate_args=False, name=None ) Note: this function does not verify the implied matrix is actually invertible nor is this condition checked even when validate_args=True. Args lower_upper lu as returned by tf.linalg.lu, i.e., if matmul(P, matmul(L, U)) = X then lower_upper = L + U - eye. perm p as returned by tf.linag.lu, i.e., if matmul(P, matmul(L, U)) = X then perm = argmax(P). rhs Matrix-shaped float Tensor representing targets for which to solve; A X = RHS. To handle vector cases, use: lu_solve(..., rhs[..., tf.newaxis])[..., 0]. validate_args Python bool indicating whether arguments should be checked for correctness. Note: this function does not verify the implied matrix is actually invertible, even when validate_args=True. Default value: False (i.e., don't validate arguments). name Python str name given to ops managed by this object. Default value: None (i.e., 'lu_solve'). Returns x The X in A @ X = RHS. Examples import numpy as np import tensorflow as tf import tensorflow_probability as tfp x = [[[1., 2], [3, 4]], [[7, 8], [3, 4]]] inv_x = tf.linalg.lu_solve(*tf.linalg.lu(x), rhs=tf.eye(2)) tf.assert_near(tf.matrix_inverse(x), inv_x) # ==> True
doc_25761
Set both the edgecolor and the facecolor. Parameters ccolor or list of rgba tuples See also Collection.set_facecolor, Collection.set_edgecolor For setting the edge or face color individually.
doc_25762
Bases: object format_dict : dictionary for format strings to be used. formatter : fall-back formatter __call__(direction, factor, values)[source] factor is ignored if value is found in the dictionary Examples using mpl_toolkits.axisartist.grid_finder.DictFormatter mpl_toolkits.axisartist.floating_axes features
doc_25763
os.O_WRONLY os.O_RDWR os.O_APPEND os.O_CREAT os.O_EXCL os.O_TRUNC The above constants are available on Unix and Windows.
doc_25764
Alias for set_linestyle.
doc_25765
Returns a new tensor with the data in input fake quantized using scale, zero_point, quant_min and quant_max. output=min(quant_max,max(quant_min,std::nearby_int(input/scale)+zero_point))\text{output} = min( \text{quant\_max}, max( \text{quant\_min}, \text{std::nearby\_int}(\text{input} / \text{scale}) + \text{zero\_point} ) ) Parameters input (Tensor) – the input value(s), in torch.float32. scale (double) – quantization scale zero_point (int64) – quantization zero_point quant_min (int64) – lower bound of the quantized domain quant_max (int64) – upper bound of the quantized domain Returns A newly fake_quantized tensor Return type Tensor Example: >>> x = torch.randn(4) >>> x tensor([ 0.0552, 0.9730, 0.3973, -1.0780]) >>> torch.fake_quantize_per_tensor_affine(x, 0.1, 0, 0, 255) tensor([0.1000, 1.0000, 0.4000, 0.0000])
doc_25766
Return the view limits (min, max) of the axis the tick belongs to.
doc_25767
'blogs.blog': lambda o: "/blogs/%s/" % o.slug, 'news.story': lambda o: "/stories/%s/%s/" % (o.pub_year, o.slug), } The model name used in this setting should be all lowercase, regardless of the case of the actual model class name. ADMINS Default: [] (Empty list) A list of all the people who get code error notifications. When DEBUG=False and AdminEmailHandler is configured in LOGGING (done by default), Django emails these people the details of exceptions raised in the request/response cycle. Each item in the list should be a tuple of (Full name, email address). Example: [('John', 'john@example.com'), ('Mary', 'mary@example.com')] ALLOWED_HOSTS Default: [] (Empty list) A list of strings representing the host/domain names that this Django site can serve. This is a security measure to prevent HTTP Host header attacks, which are possible even under many seemingly-safe web server configurations. Values in this list can be fully qualified names (e.g. 'www.example.com'), in which case they will be matched against the request’s Host header exactly (case-insensitive, not including port). A value beginning with a period can be used as a subdomain wildcard: '.example.com' will match example.com, www.example.com, and any other subdomain of example.com. A value of '*' will match anything; in this case you are responsible to provide your own validation of the Host header (perhaps in a middleware; if so this middleware must be listed first in MIDDLEWARE). Django also allows the fully qualified domain name (FQDN) of any entries. Some browsers include a trailing dot in the Host header which Django strips when performing host validation. If the Host header (or X-Forwarded-Host if USE_X_FORWARDED_HOST is enabled) does not match any value in this list, the django.http.HttpRequest.get_host() method will raise SuspiciousOperation. When DEBUG is True and ALLOWED_HOSTS is empty, the host is validated against ['.localhost', '127.0.0.1', '[::1]']. ALLOWED_HOSTS is also checked when running tests. This validation only applies via get_host(); if your code accesses the Host header directly from request.META you are bypassing this security protection. APPEND_SLASH Default: True When set to True, if the request URL does not match any of the patterns in the URLconf and it doesn’t end in a slash, an HTTP redirect is issued to the same URL with a slash appended. Note that the redirect may cause any data submitted in a POST request to be lost. The APPEND_SLASH setting is only used if CommonMiddleware is installed (see Middleware). See also PREPEND_WWW. CACHES Default: { 'default': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', } } A dictionary containing the settings for all caches to be used with Django. It is a nested dictionary whose contents maps cache aliases to a dictionary containing the options for an individual cache. The CACHES setting must configure a default cache; any number of additional caches may also be specified. If you are using a cache backend other than the local memory cache, or you need to define multiple caches, other options will be required. The following cache options are available. BACKEND Default: '' (Empty string) The cache backend to use. The built-in cache backends are: 'django.core.cache.backends.db.DatabaseCache' 'django.core.cache.backends.dummy.DummyCache' 'django.core.cache.backends.filebased.FileBasedCache' 'django.core.cache.backends.locmem.LocMemCache' 'django.core.cache.backends.memcached.PyMemcacheCache' 'django.core.cache.backends.memcached.PyLibMCCache' 'django.core.cache.backends.redis.RedisCache' You can use a cache backend that doesn’t ship with Django by setting BACKEND to a fully-qualified path of a cache backend class (i.e. mypackage.backends.whatever.WhateverCache). Changed in Django 3.2: The PyMemcacheCache backend was added. Changed in Django 4.0: The RedisCache backend was added. KEY_FUNCTION A string containing a dotted path to a function (or any callable) that defines how to compose a prefix, version and key into a final cache key. The default implementation is equivalent to the function: def make_key(key, key_prefix, version): return ':'.join([key_prefix, str(version), key]) You may use any key function you want, as long as it has the same argument signature. See the cache documentation for more information. KEY_PREFIX Default: '' (Empty string) A string that will be automatically included (prepended by default) to all cache keys used by the Django server. See the cache documentation for more information. LOCATION Default: '' (Empty string) The location of the cache to use. This might be the directory for a file system cache, a host and port for a memcache server, or an identifying name for a local memory cache. e.g.: CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache', 'LOCATION': '/var/tmp/django_cache', } } OPTIONS Default: None Extra parameters to pass to the cache backend. Available parameters vary depending on your cache backend. Some information on available parameters can be found in the cache arguments documentation. For more information, consult your backend module’s own documentation. TIMEOUT Default: 300 The number of seconds before a cache entry is considered stale. If the value of this setting is None, cache entries will not expire. A value of 0 causes keys to immediately expire (effectively “don’t cache”). VERSION Default: 1 The default version number for cache keys generated by the Django server. See the cache documentation for more information. CACHE_MIDDLEWARE_ALIAS Default: 'default' The cache connection to use for the cache middleware. CACHE_MIDDLEWARE_KEY_PREFIX Default: '' (Empty string) A string which will be prefixed to the cache keys generated by the cache middleware. This prefix is combined with the KEY_PREFIX setting; it does not replace it. See Django’s cache framework. CACHE_MIDDLEWARE_SECONDS Default: 600 The default number of seconds to cache a page for the cache middleware. See Django’s cache framework. CSRF_COOKIE_AGE Default: 31449600 (approximately 1 year, in seconds) The age of CSRF cookies, in seconds. The reason for setting a long-lived expiration time is to avoid problems in the case of a user closing a browser or bookmarking a page and then loading that page from a browser cache. Without persistent cookies, the form submission would fail in this case. Some browsers (specifically Internet Explorer) can disallow the use of persistent cookies or can have the indexes to the cookie jar corrupted on disk, thereby causing CSRF protection checks to (sometimes intermittently) fail. Change this setting to None to use session-based CSRF cookies, which keep the cookies in-memory instead of on persistent storage. CSRF_COOKIE_DOMAIN Default: None The domain to be used when setting the CSRF cookie. This can be useful for easily allowing cross-subdomain requests to be excluded from the normal cross site request forgery protection. It should be set to a string such as ".example.com" to allow a POST request from a form on one subdomain to be accepted by a view served from another subdomain. Please note that the presence of this setting does not imply that Django’s CSRF protection is safe from cross-subdomain attacks by default - please see the CSRF limitations section. CSRF_COOKIE_HTTPONLY Default: False Whether to use HttpOnly flag on the CSRF cookie. If this is set to True, client-side JavaScript will not be able to access the CSRF cookie. Designating the CSRF cookie as HttpOnly doesn’t offer any practical protection because CSRF is only to protect against cross-domain attacks. If an attacker can read the cookie via JavaScript, they’re already on the same domain as far as the browser knows, so they can do anything they like anyway. (XSS is a much bigger hole than CSRF.) Although the setting offers little practical benefit, it’s sometimes required by security auditors. If you enable this and need to send the value of the CSRF token with an AJAX request, your JavaScript must pull the value from a hidden CSRF token form input instead of from the cookie. See SESSION_COOKIE_HTTPONLY for details on HttpOnly. CSRF_COOKIE_NAME Default: 'csrftoken' The name of the cookie to use for the CSRF authentication token. This can be whatever you want (as long as it’s different from the other cookie names in your application). See Cross Site Request Forgery protection. CSRF_COOKIE_PATH Default: '/' The path set on the CSRF cookie. This should either match the URL path of your Django installation or be a parent of that path. This is useful if you have multiple Django instances running under the same hostname. They can use different cookie paths, and each instance will only see its own CSRF cookie. CSRF_COOKIE_SAMESITE Default: 'Lax' The value of the SameSite flag on the CSRF cookie. This flag prevents the cookie from being sent in cross-site requests. See SESSION_COOKIE_SAMESITE for details about SameSite. CSRF_COOKIE_SECURE Default: False Whether to use a secure cookie for the CSRF cookie. If this is set to True, the cookie will be marked as “secure”, which means browsers may ensure that the cookie is only sent with an HTTPS connection. CSRF_USE_SESSIONS Default: False Whether to store the CSRF token in the user’s session instead of in a cookie. It requires the use of django.contrib.sessions. Storing the CSRF token in a cookie (Django’s default) is safe, but storing it in the session is common practice in other web frameworks and therefore sometimes demanded by security auditors. Since the default error views require the CSRF token, SessionMiddleware must appear in MIDDLEWARE before any middleware that may raise an exception to trigger an error view (such as PermissionDenied) if you’re using CSRF_USE_SESSIONS. See Middleware ordering. CSRF_FAILURE_VIEW Default: 'django.views.csrf.csrf_failure' A dotted path to the view function to be used when an incoming request is rejected by the CSRF protection. The function should have this signature: def csrf_failure(request, reason=""): ... where reason is a short message (intended for developers or logging, not for end users) indicating the reason the request was rejected. It should return an HttpResponseForbidden. django.views.csrf.csrf_failure() accepts an additional template_name parameter that defaults to '403_csrf.html'. If a template with that name exists, it will be used to render the page. CSRF_HEADER_NAME Default: 'HTTP_X_CSRFTOKEN' The name of the request header used for CSRF authentication. As with other HTTP headers in request.META, the header name received from the server is normalized by converting all characters to uppercase, replacing any hyphens with underscores, and adding an 'HTTP_' prefix to the name. For example, if your client sends a 'X-XSRF-TOKEN' header, the setting should be 'HTTP_X_XSRF_TOKEN'. CSRF_TRUSTED_ORIGINS Default: [] (Empty list) A list of trusted origins for unsafe requests (e.g. POST). For requests that include the Origin header, Django’s CSRF protection requires that header match the origin present in the Host header. For a secure unsafe request that doesn’t include the Origin header, the request must have a Referer header that matches the origin present in the Host header. These checks prevent, for example, a POST request from subdomain.example.com from succeeding against api.example.com. If you need cross-origin unsafe requests, continuing the example, add 'https://subdomain.example.com' to this list (and/or http://... if requests originate from an insecure page). The setting also supports subdomains, so you could add 'https://*.example.com', for example, to allow access from all subdomains of example.com. Changed in Django 4.0: The values in older versions must only include the hostname (possibly with a leading dot) and not the scheme or an asterisk. Also, Origin header checking isn’t performed in older versions. DATABASES Default: {} (Empty dictionary) A dictionary containing the settings for all databases to be used with Django. It is a nested dictionary whose contents map a database alias to a dictionary containing the options for an individual database. The DATABASES setting must configure a default database; any number of additional databases may also be specified. The simplest possible settings file is for a single-database setup using SQLite. This can be configured using the following: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'mydatabase', } } When connecting to other database backends, such as MariaDB, MySQL, Oracle, or PostgreSQL, additional connection parameters will be required. See the ENGINE setting below on how to specify other database types. This example is for PostgreSQL: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'mydatabase', 'USER': 'mydatabaseuser', 'PASSWORD': 'mypassword', 'HOST': '127.0.0.1', 'PORT': '5432', } } The following inner options that may be required for more complex configurations are available: ATOMIC_REQUESTS Default: False Set this to True to wrap each view in a transaction on this database. See Tying transactions to HTTP requests. AUTOCOMMIT Default: True Set this to False if you want to disable Django’s transaction management and implement your own. ENGINE Default: '' (Empty string) The database backend to use. The built-in database backends are: 'django.db.backends.postgresql' 'django.db.backends.mysql' 'django.db.backends.sqlite3' 'django.db.backends.oracle' You can use a database backend that doesn’t ship with Django by setting ENGINE to a fully-qualified path (i.e. mypackage.backends.whatever). HOST Default: '' (Empty string) Which host to use when connecting to the database. An empty string means localhost. Not used with SQLite. If this value starts with a forward slash ('/') and you’re using MySQL, MySQL will connect via a Unix socket to the specified socket. For example: "HOST": '/var/run/mysql' If you’re using MySQL and this value doesn’t start with a forward slash, then this value is assumed to be the host. If you’re using PostgreSQL, by default (empty HOST), the connection to the database is done through UNIX domain sockets (‘local’ lines in pg_hba.conf). If your UNIX domain socket is not in the standard location, use the same value of unix_socket_directory from postgresql.conf. If you want to connect through TCP sockets, set HOST to ‘localhost’ or ‘127.0.0.1’ (‘host’ lines in pg_hba.conf). On Windows, you should always define HOST, as UNIX domain sockets are not available. NAME Default: '' (Empty string) The name of the database to use. For SQLite, it’s the full path to the database file. When specifying the path, always use forward slashes, even on Windows (e.g. C:/homes/user/mysite/sqlite3.db). CONN_MAX_AGE Default: 0 The lifetime of a database connection, as an integer of seconds. Use 0 to close database connections at the end of each request — Django’s historical behavior — and None for unlimited persistent connections. OPTIONS Default: {} (Empty dictionary) Extra parameters to use when connecting to the database. Available parameters vary depending on your database backend. Some information on available parameters can be found in the Database Backends documentation. For more information, consult your backend module’s own documentation. PASSWORD Default: '' (Empty string) The password to use when connecting to the database. Not used with SQLite. PORT Default: '' (Empty string) The port to use when connecting to the database. An empty string means the default port. Not used with SQLite. TIME_ZONE Default: None A string representing the time zone for this database connection or None. This inner option of the DATABASES setting accepts the same values as the general TIME_ZONE setting. When USE_TZ is True and this option is set, reading datetimes from the database returns aware datetimes in this time zone instead of UTC. When USE_TZ is False, it is an error to set this option. If the database backend doesn’t support time zones (e.g. SQLite, MySQL, Oracle), Django reads and writes datetimes in local time according to this option if it is set and in UTC if it isn’t. Changing the connection time zone changes how datetimes are read from and written to the database. If Django manages the database and you don’t have a strong reason to do otherwise, you should leave this option unset. It’s best to store datetimes in UTC because it avoids ambiguous or nonexistent datetimes during daylight saving time changes. Also, receiving datetimes in UTC keeps datetime arithmetic simple — there’s no need to consider potential offset changes over a DST transition. If you’re connecting to a third-party database that stores datetimes in a local time rather than UTC, then you must set this option to the appropriate time zone. Likewise, if Django manages the database but third-party systems connect to the same database and expect to find datetimes in local time, then you must set this option. If the database backend supports time zones (e.g. PostgreSQL), the TIME_ZONE option is very rarely needed. It can be changed at any time; the database takes care of converting datetimes to the desired time zone. Setting the time zone of the database connection may be useful for running raw SQL queries involving date/time functions provided by the database, such as date_trunc, because their results depend on the time zone. However, this has a downside: receiving all datetimes in local time makes datetime arithmetic more tricky — you must account for possible offset changes over DST transitions. Consider converting to local time explicitly with AT TIME ZONE in raw SQL queries instead of setting the TIME_ZONE option. DISABLE_SERVER_SIDE_CURSORS Default: False Set this to True if you want to disable the use of server-side cursors with QuerySet.iterator(). Transaction pooling and server-side cursors describes the use case. This is a PostgreSQL-specific setting. USER Default: '' (Empty string) The username to use when connecting to the database. Not used with SQLite. TEST Default: {} (Empty dictionary) A dictionary of settings for test databases; for more details about the creation and use of test databases, see The test database. Here’s an example with a test database configuration: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'USER': 'mydatabaseuser', 'NAME': 'mydatabase', 'TEST': { 'NAME': 'mytestdatabase', }, }, } The following keys in the TEST dictionary are available: CHARSET Default: None The character set encoding used to create the test database. The value of this string is passed directly through to the database, so its format is backend-specific. Supported by the PostgreSQL (postgresql) and MySQL (mysql) backends. COLLATION Default: None The collation order to use when creating the test database. This value is passed directly to the backend, so its format is backend-specific. Only supported for the mysql backend (see the MySQL manual for details). DEPENDENCIES Default: ['default'], for all databases other than default, which has no dependencies. The creation-order dependencies of the database. See the documentation on controlling the creation order of test databases for details. MIGRATE Default: True When set to False, migrations won’t run when creating the test database. This is similar to setting None as a value in MIGRATION_MODULES, but for all apps. MIRROR Default: None The alias of the database that this database should mirror during testing. This setting exists to allow for testing of primary/replica (referred to as master/slave by some databases) configurations of multiple databases. See the documentation on testing primary/replica configurations for details. NAME Default: None The name of database to use when running the test suite. If the default value (None) is used with the SQLite database engine, the tests will use a memory resident database. For all other database engines the test database will use the name 'test_' + DATABASE_NAME. See The test database. SERIALIZE Boolean value to control whether or not the default test runner serializes the database into an in-memory JSON string before running tests (used to restore the database state between tests if you don’t have transactions). You can set this to False to speed up creation time if you don’t have any test classes with serialized_rollback=True. Deprecated since version 4.0: This setting is deprecated as it can be inferred from the databases with the serialized_rollback option enabled. TEMPLATE This is a PostgreSQL-specific setting. The name of a template (e.g. 'template0') from which to create the test database. CREATE_DB Default: True This is an Oracle-specific setting. If it is set to False, the test tablespaces won’t be automatically created at the beginning of the tests or dropped at the end. CREATE_USER Default: True This is an Oracle-specific setting. If it is set to False, the test user won’t be automatically created at the beginning of the tests and dropped at the end. USER Default: None This is an Oracle-specific setting. The username to use when connecting to the Oracle database that will be used when running tests. If not provided, Django will use 'test_' + USER. PASSWORD Default: None This is an Oracle-specific setting. The password to use when connecting to the Oracle database that will be used when running tests. If not provided, Django will generate a random password. ORACLE_MANAGED_FILES Default: False This is an Oracle-specific setting. If set to True, Oracle Managed Files (OMF) tablespaces will be used. DATAFILE and DATAFILE_TMP will be ignored. TBLSPACE Default: None This is an Oracle-specific setting. The name of the tablespace that will be used when running tests. If not provided, Django will use 'test_' + USER. TBLSPACE_TMP Default: None This is an Oracle-specific setting. The name of the temporary tablespace that will be used when running tests. If not provided, Django will use 'test_' + USER + '_temp'. DATAFILE Default: None This is an Oracle-specific setting. The name of the datafile to use for the TBLSPACE. If not provided, Django will use TBLSPACE + '.dbf'. DATAFILE_TMP Default: None This is an Oracle-specific setting. The name of the datafile to use for the TBLSPACE_TMP. If not provided, Django will use TBLSPACE_TMP + '.dbf'. DATAFILE_MAXSIZE Default: '500M' This is an Oracle-specific setting. The maximum size that the DATAFILE is allowed to grow to. DATAFILE_TMP_MAXSIZE Default: '500M' This is an Oracle-specific setting. The maximum size that the DATAFILE_TMP is allowed to grow to. DATAFILE_SIZE Default: '50M' This is an Oracle-specific setting. The initial size of the DATAFILE. DATAFILE_TMP_SIZE Default: '50M' This is an Oracle-specific setting. The initial size of the DATAFILE_TMP. DATAFILE_EXTSIZE Default: '25M' This is an Oracle-specific setting. The amount by which the DATAFILE is extended when more space is required. DATAFILE_TMP_EXTSIZE Default: '25M' This is an Oracle-specific setting. The amount by which the DATAFILE_TMP is extended when more space is required. DATA_UPLOAD_MAX_MEMORY_SIZE Default: 2621440 (i.e. 2.5 MB). The maximum size in bytes that a request body may be before a SuspiciousOperation (RequestDataTooBig) is raised. The check is done when accessing request.body or request.POST and is calculated against the total request size excluding any file upload data. You can set this to None to disable the check. Applications that are expected to receive unusually large form posts should tune this setting. The amount of request data is correlated to the amount of memory needed to process the request and populate the GET and POST dictionaries. Large requests could be used as a denial-of-service attack vector if left unchecked. Since web servers don’t typically perform deep request inspection, it’s not possible to perform a similar check at that level. See also FILE_UPLOAD_MAX_MEMORY_SIZE. DATA_UPLOAD_MAX_NUMBER_FIELDS Default: 1000 The maximum number of parameters that may be received via GET or POST before a SuspiciousOperation (TooManyFields) is raised. You can set this to None to disable the check. Applications that are expected to receive an unusually large number of form fields should tune this setting. The number of request parameters is correlated to the amount of time needed to process the request and populate the GET and POST dictionaries. Large requests could be used as a denial-of-service attack vector if left unchecked. Since web servers don’t typically perform deep request inspection, it’s not possible to perform a similar check at that level. DATABASE_ROUTERS Default: [] (Empty list) The list of routers that will be used to determine which database to use when performing a database query. See the documentation on automatic database routing in multi database configurations. DATE_FORMAT Default: 'N j, Y' (e.g. Feb. 4, 2003) The default formatting to use for displaying date fields in any part of the system. Note that if USE_L10N is set to True, then the locale-dictated format has higher precedence and will be applied instead. See allowed date format strings. See also DATETIME_FORMAT, TIME_FORMAT and SHORT_DATE_FORMAT. DATE_INPUT_FORMATS Default: [ '%Y-%m-%d', '%m/%d/%Y', '%m/%d/%y', # '2006-10-25', '10/25/2006', '10/25/06' '%b %d %Y', '%b %d, %Y', # 'Oct 25 2006', 'Oct 25, 2006' '%d %b %Y', '%d %b, %Y', # '25 Oct 2006', '25 Oct, 2006' '%B %d %Y', '%B %d, %Y', # 'October 25 2006', 'October 25, 2006' '%d %B %Y', '%d %B, %Y', # '25 October 2006', '25 October, 2006' ] A list of formats that will be accepted when inputting data on a date field. Formats will be tried in order, using the first valid one. Note that these format strings use Python’s datetime module syntax, not the format strings from the date template filter. When USE_L10N is True, the locale-dictated format has higher precedence and will be applied instead. See also DATETIME_INPUT_FORMATS and TIME_INPUT_FORMATS. DATETIME_FORMAT Default: 'N j, Y, P' (e.g. Feb. 4, 2003, 4 p.m.) The default formatting to use for displaying datetime fields in any part of the system. Note that if USE_L10N is set to True, then the locale-dictated format has higher precedence and will be applied instead. See allowed date format strings. See also DATE_FORMAT, TIME_FORMAT and SHORT_DATETIME_FORMAT. DATETIME_INPUT_FORMATS Default: [ '%Y-%m-%d %H:%M:%S', # '2006-10-25 14:30:59' '%Y-%m-%d %H:%M:%S.%f', # '2006-10-25 14:30:59.000200' '%Y-%m-%d %H:%M', # '2006-10-25 14:30' '%m/%d/%Y %H:%M:%S', # '10/25/2006 14:30:59' '%m/%d/%Y %H:%M:%S.%f', # '10/25/2006 14:30:59.000200' '%m/%d/%Y %H:%M', # '10/25/2006 14:30' '%m/%d/%y %H:%M:%S', # '10/25/06 14:30:59' '%m/%d/%y %H:%M:%S.%f', # '10/25/06 14:30:59.000200' '%m/%d/%y %H:%M', # '10/25/06 14:30' ] A list of formats that will be accepted when inputting data on a datetime field. Formats will be tried in order, using the first valid one. Note that these format strings use Python’s datetime module syntax, not the format strings from the date template filter. Date-only formats are not included as datetime fields will automatically try DATE_INPUT_FORMATS in last resort. When USE_L10N is True, the locale-dictated format has higher precedence and will be applied instead. See also DATE_INPUT_FORMATS and TIME_INPUT_FORMATS. DEBUG Default: False A boolean that turns on/off debug mode. Never deploy a site into production with DEBUG turned on. One of the main features of debug mode is the display of detailed error pages. If your app raises an exception when DEBUG is True, Django will display a detailed traceback, including a lot of metadata about your environment, such as all the currently defined Django settings (from settings.py). As a security measure, Django will not include settings that might be sensitive, such as SECRET_KEY. Specifically, it will exclude any setting whose name includes any of the following: 'API' 'KEY' 'PASS' 'SECRET' 'SIGNATURE' 'TOKEN' Note that these are partial matches. 'PASS' will also match PASSWORD, just as 'TOKEN' will also match TOKENIZED and so on. Still, note that there are always going to be sections of your debug output that are inappropriate for public consumption. File paths, configuration options and the like all give attackers extra information about your server. It is also important to remember that when running with DEBUG turned on, Django will remember every SQL query it executes. This is useful when you’re debugging, but it’ll rapidly consume memory on a production server. Finally, if DEBUG is False, you also need to properly set the ALLOWED_HOSTS setting. Failing to do so will result in all requests being returned as “Bad Request (400)”. Note The default settings.py file created by django-admin startproject sets DEBUG = True for convenience. DEBUG_PROPAGATE_EXCEPTIONS Default: False If set to True, Django’s exception handling of view functions (handler500, or the debug view if DEBUG is True) and logging of 500 responses (django.request) is skipped and exceptions propagate upward. This can be useful for some test setups. It shouldn’t be used on a live site unless you want your web server (instead of Django) to generate “Internal Server Error” responses. In that case, make sure your server doesn’t show the stack trace or other sensitive information in the response. DECIMAL_SEPARATOR Default: '.' (Dot) Default decimal separator used when formatting decimal numbers. Note that if USE_L10N is set to True, then the locale-dictated format has higher precedence and will be applied instead. See also NUMBER_GROUPING, THOUSAND_SEPARATOR and USE_THOUSAND_SEPARATOR. DEFAULT_AUTO_FIELD New in Django 3.2. Default: 'django.db.models.AutoField' Default primary key field type to use for models that don’t have a field with primary_key=True. Migrating auto-created through tables The value of DEFAULT_AUTO_FIELD will be respected when creating new auto-created through tables for many-to-many relationships. Unfortunately, the primary keys of existing auto-created through tables cannot currently be updated by the migrations framework. This means that if you switch the value of DEFAULT_AUTO_FIELD and then generate migrations, the primary keys of the related models will be updated, as will the foreign keys from the through table, but the primary key of the auto-created through table will not be migrated. In order to address this, you should add a RunSQL operation to your migrations to perform the required ALTER TABLE step. You can check the existing table name through sqlmigrate, dbshell, or with the field’s remote_field.through._meta.db_table property. Explicitly defined through models are already handled by the migrations system. Allowing automatic migrations for the primary key of existing auto-created through tables may be implemented at a later date. DEFAULT_CHARSET Default: 'utf-8' Default charset to use for all HttpResponse objects, if a MIME type isn’t manually specified. Used when constructing the Content-Type header. DEFAULT_EXCEPTION_REPORTER Default: 'django.views.debug.ExceptionReporter' Default exception reporter class to be used if none has been assigned to the HttpRequest instance yet. See Custom error reports. DEFAULT_EXCEPTION_REPORTER_FILTER Default: 'django.views.debug.SafeExceptionReporterFilter' Default exception reporter filter class to be used if none has been assigned to the HttpRequest instance yet. See Filtering error reports. DEFAULT_FILE_STORAGE Default: 'django.core.files.storage.FileSystemStorage' Default file storage class to be used for any file-related operations that don’t specify a particular storage system. See Managing files. DEFAULT_FROM_EMAIL Default: 'webmaster@localhost' Default email address to use for various automated correspondence from the site manager(s). This doesn’t include error messages sent to ADMINS and MANAGERS; for that, see SERVER_EMAIL. DEFAULT_INDEX_TABLESPACE Default: '' (Empty string) Default tablespace to use for indexes on fields that don’t specify one, if the backend supports it (see Tablespaces). DEFAULT_TABLESPACE Default: '' (Empty string) Default tablespace to use for models that don’t specify one, if the backend supports it (see Tablespaces). DISALLOWED_USER_AGENTS Default: [] (Empty list) List of compiled regular expression objects representing User-Agent strings that are not allowed to visit any page, systemwide. Use this for bots/crawlers. This is only used if CommonMiddleware is installed (see Middleware). EMAIL_BACKEND Default: 'django.core.mail.backends.smtp.EmailBackend' The backend to use for sending emails. For the list of available backends see Sending email. EMAIL_FILE_PATH Default: Not defined The directory used by the file email backend to store output files. EMAIL_HOST Default: 'localhost' The host to use for sending email. See also EMAIL_PORT. EMAIL_HOST_PASSWORD Default: '' (Empty string) Password to use for the SMTP server defined in EMAIL_HOST. This setting is used in conjunction with EMAIL_HOST_USER when authenticating to the SMTP server. If either of these settings is empty, Django won’t attempt authentication. See also EMAIL_HOST_USER. EMAIL_HOST_USER Default: '' (Empty string) Username to use for the SMTP server defined in EMAIL_HOST. If empty, Django won’t attempt authentication. See also EMAIL_HOST_PASSWORD. EMAIL_PORT Default: 25 Port to use for the SMTP server defined in EMAIL_HOST. EMAIL_SUBJECT_PREFIX Default: '[Django] ' Subject-line prefix for email messages sent with django.core.mail.mail_admins or django.core.mail.mail_managers. You’ll probably want to include the trailing space. EMAIL_USE_LOCALTIME Default: False Whether to send the SMTP Date header of email messages in the local time zone (True) or in UTC (False). EMAIL_USE_TLS Default: False Whether to use a TLS (secure) connection when talking to the SMTP server. This is used for explicit TLS connections, generally on port 587. If you are experiencing hanging connections, see the implicit TLS setting EMAIL_USE_SSL. EMAIL_USE_SSL Default: False Whether to use an implicit TLS (secure) connection when talking to the SMTP server. In most email documentation this type of TLS connection is referred to as SSL. It is generally used on port 465. If you are experiencing problems, see the explicit TLS setting EMAIL_USE_TLS. Note that EMAIL_USE_TLS/EMAIL_USE_SSL are mutually exclusive, so only set one of those settings to True. EMAIL_SSL_CERTFILE Default: None If EMAIL_USE_SSL or EMAIL_USE_TLS is True, you can optionally specify the path to a PEM-formatted certificate chain file to use for the SSL connection. EMAIL_SSL_KEYFILE Default: None If EMAIL_USE_SSL or EMAIL_USE_TLS is True, you can optionally specify the path to a PEM-formatted private key file to use for the SSL connection. Note that setting EMAIL_SSL_CERTFILE and EMAIL_SSL_KEYFILE doesn’t result in any certificate checking. They’re passed to the underlying SSL connection. Please refer to the documentation of Python’s ssl.wrap_socket() function for details on how the certificate chain file and private key file are handled. EMAIL_TIMEOUT Default: None Specifies a timeout in seconds for blocking operations like the connection attempt. FILE_UPLOAD_HANDLERS Default: [ 'django.core.files.uploadhandler.MemoryFileUploadHandler', 'django.core.files.uploadhandler.TemporaryFileUploadHandler', ] A list of handlers to use for uploading. Changing this setting allows complete customization – even replacement – of Django’s upload process. See Managing files for details. FILE_UPLOAD_MAX_MEMORY_SIZE Default: 2621440 (i.e. 2.5 MB). The maximum size (in bytes) that an upload will be before it gets streamed to the file system. See Managing files for details. See also DATA_UPLOAD_MAX_MEMORY_SIZE. FILE_UPLOAD_DIRECTORY_PERMISSIONS Default: None The numeric mode to apply to directories created in the process of uploading files. This setting also determines the default permissions for collected static directories when using the collectstatic management command. See collectstatic for details on overriding it. This value mirrors the functionality and caveats of the FILE_UPLOAD_PERMISSIONS setting. FILE_UPLOAD_PERMISSIONS Default: 0o644 The numeric mode (i.e. 0o644) to set newly uploaded files to. For more information about what these modes mean, see the documentation for os.chmod(). If None, you’ll get operating-system dependent behavior. On most platforms, temporary files will have a mode of 0o600, and files saved from memory will be saved using the system’s standard umask. For security reasons, these permissions aren’t applied to the temporary files that are stored in FILE_UPLOAD_TEMP_DIR. This setting also determines the default permissions for collected static files when using the collectstatic management command. See collectstatic for details on overriding it. Warning Always prefix the mode with 0o . If you’re not familiar with file modes, please note that the 0o prefix is very important: it indicates an octal number, which is the way that modes must be specified. If you try to use 644, you’ll get totally incorrect behavior. FILE_UPLOAD_TEMP_DIR Default: None The directory to store data to (typically files larger than FILE_UPLOAD_MAX_MEMORY_SIZE) temporarily while uploading files. If None, Django will use the standard temporary directory for the operating system. For example, this will default to /tmp on *nix-style operating systems. See Managing files for details. FIRST_DAY_OF_WEEK Default: 0 (Sunday) A number representing the first day of the week. This is especially useful when displaying a calendar. This value is only used when not using format internationalization, or when a format cannot be found for the current locale. The value must be an integer from 0 to 6, where 0 means Sunday, 1 means Monday and so on. FIXTURE_DIRS Default: [] (Empty list) List of directories searched for fixture files, in addition to the fixtures directory of each application, in search order. Note that these paths should use Unix-style forward slashes, even on Windows. See Providing data with fixtures and Fixture loading. FORCE_SCRIPT_NAME Default: None If not None, this will be used as the value of the SCRIPT_NAME environment variable in any HTTP request. This setting can be used to override the server-provided value of SCRIPT_NAME, which may be a rewritten version of the preferred value or not supplied at all. It is also used by django.setup() to set the URL resolver script prefix outside of the request/response cycle (e.g. in management commands and standalone scripts) to generate correct URLs when SCRIPT_NAME is not /. FORM_RENDERER Default: 'django.forms.renderers.DjangoTemplates' The class that renders forms and form widgets. It must implement the low-level render API. Included form renderers are: 'django.forms.renderers.DjangoTemplates' 'django.forms.renderers.Jinja2' FORMAT_MODULE_PATH Default: None A full Python path to a Python package that contains custom format definitions for project locales. If not None, Django will check for a formats.py file, under the directory named as the current locale, and will use the formats defined in this file. For example, if FORMAT_MODULE_PATH is set to mysite.formats, and current language is en (English), Django will expect a directory tree like: mysite/ formats/ __init__.py en/ __init__.py formats.py You can also set this setting to a list of Python paths, for example: FORMAT_MODULE_PATH = [ 'mysite.formats', 'some_app.formats', ] When Django searches for a certain format, it will go through all given Python paths until it finds a module that actually defines the given format. This means that formats defined in packages farther up in the list will take precedence over the same formats in packages farther down. Available formats are: DATE_FORMAT DATE_INPUT_FORMATS DATETIME_FORMAT, DATETIME_INPUT_FORMATS DECIMAL_SEPARATOR FIRST_DAY_OF_WEEK MONTH_DAY_FORMAT NUMBER_GROUPING SHORT_DATE_FORMAT SHORT_DATETIME_FORMAT THOUSAND_SEPARATOR TIME_FORMAT TIME_INPUT_FORMATS YEAR_MONTH_FORMAT IGNORABLE_404_URLS Default: [] (Empty list) List of compiled regular expression objects describing URLs that should be ignored when reporting HTTP 404 errors via email (see How to manage error reporting). Regular expressions are matched against request's full paths (including query string, if any). Use this if your site does not provide a commonly requested file such as favicon.ico or robots.txt. This is only used if BrokenLinkEmailsMiddleware is enabled (see Middleware). INSTALLED_APPS Default: [] (Empty list) A list of strings designating all applications that are enabled in this Django installation. Each string should be a dotted Python path to: an application configuration class (preferred), or a package containing an application. Learn more about application configurations. Use the application registry for introspection Your code should never access INSTALLED_APPS directly. Use django.apps.apps instead. Application names and labels must be unique in INSTALLED_APPS Application names — the dotted Python path to the application package — must be unique. There is no way to include the same application twice, short of duplicating its code under another name. Application labels — by default the final part of the name — must be unique too. For example, you can’t include both django.contrib.auth and myproject.auth. However, you can relabel an application with a custom configuration that defines a different label. These rules apply regardless of whether INSTALLED_APPS references application configuration classes or application packages. When several applications provide different versions of the same resource (template, static file, management command, translation), the application listed first in INSTALLED_APPS has precedence. INTERNAL_IPS Default: [] (Empty list) A list of IP addresses, as strings, that: Allow the debug() context processor to add some variables to the template context. Can use the admindocs bookmarklets even if not logged in as a staff user. Are marked as “internal” (as opposed to “EXTERNAL”) in AdminEmailHandler emails. LANGUAGE_CODE Default: 'en-us' A string representing the language code for this installation. This should be in standard language ID format. For example, U.S. English is "en-us". See also the list of language identifiers and Internationalization and localization. USE_I18N must be active for this setting to have any effect. It serves two purposes: If the locale middleware isn’t in use, it decides which translation is served to all users. If the locale middleware is active, it provides a fallback language in case the user’s preferred language can’t be determined or is not supported by the website. It also provides the fallback translation when a translation for a given literal doesn’t exist for the user’s preferred language. See How Django discovers language preference for more details. LANGUAGE_COOKIE_AGE Default: None (expires at browser close) The age of the language cookie, in seconds. LANGUAGE_COOKIE_DOMAIN Default: None The domain to use for the language cookie. Set this to a string such as "example.com" for cross-domain cookies, or use None for a standard domain cookie. Be cautious when updating this setting on a production site. If you update this setting to enable cross-domain cookies on a site that previously used standard domain cookies, existing user cookies that have the old domain will not be updated. This will result in site users being unable to switch the language as long as these cookies persist. The only safe and reliable option to perform the switch is to change the language cookie name permanently (via the LANGUAGE_COOKIE_NAME setting) and to add a middleware that copies the value from the old cookie to a new one and then deletes the old one. LANGUAGE_COOKIE_HTTPONLY Default: False Whether to use HttpOnly flag on the language cookie. If this is set to True, client-side JavaScript will not be able to access the language cookie. See SESSION_COOKIE_HTTPONLY for details on HttpOnly. LANGUAGE_COOKIE_NAME Default: 'django_language' The name of the cookie to use for the language cookie. This can be whatever you want (as long as it’s different from the other cookie names in your application). See Internationalization and localization. LANGUAGE_COOKIE_PATH Default: '/' The path set on the language cookie. This should either match the URL path of your Django installation or be a parent of that path. This is useful if you have multiple Django instances running under the same hostname. They can use different cookie paths and each instance will only see its own language cookie. Be cautious when updating this setting on a production site. If you update this setting to use a deeper path than it previously used, existing user cookies that have the old path will not be updated. This will result in site users being unable to switch the language as long as these cookies persist. The only safe and reliable option to perform the switch is to change the language cookie name permanently (via the LANGUAGE_COOKIE_NAME setting), and to add a middleware that copies the value from the old cookie to a new one and then deletes the one. LANGUAGE_COOKIE_SAMESITE Default: None The value of the SameSite flag on the language cookie. This flag prevents the cookie from being sent in cross-site requests. See SESSION_COOKIE_SAMESITE for details about SameSite. LANGUAGE_COOKIE_SECURE Default: False Whether to use a secure cookie for the language cookie. If this is set to True, the cookie will be marked as “secure”, which means browsers may ensure that the cookie is only sent under an HTTPS connection. LANGUAGES Default: A list of all available languages. This list is continually growing and including a copy here would inevitably become rapidly out of date. You can see the current list of translated languages by looking in django/conf/global_settings.py. The list is a list of two-tuples in the format (language code, language name) – for example, ('ja', 'Japanese'). This specifies which languages are available for language selection. See Internationalization and localization. Generally, the default value should suffice. Only set this setting if you want to restrict language selection to a subset of the Django-provided languages. If you define a custom LANGUAGES setting, you can mark the language names as translation strings using the gettext_lazy() function. Here’s a sample settings file: from django.utils.translation import gettext_lazy as _ LANGUAGES = [ ('de', _('German')), ('en', _('English')), ] LANGUAGES_BIDI Default: A list of all language codes that are written right-to-left. You can see the current list of these languages by looking in django/conf/global_settings.py. The list contains language codes for languages that are written right-to-left. Generally, the default value should suffice. Only set this setting if you want to restrict language selection to a subset of the Django-provided languages. If you define a custom LANGUAGES setting, the list of bidirectional languages may contain language codes which are not enabled on a given site. LOCALE_PATHS Default: [] (Empty list) A list of directories where Django looks for translation files. See How Django discovers translations. Example: LOCALE_PATHS = [ '/home/www/project/common_files/locale', '/var/local/translations/locale', ] Django will look within each of these paths for the <locale_code>/LC_MESSAGES directories containing the actual translation files. LOGGING Default: A logging configuration dictionary. A data structure containing configuration information. The contents of this data structure will be passed as the argument to the configuration method described in LOGGING_CONFIG. Among other things, the default logging configuration passes HTTP 500 server errors to an email log handler when DEBUG is False. See also Configuring logging. You can see the default logging configuration by looking in django/utils/log.py. LOGGING_CONFIG Default: 'logging.config.dictConfig' A path to a callable that will be used to configure logging in the Django project. Points at an instance of Python’s dictConfig configuration method by default. If you set LOGGING_CONFIG to None, the logging configuration process will be skipped. MANAGERS Default: [] (Empty list) A list in the same format as ADMINS that specifies who should get broken link notifications when BrokenLinkEmailsMiddleware is enabled. MEDIA_ROOT Default: '' (Empty string) Absolute filesystem path to the directory that will hold user-uploaded files. Example: "/var/www/example.com/media/" See also MEDIA_URL. Warning MEDIA_ROOT and STATIC_ROOT must have different values. Before STATIC_ROOT was introduced, it was common to rely or fallback on MEDIA_ROOT to also serve static files; however, since this can have serious security implications, there is a validation check to prevent it. MEDIA_URL Default: '' (Empty string) URL that handles the media served from MEDIA_ROOT, used for managing stored files. It must end in a slash if set to a non-empty value. You will need to configure these files to be served in both development and production environments. If you want to use {{ MEDIA_URL }} in your templates, add 'django.template.context_processors.media' in the 'context_processors' option of TEMPLATES. Example: "http://media.example.com/" Warning There are security risks if you are accepting uploaded content from untrusted users! See the security guide’s topic on User-uploaded content for mitigation details. Warning MEDIA_URL and STATIC_URL must have different values. See MEDIA_ROOT for more details. Note If MEDIA_URL is a relative path, then it will be prefixed by the server-provided value of SCRIPT_NAME (or / if not set). This makes it easier to serve a Django application in a subpath without adding an extra configuration to the settings. MIDDLEWARE Default: None A list of middleware to use. See Middleware. MIGRATION_MODULES Default: {} (Empty dictionary) A dictionary specifying the package where migration modules can be found on a per-app basis. The default value of this setting is an empty dictionary, but the default package name for migration modules is migrations. Example: {'blog': 'blog.db_migrations'} In this case, migrations pertaining to the blog app will be contained in the blog.db_migrations package. If you provide the app_label argument, makemigrations will automatically create the package if it doesn’t already exist. When you supply None as a value for an app, Django will consider the app as an app without migrations regardless of an existing migrations submodule. This can be used, for example, in a test settings file to skip migrations while testing (tables will still be created for the apps’ models). To disable migrations for all apps during tests, you can set the MIGRATE to False instead. If MIGRATION_MODULES is used in your general project settings, remember to use the migrate --run-syncdb option if you want to create tables for the app. MONTH_DAY_FORMAT Default: 'F j' The default formatting to use for date fields on Django admin change-list pages – and, possibly, by other parts of the system – in cases when only the month and day are displayed. For example, when a Django admin change-list page is being filtered by a date drilldown, the header for a given day displays the day and month. Different locales have different formats. For example, U.S. English would say “January 1,” whereas Spanish might say “1 Enero.” Note that if USE_L10N is set to True, then the corresponding locale-dictated format has higher precedence and will be applied. See allowed date format strings. See also DATE_FORMAT, DATETIME_FORMAT, TIME_FORMAT and YEAR_MONTH_FORMAT. NUMBER_GROUPING Default: 0 Number of digits grouped together on the integer part of a number. Common use is to display a thousand separator. If this setting is 0, then no grouping will be applied to the number. If this setting is greater than 0, then THOUSAND_SEPARATOR will be used as the separator between those groups. Some locales use non-uniform digit grouping, e.g. 10,00,00,000 in en_IN. For this case, you can provide a sequence with the number of digit group sizes to be applied. The first number defines the size of the group preceding the decimal delimiter, and each number that follows defines the size of preceding groups. If the sequence is terminated with -1, no further grouping is performed. If the sequence terminates with a 0, the last group size is used for the remainder of the number. Example tuple for en_IN: NUMBER_GROUPING = (3, 2, 0) Note that if USE_L10N is set to True, then the locale-dictated format has higher precedence and will be applied instead. See also DECIMAL_SEPARATOR, THOUSAND_SEPARATOR and USE_THOUSAND_SEPARATOR. PREPEND_WWW Default: False Whether to prepend the “www.” subdomain to URLs that don’t have it. This is only used if CommonMiddleware is installed (see Middleware). See also APPEND_SLASH. ROOT_URLCONF Default: Not defined A string representing the full Python import path to your root URLconf, for example "mydjangoapps.urls". Can be overridden on a per-request basis by setting the attribute urlconf on the incoming HttpRequest object. See How Django processes a request for details. SECRET_KEY Default: '' (Empty string) A secret key for a particular Django installation. This is used to provide cryptographic signing, and should be set to a unique, unpredictable value. django-admin startproject automatically adds a randomly-generated SECRET_KEY to each new project. Uses of the key shouldn’t assume that it’s text or bytes. Every use should go through force_str() or force_bytes() to convert it to the desired type. Django will refuse to start if SECRET_KEY is not set. Warning Keep this value secret. Running Django with a known SECRET_KEY defeats many of Django’s security protections, and can lead to privilege escalation and remote code execution vulnerabilities. The secret key is used for: All sessions if you are using any other session backend than django.contrib.sessions.backends.cache, or are using the default get_session_auth_hash(). All messages if you are using CookieStorage or FallbackStorage. All PasswordResetView tokens. Any usage of cryptographic signing, unless a different key is provided. If you rotate your secret key, all of the above will be invalidated. Secret keys are not used for passwords of users and key rotation will not affect them. Note The default settings.py file created by django-admin startproject creates a unique SECRET_KEY for convenience. SECURE_CONTENT_TYPE_NOSNIFF Default: True If True, the SecurityMiddleware sets the X-Content-Type-Options: nosniff header on all responses that do not already have it. SECURE_CROSS_ORIGIN_OPENER_POLICY New in Django 4.0. Default: 'same-origin' Unless set to None, the SecurityMiddleware sets the Cross-Origin Opener Policy header on all responses that do not already have it to the value provided. SECURE_HSTS_INCLUDE_SUBDOMAINS Default: False If True, the SecurityMiddleware adds the includeSubDomains directive to the HTTP Strict Transport Security header. It has no effect unless SECURE_HSTS_SECONDS is set to a non-zero value. Warning Setting this incorrectly can irreversibly (for the value of SECURE_HSTS_SECONDS) break your site. Read the HTTP Strict Transport Security documentation first. SECURE_HSTS_PRELOAD Default: False If True, the SecurityMiddleware adds the preload directive to the HTTP Strict Transport Security header. It has no effect unless SECURE_HSTS_SECONDS is set to a non-zero value. SECURE_HSTS_SECONDS Default: 0 If set to a non-zero integer value, the SecurityMiddleware sets the HTTP Strict Transport Security header on all responses that do not already have it. Warning Setting this incorrectly can irreversibly (for some time) break your site. Read the HTTP Strict Transport Security documentation first. SECURE_PROXY_SSL_HEADER Default: None A tuple representing an HTTP header/value combination that signifies a request is secure. This controls the behavior of the request object’s is_secure() method. By default, is_secure() determines if a request is secure by confirming that a requested URL uses https://. This method is important for Django’s CSRF protection, and it may be used by your own code or third-party apps. If your Django app is behind a proxy, though, the proxy may be “swallowing” whether the original request uses HTTPS or not. If there is a non-HTTPS connection between the proxy and Django then is_secure() would always return False – even for requests that were made via HTTPS by the end user. In contrast, if there is an HTTPS connection between the proxy and Django then is_secure() would always return True – even for requests that were made originally via HTTP. In this situation, configure your proxy to set a custom HTTP header that tells Django whether the request came in via HTTPS, and set SECURE_PROXY_SSL_HEADER so that Django knows what header to look for. Set a tuple with two elements – the name of the header to look for and the required value. For example: SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') This tells Django to trust the X-Forwarded-Proto header that comes from our proxy, and any time its value is 'https', then the request is guaranteed to be secure (i.e., it originally came in via HTTPS). You should only set this setting if you control your proxy or have some other guarantee that it sets/strips this header appropriately. Note that the header needs to be in the format as used by request.META – all caps and likely starting with HTTP_. (Remember, Django automatically adds 'HTTP_' to the start of x-header names before making the header available in request.META.) Warning Modifying this setting can compromise your site’s security. Ensure you fully understand your setup before changing it. Make sure ALL of the following are true before setting this (assuming the values from the example above): Your Django app is behind a proxy. Your proxy strips the X-Forwarded-Proto header from all incoming requests. In other words, if end users include that header in their requests, the proxy will discard it. Your proxy sets the X-Forwarded-Proto header and sends it to Django, but only for requests that originally come in via HTTPS. If any of those are not true, you should keep this setting set to None and find another way of determining HTTPS, perhaps via custom middleware. SECURE_REDIRECT_EXEMPT Default: [] (Empty list) If a URL path matches a regular expression in this list, the request will not be redirected to HTTPS. The SecurityMiddleware strips leading slashes from URL paths, so patterns shouldn’t include them, e.g. SECURE_REDIRECT_EXEMPT = [r'^no-ssl/$', …]. If SECURE_SSL_REDIRECT is False, this setting has no effect. SECURE_REFERRER_POLICY Default: 'same-origin' If configured, the SecurityMiddleware sets the Referrer Policy header on all responses that do not already have it to the value provided. SECURE_SSL_HOST Default: None If a string (e.g. secure.example.com), all SSL redirects will be directed to this host rather than the originally-requested host (e.g. www.example.com). If SECURE_SSL_REDIRECT is False, this setting has no effect. SECURE_SSL_REDIRECT Default: False If True, the SecurityMiddleware redirects all non-HTTPS requests to HTTPS (except for those URLs matching a regular expression listed in SECURE_REDIRECT_EXEMPT). Note If turning this to True causes infinite redirects, it probably means your site is running behind a proxy and can’t tell which requests are secure and which are not. Your proxy likely sets a header to indicate secure requests; you can correct the problem by finding out what that header is and configuring the SECURE_PROXY_SSL_HEADER setting accordingly. SERIALIZATION_MODULES Default: Not defined A dictionary of modules containing serializer definitions (provided as strings), keyed by a string identifier for that serialization type. For example, to define a YAML serializer, use: SERIALIZATION_MODULES = {'yaml': 'path.to.yaml_serializer'} SERVER_EMAIL Default: 'root@localhost' The email address that error messages come from, such as those sent to ADMINS and MANAGERS. Why are my emails sent from a different address? This address is used only for error messages. It is not the address that regular email messages sent with send_mail() come from; for that, see DEFAULT_FROM_EMAIL. SHORT_DATE_FORMAT Default: 'm/d/Y' (e.g. 12/31/2003) An available formatting that can be used for displaying date fields on templates. Note that if USE_L10N is set to True, then the corresponding locale-dictated format has higher precedence and will be applied. See allowed date format strings. See also DATE_FORMAT and SHORT_DATETIME_FORMAT. SHORT_DATETIME_FORMAT Default: 'm/d/Y P' (e.g. 12/31/2003 4 p.m.) An available formatting that can be used for displaying datetime fields on templates. Note that if USE_L10N is set to True, then the corresponding locale-dictated format has higher precedence and will be applied. See allowed date format strings. See also DATE_FORMAT and SHORT_DATE_FORMAT. SIGNING_BACKEND Default: 'django.core.signing.TimestampSigner' The backend used for signing cookies and other data. See also the Cryptographic signing documentation. SILENCED_SYSTEM_CHECKS Default: [] (Empty list) A list of identifiers of messages generated by the system check framework (i.e. ["models.W001"]) that you wish to permanently acknowledge and ignore. Silenced checks will not be output to the console. See also the System check framework documentation. TEMPLATES Default: [] (Empty list) A list containing the settings for all template engines to be used with Django. Each item of the list is a dictionary containing the options for an individual engine. Here’s a setup that tells the Django template engine to load templates from the templates subdirectory inside each installed application: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'APP_DIRS': True, }, ] The following options are available for all backends. BACKEND Default: Not defined The template backend to use. The built-in template backends are: 'django.template.backends.django.DjangoTemplates' 'django.template.backends.jinja2.Jinja2' You can use a template backend that doesn’t ship with Django by setting BACKEND to a fully-qualified path (i.e. 'mypackage.whatever.Backend'). NAME Default: see below The alias for this particular template engine. It’s an identifier that allows selecting an engine for rendering. Aliases must be unique across all configured template engines. It defaults to the name of the module defining the engine class, i.e. the next to last piece of BACKEND, when it isn’t provided. For example if the backend is 'mypackage.whatever.Backend' then its default name is 'whatever'. DIRS Default: [] (Empty list) Directories where the engine should look for template source files, in search order. APP_DIRS Default: False Whether the engine should look for template source files inside installed applications. Note The default settings.py file created by django-admin startproject sets 'APP_DIRS': True. OPTIONS Default: {} (Empty dict) Extra parameters to pass to the template backend. Available parameters vary depending on the template backend. See DjangoTemplates and Jinja2 for the options of the built-in backends. TEST_RUNNER Default: 'django.test.runner.DiscoverRunner' The name of the class to use for starting the test suite. See Using different testing frameworks. TEST_NON_SERIALIZED_APPS Default: [] (Empty list) In order to restore the database state between tests for TransactionTestCases and database backends without transactions, Django will serialize the contents of all apps when it starts the test run so it can then reload from that copy before running tests that need it. This slows down the startup time of the test runner; if you have apps that you know don’t need this feature, you can add their full names in here (e.g. 'django.contrib.contenttypes') to exclude them from this serialization process. THOUSAND_SEPARATOR Default: ',' (Comma) Default thousand separator used when formatting numbers. This setting is used only when USE_THOUSAND_SEPARATOR is True and NUMBER_GROUPING is greater than 0. Note that if USE_L10N is set to True, then the locale-dictated format has higher precedence and will be applied instead. See also NUMBER_GROUPING, DECIMAL_SEPARATOR and USE_THOUSAND_SEPARATOR. TIME_FORMAT Default: 'P' (e.g. 4 p.m.) The default formatting to use for displaying time fields in any part of the system. Note that if USE_L10N is set to True, then the locale-dictated format has higher precedence and will be applied instead. See allowed date format strings. See also DATE_FORMAT and DATETIME_FORMAT. TIME_INPUT_FORMATS Default: [ '%H:%M:%S', # '14:30:59' '%H:%M:%S.%f', # '14:30:59.000200' '%H:%M', # '14:30' ] A list of formats that will be accepted when inputting data on a time field. Formats will be tried in order, using the first valid one. Note that these format strings use Python’s datetime module syntax, not the format strings from the date template filter. When USE_L10N is True, the locale-dictated format has higher precedence and will be applied instead. See also DATE_INPUT_FORMATS and DATETIME_INPUT_FORMATS. TIME_ZONE Default: 'America/Chicago' A string representing the time zone for this installation. See the list of time zones. Note Since Django was first released with the TIME_ZONE set to 'America/Chicago', the global setting (used if nothing is defined in your project’s settings.py) remains 'America/Chicago' for backwards compatibility. New project templates default to 'UTC'. Note that this isn’t necessarily the time zone of the server. For example, one server may serve multiple Django-powered sites, each with a separate time zone setting. When USE_TZ is False, this is the time zone in which Django will store all datetimes. When USE_TZ is True, this is the default time zone that Django will use to display datetimes in templates and to interpret datetimes entered in forms. On Unix environments (where time.tzset() is implemented), Django sets the os.environ['TZ'] variable to the time zone you specify in the TIME_ZONE setting. Thus, all your views and models will automatically operate in this time zone. However, Django won’t set the TZ environment variable if you’re using the manual configuration option as described in manually configuring settings. If Django doesn’t set the TZ environment variable, it’s up to you to ensure your processes are running in the correct environment. Note Django cannot reliably use alternate time zones in a Windows environment. If you’re running Django on Windows, TIME_ZONE must be set to match the system time zone. USE_DEPRECATED_PYTZ New in Django 4.0. Default: False A boolean that specifies whether to use pytz, rather than zoneinfo, as the default time zone implementation. Deprecated since version 4.0: This transitional setting is deprecated. Support for using pytz will be removed in Django 5.0. USE_I18N Default: True A boolean that specifies whether Django’s translation system should be enabled. This provides a way to turn it off, for performance. If this is set to False, Django will make some optimizations so as not to load the translation machinery. See also LANGUAGE_CODE, USE_L10N and USE_TZ. Note The default settings.py file created by django-admin startproject includes USE_I18N = True for convenience. USE_L10N Default: True A boolean that specifies if localized formatting of data will be enabled by default or not. If this is set to True, e.g. Django will display numbers and dates using the format of the current locale. See also LANGUAGE_CODE, USE_I18N and USE_TZ. Changed in Django 4.0: In older versions, the default value is False. Deprecated since version 4.0: This setting is deprecated. Starting with Django 5.0, localized formatting of data will always be enabled. For example Django will display numbers and dates using the format of the current locale. USE_THOUSAND_SEPARATOR Default: False A boolean that specifies whether to display numbers using a thousand separator. When set to True and USE_L10N is also True, Django will format numbers using the NUMBER_GROUPING and THOUSAND_SEPARATOR settings. These settings may also be dictated by the locale, which takes precedence. See also DECIMAL_SEPARATOR, NUMBER_GROUPING and THOUSAND_SEPARATOR. USE_TZ Default: False Note In Django 5.0, the default value will change from False to True. A boolean that specifies if datetimes will be timezone-aware by default or not. If this is set to True, Django will use timezone-aware datetimes internally. When USE_TZ is False, Django will use naive datetimes in local time, except when parsing ISO 8601 formatted strings, where timezone information will always be retained if present. See also TIME_ZONE, USE_I18N and USE_L10N. Note The default settings.py file created by django-admin startproject includes USE_TZ = True for convenience. USE_X_FORWARDED_HOST Default: False A boolean that specifies whether to use the X-Forwarded-Host header in preference to the Host header. This should only be enabled if a proxy which sets this header is in use. This setting takes priority over USE_X_FORWARDED_PORT. Per RFC 7239#section-5.3, the X-Forwarded-Host header can include the port number, in which case you shouldn’t use USE_X_FORWARDED_PORT. USE_X_FORWARDED_PORT Default: False A boolean that specifies whether to use the X-Forwarded-Port header in preference to the SERVER_PORT META variable. This should only be enabled if a proxy which sets this header is in use. USE_X_FORWARDED_HOST takes priority over this setting. WSGI_APPLICATION Default: None The full Python path of the WSGI application object that Django’s built-in servers (e.g. runserver) will use. The django-admin startproject management command will create a standard wsgi.py file with an application callable in it, and point this setting to that application. If not set, the return value of django.core.wsgi.get_wsgi_application() will be used. In this case, the behavior of runserver will be identical to previous Django versions. YEAR_MONTH_FORMAT Default: 'F Y' The default formatting to use for date fields on Django admin change-list pages – and, possibly, by other parts of the system – in cases when only the year and month are displayed. For example, when a Django admin change-list page is being filtered by a date drilldown, the header for a given month displays the month and the year. Different locales have different formats. For example, U.S. English would say “January 2006,” whereas another locale might say “2006/January.” Note that if USE_L10N is set to True, then the corresponding locale-dictated format has higher precedence and will be applied. See allowed date format strings. See also DATE_FORMAT, DATETIME_FORMAT, TIME_FORMAT and MONTH_DAY_FORMAT. X_FRAME_OPTIONS Default: 'DENY' The default value for the X-Frame-Options header used by XFrameOptionsMiddleware. See the clickjacking protection documentation. Auth Settings for django.contrib.auth. AUTHENTICATION_BACKENDS Default: ['django.contrib.auth.backends.ModelBackend'] A list of authentication backend classes (as strings) to use when attempting to authenticate a user. See the authentication backends documentation for details. AUTH_USER_MODEL Default: 'auth.User' The model to use to represent a User. See Substituting a custom User model. Warning You cannot change the AUTH_USER_MODEL setting during the lifetime of a project (i.e. once you have made and migrated models that depend on it) without serious effort. It is intended to be set at the project start, and the model it refers to must be available in the first migration of the app that it lives in. See Substituting a custom User model for more details. LOGIN_REDIRECT_URL Default: '/accounts/profile/' The URL or named URL pattern where requests are redirected after login when the LoginView doesn’t get a next GET parameter. LOGIN_URL Default: '/accounts/login/' The URL or named URL pattern where requests are redirected for login when using the login_required() decorator, LoginRequiredMixin, or AccessMixin. LOGOUT_REDIRECT_URL Default: None The URL or named URL pattern where requests are redirected after logout if LogoutView doesn’t have a next_page attribute. If None, no redirect will be performed and the logout view will be rendered. PASSWORD_RESET_TIMEOUT Default: 259200 (3 days, in seconds) The number of seconds a password reset link is valid for. Used by the PasswordResetConfirmView. Note Reducing the value of this timeout doesn’t make any difference to the ability of an attacker to brute-force a password reset token. Tokens are designed to be safe from brute-forcing without any timeout. This timeout exists to protect against some unlikely attack scenarios, such as someone gaining access to email archives that may contain old, unused password reset tokens. PASSWORD_HASHERS See How Django stores passwords. Default: [ 'django.contrib.auth.hashers.PBKDF2PasswordHasher', 'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher', 'django.contrib.auth.hashers.Argon2PasswordHasher', 'django.contrib.auth.hashers.BCryptSHA256PasswordHasher', ] AUTH_PASSWORD_VALIDATORS Default: [] (Empty list) The list of validators that are used to check the strength of user’s passwords. See Password validation for more details. By default, no validation is performed and all passwords are accepted. Messages Settings for django.contrib.messages. MESSAGE_LEVEL Default: messages.INFO Sets the minimum message level that will be recorded by the messages framework. See message levels for more details. Important If you override MESSAGE_LEVEL in your settings file and rely on any of the built-in constants, you must import the constants module directly to avoid the potential for circular imports, e.g.: from django.contrib.messages import constants as message_constants MESSAGE_LEVEL = message_constants.DEBUG If desired, you may specify the numeric values for the constants directly according to the values in the above constants table. MESSAGE_STORAGE Default: 'django.contrib.messages.storage.fallback.FallbackStorage' Controls where Django stores message data. Valid values are: 'django.contrib.messages.storage.fallback.FallbackStorage' 'django.contrib.messages.storage.session.SessionStorage' 'django.contrib.messages.storage.cookie.CookieStorage' See message storage backends for more details. The backends that use cookies – CookieStorage and FallbackStorage – use the value of SESSION_COOKIE_DOMAIN, SESSION_COOKIE_SECURE and SESSION_COOKIE_HTTPONLY when setting their cookies. MESSAGE_TAGS Default: { messages.DEBUG: 'debug', messages.INFO: 'info', messages.SUCCESS: 'success', messages.WARNING: 'warning', messages.ERROR: 'error', } This sets the mapping of message level to message tag, which is typically rendered as a CSS class in HTML. If you specify a value, it will extend the default. This means you only have to specify those values which you need to override. See Displaying messages above for more details. Important If you override MESSAGE_TAGS in your settings file and rely on any of the built-in constants, you must import the constants module directly to avoid the potential for circular imports, e.g.: from django.contrib.messages import constants as message_constants MESSAGE_TAGS = {message_constants.INFO: ''} If desired, you may specify the numeric values for the constants directly according to the values in the above constants table. Sessions Settings for django.contrib.sessions. SESSION_CACHE_ALIAS Default: 'default' If you’re using cache-based session storage, this selects the cache to use. SESSION_COOKIE_AGE Default: 1209600 (2 weeks, in seconds) The age of session cookies, in seconds. SESSION_COOKIE_DOMAIN Default: None The domain to use for session cookies. Set this to a string such as "example.com" for cross-domain cookies, or use None for a standard domain cookie. To use cross-domain cookies with CSRF_USE_SESSIONS, you must include a leading dot (e.g. ".example.com") to accommodate the CSRF middleware’s referer checking. Be cautious when updating this setting on a production site. If you update this setting to enable cross-domain cookies on a site that previously used standard domain cookies, existing user cookies will be set to the old domain. This may result in them being unable to log in as long as these cookies persist. This setting also affects cookies set by django.contrib.messages. SESSION_COOKIE_HTTPONLY Default: True Whether to use HttpOnly flag on the session cookie. If this is set to True, client-side JavaScript will not be able to access the session cookie. HttpOnly is a flag included in a Set-Cookie HTTP response header. It’s part of the RFC 6265#section-4.1.2.6 standard for cookies and can be a useful way to mitigate the risk of a client-side script accessing the protected cookie data. This makes it less trivial for an attacker to escalate a cross-site scripting vulnerability into full hijacking of a user’s session. There aren’t many good reasons for turning this off. Your code shouldn’t read session cookies from JavaScript. SESSION_COOKIE_NAME Default: 'sessionid' The name of the cookie to use for sessions. This can be whatever you want (as long as it’s different from the other cookie names in your application). SESSION_COOKIE_PATH Default: '/' The path set on the session cookie. This should either match the URL path of your Django installation or be parent of that path. This is useful if you have multiple Django instances running under the same hostname. They can use different cookie paths, and each instance will only see its own session cookie. SESSION_COOKIE_SAMESITE Default: 'Lax' The value of the SameSite flag on the session cookie. This flag prevents the cookie from being sent in cross-site requests thus preventing CSRF attacks and making some methods of stealing session cookie impossible. Possible values for the setting are: 'Strict': prevents the cookie from being sent by the browser to the target site in all cross-site browsing context, even when following a regular link. For example, for a GitHub-like website this would mean that if a logged-in user follows a link to a private GitHub project posted on a corporate discussion forum or email, GitHub will not receive the session cookie and the user won’t be able to access the project. A bank website, however, most likely doesn’t want to allow any transactional pages to be linked from external sites so the 'Strict' flag would be appropriate. 'Lax' (default): provides a balance between security and usability for websites that want to maintain user’s logged-in session after the user arrives from an external link. In the GitHub scenario, the session cookie would be allowed when following a regular link from an external website and be blocked in CSRF-prone request methods (e.g. POST). 'None' (string): the session cookie will be sent with all same-site and cross-site requests. False: disables the flag. Note Modern browsers provide a more secure default policy for the SameSite flag and will assume Lax for cookies without an explicit value set. SESSION_COOKIE_SECURE Default: False Whether to use a secure cookie for the session cookie. If this is set to True, the cookie will be marked as “secure”, which means browsers may ensure that the cookie is only sent under an HTTPS connection. Leaving this setting off isn’t a good idea because an attacker could capture an unencrypted session cookie with a packet sniffer and use the cookie to hijack the user’s session. SESSION_ENGINE Default: 'django.contrib.sessions.backends.db' Controls where Django stores session data. Included engines are: 'django.contrib.sessions.backends.db' 'django.contrib.sessions.backends.file' 'django.contrib.sessions.backends.cache' 'django.contrib.sessions.backends.cached_db' 'django.contrib.sessions.backends.signed_cookies' See Configuring the session engine for more details. SESSION_EXPIRE_AT_BROWSER_CLOSE Default: False Whether to expire the session when the user closes their browser. See Browser-length sessions vs. persistent sessions. SESSION_FILE_PATH Default: None If you’re using file-based session storage, this sets the directory in which Django will store session data. When the default value (None) is used, Django will use the standard temporary directory for the system. SESSION_SAVE_EVERY_REQUEST Default: False Whether to save the session data on every request. If this is False (default), then the session data will only be saved if it has been modified – that is, if any of its dictionary values have been assigned or deleted. Empty sessions won’t be created, even if this setting is active. SESSION_SERIALIZER Default: 'django.contrib.sessions.serializers.JSONSerializer' Full import path of a serializer class to use for serializing session data. Included serializers are: 'django.contrib.sessions.serializers.PickleSerializer' 'django.contrib.sessions.serializers.JSONSerializer' See Session serialization for details, including a warning regarding possible remote code execution when using PickleSerializer. Sites Settings for django.contrib.sites. SITE_ID Default: Not defined The ID, as an integer, of the current site in the django_site database table. This is used so that application data can hook into specific sites and a single database can manage content for multiple sites. Static Files Settings for django.contrib.staticfiles. STATIC_ROOT Default: None The absolute path to the directory where collectstatic will collect static files for deployment. Example: "/var/www/example.com/static/" If the staticfiles contrib app is enabled (as in the default project template), the collectstatic management command will collect static files into this directory. See the how-to on managing static files for more details about usage. Warning This should be an initially empty destination directory for collecting your static files from their permanent locations into one directory for ease of deployment; it is not a place to store your static files permanently. You should do that in directories that will be found by staticfiles’s finders, which by default, are 'static/' app sub-directories and any directories you include in STATICFILES_DIRS). STATIC_URL Default: None URL to use when referring to static files located in STATIC_ROOT. Example: "static/" or "http://static.example.com/" If not None, this will be used as the base path for asset definitions (the Media class) and the staticfiles app. It must end in a slash if set to a non-empty value. You may need to configure these files to be served in development and will definitely need to do so in production. Note If STATIC_URL is a relative path, then it will be prefixed by the server-provided value of SCRIPT_NAME (or / if not set). This makes it easier to serve a Django application in a subpath without adding an extra configuration to the settings. STATICFILES_DIRS Default: [] (Empty list) This setting defines the additional locations the staticfiles app will traverse if the FileSystemFinder finder is enabled, e.g. if you use the collectstatic or findstatic management command or use the static file serving view. This should be set to a list of strings that contain full paths to your additional files directory(ies) e.g.: STATICFILES_DIRS = [ "/home/special.polls.com/polls/static", "/home/polls.com/polls/static", "/opt/webfiles/common", ] Note that these paths should use Unix-style forward slashes, even on Windows (e.g. "C:/Users/user/mysite/extra_static_content"). Prefixes (optional) In case you want to refer to files in one of the locations with an additional namespace, you can optionally provide a prefix as (prefix, path) tuples, e.g.: STATICFILES_DIRS = [ # ... ("downloads", "/opt/webfiles/stats"), ] For example, assuming you have STATIC_URL set to 'static/', the collectstatic management command would collect the “stats” files in a 'downloads' subdirectory of STATIC_ROOT. This would allow you to refer to the local file '/opt/webfiles/stats/polls_20101022.tar.gz' with '/static/downloads/polls_20101022.tar.gz' in your templates, e.g.: <a href="{% static 'downloads/polls_20101022.tar.gz' %}"> STATICFILES_STORAGE Default: 'django.contrib.staticfiles.storage.StaticFilesStorage' The file storage engine to use when collecting static files with the collectstatic management command. A ready-to-use instance of the storage backend defined in this setting can be found at django.contrib.staticfiles.storage.staticfiles_storage. For an example, see Serving static files from a cloud service or CDN. STATICFILES_FINDERS Default: [ 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', ] The list of finder backends that know how to find static files in various locations. The default will find files stored in the STATICFILES_DIRS setting (using django.contrib.staticfiles.finders.FileSystemFinder) and in a static subdirectory of each app (using django.contrib.staticfiles.finders.AppDirectoriesFinder). If multiple files with the same name are present, the first file that is found will be used. One finder is disabled by default: django.contrib.staticfiles.finders.DefaultStorageFinder. If added to your STATICFILES_FINDERS setting, it will look for static files in the default file storage as defined by the DEFAULT_FILE_STORAGE setting. Note When using the AppDirectoriesFinder finder, make sure your apps can be found by staticfiles by adding the app to the INSTALLED_APPS setting of your site. Static file finders are currently considered a private interface, and this interface is thus undocumented. Core Settings Topical Index Cache CACHES CACHE_MIDDLEWARE_ALIAS CACHE_MIDDLEWARE_KEY_PREFIX CACHE_MIDDLEWARE_SECONDS Database DATABASES DATABASE_ROUTERS DEFAULT_INDEX_TABLESPACE DEFAULT_TABLESPACE Debugging DEBUG DEBUG_PROPAGATE_EXCEPTIONS Email ADMINS DEFAULT_CHARSET DEFAULT_FROM_EMAIL EMAIL_BACKEND EMAIL_FILE_PATH EMAIL_HOST EMAIL_HOST_PASSWORD EMAIL_HOST_USER EMAIL_PORT EMAIL_SSL_CERTFILE EMAIL_SSL_KEYFILE EMAIL_SUBJECT_PREFIX EMAIL_TIMEOUT EMAIL_USE_LOCALTIME EMAIL_USE_TLS MANAGERS SERVER_EMAIL Error reporting DEFAULT_EXCEPTION_REPORTER DEFAULT_EXCEPTION_REPORTER_FILTER IGNORABLE_404_URLS MANAGERS SILENCED_SYSTEM_CHECKS File uploads DEFAULT_FILE_STORAGE FILE_UPLOAD_HANDLERS FILE_UPLOAD_MAX_MEMORY_SIZE FILE_UPLOAD_PERMISSIONS FILE_UPLOAD_TEMP_DIR MEDIA_ROOT MEDIA_URL Forms FORM_RENDERER Globalization (i18n/l10n) DATE_FORMAT DATE_INPUT_FORMATS DATETIME_FORMAT DATETIME_INPUT_FORMATS DECIMAL_SEPARATOR FIRST_DAY_OF_WEEK FORMAT_MODULE_PATH LANGUAGE_CODE LANGUAGE_COOKIE_AGE LANGUAGE_COOKIE_DOMAIN LANGUAGE_COOKIE_HTTPONLY LANGUAGE_COOKIE_NAME LANGUAGE_COOKIE_PATH LANGUAGE_COOKIE_SAMESITE LANGUAGE_COOKIE_SECURE LANGUAGES LANGUAGES_BIDI LOCALE_PATHS MONTH_DAY_FORMAT NUMBER_GROUPING SHORT_DATE_FORMAT SHORT_DATETIME_FORMAT THOUSAND_SEPARATOR TIME_FORMAT TIME_INPUT_FORMATS TIME_ZONE USE_I18N USE_L10N USE_THOUSAND_SEPARATOR USE_TZ YEAR_MONTH_FORMAT HTTP DATA_UPLOAD_MAX_MEMORY_SIZE DATA_UPLOAD_MAX_NUMBER_FIELDS DEFAULT_CHARSET DISALLOWED_USER_AGENTS FORCE_SCRIPT_NAME INTERNAL_IPS MIDDLEWARE Security SECURE_CONTENT_TYPE_NOSNIFF SECURE_CROSS_ORIGIN_OPENER_POLICY SECURE_HSTS_INCLUDE_SUBDOMAINS SECURE_HSTS_PRELOAD SECURE_HSTS_SECONDS SECURE_PROXY_SSL_HEADER SECURE_REDIRECT_EXEMPT SECURE_REFERRER_POLICY SECURE_SSL_HOST SECURE_SSL_REDIRECT SIGNING_BACKEND USE_X_FORWARDED_HOST USE_X_FORWARDED_PORT WSGI_APPLICATION Logging LOGGING LOGGING_CONFIG Models ABSOLUTE_URL_OVERRIDES FIXTURE_DIRS INSTALLED_APPS Security Cross Site Request Forgery Protection CSRF_COOKIE_DOMAIN CSRF_COOKIE_NAME CSRF_COOKIE_PATH CSRF_COOKIE_SAMESITE CSRF_COOKIE_SECURE CSRF_FAILURE_VIEW CSRF_HEADER_NAME CSRF_TRUSTED_ORIGINS CSRF_USE_SESSIONS SECRET_KEY X_FRAME_OPTIONS Serialization DEFAULT_CHARSET SERIALIZATION_MODULES Templates TEMPLATES Testing Database: TEST TEST_NON_SERIALIZED_APPS TEST_RUNNER URLs APPEND_SLASH PREPEND_WWW ROOT_URLCONF
doc_25768
See Migration guide for more details. tf.compat.v1.raw_ops.TensorListGetItem tf.raw_ops.TensorListGetItem( input_handle, index, element_shape, element_dtype, name=None ) input_handle: the list index: the position in the list from which an element will be retrieved item: the element at that position Args input_handle A Tensor of type variant. index A Tensor of type int32. element_shape A Tensor of type int32. element_dtype A tf.DType. name A name for the operation (optional). Returns A Tensor of type element_dtype.
doc_25769
Returns the object to which to pointer points. Assigning to this attribute changes the pointer to point to the assigned object.
doc_25770
Casts all floating point parameters and buffers to float datatype. Returns self Return type Module
doc_25771
A wrapper to convert a file-like object to an iterator. The resulting objects support both __getitem__() and __iter__() iteration styles, for compatibility with Python 2.1 and Jython. As the object is iterated over, the optional blksize parameter will be repeatedly passed to the filelike object’s read() method to obtain bytestrings to yield. When read() returns an empty bytestring, iteration is ended and is not resumable. If filelike has a close() method, the returned object will also have a close() method, and it will invoke the filelike object’s close() method when called. Example usage: from io import StringIO from wsgiref.util import FileWrapper # We're using a StringIO-buffer for as the file-like object filelike = StringIO("This is an example file-like object"*10) wrapper = FileWrapper(filelike, blksize=5) for chunk in wrapper: print(chunk) Deprecated since version 3.8: Support for sequence protocol is deprecated.
doc_25772
Set the hatching pattern hatch can be one of: / - diagonal hatching \ - back diagonal | - vertical - - horizontal + - crossed x - crossed diagonal o - small circle O - large circle . - dots * - stars Letters can be combined, in which case all the specified hatchings are done. If same letter repeats, it increases the density of hatching of that pattern. Hatching is supported in the PostScript, PDF, SVG and Agg backends only. Unlike other properties such as linewidth and colors, hatching can only be specified for the collection as a whole, not separately for each member. Parameters hatch{'/', '\', '|', '-', '+', 'x', 'o', 'O', '.', '*'}
doc_25773
Bernoulli Restricted Boltzmann Machine (RBM). A Restricted Boltzmann Machine with binary visible units and binary hidden units. Parameters are estimated using Stochastic Maximum Likelihood (SML), also known as Persistent Contrastive Divergence (PCD) [2]. The time complexity of this implementation is O(d ** 2) assuming d ~ n_features ~ n_components. Read more in the User Guide. Parameters n_componentsint, default=256 Number of binary hidden units. learning_ratefloat, default=0.1 The learning rate for weight updates. It is highly recommended to tune this hyper-parameter. Reasonable values are in the 10**[0., -3.] range. batch_sizeint, default=10 Number of examples per minibatch. n_iterint, default=10 Number of iterations/sweeps over the training dataset to perform during training. verboseint, default=0 The verbosity level. The default, zero, means silent mode. random_stateint, RandomState instance or None, default=None Determines random number generation for: Gibbs sampling from visible and hidden layers. Initializing components, sampling from layers during fit. Corrupting the data when scoring samples. Pass an int for reproducible results across multiple function calls. See Glossary. Attributes intercept_hidden_array-like of shape (n_components,) Biases of the hidden units. intercept_visible_array-like of shape (n_features,) Biases of the visible units. components_array-like of shape (n_components, n_features) Weight matrix, where n_features in the number of visible units and n_components is the number of hidden units. h_samples_array-like of shape (batch_size, n_components) Hidden Activation sampled from the model distribution, where batch_size in the number of examples per minibatch and n_components is the number of hidden units. References [1] Hinton, G. E., Osindero, S. and Teh, Y. A fast learning algorithm for deep belief nets. Neural Computation 18, pp 1527-1554. https://www.cs.toronto.edu/~hinton/absps/fastnc.pdf [2] Tieleman, T. Training Restricted Boltzmann Machines using Approximations to the Likelihood Gradient. International Conference on Machine Learning (ICML) 2008 Examples >>> import numpy as np >>> from sklearn.neural_network import BernoulliRBM >>> X = np.array([[0, 0, 0], [0, 1, 1], [1, 0, 1], [1, 1, 1]]) >>> model = BernoulliRBM(n_components=2) >>> model.fit(X) BernoulliRBM(n_components=2) Methods fit(X[, y]) Fit the model to the data X. fit_transform(X[, y]) Fit to data, then transform it. get_params([deep]) Get parameters for this estimator. gibbs(v) Perform one Gibbs sampling step. partial_fit(X[, y]) Fit the model to the data X which should contain a partial segment of the data. score_samples(X) Compute the pseudo-likelihood of X. set_params(**params) Set the parameters of this estimator. transform(X) Compute the hidden layer activation probabilities, P(h=1|v=X). fit(X, y=None) [source] Fit the model to the data X. Parameters X{array-like, sparse matrix} of shape (n_samples, n_features) Training data. Returns selfBernoulliRBM The fitted model. 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. gibbs(v) [source] Perform one Gibbs sampling step. Parameters vndarray of shape (n_samples, n_features) Values of the visible layer to start from. Returns v_newndarray of shape (n_samples, n_features) Values of the visible layer after one Gibbs step. partial_fit(X, y=None) [source] Fit the model to the data X which should contain a partial segment of the data. Parameters Xndarray of shape (n_samples, n_features) Training data. Returns selfBernoulliRBM The fitted model. score_samples(X) [source] Compute the pseudo-likelihood of X. Parameters X{array-like, sparse matrix} of shape (n_samples, n_features) Values of the visible layer. Must be all-boolean (not checked). Returns pseudo_likelihoodndarray of shape (n_samples,) Value of the pseudo-likelihood (proxy for likelihood). Notes This method is not deterministic: it computes a quantity called the free energy on X, then on a randomly corrupted version of X, and returns the log of the logistic function of the difference. 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] Compute the hidden layer activation probabilities, P(h=1|v=X). Parameters X{array-like, sparse matrix} of shape (n_samples, n_features) The data to be transformed. Returns hndarray of shape (n_samples, n_components) Latent representations of the data.
doc_25774
See Migration guide for more details. tf.compat.v1.required_space_to_batch_paddings tf.required_space_to_batch_paddings( input_shape, block_shape, base_paddings=None, name=None ) This function can be used to calculate a suitable paddings argument for use with space_to_batch_nd and batch_to_space_nd. Args input_shape int32 Tensor of shape [N]. block_shape int32 Tensor of shape [N]. base_paddings Optional int32 Tensor of shape [N, 2]. Specifies the minimum amount of padding to use. All elements must be >= 0. If not specified, defaults to 0. name string. Optional name prefix. Returns (paddings, crops), where: paddings and crops are int32 Tensors of rank 2 and shape [N, 2] satisfying paddings[i, 0] = base_paddings[i, 0]. 0 <= paddings[i, 1] - base_paddings[i, 1] < block_shapei % block_shape[i] == 0 crops[i, 0] = 0 crops[i, 1] = paddings[i, 1] - base_paddings[i, 1] Raises: ValueError if called with incompatible shapes.
doc_25775
Default widget: CheckboxInput Empty value: False Normalizes to: A Python True or False value. Validates that the value is True (e.g. the check box is checked) if the field has required=True. Error message keys: required Note Since all Field subclasses have required=True by default, the validation condition here is important. If you want to include a boolean in your form that can be either True or False (e.g. a checked or unchecked checkbox), you must remember to pass in required=False when creating the BooleanField.
doc_25776
Set the name of the Task. The value argument can be any object, which is then converted to a string. In the default Task implementation, the name will be visible in the repr() output of a task object. New in version 3.8.
doc_25777
time_raised = models.DateTimeField(default=timezone.now, editable=False) reference = models.CharField(unique=True, max_length=20) description = models.TextField() Here's a basic ModelSerializer that we can use for creating or updating instances of CustomerReportRecord: class CustomerReportSerializer(serializers.ModelSerializer): class Meta: model = CustomerReportRecord If we open up the Django shell using manage.py shell we can now >>> from project.example.serializers import CustomerReportSerializer >>> serializer = CustomerReportSerializer() >>> print(repr(serializer)) CustomerReportSerializer(): id = IntegerField(label='ID', read_only=True) time_raised = DateTimeField(read_only=True) reference = CharField(max_length=20, validators=[<UniqueValidator(queryset=CustomerReportRecord.objects.all())>]) description = CharField(style={'type': 'textarea'}) The interesting bit here is the reference field. We can see that the uniqueness constraint is being explicitly enforced by a validator on the serializer field. Because of this more explicit style REST framework includes a few validator classes that are not available in core Django. These classes are detailed below. UniqueValidator This validator can be used to enforce the unique=True constraint on model fields. It takes a single required argument, and an optional messages argument: queryset required - This is the queryset against which uniqueness should be enforced. message - The error message that should be used when validation fails. lookup - The lookup used to find an existing instance with the value being validated. Defaults to 'exact'. This validator should be applied to serializer fields, like so: from rest_framework.validators import UniqueValidator slug = SlugField( max_length=100, validators=[UniqueValidator(queryset=BlogPost.objects.all())] ) UniqueTogetherValidator This validator can be used to enforce unique_together constraints on model instances. It has two required arguments, and a single optional messages argument: queryset required - This is the queryset against which uniqueness should be enforced. fields required - A list or tuple of field names which should make a unique set. These must exist as fields on the serializer class. message - The error message that should be used when validation fails. The validator should be applied to serializer classes, like so: from rest_framework.validators import UniqueTogetherValidator class ExampleSerializer(serializers.Serializer): # ... class Meta: # ToDo items belong to a parent list, and have an ordering defined # by the 'position' field. No two items in a given list may share # the same position. validators = [ UniqueTogetherValidator( queryset=ToDoItem.objects.all(), fields=['list', 'position'] ) ] Note: The UniqueTogetherValidator class always imposes an implicit constraint that all the fields it applies to are always treated as required. Fields with default values are an exception to this as they always supply a value even when omitted from user input. UniqueForDateValidator UniqueForMonthValidator UniqueForYearValidator These validators can be used to enforce the unique_for_date, unique_for_month and unique_for_year constraints on model instances. They take the following arguments: queryset required - This is the queryset against which uniqueness should be enforced. field required - A field name against which uniqueness in the given date range will be validated. This must exist as a field on the serializer class. date_field required - A field name which will be used to determine date range for the uniqueness constrain. This must exist as a field on the serializer class. message - The error message that should be used when validation fails. The validator should be applied to serializer classes, like so: from rest_framework.validators import UniqueForYearValidator class ExampleSerializer(serializers.Serializer): # ... class Meta: # Blog posts should have a slug that is unique for the current year. validators = [ UniqueForYearValidator( queryset=BlogPostItem.objects.all(), field='slug', date_field='published' ) ] The date field that is used for the validation is always required to be present on the serializer class. You can't simply rely on a model class default=..., because the value being used for the default wouldn't be generated until after the validation has run. There are a couple of styles you may want to use for this depending on how you want your API to behave. If you're using ModelSerializer you'll probably simply rely on the defaults that REST framework generates for you, but if you are using Serializer or simply want more explicit control, use on of the styles demonstrated below. Using with a writable date field. If you want the date field to be writable the only thing worth noting is that you should ensure that it is always available in the input data, either by setting a default argument, or by setting required=True. published = serializers.DateTimeField(required=True) Using with a read-only date field. If you want the date field to be visible, but not editable by the user, then set read_only=True and additionally set a default=... argument. published = serializers.DateTimeField(read_only=True, default=timezone.now) Using with a hidden date field. If you want the date field to be entirely hidden from the user, then use HiddenField. This field type does not accept user input, but instead always returns its default value to the validated_data in the serializer. published = serializers.HiddenField(default=timezone.now) Note: The UniqueFor<Range>Validator classes impose an implicit constraint that the fields they are applied to are always treated as required. Fields with default values are an exception to this as they always supply a value even when omitted from user input. Advanced field defaults Validators that are applied across multiple fields in the serializer can sometimes require a field input that should not be provided by the API client, but that is available as input to the validator. Two patterns that you may want to use for this sort of validation include: Using HiddenField. This field will be present in validated_data but will not be used in the serializer output representation. Using a standard field with read_only=True, but that also includes a default=… argument. This field will be used in the serializer output representation, but cannot be set directly by the user. REST framework includes a couple of defaults that may be useful in this context. CurrentUserDefault A default class that can be used to represent the current user. In order to use this, the 'request' must have been provided as part of the context dictionary when instantiating the serializer. owner = serializers.HiddenField( default=serializers.CurrentUserDefault() ) CreateOnlyDefault A default class that can be used to only set a default argument during create operations. During updates the field is omitted. It takes a single argument, which is the default value or callable that should be used during create operations. created_at = serializers.DateTimeField( default=serializers.CreateOnlyDefault(timezone.now) ) Limitations of validators There are some ambiguous cases where you'll need to instead handle validation explicitly, rather than relying on the default serializer classes that ModelSerializer generates. In these cases you may want to disable the automatically generated validators, by specifying an empty list for the serializer Meta.validators attribute. Optional fields By default "unique together" validation enforces that all fields be required=True. In some cases, you might want to explicit apply required=False to one of the fields, in which case the desired behaviour of the validation is ambiguous. In this case you will typically need to exclude the validator from the serializer class, and instead write any validation logic explicitly, either in the .validate() method, or else in the view. For example: class BillingRecordSerializer(serializers.ModelSerializer): def validate(self, attrs): # Apply custom validation either here, or in the view. class Meta: fields = ['client', 'date', 'amount'] extra_kwargs = {'client': {'required': False}} validators = [] # Remove a default "unique together" constraint. Updating nested serializers When applying an update to an existing instance, uniqueness validators will exclude the current instance from the uniqueness check. The current instance is available in the context of the uniqueness check, because it exists as an attribute on the serializer, having initially been passed using instance=... when instantiating the serializer. In the case of update operations on nested serializers there's no way of applying this exclusion, because the instance is not available. Again, you'll probably want to explicitly remove the validator from the serializer class, and write the code for the validation constraint explicitly, in a .validate() method, or in the view. Debugging complex cases If you're not sure exactly what behavior a ModelSerializer class will generate it is usually a good idea to run manage.py shell, and print an instance of the serializer, so that you can inspect the fields and validators that it automatically generates for you. >>> serializer = MyComplexModelSerializer() >>> print(serializer) class MyComplexModelSerializer: my_fields = ... Also keep in mind that with complex cases it can often be better to explicitly define your serializer classes, rather than relying on the default ModelSerializer behavior. This involves a little more code, but ensures that the resulting behavior is more transparent. Writing custom validators You can use any of Django's existing validators, or write your own custom validators. Function based A validator may be any callable that raises a serializers.ValidationError on failure. def even_number(value): if value % 2 != 0: raise serializers.ValidationError('This field must be an even number.') Field-level validation You can specify custom field-level validation by adding .validate_<field_name> methods to your Serializer subclass. This is documented in the Serializer docs Class-based To write a class-based validator, use the __call__ method. Class-based validators are useful as they allow you to parameterize and reuse behavior. class MultipleOf: def __init__(self, base): self.base = base def __call__(self, value): if value % self.base != 0: message = 'This field must be a multiple of %d.' % self.base raise serializers.ValidationError(message) Accessing the context In some advanced cases you might want a validator to be passed the serializer field it is being used with as additional context. You can do so by setting a requires_context = True attribute on the validator. The __call__ method will then be called with the serializer_field or serializer as an additional argument. requires_context = True def __call__(self, value, serializer_field): ... validators.py
doc_25778
The original header value.
doc_25779
Print the output of bpformat() to the file out, or if it is None, to standard output.
doc_25780
get the current error message get_error() -> errorstr SDL maintains an internal error message. This message will usually be given to you when pygame.error() is raised, so this function will rarely be needed.
doc_25781
Indexes of the maximum values along an axis. Return the indexes of the first occurrences of the maximum values along the specified axis. If axis is None, the index is for the flattened matrix. Parameters See `numpy.argmax` for complete descriptions See also numpy.argmax Notes This is the same as ndarray.argmax, but returns a matrix object where ndarray.argmax would return an ndarray. Examples >>> x = np.matrix(np.arange(12).reshape((3,4))); x matrix([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11]]) >>> x.argmax() 11 >>> x.argmax(0) matrix([[2, 2, 2, 2]]) >>> x.argmax(1) matrix([[3], [3], [3]])
doc_25782
tf.compat.v1.nn.rnn_cell.LSTMCell( num_units, use_peepholes=False, cell_clip=None, initializer=None, num_proj=None, proj_clip=None, num_unit_shards=None, num_proj_shards=None, forget_bias=1.0, state_is_tuple=True, activation=None, reuse=None, name=None, dtype=None, **kwargs ) The default non-peephole implementation is based on (Gers et al., 1999). The peephole implementation is based on (Sak et al., 2014). The class uses optional peep-hole connections, optional cell clipping, and an optional projection layer. Note that this cell is not optimized for performance. Please use tf.contrib.cudnn_rnn.CudnnLSTM for better performance on GPU, or tf.contrib.rnn.LSTMBlockCell and tf.contrib.rnn.LSTMBlockFusedCell for better performance on CPU. References: Long short-term memory recurrent neural network architectures for large scale acoustic modeling: Sak et al., 2014 (pdf) Learning to forget: Gers et al., 1999 (pdf) Long Short-Term Memory: Hochreiter et al., 1997 (pdf) Args num_units int, The number of units in the LSTM cell. use_peepholes bool, set True to enable diagonal/peephole connections. cell_clip (optional) A float value, if provided the cell state is clipped by this value prior to the cell output activation. initializer (optional) The initializer to use for the weight and projection matrices. num_proj (optional) int, The output dimensionality for the projection matrices. If None, no projection is performed. proj_clip (optional) A float value. If num_proj > 0 and proj_clip is provided, then the projected values are clipped elementwise to within [-proj_clip, proj_clip]. num_unit_shards Deprecated, will be removed by Jan. 2017. Use a variable_scope partitioner instead. num_proj_shards Deprecated, will be removed by Jan. 2017. Use a variable_scope partitioner instead. forget_bias Biases of the forget gate are initialized by default to 1 in order to reduce the scale of forgetting at the beginning of the training. Must set it manually to 0.0 when restoring from CudnnLSTM trained checkpoints. state_is_tuple If True, accepted and returned states are 2-tuples of the c_state and m_state. If False, they are concatenated along the column axis. This latter behavior will soon be deprecated. activation Activation function of the inner states. Default: tanh. It could also be string that is within Keras activation function names. reuse (optional) Python boolean describing whether to reuse variables in an existing scope. If not True, and the existing scope already has the given variables, an error is raised. name String, the name of the layer. Layers with the same name will share weights, but to avoid mistakes we require reuse=True in such cases. dtype Default dtype of the layer (default of None means use the type of the first input). Required when build is called before call. **kwargs Dict, keyword named properties for common layer attributes, like trainable etc when constructing the cell from configs of get_config(). When restoring from CudnnLSTM-trained checkpoints, use CudnnCompatibleLSTMCell instead. Attributes graph output_size Integer or TensorShape: size of outputs produced by this cell. scope_name state_size size(s) of state(s) used by this cell. It can be represented by an Integer, a TensorShape or a tuple of Integers or TensorShapes. Methods get_initial_state View source get_initial_state( inputs=None, batch_size=None, dtype=None ) zero_state View source zero_state( batch_size, dtype ) Return zero-filled state tensor(s). Args batch_size int, float, or unit Tensor representing the batch size. dtype the data type to use for the state. Returns If state_size is an int or TensorShape, then the return value is a N-D tensor of shape [batch_size, state_size] filled with zeros. If state_size is a nested list or tuple, then the return value is a nested list or tuple (of the same structure) of 2-D tensors with the shapes [batch_size, s] for each s in state_size.
doc_25783
assertNotIn(member, container, msg=None) Test that member is (or is not) in container. New in version 3.1.
doc_25784
Default widget: NullBooleanSelect Empty value: None Normalizes to: A Python True, False or None value. Validates nothing (i.e., it never raises a ValidationError). NullBooleanField may be used with widgets such as Select or RadioSelect by providing the widget choices: NullBooleanField( widget=Select( choices=[ ('', 'Unknown'), (True, 'Yes'), (False, 'No'), ] ) )
doc_25785
Instances of the TestCase class represent the logical test units in the unittest universe. This class is intended to be used as a base class, with specific tests being implemented by concrete subclasses. This class implements the interface needed by the test runner to allow it to drive the tests, and methods that the test code can use to check for and report various kinds of failure. Each instance of TestCase will run a single base method: the method named methodName. In most uses of TestCase, you will neither change the methodName nor reimplement the default runTest() method. Changed in version 3.2: TestCase can be instantiated successfully without providing a methodName. This makes it easier to experiment with TestCase from the interactive interpreter. TestCase instances provide three groups of methods: one group used to run the test, another used by the test implementation to check conditions and report failures, and some inquiry methods allowing information about the test itself to be gathered. Methods in the first group (running the test) are: setUp() Method called to prepare the test fixture. This is called immediately before calling the test method; other than AssertionError or SkipTest, any exception raised by this method will be considered an error rather than a test failure. The default implementation does nothing. tearDown() Method called immediately after the test method has been called and the result recorded. This is called even if the test method raised an exception, so the implementation in subclasses may need to be particularly careful about checking internal state. Any exception, other than AssertionError or SkipTest, raised by this method will be considered an additional error rather than a test failure (thus increasing the total number of reported errors). This method will only be called if the setUp() succeeds, regardless of the outcome of the test method. The default implementation does nothing. setUpClass() A class method called before tests in an individual class are run. setUpClass is called with the class as the only argument and must be decorated as a classmethod(): @classmethod def setUpClass(cls): ... See Class and Module Fixtures for more details. New in version 3.2. tearDownClass() A class method called after tests in an individual class have run. tearDownClass is called with the class as the only argument and must be decorated as a classmethod(): @classmethod def tearDownClass(cls): ... See Class and Module Fixtures for more details. New in version 3.2. run(result=None) Run the test, collecting the result into the TestResult object passed as result. If result is omitted or None, a temporary result object is created (by calling the defaultTestResult() method) and used. The result object is returned to run()’s caller. The same effect may be had by simply calling the TestCase instance. Changed in version 3.3: Previous versions of run did not return the result. Neither did calling an instance. skipTest(reason) Calling this during a test method or setUp() skips the current test. See Skipping tests and expected failures for more information. New in version 3.1. subTest(msg=None, **params) Return a context manager which executes the enclosed code block as a subtest. msg and params are optional, arbitrary values which are displayed whenever a subtest fails, allowing you to identify them clearly. A test case can contain any number of subtest declarations, and they can be arbitrarily nested. See Distinguishing test iterations using subtests for more information. New in version 3.4. debug() Run the test without collecting the result. This allows exceptions raised by the test to be propagated to the caller, and can be used to support running tests under a debugger. The TestCase class provides several assert methods to check for and report failures. The following table lists the most commonly used methods (see the tables below for more assert methods): Method Checks that New in assertEqual(a, b) a == b assertNotEqual(a, b) a != b assertTrue(x) bool(x) is True assertFalse(x) bool(x) is False assertIs(a, b) a is b 3.1 assertIsNot(a, b) a is not b 3.1 assertIsNone(x) x is None 3.1 assertIsNotNone(x) x is not None 3.1 assertIn(a, b) a in b 3.1 assertNotIn(a, b) a not in b 3.1 assertIsInstance(a, b) isinstance(a, b) 3.2 assertNotIsInstance(a, b) not isinstance(a, b) 3.2 All the assert methods accept a msg argument that, if specified, is used as the error message on failure (see also longMessage). Note that the msg keyword argument can be passed to assertRaises(), assertRaisesRegex(), assertWarns(), assertWarnsRegex() only when they are used as a context manager. assertEqual(first, second, msg=None) Test that first and second are equal. If the values do not compare equal, the test will fail. In addition, if first and second are the exact same type and one of list, tuple, dict, set, frozenset or str or any type that a subclass registers with addTypeEqualityFunc() the type-specific equality function will be called in order to generate a more useful default error message (see also the list of type-specific methods). Changed in version 3.1: Added the automatic calling of type-specific equality function. Changed in version 3.2: assertMultiLineEqual() added as the default type equality function for comparing strings. assertNotEqual(first, second, msg=None) Test that first and second are not equal. If the values do compare equal, the test will fail. assertTrue(expr, msg=None) assertFalse(expr, msg=None) Test that expr is true (or false). Note that this is equivalent to bool(expr) is True and not to expr is True (use assertIs(expr, True) for the latter). This method should also be avoided when more specific methods are available (e.g. assertEqual(a, b) instead of assertTrue(a == b)), because they provide a better error message in case of failure. assertIs(first, second, msg=None) assertIsNot(first, second, msg=None) Test that first and second are (or are not) the same object. New in version 3.1. assertIsNone(expr, msg=None) assertIsNotNone(expr, msg=None) Test that expr is (or is not) None. New in version 3.1. assertIn(member, container, msg=None) assertNotIn(member, container, msg=None) Test that member is (or is not) in container. New in version 3.1. assertIsInstance(obj, cls, msg=None) assertNotIsInstance(obj, cls, msg=None) Test that obj is (or is not) an instance of cls (which can be a class or a tuple of classes, as supported by isinstance()). To check for the exact type, use assertIs(type(obj), cls). New in version 3.2. It is also possible to check the production of exceptions, warnings, and log messages using the following methods: Method Checks that New in assertRaises(exc, fun, *args, **kwds) fun(*args, **kwds) raises exc assertRaisesRegex(exc, r, fun, *args, **kwds) fun(*args, **kwds) raises exc and the message matches regex r 3.1 assertWarns(warn, fun, *args, **kwds) fun(*args, **kwds) raises warn 3.2 assertWarnsRegex(warn, r, fun, *args, **kwds) fun(*args, **kwds) raises warn and the message matches regex r 3.2 assertLogs(logger, level) The with block logs on logger with minimum level 3.4 assertRaises(exception, callable, *args, **kwds) assertRaises(exception, *, msg=None) Test that an exception is raised when callable is called with any positional or keyword arguments that are also passed to assertRaises(). The test passes if exception is raised, is an error if another exception is raised, or fails if no exception is raised. To catch any of a group of exceptions, a tuple containing the exception classes may be passed as exception. If only the exception and possibly the msg arguments are given, return a context manager so that the code under test can be written inline rather than as a function: with self.assertRaises(SomeException): do_something() When used as a context manager, assertRaises() accepts the additional keyword argument msg. The context manager will store the caught exception object in its exception attribute. This can be useful if the intention is to perform additional checks on the exception raised: with self.assertRaises(SomeException) as cm: do_something() the_exception = cm.exception self.assertEqual(the_exception.error_code, 3) Changed in version 3.1: Added the ability to use assertRaises() as a context manager. Changed in version 3.2: Added the exception attribute. Changed in version 3.3: Added the msg keyword argument when used as a context manager. assertRaisesRegex(exception, regex, callable, *args, **kwds) assertRaisesRegex(exception, regex, *, msg=None) Like assertRaises() but also tests that regex matches on the string representation of the raised exception. regex may be a regular expression object or a string containing a regular expression suitable for use by re.search(). Examples: self.assertRaisesRegex(ValueError, "invalid literal for.*XYZ'$", int, 'XYZ') or: with self.assertRaisesRegex(ValueError, 'literal'): int('XYZ') New in version 3.1: Added under the name assertRaisesRegexp. Changed in version 3.2: Renamed to assertRaisesRegex(). Changed in version 3.3: Added the msg keyword argument when used as a context manager. assertWarns(warning, callable, *args, **kwds) assertWarns(warning, *, msg=None) Test that a warning is triggered when callable is called with any positional or keyword arguments that are also passed to assertWarns(). The test passes if warning is triggered and fails if it isn’t. Any exception is an error. To catch any of a group of warnings, a tuple containing the warning classes may be passed as warnings. If only the warning and possibly the msg arguments are given, return a context manager so that the code under test can be written inline rather than as a function: with self.assertWarns(SomeWarning): do_something() When used as a context manager, assertWarns() accepts the additional keyword argument msg. The context manager will store the caught warning object in its warning attribute, and the source line which triggered the warnings in the filename and lineno attributes. This can be useful if the intention is to perform additional checks on the warning caught: with self.assertWarns(SomeWarning) as cm: do_something() self.assertIn('myfile.py', cm.filename) self.assertEqual(320, cm.lineno) This method works regardless of the warning filters in place when it is called. New in version 3.2. Changed in version 3.3: Added the msg keyword argument when used as a context manager. assertWarnsRegex(warning, regex, callable, *args, **kwds) assertWarnsRegex(warning, regex, *, msg=None) Like assertWarns() but also tests that regex matches on the message of the triggered warning. regex may be a regular expression object or a string containing a regular expression suitable for use by re.search(). Example: self.assertWarnsRegex(DeprecationWarning, r'legacy_function\(\) is deprecated', legacy_function, 'XYZ') or: with self.assertWarnsRegex(RuntimeWarning, 'unsafe frobnicating'): frobnicate('/etc/passwd') New in version 3.2. Changed in version 3.3: Added the msg keyword argument when used as a context manager. assertLogs(logger=None, level=None) A context manager to test that at least one message is logged on the logger or one of its children, with at least the given level. If given, logger should be a logging.Logger object or a str giving the name of a logger. The default is the root logger, which will catch all messages that were not blocked by a non-propagating descendent logger. If given, level should be either a numeric logging level or its string equivalent (for example either "ERROR" or logging.ERROR). The default is logging.INFO. The test passes if at least one message emitted inside the with block matches the logger and level conditions, otherwise it fails. The object returned by the context manager is a recording helper which keeps tracks of the matching log messages. It has two attributes: records A list of logging.LogRecord objects of the matching log messages. output A list of str objects with the formatted output of matching messages. Example: with self.assertLogs('foo', level='INFO') as cm: logging.getLogger('foo').info('first message') logging.getLogger('foo.bar').error('second message') self.assertEqual(cm.output, ['INFO:foo:first message', 'ERROR:foo.bar:second message']) New in version 3.4. There are also other methods used to perform more specific checks, such as: Method Checks that New in assertAlmostEqual(a, b) round(a-b, 7) == 0 assertNotAlmostEqual(a, b) round(a-b, 7) != 0 assertGreater(a, b) a > b 3.1 assertGreaterEqual(a, b) a >= b 3.1 assertLess(a, b) a < b 3.1 assertLessEqual(a, b) a <= b 3.1 assertRegex(s, r) r.search(s) 3.1 assertNotRegex(s, r) not r.search(s) 3.2 assertCountEqual(a, b) a and b have the same elements in the same number, regardless of their order. 3.2 assertAlmostEqual(first, second, places=7, msg=None, delta=None) assertNotAlmostEqual(first, second, places=7, msg=None, delta=None) Test that first and second are approximately (or not approximately) equal by computing the difference, rounding to the given number of decimal places (default 7), and comparing to zero. Note that these methods round the values to the given number of decimal places (i.e. like the round() function) and not significant digits. If delta is supplied instead of places then the difference between first and second must be less or equal to (or greater than) delta. Supplying both delta and places raises a TypeError. Changed in version 3.2: assertAlmostEqual() automatically considers almost equal objects that compare equal. assertNotAlmostEqual() automatically fails if the objects compare equal. Added the delta keyword argument. assertGreater(first, second, msg=None) assertGreaterEqual(first, second, msg=None) assertLess(first, second, msg=None) assertLessEqual(first, second, msg=None) Test that first is respectively >, >=, < or <= than second depending on the method name. If not, the test will fail: >>> self.assertGreaterEqual(3, 4) AssertionError: "3" unexpectedly not greater than or equal to "4" New in version 3.1. assertRegex(text, regex, msg=None) assertNotRegex(text, regex, msg=None) Test that a regex search matches (or does not match) text. In case of failure, the error message will include the pattern and the text (or the pattern and the part of text that unexpectedly matched). regex may be a regular expression object or a string containing a regular expression suitable for use by re.search(). New in version 3.1: Added under the name assertRegexpMatches. Changed in version 3.2: The method assertRegexpMatches() has been renamed to assertRegex(). New in version 3.2: assertNotRegex(). New in version 3.5: The name assertNotRegexpMatches is a deprecated alias for assertNotRegex(). assertCountEqual(first, second, msg=None) Test that sequence first contains the same elements as second, regardless of their order. When they don’t, an error message listing the differences between the sequences will be generated. Duplicate elements are not ignored when comparing first and second. It verifies whether each element has the same count in both sequences. Equivalent to: assertEqual(Counter(list(first)), Counter(list(second))) but works with sequences of unhashable objects as well. New in version 3.2. The assertEqual() method dispatches the equality check for objects of the same type to different type-specific methods. These methods are already implemented for most of the built-in types, but it’s also possible to register new methods using addTypeEqualityFunc(): addTypeEqualityFunc(typeobj, function) Registers a type-specific method called by assertEqual() to check if two objects of exactly the same typeobj (not subclasses) compare equal. function must take two positional arguments and a third msg=None keyword argument just as assertEqual() does. It must raise self.failureException(msg) when inequality between the first two parameters is detected – possibly providing useful information and explaining the inequalities in details in the error message. New in version 3.1. The list of type-specific methods automatically used by assertEqual() are summarized in the following table. Note that it’s usually not necessary to invoke these methods directly. Method Used to compare New in assertMultiLineEqual(a, b) strings 3.1 assertSequenceEqual(a, b) sequences 3.1 assertListEqual(a, b) lists 3.1 assertTupleEqual(a, b) tuples 3.1 assertSetEqual(a, b) sets or frozensets 3.1 assertDictEqual(a, b) dicts 3.1 assertMultiLineEqual(first, second, msg=None) Test that the multiline string first is equal to the string second. When not equal a diff of the two strings highlighting the differences will be included in the error message. This method is used by default when comparing strings with assertEqual(). New in version 3.1. assertSequenceEqual(first, second, msg=None, seq_type=None) Tests that two sequences are equal. If a seq_type is supplied, both first and second must be instances of seq_type or a failure will be raised. If the sequences are different an error message is constructed that shows the difference between the two. This method is not called directly by assertEqual(), but it’s used to implement assertListEqual() and assertTupleEqual(). New in version 3.1. assertListEqual(first, second, msg=None) assertTupleEqual(first, second, msg=None) Tests that two lists or tuples are equal. If not, an error message is constructed that shows only the differences between the two. An error is also raised if either of the parameters are of the wrong type. These methods are used by default when comparing lists or tuples with assertEqual(). New in version 3.1. assertSetEqual(first, second, msg=None) Tests that two sets are equal. If not, an error message is constructed that lists the differences between the sets. This method is used by default when comparing sets or frozensets with assertEqual(). Fails if either of first or second does not have a set.difference() method. New in version 3.1. assertDictEqual(first, second, msg=None) Test that two dictionaries are equal. If not, an error message is constructed that shows the differences in the dictionaries. This method will be used by default to compare dictionaries in calls to assertEqual(). New in version 3.1. Finally the TestCase provides the following methods and attributes: fail(msg=None) Signals a test failure unconditionally, with msg or None for the error message. failureException This class attribute gives the exception raised by the test method. If a test framework needs to use a specialized exception, possibly to carry additional information, it must subclass this exception in order to “play fair” with the framework. The initial value of this attribute is AssertionError. longMessage This class attribute determines what happens when a custom failure message is passed as the msg argument to an assertXYY call that fails. True is the default value. In this case, the custom message is appended to the end of the standard failure message. When set to False, the custom message replaces the standard message. The class setting can be overridden in individual test methods by assigning an instance attribute, self.longMessage, to True or False before calling the assert methods. The class setting gets reset before each test call. New in version 3.1. maxDiff This attribute controls the maximum length of diffs output by assert methods that report diffs on failure. It defaults to 80*8 characters. Assert methods affected by this attribute are assertSequenceEqual() (including all the sequence comparison methods that delegate to it), assertDictEqual() and assertMultiLineEqual(). Setting maxDiff to None means that there is no maximum length of diffs. New in version 3.2. Testing frameworks can use the following methods to collect information on the test: countTestCases() Return the number of tests represented by this test object. For TestCase instances, this will always be 1. defaultTestResult() Return an instance of the test result class that should be used for this test case class (if no other result instance is provided to the run() method). For TestCase instances, this will always be an instance of TestResult; subclasses of TestCase should override this as necessary. id() Return a string identifying the specific test case. This is usually the full name of the test method, including the module and class name. shortDescription() Returns a description of the test, or None if no description has been provided. The default implementation of this method returns the first line of the test method’s docstring, if available, or None. Changed in version 3.1: In 3.1 this was changed to add the test name to the short description even in the presence of a docstring. This caused compatibility issues with unittest extensions and adding the test name was moved to the TextTestResult in Python 3.2. addCleanup(function, /, *args, **kwargs) Add a function to be called after tearDown() to cleanup resources used during the test. Functions will be called in reverse order to the order they are added (LIFO). They are called with any arguments and keyword arguments passed into addCleanup() when they are added. If setUp() fails, meaning that tearDown() is not called, then any cleanup functions added will still be called. New in version 3.1. doCleanups() This method is called unconditionally after tearDown(), or after setUp() if setUp() raises an exception. It is responsible for calling all the cleanup functions added by addCleanup(). If you need cleanup functions to be called prior to tearDown() then you can call doCleanups() yourself. doCleanups() pops methods off the stack of cleanup functions one at a time, so it can be called at any time. New in version 3.1. classmethod addClassCleanup(function, /, *args, **kwargs) Add a function to be called after tearDownClass() to cleanup resources used during the test class. Functions will be called in reverse order to the order they are added (LIFO). They are called with any arguments and keyword arguments passed into addClassCleanup() when they are added. If setUpClass() fails, meaning that tearDownClass() is not called, then any cleanup functions added will still be called. New in version 3.8. classmethod doClassCleanups() This method is called unconditionally after tearDownClass(), or after setUpClass() if setUpClass() raises an exception. It is responsible for calling all the cleanup functions added by addClassCleanup(). If you need cleanup functions to be called prior to tearDownClass() then you can call doClassCleanups() yourself. doClassCleanups() pops methods off the stack of cleanup functions one at a time, so it can be called at any time. New in version 3.8.
doc_25786
Returned by Map.bind() or Map.bind_to_environ() and does the URL matching and building based on runtime information. Parameters map (werkzeug.routing.Map) – server_name (str) – script_name (str) – subdomain (Optional[str]) – url_scheme (str) – path_info (str) – default_method (str) – query_args (Optional[Union[Mapping[str, Any], str]]) – allowed_methods(path_info=None) Returns the valid methods that match for a given path. Changelog New in version 0.7. Parameters path_info (Optional[str]) – Return type Iterable[str] build(endpoint, values=None, method=None, force_external=False, append_unknown=True, url_scheme=None) Building URLs works pretty much the other way round. Instead of match you call build and pass it the endpoint and a dict of arguments for the placeholders. The build function also accepts an argument called force_external which, if you set it to True will force external URLs. Per default external URLs (include the server name) will only be used if the target URL is on a different subdomain. >>> m = Map([ ... Rule('/', endpoint='index'), ... Rule('/downloads/', endpoint='downloads/index'), ... Rule('/downloads/<int:id>', endpoint='downloads/show') ... ]) >>> urls = m.bind("example.com", "/") >>> urls.build("index", {}) '/' >>> urls.build("downloads/show", {'id': 42}) '/downloads/42' >>> urls.build("downloads/show", {'id': 42}, force_external=True) 'http://example.com/downloads/42' Because URLs cannot contain non ASCII data you will always get bytes back. Non ASCII characters are urlencoded with the charset defined on the map instance. Additional values are converted to strings and appended to the URL as URL querystring parameters: >>> urls.build("index", {'q': 'My Searchstring'}) '/?q=My+Searchstring' When processing those additional values, lists are furthermore interpreted as multiple values (as per werkzeug.datastructures.MultiDict): >>> urls.build("index", {'q': ['a', 'b', 'c']}) '/?q=a&q=b&q=c' Passing a MultiDict will also add multiple values: >>> urls.build("index", MultiDict((('p', 'z'), ('q', 'a'), ('q', 'b')))) '/?p=z&q=a&q=b' If a rule does not exist when building a BuildError exception is raised. The build method accepts an argument called method which allows you to specify the method you want to have an URL built for if you have different methods for the same endpoint specified. Parameters endpoint (str) – the endpoint of the URL to build. values (Optional[Mapping[str, Any]]) – the values for the URL to build. Unhandled values are appended to the URL as query parameters. method (Optional[str]) – the HTTP method for the rule if there are different URLs for different methods on the same endpoint. force_external (bool) – enforce full canonical external URLs. If the URL scheme is not provided, this will generate a protocol-relative URL. append_unknown (bool) – unknown parameters are appended to the generated URL as query string argument. Disable this if you want the builder to ignore those. url_scheme (Optional[str]) – Scheme to use in place of the bound url_scheme. Return type str Changed in version 2.0: Added the url_scheme parameter. Changelog New in version 0.6: Added the append_unknown parameter. dispatch(view_func, path_info=None, method=None, catch_http_exceptions=False) Does the complete dispatching process. view_func is called with the endpoint and a dict with the values for the view. It should look up the view function, call it, and return a response object or WSGI application. http exceptions are not caught by default so that applications can display nicer error messages by just catching them by hand. If you want to stick with the default error messages you can pass it catch_http_exceptions=True and it will catch the http exceptions. Here a small example for the dispatch usage: from werkzeug.wrappers import Request, Response from werkzeug.wsgi import responder from werkzeug.routing import Map, Rule def on_index(request): return Response('Hello from the index') url_map = Map([Rule('/', endpoint='index')]) views = {'index': on_index} @responder def application(environ, start_response): request = Request(environ) urls = url_map.bind_to_environ(environ) return urls.dispatch(lambda e, v: views[e](request, **v), catch_http_exceptions=True) Keep in mind that this method might return exception objects, too, so use Response.force_type to get a response object. Parameters view_func (Callable[[str, Mapping[str, Any]], WSGIApplication]) – a function that is called with the endpoint as first argument and the value dict as second. Has to dispatch to the actual view function with this information. (see above) path_info (Optional[str]) – the path info to use for matching. Overrides the path info specified on binding. method (Optional[str]) – the HTTP method used for matching. Overrides the method specified on binding. catch_http_exceptions (bool) – set to True to catch any of the werkzeug HTTPExceptions. Return type WSGIApplication get_host(domain_part) Figures out the full host name for the given domain part. The domain part is a subdomain in case host matching is disabled or a full host name. Parameters domain_part (Optional[str]) – Return type str make_alias_redirect_url(path, endpoint, values, method, query_args) Internally called to make an alias redirect URL. Parameters path (str) – endpoint (str) – values (Mapping[str, Any]) – method (str) – query_args (Union[Mapping[str, Any], str]) – Return type str match(path_info=None, method=None, return_rule=False, query_args=None, websocket=None) The usage is simple: you just pass the match method the current path info as well as the method (which defaults to GET). The following things can then happen: you receive a NotFound exception that indicates that no URL is matching. A NotFound exception is also a WSGI application you can call to get a default page not found page (happens to be the same object as werkzeug.exceptions.NotFound) you receive a MethodNotAllowed exception that indicates that there is a match for this URL but not for the current request method. This is useful for RESTful applications. you receive a RequestRedirect exception with a new_url attribute. This exception is used to notify you about a request Werkzeug requests from your WSGI application. This is for example the case if you request /foo although the correct URL is /foo/ You can use the RequestRedirect instance as response-like object similar to all other subclasses of HTTPException. you receive a WebsocketMismatch exception if the only match is a WebSocket rule but the bind is an HTTP request, or if the match is an HTTP rule but the bind is a WebSocket request. you get a tuple in the form (endpoint, arguments) if there is a match (unless return_rule is True, in which case you get a tuple in the form (rule, arguments)) If the path info is not passed to the match method the default path info of the map is used (defaults to the root URL if not defined explicitly). All of the exceptions raised are subclasses of HTTPException so they can be used as WSGI responses. They will all render generic error or redirect pages. Here is a small example for matching: >>> m = Map([ ... Rule('/', endpoint='index'), ... Rule('/downloads/', endpoint='downloads/index'), ... Rule('/downloads/<int:id>', endpoint='downloads/show') ... ]) >>> urls = m.bind("example.com", "/") >>> urls.match("/", "GET") ('index', {}) >>> urls.match("/downloads/42") ('downloads/show', {'id': 42}) And here is what happens on redirect and missing URLs: >>> urls.match("/downloads") Traceback (most recent call last): ... RequestRedirect: http://example.com/downloads/ >>> urls.match("/missing") Traceback (most recent call last): ... NotFound: 404 Not Found Parameters path_info (Optional[str]) – the path info to use for matching. Overrides the path info specified on binding. method (Optional[str]) – the HTTP method used for matching. Overrides the method specified on binding. return_rule (bool) – return the rule that matched instead of just the endpoint (defaults to False). query_args (Optional[Union[Mapping[str, Any], str]]) – optional query arguments that are used for automatic redirects as string or dictionary. It’s currently not possible to use the query arguments for URL matching. websocket (Optional[bool]) – Match WebSocket instead of HTTP requests. A websocket request has a ws or wss url_scheme. This overrides that detection. Return type Tuple[Union[str, werkzeug.routing.Rule], Mapping[str, Any]] Changelog New in version 1.0: Added websocket. Changed in version 0.8: query_args can be a string. New in version 0.7: Added query_args. New in version 0.6: Added return_rule. test(path_info=None, method=None) Test if a rule would match. Works like match but returns True if the URL matches, or False if it does not exist. Parameters path_info (Optional[str]) – the path info to use for matching. Overrides the path info specified on binding. method (Optional[str]) – the HTTP method used for matching. Overrides the method specified on binding. Return type bool
doc_25787
tf.keras.regularizers.l2 Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.regularizers.L2, tf.compat.v1.keras.regularizers.l2 tf.keras.regularizers.L2( l2=0.01, **kwargs ) The L2 regularization penalty is computed as: loss = l2 * reduce_sum(square(x)) L2 may be passed to a layer as a string identifier: dense = tf.keras.layers.Dense(3, kernel_regularizer='l2') In this case, the default value used is l2=0.01. Attributes l2 Float; L2 regularization factor. Methods from_config View source @classmethod from_config( config ) Creates a regularizer from its config. This method is the reverse of get_config, capable of instantiating the same regularizer from the config dictionary. This method is used by Keras model_to_estimator, saving and loading models to HDF5 formats, Keras model cloning, some visualization utilities, and exporting models to and from JSON. Arguments config A Python dictionary, typically the output of get_config. Returns A regularizer instance. get_config View source get_config() Returns the config of the regularizer. An regularizer config is a Python dictionary (serializable) containing all configuration parameters of the regularizer. The same regularizer can be reinstantiated later (without any saved state) from this configuration. This method is optional if you are just training and executing models, exporting to and from SavedModels, or using weight checkpoints. This method is required for Keras model_to_estimator, saving and loading models to HDF5 formats, Keras model cloning, some visualization utilities, and exporting models to and from JSON. Returns Python dictionary. __call__ View source __call__( x ) Compute a regularization penalty from an input tensor.
doc_25788
Controls when quotes should be generated by the writer and recognised by the reader. It can take on any of the QUOTE_* constants (see section Module Contents) and defaults to QUOTE_MINIMAL.
doc_25789
True if a domain was explicitly specified by the server.
doc_25790
Return number of unique elements in the object. Excludes NA values by default. Parameters dropna:bool, default True Don’t include NaN in the count. Returns int See also DataFrame.nunique Method nunique for DataFrame. Series.count Count non-NA/null observations in the Series. Examples >>> s = pd.Series([1, 3, 5, 7, 7]) >>> s 0 1 1 3 2 5 3 7 4 7 dtype: int64 >>> s.nunique() 4
doc_25791
Return the center of the ellipse.
doc_25792
Return a dict of cells in the table mapping (row, column) to Cells. Notes You can also directly index into the Table object to access individual cells: cell = table[row, col]
doc_25793
See Migration guide for more details. tf.compat.v1.test.TestCase.failureException tf.test.TestCase.failureException( *args, **kwargs )
doc_25794
Turns a language name (en-us) into a locale name (en_US).
doc_25795
New view of array with the same data. Note Passing None for dtype is different from omitting the parameter, since the former invokes dtype(None) which is an alias for dtype('float_'). Parameters dtypedata-type or ndarray sub-class, optional Data-type descriptor of the returned view, e.g., float32 or int16. Omitting it results in the view having the same data-type as a. This argument can also be specified as an ndarray sub-class, which then specifies the type of the returned object (this is equivalent to setting the type parameter). typePython type, optional Type of the returned view, e.g., ndarray or matrix. Again, omission of the parameter results in type preservation. Notes a.view() is used two different ways: a.view(some_dtype) or a.view(dtype=some_dtype) constructs a view of the array’s memory with a different data-type. This can cause a reinterpretation of the bytes of memory. a.view(ndarray_subclass) or a.view(type=ndarray_subclass) just returns an instance of ndarray_subclass that looks at the same array (same shape, dtype, etc.) This does not cause a reinterpretation of the memory. For a.view(some_dtype), if some_dtype has a different number of bytes per entry than the previous dtype (for example, converting a regular array to a structured array), then the behavior of the view cannot be predicted just from the superficial appearance of a (shown by print(a)). It also depends on exactly how a is stored in memory. Therefore if a is C-ordered versus fortran-ordered, versus defined as a slice or transpose, etc., the view may give different results. Examples >>> x = np.array([(1, 2)], dtype=[('a', np.int8), ('b', np.int8)]) Viewing array data using a different type and dtype: >>> y = x.view(dtype=np.int16, type=np.matrix) >>> y matrix([[513]], dtype=int16) >>> print(type(y)) <class 'numpy.matrix'> Creating a view on a structured array so it can be used in calculations >>> x = np.array([(1, 2),(3,4)], dtype=[('a', np.int8), ('b', np.int8)]) >>> xv = x.view(dtype=np.int8).reshape(-1,2) >>> xv array([[1, 2], [3, 4]], dtype=int8) >>> xv.mean(0) array([2., 3.]) Making changes to the view changes the underlying array >>> xv[0,1] = 20 >>> x array([(1, 20), (3, 4)], dtype=[('a', 'i1'), ('b', 'i1')]) Using a view to convert an array to a recarray: >>> z = x.view(np.recarray) >>> z.a array([1, 3], dtype=int8) Views share data: >>> x[0] = (9, 10) >>> z[0] (9, 10) Views that change the dtype size (bytes per entry) should normally be avoided on arrays defined by slices, transposes, fortran-ordering, etc.: >>> x = np.array([[1,2,3],[4,5,6]], dtype=np.int16) >>> y = x[:, 0:2] >>> y array([[1, 2], [4, 5]], dtype=int16) >>> y.view(dtype=[('width', np.int16), ('length', np.int16)]) Traceback (most recent call last): ... ValueError: To change to a dtype of a different size, the array must be C-contiguous >>> z = y.copy() >>> z.view(dtype=[('width', np.int16), ('length', np.int16)]) array([[(1, 2)], [(4, 5)]], dtype=[('width', '<i2'), ('length', '<i2')])
doc_25796
See WKBWriter.outdim.
doc_25797
The process’s name. The name is a string used for identification purposes only. It has no semantics. Multiple processes may be given the same name. The initial name is set by the constructor. If no explicit name is provided to the constructor, a name of the form ‘Process-N1:N2:…:Nk’ is constructed, where each Nk is the N-th child of its parent.
doc_25798
The Expires entity-header field gives the date/time after which the response is considered stale. A stale cache entry may not normally be returned by a cache. Changed in version 2.0: The datetime object is timezone-aware.
doc_25799
Raised when the result of an arithmetic operation is too large to be represented. This cannot occur for integers (which would rather raise MemoryError than give up). However, for historical reasons, OverflowError is sometimes raised for integers that are outside a required range. Because of the lack of standardization of floating point exception handling in C, most floating point operations are not checked.