mteb/SWEbenchLiteRR huggingface dataset:
Messages framework incorrectly serializes/deserializes extra_tags when it's an empty string
Description
	
When a message is serialised and then deserialised with any of the built in storage backends, then extra_tags=="" is converted to extra_tags==None. This is because MessageEncoder checks for the truthyness of extra_tags rather than checking it is not None.
To replicate this bug
>>> from django.conf import settings
>>> settings.configure() # Just to allow the following import
>>> from django.contrib.messages.storage.base import Message
>>> from django.contrib.messages.storage.cookie import MessageEncoder, MessageDecoder
>>> original_message = Message(10, "Here is a message", extra_tags="")
>>> encoded_message = MessageEncoder().encode(original_message)
>>> decoded_message = MessageDecoder().decode(encoded_message)
>>> original_message.extra_tags == ""
True
>>> decoded_message.extra_tags is None
True
Effect of the bug in application behaviour
This error occurred in the wild with a template tag similar to the following:
{% if x not in message.extra_tags %}
When the message was displayed as part of a redirect, it had been serialised and deserialized which meant that extra_tags was None instead of the empty string. This caused an error.
It's important to note that this bug affects all of the standard API (messages.debug, messages.info etc. all have a default value of extra_tags equal to "").
Comparing string to array in _estimate_mi
In ``_estimate_mi`` there is ``discrete_features == 'auto'`` but discrete features can be an array of indices or a boolean mask.
This will error in future versions of numpy.
Also this means we never test this function with discrete features != 'auto', it seems?
Wrong Derivative kind attribute
I'm playing around with the `kind` attribute.

The following is correct:

```
from sympy import Integral, Derivative
from sympy import MatrixSymbol
from sympy.abc import x
A = MatrixSymbol('A', 2, 2)
i = Integral(A, x)
i.kind
# MatrixKind(NumberKind)
```

This one is wrong:
```
d = Derivative(A, x)
d.kind
# UndefinedKind
```
0**-oo produces 0, the documentation says it should produce zoo
Using SymPy 1.5.1, evaluate `0**-oo` produces `0`.

The documentation for the Pow class states that it should return `ComplexInfinity`, aka `zoo`

| expr | value | reason |
| :-- | :-- | :--|
| `0**-oo` | `zoo` | This is not strictly true, as 0**oo may be oscillating between positive and negative values or rotating in the complex plane. It is convenient, however, when the base is positive.|
autodoc_type_aliases does not effect to variables and attributes
**Describe the bug**
autodoc_type_aliases does not effect to variables and attributes

**To Reproduce**

```
# example.py
from __future__ import annotations


#: blah blah blah
var: String


class MyString:
    "mystring"

    #: blah blah blah
    var: String
```
```
# index.rst
.. automodule:: example
   :members:
   :undoc-members:
```
```
# conf.py
autodoc_type_aliases = {
    'String': 'example.MyString'
}
```

**Expected behavior**
`autodoc_type_aliases` should be applied to `example.var` and `example.MyString.var`.

**Your project**
N/A

**Screenshots**
N/A

**Environment info**
- OS: Mac
- Python version: 3.9.0
- Sphinx version: HEAD of 3.x branch
- Sphinx extensions: sphinx.ext.autodoc
- Extra tools: Nothing

**Additional context**
N/A
Wrong result with apart
```
Python 3.6.0 |Continuum Analytics, Inc.| (default, Dec 23 2016, 12:22:00) 
Type "copyright", "credits" or "license" for more information.

IPython 5.1.0 -- An enhanced Interactive Python.
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about 'object', use 'object??' for extra details.

In [1]: from sympy import symbols

In [2]: a = symbols('a', real=True)

In [3]: t = symbols('t', real=True, negative=False)

In [4]: bug = a * (-t + (-t + 1) * (2 * t - 1)) / (2 * t - 1)

In [5]: bug.subs(a, 1)
Out[5]: (-t + (-t + 1)*(2*t - 1))/(2*t - 1)

In [6]: bug.subs(a, 1).apart()
Out[6]: -t + 1/2 - 1/(2*(2*t - 1))

In [7]: bug.subs(a, 1).apart(t)
Out[7]: -t + 1/2 - 1/(2*(2*t - 1))

In [8]: bug.apart(t)
Out[8]: -a*t

In [9]: import sympy; sympy.__version__
Out[9]: '1.0'
```
Wrong result with apart
```
Python 3.6.0 |Continuum Analytics, Inc.| (default, Dec 23 2016, 12:22:00) 
Type "copyright", "credits" or "license" for more information.

IPython 5.1.0 -- An enhanced Interactive Python.
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about 'object', use 'object??' for extra details.

In [1]: from sympy import symbols

In [2]: a = symbols('a', real=True)

In [3]: t = symbols('t', real=True, negative=False)

In [4]: bug = a * (-t + (-t + 1) * (2 * t - 1)) / (2 * t - 1)

In [5]: bug.subs(a, 1)
Out[5]: (-t + (-t + 1)*(2*t - 1))/(2*t - 1)

In [6]: bug.subs(a, 1).apart()
Out[6]: -t + 1/2 - 1/(2*(2*t - 1))

In [7]: bug.subs(a, 1).apart(t)
Out[7]: -t + 1/2 - 1/(2*(2*t - 1))

In [8]: bug.apart(t)
Out[8]: -a*t

In [9]: import sympy; sympy.__version__
Out[9]: '1.0'
```
ForeignKey's to_field parameter gets the old field's name when renaming a PrimaryKey.
Description
	
Having these two models 
class ModelA(models.Model):
	field_wrong = models.CharField('field1', max_length=50, primary_key=True) # I'm a Primary key.
class ModelB(models.Model):
	field_fk = models.ForeignKey(ModelA, blank=True, null=True, on_delete=models.CASCADE) 
... migrations applyed ...
the ModelA.field_wrong field has been renamed ... and Django recognizes the "renaming"
# Primary key renamed
class ModelA(models.Model):
	field_fixed = models.CharField('field1', max_length=50, primary_key=True) # I'm a Primary key.
Attempts to to_field parameter. 
The to_field points to the old_name (field_typo) and not to the new one ("field_fixed")
class Migration(migrations.Migration):
	dependencies = [
		('app1', '0001_initial'),
	]
	operations = [
		migrations.RenameField(
			model_name='modela',
			old_name='field_wrong',
			new_name='field_fixed',
		),
		migrations.AlterField(
			model_name='modelb',
			name='modela',
			field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='app1.ModelB', to_field='field_wrong'),
		),
	]
legend draggable as keyword
<!--To help us understand and resolve your issue, please fill out the form to the best of your ability.-->
<!--You can feel free to delete the sections that do not apply.-->

### Feature request

**There is not keyword to make legend draggable at creation**

<!--A short 1-2 sentences that succinctly describes the bug-->

Is there a code reason why one can not add a "draggable=True" keyword to the __init__ function for Legend?  This would be more handy than having to call it after legend creation.  And, naively, it would seem simple to do.  But maybe there is a reason why it would not work?
Return values of non converged affinity propagation clustering
The affinity propagation Documentation states: 
"When the algorithm does not converge, it returns an empty array as cluster_center_indices and -1 as label for each training sample."

Example:
```python
from sklearn.cluster import AffinityPropagation
import pandas as pd

data = pd.DataFrame([[1,0,0,0,0,0],[0,1,1,1,0,0],[0,0,1,0,0,1]])
af = AffinityPropagation(affinity='euclidean', verbose=True, copy=False, max_iter=2).fit(data)

print(af.cluster_centers_indices_)
print(af.labels_)

```
I would expect that the clustering here (which does not converge) prints first an empty List and then [-1,-1,-1], however, I get [2] as cluster center and [0,0,0] as cluster labels. 
The only way I currently know if the clustering fails is if I use the verbose option, however that is very unhandy. A hacky solution is to check if max_iter == n_iter_ but it could have converged exactly 15 iterations before max_iter (although unlikely).
I am not sure if this is intended behavior and the documentation is wrong?

For my use-case within a bigger script, I would prefer to get back -1 values or have a property to check if it has converged, as otherwise, a user might not be aware that the clustering never converged.


#### Versions
System:
    python: 3.6.7 | packaged by conda-forge | (default, Nov 21 2018, 02:32:25)  [GCC 4.8.2 20140120 (Red Hat 4.8.2-15)]
executable: /home/jenniferh/Programs/anaconda3/envs/TF_RDKit_1_19/bin/python
   machine: Linux-4.15.0-52-generic-x86_64-with-debian-stretch-sid
BLAS:
    macros: SCIPY_MKL_H=None, HAVE_CBLAS=None
  lib_dirs: /home/jenniferh/Programs/anaconda3/envs/TF_RDKit_1_19/lib
cblas_libs: mkl_rt, pthread
Python deps:
    pip: 18.1
   setuptools: 40.6.3
   sklearn: 0.20.3
   numpy: 1.15.4
   scipy: 1.2.0
   Cython: 0.29.2
   pandas: 0.23.4
LaTeX printer inconsistent with pretty printer
The LaTeX printer should always give the same output as the pretty printer, unless better output is possible from LaTeX. In some cases it is inconsistent. For instance:

``` py
In [9]: var('x', positive=True)
Out[9]: x

In [10]: latex(exp(-x)*log(x))
Out[10]: '\\frac{1}{e^{x}} \\log{\\left (x \\right )}'

In [11]: pprint(exp(-x)*log(x))
 -x
ℯ  ⋅log(x)
```

(I also don't think the assumptions should affect printing). 

``` py
In [14]: var('x y')
Out[14]: (x, y)

In [15]: latex(1/(x + y)/2)
Out[15]: '\\frac{1}{2 x + 2 y}'

In [16]: pprint(1/(x + y)/2)
    1
─────────
2⋅(x + y)
```
Wrong matrix element fetched from BlockMatrix
Given this code:
```
from sympy import *
n, i = symbols('n, i', integer=True)
A = MatrixSymbol('A', 1, 1)
B = MatrixSymbol('B', n, 1)
C = BlockMatrix([[A], [B]])
print('C is')
pprint(C)
print('C[i, 0] is')
pprint(C[i, 0])
```
I get this output:
```
C is
⎡A⎤
⎢ ⎥
⎣B⎦
C[i, 0] is
(A)[i, 0]
```
`(A)[i, 0]` is the wrong here. `C[i, 0]` should not be simplified as that element may come from either `A` or `B`.
Simplify of simple trig expression fails
trigsimp in various versions, including 1.5, incorrectly simplifies cos(x)+sqrt(sin(x)**2) as though it were cos(x)+sin(x) for general complex x. (Oddly it gets this right if x is real.)

Embarrassingly I found this by accident while writing sympy-based teaching material...
Mod(x**2, x) is not (always) 0
When the base is not an integer, `x**2 % x` is not 0. The base is not tested to be an integer in Mod's eval logic:

```
if (p == q or p == -q or
        p.is_Pow and p.exp.is_Integer and p.base == q or
        p.is_integer and q == 1):
    return S.Zero
```

so

```
>>> Mod(x**2, x)
0
```
but
```
>>> x = S(1.5)
>>> Mod(x**2, x)
0.75
```
xlim_changed not emitted on shared axis
<!--To help us understand and resolve your issue, please fill out the form to the best of your ability.-->
<!--You can feel free to delete the sections that do not apply.-->

### Bug report

**Bug summary**

When an axis is shared with another its registered "xlim_changed" callbacks does not get called when the change is induced by a shared axis (via sharex=). 

In _base.py the set_xlim for sibling axis are called with emit=False:

```
matplotlib/lib/matplotlib/axes/_base.py:

/.../
def set_xlim(...)
/.../
        if emit:
            self.callbacks.process('xlim_changed', self)
            # Call all of the other x-axes that are shared with this one
            for other in self._shared_x_axes.get_siblings(self):
                if other is not self:
                    other.set_xlim(self.viewLim.intervalx,
                                   emit=False, auto=auto)
```

I'm very new to matplotlib, so perhaps there is a good reason for this? emit=False seems to disable both continued "inheritance" of axis (why?) and triggering of change callbacks (looking at the code above).

It seems like one would at least want to trigger the xlim_changed callbacks as they would be intended to react to any change in axis limits.

Edit: Setting emit=True seems to introduce a recursion issue (not sure why but as inheritance seems to be passed along anyway it doesn't really matter). Moving the callback call to outside of the "if emit:"-statement seems to solve the issue as far as I can see when trying it out. Any reason to keep it inside the if-statement?
Fix numberformat.py "string index out of range" when null
Description
	
When:
if str_number[0] == "-"
encounters a number field that's null when formatting for the admin list_display this causes an 
IndexError: string index out of range
I can attach the proposed fix here, or open a pull request on GitHub if you like?
QuerySet.Delete - inconsistent result when zero objects deleted
Description
	
The result format of the QuerySet.Delete method is a tuple: (X, Y) 
X - is the total amount of deleted objects (including foreign key deleted objects)
Y - is a dictionary specifying counters of deleted objects for each specific model (the key is the _meta.label of the model and the value is counter of deleted objects of this model).
Example: <class 'tuple'>: (2, {'my_app.FileAccess': 1, 'my_app.File': 1})
When there are zero objects to delete in total - the result is inconsistent:
For models with foreign keys - the result will be: <class 'tuple'>: (0, {})
For "simple" models without foreign key - the result will be: <class 'tuple'>: (0, {'my_app.BlockLibrary': 0})
I would expect there will be no difference between the two cases: Either both will have the empty dictionary OR both will have dictionary with model-label keys and zero value.
migrate management command does not respect database parameter when adding Permissions.
Description
	 
		(last modified by Vasanth)
	 
When invoking migrate with a database parameter, the migration runs successfully. However, there seems to be a DB read request that runs after the migration. This call does not respect the db param and invokes the db router .
When naming the db as a parameter, all DB calls in the context of the migrate command are expected to use the database specified.
I came across this as I am currently using a thread-local variable to get the active DB with a custom DB router for a multi-tenant service .
Minimal example 
Setup the custom middleware and custom DB Router as show below. Then run any DB migration. We see that "read {}" is being printed before the exception message.
Ideally none of this code must be called as the DB was specified during management command.
from threading import local
from django.conf import settings
local_state = local()
class InvalidTenantException(Exception):
	pass
class TenantSubdomainMiddleware:
	def __init__(self, get_response):
		self.get_response = get_response
	def __call__(self, request):
		## Get Subdomain
		host = request.get_host().split(":")[0]
		local_state.subdomain = (
			# We assume single level of subdomain : app.service.com 
			# HOST_IP : used to for local dev. 
			host if host in settings.HOST_IP else host.split(".")[0]
		)
		response = self.get_response(request)
		return response
class TenantDatabaseRouter:
	def _default_db(self):
		subdomain = getattr(local_state, "subdomain", None)
		if subdomain is not None and subdomain in settings.TENANT_MAP:
			db_name = settings.TENANT_MAP[local_state.subdomain]
			return db_name
		else:
			raise InvalidTenantException()
	def db_for_read(self, model, **hints):
		print("read", hints)
		return self._default_db()
	def db_for_write(self, model, **hints):
		print("write", hints)
		return self._default_db()
	def allow_relation(self, obj1, obj2, **hints):
		return None
	def allow_migrate(self, db, app_label, model_name=None, **hints):
		return None
## settings.py
MIDDLEWARE = [
	"utils.tenant_db_router.TenantSubdomainMiddleware",
	"django.middleware.security.SecurityMiddleware",
	...
]
TENANT_MAP = {"localhost":"default", "tenant_1":"default"}
DATABASE_ROUTERS = ["utils.tenant_db_router.TenantDatabaseRouter"]
Improve handling of skip for module level
This is potentially about updating docs, updating error messages or introducing a new API.

Consider the following scenario:

`pos_only.py` is using Python 3,8 syntax:
```python
def foo(a, /, b):
    return a + b
```

It should not be tested under Python 3.6 and 3.7.
This is a proper way to skip the test in Python older than 3.8:
```python
from pytest import raises, skip
import sys
if sys.version_info < (3, 8):
    skip(msg="Requires Python >= 3.8", allow_module_level=True)

# import must be after the module level skip:
from pos_only import *

def test_foo():
    assert foo(10, 20) == 30
    assert foo(10, b=20) == 30
    with raises(TypeError):
        assert foo(a=10, b=20)
```

My actual test involves parameterize and a 3.8 only class, so skipping the test itself is not sufficient because the 3.8 class was used in the parameterization.

A naive user will try to initially skip the module like:

```python
if sys.version_info < (3, 8):
    skip(msg="Requires Python >= 3.8")
```
This issues this error:

>Using pytest.skip outside of a test is not allowed. To decorate a test function, use the @pytest.mark.skip or @pytest.mark.skipif decorators instead, and to skip a module use `pytestmark = pytest.mark.{skip,skipif}.

The proposed solution `pytestmark = pytest.mark.{skip,skipif}`, does not work  in my case: pytest continues to process the file and fail when it hits the 3.8 syntax (when running with an older version of Python).

The correct solution, to use skip as a function is actively discouraged by the error message.

This area feels a bit unpolished.
A few ideas to improve:

1. Explain skip with  `allow_module_level` in the error message. this seems in conflict with the spirit of the message.
2. Create an alternative API to skip a module to make things easier: `skip_module("reason")`, which can call `_skip(msg=msg, allow_module_level=True)`.
Support for serialization of combination of Enum flags.
Description
	 
		(last modified by Willem Van Onsem)
	 
If we work with a field:
regex_flags = models.IntegerField(default=re.UNICODE | re.IGNORECASE)
This is turned into a migration with:
default=re.RegexFlag[None]
This is due to the fact that the EnumSerializer aims to work with the .name of the item, but if there is no single item for the given value, then there is no such name.
In that case, we can use enum._decompose to obtain a list of names, and create an expression to create the enum value by "ORing" the items together.
Generate man page section directories
**Current man page generation does not conform to `MANPATH` search functionality**
Currently, all generated man pages are placed in to a single-level directory: `<build-dir>/man`. Unfortunately, this cannot be used in combination with the unix `MANPATH` environment variable. The `man` program explicitly looks for man pages in section directories (such as `man/man1`, etc.). 

**Describe the solution you'd like**
It would be great if sphinx would automatically create the section directories (e.g., `man/man1/`, `man/man3/`, etc.) and place each generated man page within appropriate section.

**Describe alternatives you've considered**
This problem can be over come within our project’s build system, ensuring the built man pages are installed in a correct location, but it would be nice if the build directory had the proper layout.

I’m happy to take a crack at implementing a fix, though this change in behavior may break some people who expect everything to appear in a `man/` directory.
detection of infinite solution request
```python
>>> solve_poly_system((x - 1,), x, y)
Traceback (most recent call last):
...
NotImplementedError:
only zero-dimensional systems supported (finite number of solutions)
>>> solve_poly_system((y - 1,), x, y)  <--- this is not handled correctly
[(1,)]
```
```diff
diff --git a/sympy/solvers/polysys.py b/sympy/solvers/polysys.py
index b9809fd4e9..674322d4eb 100644
--- a/sympy/solvers/polysys.py
+++ b/sympy/solvers/polysys.py
@@ -240,7 +240,7 @@ def _solve_reduced_system(system, gens, entry=False):
 
         univariate = list(filter(_is_univariate, basis))
 
-        if len(univariate) == 1:
+        if len(univariate) == 1 and len(gens) == 1:
             f = univariate.pop()
         else:
             raise NotImplementedError(filldedent('''
diff --git a/sympy/solvers/tests/test_polysys.py b/sympy/solvers/tests/test_polysys.py
index 58419f8762..9e674a6fe6 100644
--- a/sympy/solvers/tests/test_polysys.py
+++ b/sympy/solvers/tests/test_polysys.py
@@ -48,6 +48,10 @@ def test_solve_poly_system():
     raises(NotImplementedError, lambda: solve_poly_system(
         [z, -2*x*y**2 + x + y**2*z, y**2*(-z - 4) + 2]))
     raises(PolynomialError, lambda: solve_poly_system([1/x], x))
+    raises(NotImplementedError, lambda: solve_poly_system(
+        Poly(x - 1, x, y), (x, y)))
+    raises(NotImplementedError, lambda: solve_poly_system(
+        Poly(y - 1, x, y), (x, y)))
 
 
 def test_solve_biquadratic():
```
Allow returning IDs in QuerySet.bulk_create() when updating conflicts.
Description
	
Currently, when using bulk_create with a conflict handling flag turned on (e.g. ignore_conflicts or update_conflicts), the primary keys are not set in the returned queryset, as documented in bulk_create.
While I understand using ignore_conflicts can lead to PostgreSQL not returning the IDs when a row is ignored (see ​this SO thread), I don't understand why we don't return the IDs in the case of update_conflicts.
For instance:
MyModel.objects.bulk_create([MyModel(...)], update_conflicts=True, update_fields=[...], unique_fields=[...])
generates a query without a RETURNING my_model.id part:
INSERT INTO "my_model" (...)
VALUES (...)
	ON CONFLICT(...) DO UPDATE ...
If I append the RETURNING my_model.id clause, the query is indeed valid and the ID is returned (checked with PostgreSQL).
I investigated a bit and ​this in Django source is where the returning_fields gets removed.
I believe we could discriminate the cases differently so as to keep those returning_fields in the case of update_conflicts.
This would be highly helpful when using bulk_create as a bulk upsert feature.
Template filter `join` should not escape the joining string if `autoescape` is `off`
Description
	
Consider the following template code snippet:
{% autoescape off %}
{{ some_list|join:some_var }}
{% endautoescape %}
in this case, the items inside some_list will not be escaped (matching the expected behavior) but some_var will forcibly be escaped. From the docs for autoescape or join I don't think this is expected behavior.
The following testcase illustrates what I think is a bug in the join filter (run inside the template_tests/filter_tests folder):
from django.template.defaultfilters import escape
from django.test import SimpleTestCase
from ..utils import setup
class RegressionTests(SimpleTestCase):
	@setup({"join01": '{{ some_list|join:some_var }}'})
	def test_join01(self):
		some_list = ["<p>Hello World!</p>", "beta & me", "<script>Hi!</script>"]
		some_var = "<br/>"
		output = self.engine.render_to_string("join01", {"some_list": some_list, "some_var": some_var})
		self.assertEqual(output, escape(some_var.join(some_list)))
	@setup({"join02": '{% autoescape off %}{{ some_list|join:some_var }}{% endautoescape %}'})
	def test_join02(self):
		some_list = ["<p>Hello World!</p>", "beta & me", "<script>Hi!</script>"]
		some_var = "<br/>"
		output = self.engine.render_to_string("join02", {"some_list": some_list, "some_var": some_var})
		self.assertEqual(output, some_var.join(some_list))
Result of this run in current main is:
.F
======================================================================
FAIL: test_join02 (template_tests.filter_tests.test_regression.RegressionTests.test_join02)
----------------------------------------------------------------------
Traceback (most recent call last):
 File "/home/nessita/fellowship/django/django/test/utils.py", line 443, in inner
	return func(*args, **kwargs)
		 ^^^^^^^^^^^^^^^^^^^^^
 File "/home/nessita/fellowship/django/tests/template_tests/utils.py", line 58, in inner
	func(self)
 File "/home/nessita/fellowship/django/tests/template_tests/filter_tests/test_regression.py", line 21, in test_join02
	self.assertEqual(output, some_var.join(some_list))
AssertionError: '<p>Hello World!</p>&lt;br/&gt;beta & me&lt;br/&gt;<script>Hi!</script>' != '<p>Hello World!</p><br/>beta & me<br/><script>Hi!</script>'
----------------------------------------------------------------------
Ran 2 tests in 0.007s
v3.3 upgrade started generating "WARNING: no number is assigned for table" warnings
We've updated to Sphinx 3.3 in our documentation, and suddenly the following warning started popping up in our builds when we build either `singlehtml` or `latex`.:

`WARNING: no number is assigned for table:`

I looked through the changelog but it didn't seem like there was anything related to `numref` that was changed, but perhaps I missed something? Could anyone point me to a change in the numref logic so I can figure out where these warnings are coming from?
Inherited model doesn't correctly order by "-pk" when specified on Parent.Meta.ordering
Description
	
Given the following model definition:
from django.db import models
class Parent(models.Model):
	class Meta:
		ordering = ["-pk"]
class Child(Parent):
	pass
Querying the Child class results in the following:
>>> print(Child.objects.all().query)
SELECT "myapp_parent"."id", "myapp_child"."parent_ptr_id" FROM "myapp_child" INNER JOIN "myapp_parent" ON ("myapp_child"."parent_ptr_id" = "myapp_parent"."id") ORDER BY "myapp_parent"."id" ASC
The query is ordered ASC but I expect the order to be DESC.
Model.get_FOO_display() does not work correctly with inherited choices.
Description
	 
		(last modified by Mariusz Felisiak)
	 
Given a base model with choices A containing 3 tuples
Child Model inherits the base model overrides the choices A and adds 2 more tuples
get_foo_display does not work correctly for the new tuples added
Example:
class A(models.Model):
 foo_choice = [("A","output1"),("B","output2")]
 field_foo = models.CharField(max_length=254,choices=foo_choice)
 class Meta:
	 abstract = True
class B(A):
 foo_choice = [("A","output1"),("B","output2"),("C","output3")]
 field_foo = models.CharField(max_length=254,choices=foo_choice)
Upon invoking get_field_foo_display() on instance of B , 
For value "A" and "B" the output works correctly i.e. returns "output1" / "output2"
but for value "C" the method returns "C" and not "output3" which is the expected behaviour
Display fixture scope with `pytest --fixtures`
It would be useful to show fixture scopes with `pytest --fixtures`; currently the only way to learn the scope of a fixture is look at the docs (when that is documented) or at the source code.
Django throws error when different apps with different models have the same name table name.
Description
	
Error message:
table_name: (models.E028) db_table 'table_name' is used by multiple models: base.ModelName, app2.ModelName.
We have a Base app that points to a central database and that has its own tables. We then have multiple Apps that talk to their own databases. Some share the same table names.
We have used this setup for a while, but after upgrading to Django 2.2 we're getting an error saying we're not allowed 2 apps, with 2 different models to have the same table names. 
Is this correct behavior? We've had to roll back to Django 2.0 for now.
Hostname and timestamp properties in generated JUnit XML reports
Pytest enables generating JUnit XML reports of the tests.

However, there are some properties missing, specifically `hostname` and `timestamp` from the `testsuite` XML element. Is there an option to include them?

Example of a pytest XML report:
```xml
<?xml version="1.0" encoding="utf-8"?>
<testsuite errors="0" failures="2" name="check" skipped="0" tests="4" time="0.049">
	<testcase classname="test_sample.TestClass" file="test_sample.py" line="3" name="test_addOne_normal" time="0.001"></testcase>
	<testcase classname="test_sample.TestClass" file="test_sample.py" line="6" name="test_addOne_edge" time="0.001"></testcase>
</testsuite>
```

Example of a junit XML report:
```xml
<?xml version="1.0" encoding="UTF-8"?>
<testsuite name="location.GeoLocationTest" tests="2" skipped="0" failures="0" errors="0" timestamp="2019-04-22T10:32:27" hostname="Anass-MacBook-Pro.local" time="0.048">
  <properties/>
  <testcase name="testIoException()" classname="location.GeoLocationTest" time="0.044"/>
  <testcase name="testJsonDeserialization()" classname="location.GeoLocationTest" time="0.003"/>
  <system-out><![CDATA[]]></system-out>
  <system-err><![CDATA[]]></system-err>
</testsuite>
```
[Bug]: Setting matplotlib.pyplot.style.library['seaborn-colorblind'] result in key error on matplotlib v3.6.1
### Bug summary

I have code that executes:
```
import matplotlib.pyplot as plt
the_rc = plt.style.library["seaborn-colorblind"]
```

Using version 3.4.3 of matplotlib, this works fine. I recently installed my code on a machine with matplotlib version 3.6.1 and upon importing my code, this generated a key error for line `the_rc = plt.style.library["seaborn-colorblind"]` saying "seaborn-colorblind" was a bad key.

### Code for reproduction

```python
import matplotlib.pyplot as plt
the_rc = plt.style.library["seaborn-colorblind"]
```


### Actual outcome

Traceback (most recent call last):
KeyError: 'seaborn-colorblind'

### Expected outcome

seaborn-colorblind should be set as the matplotlib library style and I should be able to continue plotting with that style.

### Additional information

- Bug occurs with matplotlib version 3.6.1
- Bug does not occur with matplotlib version 3.4.3
- Tested on MacOSX and Ubuntu (same behavior on both)

### Operating system

OS/X

### Matplotlib Version

3.6.1

### Matplotlib Backend

MacOSX

### Python version

3.9.7

### Jupyter version

_No response_

### Installation

pip
Filtering on query result overrides GROUP BY of internal query
Description
	
from django.contrib.auth import models
a = models.User.objects.filter(email__isnull=True).values('email').annotate(m=Max('id')).values('m')
print(a.query) # good
# SELECT MAX("auth_user"."id") AS "m" FROM "auth_user" WHERE "auth_user"."email" IS NULL GROUP BY "auth_user"."email"
print(a[:1].query) # good
# SELECT MAX("auth_user"."id") AS "m" FROM "auth_user" WHERE "auth_user"."email" IS NULL GROUP BY "auth_user"."email" LIMIT 1
b = models.User.objects.filter(id=a[:1])
print(b.query) # GROUP BY U0."id" should be GROUP BY U0."email"
# SELECT ... FROM "auth_user" WHERE "auth_user"."id" = (SELECT U0."id" FROM "auth_user" U0 WHERE U0."email" IS NULL GROUP BY U0."id" LIMIT 1)
Add check for fields of UniqueConstraints.
Description
	 
		(last modified by Marnanel Thurman)
	 
When a model gains a UniqueConstraint, makemigrations doesn't check that the fields named therein actually exist.
This is in contrast to the older unique_together syntax, which raises models.E012 if the fields don't exist.
In the attached demonstration, you'll need to uncomment "with_unique_together" in settings.py in order to show that unique_together raises E012.
Optional URL params crash some view functions.
Description
	
My use case, running fine with Django until 2.2:
URLConf:
urlpatterns += [
	...
	re_path(r'^module/(?P<format>(html|json|xml))?/?$', views.modules, name='modules'),
]
View:
def modules(request, format='html'):
	...
	return render(...)
With Django 3.0, this is now producing an error:
Traceback (most recent call last):
 File "/l10n/venv/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner
	response = get_response(request)
 File "/l10n/venv/lib/python3.6/site-packages/django/core/handlers/base.py", line 115, in _get_response
	response = self.process_exception_by_middleware(e, request)
 File "/l10n/venv/lib/python3.6/site-packages/django/core/handlers/base.py", line 113, in _get_response
	response = wrapped_callback(request, *callback_args, **callback_kwargs)
Exception Type: TypeError at /module/
Exception Value: modules() takes from 1 to 2 positional arguments but 3 were given
Multi-level FilteredRelation with select_related() may set wrong related object.
Description
	
test case:
# add to known_related_objects.tests.ExistingRelatedInstancesTests
	def test_wrong_select_related(self):
		with self.assertNumQueries(3):
			p = list(PoolStyle.objects.annotate(
				tournament_pool=FilteredRelation('pool__tournament__pool'),
				).select_related('tournament_pool'))
			self.assertEqual(p[0].pool.tournament, p[0].tournament_pool.tournament)
result:
======================================================================
FAIL: test_wrong_select_related (known_related_objects.tests.ExistingRelatedInstancesTests.test_wrong_select_related)
----------------------------------------------------------------------
Traceback (most recent call last):
 File "D:\Work\django\tests\known_related_objects\tests.py", line 171, in test_wrong_select_related
	self.assertEqual(p[0].pool.tournament, p[0].tournament_pool.tournament)
AssertionError: <Tournament: Tournament object (1)> != <PoolStyle: PoolStyle object (1)>
----------------------------------------------------------------------
django-admin startapp with trailing slash in directory name results in error
Description
	
Bash tab-completion appends trailing slashes to directory names. django-admin startapp name directory/ results in the error:
CommandError: '' is not a valid app directory. Please make sure the directory is a valid identifier.
The error is caused by ​line 77 of django/core/management/templates.py by calling basename() on the path with no consideration for a trailing slash:
self.validate_name(os.path.basename(target), 'directory')
Removing potential trailing slashes would solve the problem:
self.validate_name(os.path.basename(target.rstrip(os.sep)), 'directory')
Add check to ensure max_length fits longest choice.
Description
	
There is currently no check to ensure that Field.max_length is large enough to fit the longest value in Field.choices.
This would be very helpful as often this mistake is not noticed until an attempt is made to save a record with those values that are too long.
pairplot raises KeyError with MultiIndex DataFrame
When trying to pairplot a MultiIndex DataFrame, `pairplot` raises a `KeyError`:

MRE:

```python
import numpy as np
import pandas as pd
import seaborn as sns


data = {
    ("A", "1"): np.random.rand(100),
    ("A", "2"): np.random.rand(100),
    ("B", "1"): np.random.rand(100),
    ("B", "2"): np.random.rand(100),
}
df = pd.DataFrame(data)
sns.pairplot(df)
```

Output:

```
[c:\Users\KLuu\anaconda3\lib\site-packages\seaborn\axisgrid.py](file:///C:/Users/KLuu/anaconda3/lib/site-packages/seaborn/axisgrid.py) in pairplot(data, hue, hue_order, palette, vars, x_vars, y_vars, kind, diag_kind, markers, height, aspect, corner, dropna, plot_kws, diag_kws, grid_kws, size)
   2142     diag_kws.setdefault("legend", False)
   2143     if diag_kind == "hist":
-> 2144         grid.map_diag(histplot, **diag_kws)
   2145     elif diag_kind == "kde":
   2146         diag_kws.setdefault("fill", True)

[c:\Users\KLuu\anaconda3\lib\site-packages\seaborn\axisgrid.py](file:///C:/Users/KLuu/anaconda3/lib/site-packages/seaborn/axisgrid.py) in map_diag(self, func, **kwargs)
   1488                 plt.sca(ax)
   1489 
-> 1490             vector = self.data[var]
   1491             if self._hue_var is not None:
   1492                 hue = self.data[self._hue_var]

[c:\Users\KLuu\anaconda3\lib\site-packages\pandas\core\frame.py](file:///C:/Users/KLuu/anaconda3/lib/site-packages/pandas/core/frame.py) in __getitem__(self, key)
   3765             if is_iterator(key):
   3766                 key = list(key)
-> 3767             indexer = self.columns._get_indexer_strict(key, "columns")[1]
   3768 
   3769         # take() does not accept boolean indexers

[c:\Users\KLuu\anaconda3\lib\site-packages\pandas\core\indexes\multi.py](file:///C:/Users/KLuu/anaconda3/lib/site-packages/pandas/core/indexes/multi.py) in _get_indexer_strict(self, key, axis_name)
   2534             indexer = self._get_indexer_level_0(keyarr)
   2535 
-> 2536             self._raise_if_missing(key, indexer, axis_name)
   2537             return self[indexer], indexer
   2538 

[c:\Users\KLuu\anaconda3\lib\site-packages\pandas\core\indexes\multi.py](file:///C:/Users/KLuu/anaconda3/lib/site-packages/pandas/core/indexes/multi.py) in _raise_if_missing(self, key, indexer, axis_name)
   2552                 cmask = check == -1
   2553                 if cmask.any():
-> 2554                     raise KeyError(f"{keyarr[cmask]} not in index")
   2555                 # We get here when levels still contain values which are not
   2556                 # actually in Index anymore

KeyError: "['1'] not in index"
```

A workaround is to "flatten" the columns:

```python
df.columns = ["".join(column) for column in df.columns]
```
Poly(domain='RR[y,z]') doesn't work
``` py
In [14]: Poly(1.2*x*y*z, x)
Out[14]: Poly(1.2*y*z*x, x, domain='RR[y,z]')

In [15]: Poly(1.2*x*y*z, x, domain='RR[y,z]')
---------------------------------------------------------------------------
OptionError                               Traceback (most recent call last)
<ipython-input-15-d83389519ae1> in <module>()
----> 1 Poly(1.2*x*y*z, x, domain='RR[y,z]')

/Users/aaronmeurer/Documents/Python/sympy/sympy-scratch/sympy/polys/polytools.py in __new__(cls, rep, *gens, **args)
     69     def __new__(cls, rep, *gens, **args):
     70         """Create a new polynomial instance out of something useful. """
---> 71         opt = options.build_options(gens, args)
     72
     73         if 'order' in opt:

/Users/aaronmeurer/Documents/Python/sympy/sympy-scratch/sympy/polys/polyoptions.py in build_options(gens, args)
    718
    719     if len(args) != 1 or 'opt' not in args or gens:
--> 720         return Options(gens, args)
    721     else:
    722         return args['opt']

/Users/aaronmeurer/Documents/Python/sympy/sympy-scratch/sympy/polys/polyoptions.py in __init__(self, gens, args, flags, strict)
    151                     self[option] = cls.preprocess(value)
    152
--> 153         preprocess_options(args)
    154
    155         for key, value in dict(defaults).items():

/Users/aaronmeurer/Documents/Python/sympy/sympy-scratch/sympy/polys/polyoptions.py in preprocess_options(args)
    149
    150                 if value is not None:
--> 151                     self[option] = cls.preprocess(value)
    152
    153         preprocess_options(args)

/Users/aaronmeurer/Documents/Python/sympy/sympy-scratch/sympy/polys/polyoptions.py in preprocess(cls, domain)
    480                 return sympy.polys.domains.QQ.algebraic_field(*gens)
    481
--> 482         raise OptionError('expected a valid domain specification, got %s' % domain)
    483
    484     @classmethod

OptionError: expected a valid domain specification, got RR[y,z]
```

Also, the wording of error message could be improved
Ignore missing variables when concatenating datasets?
Several users (@raj-kesavan, @richardotis, now myself) have wondered about how to concatenate xray Datasets with different variables.

With the current `xray.concat`, you need to awkwardly create dummy variables filled with `NaN` in datasets that don't have them (or drop mismatched variables entirely). Neither of these are great options -- `concat` should have an option (the default?) to take care of this for the user.

This would also be more consistent with `pd.concat`, which takes a more relaxed approach to matching dataframes with different variables (it does an outer join).
LaTeX printer does not use the same order of monomials as pretty and str 
When printing a Poly, the str and pretty printers use the logical order of monomials, from highest to lowest degrees. But latex printer does not. 
```
>>> var('a b c x')
>>> p = Poly([a, 1, b, 2, c, 3], x)
>>> p
Poly(a*x**5 + x**4 + b*x**3 + 2*x**2 + c*x + 3, x, domain='ZZ[a,b,c]')
>>> pretty(p)
"Poly(a*x**5 + x**4 + b*x**3 + 2*x**2 + c*x + 3, x, domain='ZZ[a,b,c]')"
>>> latex(p)
'\\operatorname{Poly}{\\left( a x^{5} + b x^{3} + c x + x^{4} + 2 x^{2} + 3, x, domain=\\mathbb{Z}\\left[a, b, c\\right] \\right)}'
```
Bug in expand of TensorProduct + Workaround + Fix
### Error description
The expansion of a TensorProduct object stops incomplete if summands in the tensor product factors have (scalar) factors, e.g.
```
from sympy import *
from sympy.physics.quantum import *
U = Operator('U')
V = Operator('V')
P = TensorProduct(2*U - V, U + V)
print(P) 
# (2*U - V)x(U + V)
print(P.expand(tensorproduct=True)) 
#result: 2*Ux(U + V) - Vx(U + V) #expansion has missed 2nd tensor factor and is incomplete
```
This is clearly not the expected behaviour. It also effects other functions that rely on .expand(tensorproduct=True), as e.g. qapply() .

### Work around
Repeat .expand(tensorproduct=True) as may times as there are tensor factors, resp. until the expanded term does no longer change. This is however only reasonable in interactive session and not in algorithms.

### Code Fix
.expand relies on the method TensorProduct._eval_expand_tensorproduct(). The issue arises from an inprecise check in TensorProduct._eval_expand_tensorproduct() whether a recursive call is required; it fails when the creation of a TensorProduct object returns commutative (scalar) factors up front: in that case the constructor returns a Mul(c_factors, TensorProduct(..)).
I thus propose the following  code fix in TensorProduct._eval_expand_tensorproduct() in quantum/tensorproduct.py.  I have marked the four lines to be added / modified:
```
    def _eval_expand_tensorproduct(self, **hints):
                ...
                for aa in args[i].args:
                    tp = TensorProduct(*args[:i] + (aa,) + args[i + 1:])
                    c_part, nc_part = tp.args_cnc() #added
                    if len(nc_part)==1 and isinstance(nc_part[0], TensorProduct): #modified
                        nc_part = (nc_part[0]._eval_expand_tensorproduct(), ) #modified
                    add_args.append(Mul(*c_part)*Mul(*nc_part)) #modified
                break
                ...
```
The fix splits of commutative (scalar) factors from the tp returned. The TensorProduct object will be the one nc factor in nc_part (see TensorProduct.__new__ constructor), if any. Note that the constructor will return 0 if a tensor factor is 0, so there is no guarantee that tp contains a TensorProduct object (e.g. TensorProduct(U-U, U+V).
QuerySet.defer() doesn't clear deferred field when chaining with only().
Description
	
Considering a simple Company model with four fields: id, name, trade_number and country. If we evaluate a queryset containing a .defer() following a .only(), the generated sql query selects unexpected fields. For example: 
Company.objects.only("name").defer("name")
loads all the fields with the following query:
SELECT "company"."id", "company"."name", "company"."trade_number", "company"."country" FROM "company"
and 
Company.objects.only("name").defer("name").defer("country")
also loads all the fields with the same query:
SELECT "company"."id", "company"."name", "company"."trade_number", "company"."country" FROM "company"
In those two cases, i would expect the sql query to be:
SELECT "company"."id" FROM "company"
In the following example, we get the expected behavior:
Company.objects.only("name", "country").defer("name")
only loads "id" and "country" fields with the following query:
SELECT "company"."id", "company"."country" FROM "company"
Update colorbar after changing mappable.norm
How can I update a colorbar, after I changed the norm instance of the colorbar?

`colorbar.update_normal(mappable)` has now effect and `colorbar.update_bruteforce(mappable)` throws a `ZeroDivsionError`-Exception.

Consider this example:

``` python
import matplotlib.pyplot as plt
from matplotlib.colors import LogNorm
import numpy as np

img = 10**np.random.normal(1, 1, size=(50, 50))

fig, ax = plt.subplots(1, 1)
plot = ax.imshow(img, cmap='gray')
cb = fig.colorbar(plot, ax=ax)
plot.norm = LogNorm()
cb.update_normal(plot)  # no effect
cb.update_bruteforce(plot)  # throws ZeroDivisionError
plt.show()
```

Output for `cb.update_bruteforce(plot)`:

```
Traceback (most recent call last):
  File "test_norm.py", line 12, in <module>
    cb.update_bruteforce(plot)
  File "/home/maxnoe/.local/anaconda3/lib/python3.4/site-packages/matplotlib/colorbar.py", line 967, in update_bruteforce
    self.draw_all()
  File "/home/maxnoe/.local/anaconda3/lib/python3.4/site-packages/matplotlib/colorbar.py", line 342, in draw_all
    self._process_values()
  File "/home/maxnoe/.local/anaconda3/lib/python3.4/site-packages/matplotlib/colorbar.py", line 664, in _process_values
    b = self.norm.inverse(self._uniform_y(self.cmap.N + 1))
  File "/home/maxnoe/.local/anaconda3/lib/python3.4/site-packages/matplotlib/colors.py", line 1011, in inverse
    return vmin * ma.power((vmax / vmin), val)
ZeroDivisionError: division by zero
```
Using __isnull=True on a KeyTransform should not match JSON null on SQLite and Oracle
Description
	
The KeyTransformIsNull lookup borrows the logic from HasKey for isnull=False, which is correct. If isnull=True, the query should only match objects that do not have the key. The query is correct for MariaDB, MySQL, and PostgreSQL. However, on SQLite and Oracle, the query also matches objects that have the key with the value null, which is incorrect.
To confirm, edit tests.model_fields.test_jsonfield.TestQuerying.test_isnull_key. For the first assertion, change
		self.assertSequenceEqual(
			NullableJSONModel.objects.filter(value__a__isnull=True),
			self.objs[:3] + self.objs[5:],
		)
to
		self.assertSequenceEqual(
			NullableJSONModel.objects.filter(value__j__isnull=True),
			self.objs[:4] + self.objs[5:],
		)
The test previously only checks with value__a which could not catch this behavior because the value is not JSON null.
`Session.resolve_redirects` copies the original request for all subsequent requests, can cause incorrect method selection
Consider the following redirection chain:

```
POST /do_something HTTP/1.1
Host: server.example.com
...

HTTP/1.1 303 See Other
Location: /new_thing_1513

GET /new_thing_1513
Host: server.example.com
...

HTTP/1.1 307 Temporary Redirect
Location: //failover.example.com/new_thing_1513
```

The intermediate 303 See Other has caused the POST to be converted to
a GET.  The subsequent 307 should preserve the GET.  However, because
`Session.resolve_redirects` starts each iteration by copying the _original_
request object, Requests will issue a POST!
pytest --collect-only needs a one char shortcut command
I find myself needing to run `--collect-only` very often and that cli argument is a very long to type one. 

I do think that it would be great to allocate a character for it, not sure which one yet. Please use up/down thumbs to vote if you would find it useful or not and eventually proposing which char should be used. 

Clearly this is a change very easy to implement but first I want to see if others would find it useful or not.
pytest --collect-only needs a one char shortcut command
I find myself needing to run `--collect-only` very often and that cli argument is a very long to type one. 

I do think that it would be great to allocate a character for it, not sure which one yet. Please use up/down thumbs to vote if you would find it useful or not and eventually proposing which char should be used. 

Clearly this is a change very easy to implement but first I want to see if others would find it useful or not.
sympy.polys.factortools.dmp_zz_mignotte_bound improvement
The method `dup_zz_mignotte_bound(f, K)` can be significantly improved by using the **Knuth-Cohen bound** instead. After our research with Prof. Ag.Akritas we have implemented the Knuth-Cohen bound among others, and compare them among dozens of polynomials with different degree, density and coefficients range. Considering the results and the feedback from Mr.Kalevi Suominen, our proposal is that the mignotte_bound should be replaced by the knuth-cohen bound.
Also, `dmp_zz_mignotte_bound(f, u, K)` for mutli-variants polynomials should be replaced appropriately.