mteb/SWEbenchLiteRR huggingface dataset:
Display of SeqFormula()
```
import sympy as sp
k, m, n = sp.symbols('k m n', integer=True)
sp.init_printing()

sp.SeqFormula(n**2, (n,0,sp.oo))
```

The Jupyter rendering of this command backslash-escapes the brackets producing:

`\left\[0, 1, 4, 9, \ldots\right\]`

Copying this output to a markdown cell this does not render properly.  Whereas:

`[0, 1, 4, 9, \ldots ]`

does render just fine.  

So - sequence output should not backslash-escape square brackets, or, `\]` should instead render?
regression in input validation of clustering metrics
```python
from sklearn.metrics.cluster import mutual_info_score
import numpy as np

x = np.random.choice(['a', 'b'], size=20).astype(object)
mutual_info_score(x, x)
```
ValueError: could not convert string to float: 'b'

while
```python
x = np.random.choice(['a', 'b'], size=20)
mutual_info_score(x, x)
```
works with a warning?

this worked in 0.21.1 without a warning (as I think it should)


Edit by @ogrisel: I removed the `.astype(object)` in the second code snippet.
Bug: maximum recusion depth error when checking is_zero of cosh expression
The following code causes a `RecursionError: maximum recursion depth exceeded while calling a Python object` error when checked if it is zero:
```
expr =sympify("cosh(acos(-i + acosh(-g + i)))")
expr.is_zero
```
Subquery.as_sql() generates invalid SQL.
Description
	 
		(last modified by M1ha Shvn)
	 
Since ​this commit Subquery.as_sql(...) method returns incorrect SQL removing first and last symbols instead of absent breakets. Adding Subquery().query.subquery = True attribute fixes the problem. From my point of view, it should be set in Subquery constructor.
from django.db import connection
from apps.models import App
q = Subquery(App.objects.all())
print(str(q.query))
# Output SQL is valid:
# 'SELECT "apps_app"."id", "apps_app"."name" FROM "apps_app"'
print(q.as_sql(q.query.get_compiler('default'), connection))
# Outptut SQL is invalid (no S letter at the beggining and " symbol at the end):
# ('(ELECT "apps_app"."id", "apps_app"."name" FROM "apps_app)', ())
q.query.subquery = True
print(q.as_sql(q.query.get_compiler('default'), connection))
# Outputs correct result
('(SELECT "apps_app"."id", "apps_app"."name" FROM "apps_app")', ())
Customizable management command formatters.
Description
	
With code like:
class Command(BaseCommand):
	help = '''
	Import a contract from tzkt.
	Example usage:
		./manage.py tzkt_import 'Tezos Mainnet' KT1HTDtMBRCKoNHjfWEEvXneGQpCfPAt6BRe
	'''
Help output is:
$ ./manage.py help tzkt_import
usage: manage.py tzkt_import [-h] [--api API] [--version] [-v {0,1,2,3}] [--settings SETTINGS]
							 [--pythonpath PYTHONPATH] [--traceback] [--no-color] [--force-color]
							 [--skip-checks]
							 blockchain target
Import a contract from tzkt Example usage: ./manage.py tzkt_import 'Tezos Mainnet'
KT1HTDtMBRCKoNHjfWEEvXneGQpCfPAt6BRe
positional arguments:
 blockchain			Name of the blockchain to import into
 target				Id of the contract to import
When that was expected:
$ ./manage.py help tzkt_import
usage: manage.py tzkt_import [-h] [--api API] [--version] [-v {0,1,2,3}] [--settings SETTINGS]
							 [--pythonpath PYTHONPATH] [--traceback] [--no-color] [--force-color]
							 [--skip-checks]
							 blockchain target
Import a contract from tzkt 
Example usage: 
	./manage.py tzkt_import 'Tezos Mainnet' KT1HTDtMBRCKoNHjfWEEvXneGQpCfPAt6BRe
positional arguments:
 blockchain			Name of the blockchain to import into
 target				Id of the contract to import
Rendering empty_form crashes when empty_permitted is passed to form_kwargs
Description
	
Issue
When explicitly setting form_kwargs = {'empty_permitted':True} or form_kwargs = {'empty_permitted':False} , a KeyError occurs when rendering a template that uses a formset's empty_form.
Expected Behavior
empty_permitted is ignored for formset.empty_form since empty_permitted is irrelevant for empty_form, as empty_form is not meant to be used to pass data and therefore does not need to be validated.
Steps to Reproduce
# views.py
from django.shortcuts import render
from .models import MyModel
def test_view(request):
	context = {}
	ff = modelformset_factory(MyModel, fields = ['a_field'])
	context['formset'] = ff(
		queryset = MyModel.objects.none(),
		form_kwargs = {'empty_permitted':True} # or form_kwargs = {'empty_permitted':False}
	)
	return render(request, 'my_app/my_model_formset.html', context)
# urls.py
from django.urls import path, include
from .views import test_view
urlpatterns = [
	path('test', test_view)
]
# my_model_formset.html
{% extends "my_app/base.html" %}
{% block content %}
<form id="my-form" method="post">
 {% csrf_token %}
 {{ formset }}
 <input type="submit" value="Save">
</form>
{{ formset.empty_form }}
{% endblock %}
Added model class to app_list context
Description
	 
		(last modified by Raffaele Salmaso)
	 
I need to manipulate the app_list in my custom admin view, and the easiest way to get the result is to have access to the model class (currently the dictionary is a serialized model).
In addition I would make the _build_app_dict method public, as it is used by the two views index and app_index.
can't simplify sin/cos with Rational?
latest cloned sympy, python 3 on windows
firstly, cos, sin with symbols can be simplified; rational number can be simplified
```python
from sympy import *

x, y = symbols('x, y', real=True)
r = sin(x)*sin(y) + cos(x)*cos(y)
print(r)
print(r.simplify())
print()

r = Rational(1, 50) - Rational(1, 25)
print(r)
print(r.simplify())
print()
```
says
```cmd
sin(x)*sin(y) + cos(x)*cos(y)
cos(x - y)

-1/50
-1/50
```

but
```python
t1 = Matrix([sin(Rational(1, 50)), cos(Rational(1, 50)), 0])
t2 = Matrix([sin(Rational(1, 25)), cos(Rational(1, 25)), 0])
r = t1.dot(t2)
print(r)
print(r.simplify())
print()

r = sin(Rational(1, 50))*sin(Rational(1, 25)) + cos(Rational(1, 50))*cos(Rational(1, 25))
print(r)
print(r.simplify())
print()

print(acos(r))
print(acos(r).simplify())
print()
```
says
```cmd
sin(1/50)*sin(1/25) + cos(1/50)*cos(1/25)
sin(1/50)*sin(1/25) + cos(1/50)*cos(1/25)

sin(1/50)*sin(1/25) + cos(1/50)*cos(1/25)
sin(1/50)*sin(1/25) + cos(1/50)*cos(1/25)

acos(sin(1/50)*sin(1/25) + cos(1/50)*cos(1/25))
acos(sin(1/50)*sin(1/25) + cos(1/50)*cos(1/25))
```
Bug with milli prefix
What happened:
```
In [1]: from sympy.physics.units import milli, W
In [2]: milli*W == 1
Out[2]: True
In [3]: W*milli
Out[3]: watt*Prefix(milli, m, -3, 10)
```
What I expected to happen: milli*W should evaluate to milli watts / mW

`milli*W` or more generally `milli` times some unit evaluates to the number 1. I have tried this with Watts and Volts, I'm not sure what other cases this happens. I'm using sympy version 1.11.1-1 on Arch Linux with Python 3.10.9. If you cannot reproduce I would be happy to be of any assitance.
BlockDiagMatrix with one element cannot be converted to regular Matrix
Creating a BlockDiagMatrix with one Matrix element will raise if trying to convert it back to a regular Matrix:

```python
M = sympy.Matrix([[1, 2], [3, 4]])
D = sympy.BlockDiagMatrix(M)
B = sympy.Matrix(D)
```

```
Traceback (most recent call last):

  File "<ipython-input-37-5b65c1f8f23e>", line 3, in <module>
    B = sympy.Matrix(D)

  File "/home/rikard/.local/lib/python3.7/site-packages/sympy/matrices/dense.py", line 430, in __new__
    return cls._new(*args, **kwargs)

  File "/home/rikard/.local/lib/python3.7/site-packages/sympy/matrices/dense.py", line 442, in _new
    rows, cols, flat_list = cls._handle_creation_inputs(*args, **kwargs)

  File "/home/rikard/.local/lib/python3.7/site-packages/sympy/matrices/matrices.py", line 2528, in _handle_creation_inputs
    return args[0].rows, args[0].cols, args[0].as_explicit()._mat

  File "/home/rikard/.local/lib/python3.7/site-packages/sympy/matrices/expressions/matexpr.py", line 340, in as_explicit
    for i in range(self.rows)])

  File "/home/rikard/.local/lib/python3.7/site-packages/sympy/matrices/expressions/matexpr.py", line 340, in <listcomp>
    for i in range(self.rows)])

  File "/home/rikard/.local/lib/python3.7/site-packages/sympy/matrices/expressions/matexpr.py", line 339, in <listcomp>
    for j in range(self.cols)]

  File "/home/rikard/.local/lib/python3.7/site-packages/sympy/matrices/expressions/matexpr.py", line 289, in __getitem__
    return self._entry(i, j)

  File "/home/rikard/.local/lib/python3.7/site-packages/sympy/matrices/expressions/blockmatrix.py", line 248, in _entry
    return self.blocks[row_block, col_block][i, j]

TypeError: 'One' object is not subscriptable
```

Instead having two elements will work as expected:

```python
M = sympy.Matrix([[1, 2], [3, 4]])
D = sympy.BlockDiagMatrix(M, M)
B = sympy.Matrix(D)
```

```
Matrix([
[1, 2, 0, 0],
[3, 4, 0, 0],
[0, 0, 1, 2],
[0, 0, 3, 4]])
```
This issue exists for sympy 1.5.1 but not for sympy 1.4
display bug while using pretty_print with sympy.vector object in the terminal
The following code jumbles some of the outputs in the terminal, essentially by inserting the unit vector in the middle -
```python
from sympy import *
from sympy.vector import CoordSys3D, Del

init_printing()

delop = Del()
CC_ = CoordSys3D("C")
x,    y,    z    = CC_.x, CC_.y, CC_.z
xhat, yhat, zhat = CC_.i, CC_.j, CC_.k

t = symbols("t")
ten = symbols("10", positive=True)
eps, mu = 4*pi*ten**(-11), ten**(-5)

Bx = 2 * ten**(-4) * cos(ten**5 * t) * sin(ten**(-3) * y)
vecB = Bx * xhat
vecE = (1/eps) * Integral(delop.cross(vecB/mu).doit(), t)

pprint(vecB)
print()
pprint(vecE)
print()
pprint(vecE.doit())
```

Output:
```python
⎛     ⎛y_C⎞    ⎛  5  ⎞⎞    
⎜2⋅sin⎜───⎟ i_C⋅cos⎝10 ⋅t⎠⎟
⎜     ⎜  3⎟           ⎟    
⎜     ⎝10 ⎠           ⎟    
⎜─────────────────────⎟    
⎜           4         ⎟    
⎝         10          ⎠    

⎛     ⌠                           ⎞    
⎜     ⎮       ⎛y_C⎞    ⎛  5  ⎞    ⎟ k_C
⎜     ⎮ -2⋅cos⎜───⎟⋅cos⎝10 ⋅t⎠    ⎟    
⎜     ⎮       ⎜  3⎟               ⎟    
⎜  11 ⎮       ⎝10 ⎠               ⎟    
⎜10  ⋅⎮ ─────────────────────── dt⎟    
⎜     ⎮             2             ⎟    
⎜     ⎮           10              ⎟    
⎜     ⌡                           ⎟    
⎜─────────────────────────────────⎟    
⎝               4⋅π               ⎠    

⎛   4    ⎛  5  ⎞    ⎛y_C⎞ ⎞    
⎜-10 ⋅sin⎝10 ⋅t⎠⋅cos⎜───⎟ k_C ⎟
⎜                   ⎜  3⎟ ⎟    
⎜                   ⎝10 ⎠ ⎟    
⎜─────────────────────────⎟    
⎝           2⋅π           ⎠    ```
inaccurate rendering of pi**(1/E)
This claims to be version 1.5.dev; I just merged from the project master, so I hope this is current.  I didn't notice this bug among others in printing.pretty.

```
In [52]: pi**(1/E)                                                               
Out[52]: 
-1___
╲╱ π 

```
LaTeX and str not fooled:
```
In [53]: print(latex(pi**(1/E)))                                                 
\pi^{e^{-1}}

In [54]: str(pi**(1/E))                                                          
Out[54]: 'pi**exp(-1)'
```
Incorrect caching of skipif/xfail string condition evaluation
Version: pytest 5.4.3, current master

pytest caches the evaluation of the string in e.g. `@pytest.mark.skipif("sys.platform == 'win32'")`. The caching key is only the string itself (see `cached_eval` in `_pytest/mark/evaluate.py`). However, the evaluation also depends on the item's globals, so the caching can lead to incorrect results. Example:

```py
# test_module_1.py
import pytest

skip = True

@pytest.mark.skipif("skip")
def test_should_skip():
    assert False
```

```py
# test_module_2.py
import pytest

skip = False

@pytest.mark.skipif("skip")
def test_should_not_skip():
    assert False
```

Running `pytest test_module_1.py test_module_2.py`.

Expected: `test_should_skip` is skipped, `test_should_not_skip` is not skipped.

Actual: both are skipped.

---

I think the most appropriate fix is to simply remove the caching, which I don't think is necessary really, and inline `cached_eval` into `MarkEvaluator._istrue`.
autodoc_typehints does not effect to overloaded callables
**Describe the bug**
autodoc_typehints does not effect to overloaded callables.

**To Reproduce**

```
# in conf.py
autodoc_typehints = 'none'
```
```
# in index.rst
.. automodule:: example
   :members:
   :undoc-members:
```
```
# in example.py
from typing import overload


@overload
def foo(x: int) -> int:
    ...


@overload
def foo(x: float) -> float:
    ...


def foo(x):
    return x
```

**Expected behavior**
All typehints for overloaded callables are obeyed `autodoc_typehints` setting.

**Your project**
No

**Screenshots**
No

**Environment info**
- OS: Mac
- Python version: 3.8.2
- Sphinx version: 3.1.0dev
- Sphinx extensions: sphinx.ext.autodoc
- Extra tools: No

**Additional context**
No
DataSet.update causes chunked dask DataArray to evalute its values eagerly 
**What happened**:
Used `DataSet.update` to update a chunked dask DataArray, but the DataArray is no longer chunked after the update.

**What you expected to happen**:
The chunked DataArray should still be chunked after the update

**Minimal Complete Verifiable Example**:

```python
foo = xr.DataArray(np.random.randn(3, 3), dims=("x", "y")).chunk()  # foo is chunked
ds = xr.Dataset({"foo": foo, "bar": ("x", [1, 2, 3])})  # foo is still chunked here
ds  # you can verify that foo is chunked
```
```python
update_dict = {"foo": (("x", "y"), ds.foo[1:, :]), "bar": ("x", ds.bar[1:])}
update_dict["foo"][1]  # foo is still chunked
```
```python
ds.update(update_dict)
ds  # now foo is no longer chunked
```

**Environment**:

<details><summary>Output of <tt>xr.show_versions()</tt></summary>

```
commit: None
python: 3.8.3 (default, Jul  2 2020, 11:26:31) 
[Clang 10.0.0 ]
python-bits: 64
OS: Darwin
OS-release: 19.6.0
machine: x86_64
processor: i386
byteorder: little
LC_ALL: None
LANG: en_US.UTF-8
LOCALE: en_US.UTF-8
libhdf5: 1.10.6
libnetcdf: None

xarray: 0.16.0
pandas: 1.0.5
numpy: 1.18.5
scipy: 1.5.0
netCDF4: None
pydap: None
h5netcdf: None
h5py: 2.10.0
Nio: None
zarr: None
cftime: None
nc_time_axis: None
PseudoNetCDF: None
rasterio: None
cfgrib: None
iris: None
bottleneck: None
dask: 2.20.0
distributed: 2.20.0
matplotlib: 3.2.2
cartopy: None
seaborn: None
numbagg: None
pint: None
setuptools: 49.2.0.post20200714
pip: 20.1.1
conda: None
pytest: 5.4.3
IPython: 7.16.1
sphinx: None
```

</details>
Dataset constructor with DataArray triggers computation
Is it intentional that creating a Dataset with a DataArray and dimension names for a single variable causes computation of that variable?  In other words, why does ```xr.Dataset(dict(a=('d0', xr.DataArray(da.random.random(10)))))``` cause the dask array to compute?

A longer example:

```python
import dask.array as da
import xarray as xr
x = da.random.randint(1, 10, size=(100, 25))
ds = xr.Dataset(dict(a=xr.DataArray(x, dims=('x', 'y'))))
type(ds.a.data)
dask.array.core.Array

# Recreate the dataset with the same array, but also redefine the dimensions
ds2 = xr.Dataset(dict(a=(('x', 'y'), ds.a))
type(ds2.a.data)
numpy.ndarray
```
Issue with a substitution that leads to an undefined expression
```
Python 3.6.4 |Anaconda custom (64-bit)| (default, Dec 21 2017, 15:39:08) 
Type 'copyright', 'credits' or 'license' for more information
IPython 6.2.1 -- An enhanced Interactive Python. Type '?' for help.

In [1]: from sympy import *

In [2]: a,b = symbols('a,b')

In [3]: r = (1/(a+b) + 1/(a-b))/(1/(a+b) - 1/(a-b))

In [4]: r.subs(b,a)
Out[4]: 1

In [6]: import sympy

In [7]: sympy.__version__
Out[7]: '1.1.1'
```

If b is substituted by a, r is undefined. It is possible to calculate the limit
`r.limit(b,a) # -1`

But whenever a subexpression of r is undefined, r itself is undefined.
Add easily comparable version info to toplevel
<!--
Welcome! Thanks for thinking of a way to improve Matplotlib.


Before creating a new feature request please search the issues for relevant feature requests.
-->

### Problem

Currently matplotlib only exposes `__version__`.  For quick version checks, exposing either a `version_info` tuple (which can be compared with other tuples) or a `LooseVersion` instance (which can be properly compared with other strings) would be a small usability improvement.

(In practice I guess boring string comparisons will work just fine until we hit mpl 3.10 or 4.10 which is unlikely to happen soon, but that feels quite dirty :))
<!--
Provide a clear and concise description of the problem this feature will solve. 

For example:
* I'm always frustrated when [...] because [...]
* I would like it if [...] happened when I [...] because [...]
* Here is a sample image of what I am asking for [...]
-->

### Proposed Solution

I guess I slightly prefer `LooseVersion`, but exposing just a `version_info` tuple is much more common in other packages (and perhaps simpler to understand).  The hardest(?) part is probably just bikeshedding this point :-)
<!-- Provide a clear and concise description of a way to accomplish what you want. For example:

* Add an option so that when [...]  [...] will happen
 -->

### Additional context and prior art

`version_info` is a pretty common thing (citation needed).
<!-- Add any other context or screenshots about the feature request here. You can also include links to examples of other programs that have something similar to your request. For example:

* Another project [...] solved this by [...]
-->
[Bug]: scalar mappable format_cursor_data crashes on BoundarNorm
### Bug summary

In 3.5.0 if you do:

```python
import matplotlib.pyplot as plt
import numpy as np
import matplotlib as mpl

fig, ax = plt.subplots()
norm = mpl.colors.BoundaryNorm(np.linspace(-4, 4, 5), 256)
X = np.random.randn(10, 10)
pc = ax.imshow(X, cmap='RdBu_r', norm=norm)
```

and mouse over the image, it crashes with

```
File "/Users/jklymak/matplotlib/lib/matplotlib/artist.py", line 1282, in format_cursor_data
    neighbors = self.norm.inverse(
  File "/Users/jklymak/matplotlib/lib/matplotlib/colors.py", line 1829, in inverse
    raise ValueError("BoundaryNorm is not invertible")
ValueError: BoundaryNorm is not invertible
```

and interaction stops.  

Not sure if we should have a special check here, a try-except, or actually just make BoundaryNorm approximately invertible.  


### Matplotlib Version

main 3.5.0


[Bug]: scalar mappable format_cursor_data crashes on BoundarNorm
### Bug summary

In 3.5.0 if you do:

```python
import matplotlib.pyplot as plt
import numpy as np
import matplotlib as mpl

fig, ax = plt.subplots()
norm = mpl.colors.BoundaryNorm(np.linspace(-4, 4, 5), 256)
X = np.random.randn(10, 10)
pc = ax.imshow(X, cmap='RdBu_r', norm=norm)
```

and mouse over the image, it crashes with

```
File "/Users/jklymak/matplotlib/lib/matplotlib/artist.py", line 1282, in format_cursor_data
    neighbors = self.norm.inverse(
  File "/Users/jklymak/matplotlib/lib/matplotlib/colors.py", line 1829, in inverse
    raise ValueError("BoundaryNorm is not invertible")
ValueError: BoundaryNorm is not invertible
```

and interaction stops.  

Not sure if we should have a special check here, a try-except, or actually just make BoundaryNorm approximately invertible.  


### Matplotlib Version

main 3.5.0
"--notes" option ignores note tags that are entirely punctuation
### Bug description

If a note tag specified with the `--notes` option is entirely punctuation, pylint won't report a fixme warning (W0511).

```python
# YES: yes
# ???: no
```

`pylint test.py --notes="YES,???"` will return a fixme warning (W0511) for the first line, but not the second.

### Configuration

```ini
Default
```


### Command used

```shell
pylint test.py --notes="YES,???"
```


### Pylint output

```shell
************* Module test
test.py:1:1: W0511: YES: yes (fixme)
```


### Expected behavior

```
************* Module test
test.py:1:1: W0511: YES: yes (fixme)
test.py:2:1: W0511: ???: no (fixme)
```

### Pylint version

```shell
pylint 2.12.2
astroid 2.9.0
Python 3.10.2 (main, Feb  2 2022, 05:51:25) [Clang 13.0.0 (clang-1300.0.29.3)]
```


### OS / Environment

macOS 11.6.1

### Additional dependencies

_No response_
[Bug]: Constrained layout UserWarning even when False
### Bug summary

When using layout settings such as `plt.subplots_adjust` or `bbox_inches='tight`, a UserWarning is produced due to incompatibility with constrained_layout, even if constrained_layout = False. This was not the case in previous versions.

### Code for reproduction

```python
import matplotlib.pyplot as plt
import numpy as np
a = np.linspace(0,2*np.pi,100)
b = np.sin(a)
c = np.cos(a)
fig,ax = plt.subplots(1,2,figsize=(8,2),constrained_layout=False)
ax[0].plot(a,b)
ax[1].plot(a,c)
plt.subplots_adjust(wspace=0)
```


### Actual outcome

The plot works fine but the warning is generated

`/var/folders/ss/pfgdfm2x7_s4cyw2v0b_t7q80000gn/T/ipykernel_76923/4170965423.py:7: UserWarning: This figure was using a layout engine that is incompatible with subplots_adjust and/or tight_layout; not calling subplots_adjust.
  plt.subplots_adjust(wspace=0)`

### Expected outcome

no warning

### Additional information

Warning disappears when constrained_layout=False is removed

### Operating system

OS/X

### Matplotlib Version

3.6.0

### Matplotlib Backend

_No response_

### Python version

_No response_

### Jupyter version

_No response_

### Installation

conda
simplifying exponential -> trig identities
```
f = 1 / 2 * (-I*exp(I*k) + I*exp(-I*k))
trigsimp(f)
```

Ideally, this would yield `sin(k)`. Is there a way to do this?

As a corollary, it would be awesome if 

```
f = 1 / 2 / k* (-I*exp(I*k) + I*exp(-I*k))
trigsimp(f)
```

could yield `sinc(k)`. Thank you for your consideration!
check_for_template_tags_with_the_same_name with libraries in TEMPLATES
Description
	
I didn't explore this thoroughly, but I think there might be an issue with the check_for_template_tags_with_the_same_name when you add a template tag library into TEMPLATES['OPTIONS']['librairies'].
I'm getting an error like: 
(templates.E003) 'my_tags' is used for multiple template tag modules: 'someapp.templatetags.my_tags', 'someapp.templatetags.my_tags'
Migration auth.0011_update_proxy_permissions fails for models recreated as a proxy.
Description
	 
		(last modified by Mariusz Felisiak)
	 
I am trying to update my project to Django 2.2. When I launch python manage.py migrate, I get this error message when migration auth.0011_update_proxy_permissions is applying (full stacktrace is available ​here):
django.db.utils.IntegrityError: duplicate key value violates unique constraint "idx_18141_auth_permission_content_type_id_01ab375a_uniq" DETAIL: Key (co.ntent_type_id, codename)=(12, add_agency) already exists.
It looks like the migration is trying to re-create already existing entries in the auth_permission table. At first I though it cloud because we recently renamed a model. But after digging and deleting the entries associated with the renamed model from our database in the auth_permission table, the problem still occurs with other proxy models.
I tried to update directly from 2.0.13 and 2.1.8. The issues appeared each time. I also deleted my venv and recreated it without an effect.
I searched for a ticket about this on the bug tracker but found nothing. I also posted this on ​django-users and was asked to report this here.
autodoc: The annotation only member in superclass is treated as "undocumented"
**Describe the bug**
autodoc: The annotation only member in superclass is treated as "undocumented".

**To Reproduce**

```
# example.py
class Foo:
    """docstring"""
    attr1: int  #: docstring


class Bar(Foo):
    """docstring"""
    attr2: str  #: docstring
```
```
# index.rst
.. autoclass:: example.Bar
   :members:
   :inherited-members:
```

`Bar.attr1` is not documented. It will be shown if I give `:undoc-members:` option to the autoclass directive call. It seems the attribute is treated as undocumented.

**Expected behavior**
It should be shown.

**Your project**
No

**Screenshots**
No

**Environment info**
- OS: Mac
- Python version: 3.9.1
- Sphinx version: HEAD of 3.x
- Sphinx extensions: sphinx.ext.autodoc
- Extra tools: No

**Additional context**
No
[Bug]: using clf and pyplot.draw in range slider on_changed callback blocks input to widgets
### Bug summary

When using clear figure, adding new widgets and then redrawing the current figure in the on_changed callback of a range slider the inputs to all the widgets in the figure are blocked. When doing the same in the button callback on_clicked, everything works fine.

### Code for reproduction

```python
import matplotlib.pyplot as pyplot
import matplotlib.widgets as widgets

def onchanged(values):
    print("on changed")
    print(values)
    pyplot.clf()
    addElements()
    pyplot.draw()

def onclick(e):
    print("on click")
    pyplot.clf()
    addElements()
    pyplot.draw()

def addElements():
    ax = pyplot.axes([0.1, 0.45, 0.8, 0.1])
    global slider
    slider = widgets.RangeSlider(ax, "Test", valmin=1, valmax=10, valinit=(1, 10))
    slider.on_changed(onchanged)
    ax = pyplot.axes([0.1, 0.30, 0.8, 0.1])
    global button
    button = widgets.Button(ax, "Test")
    button.on_clicked(onclick)

addElements()

pyplot.show()
```


### Actual outcome

The widgets can't receive any input from a mouse click, when redrawing in the on_changed callback of a range Slider. 
When using a button, there is no problem.

### Expected outcome

The range slider callback on_changed behaves the same as the button callback on_clicked.

### Additional information

The problem also occurred on Manjaro with:
- Python version: 3.10.9
- Matplotlib version: 3.6.2
- Matplotlib backend: QtAgg
- Installation of matplotlib via Linux package manager


### Operating system

Windows 10

### Matplotlib Version

3.6.2

### Matplotlib Backend

TkAgg

### Python version

3.11.0

### Jupyter version

_No response_

### Installation

pip
tmpdir creation fails when the username contains illegal characters for directory names
`tmpdir`, `tmpdir_factory` and `tmp_path_factory` rely on `getpass.getuser()` for determining the `basetemp` directory. I found that the user name returned by `getpass.getuser()` may return characters that are not allowed for directory names. This may lead to errors while creating the temporary directory.

The situation in which I reproduced this issue was while being logged in through an ssh connection into my Windows 10 x64 Enterprise version (1909) using an OpenSSH_for_Windows_7.7p1 server. In this configuration the command `python -c "import getpass; print(getpass.getuser())"` returns my domain username e.g. `contoso\john_doe` instead of `john_doe` as when logged in regularly using a local session.

When trying to create a temp directory in pytest through e.g. `tmpdir_factory.mktemp('foobar')` this fails with the following error message:
```
self = WindowsPath('C:/Users/john_doe/AppData/Local/Temp/pytest-of-contoso/john_doe')
mode = 511, parents = False, exist_ok = True

    def mkdir(self, mode=0o777, parents=False, exist_ok=False):
        """
        Create a new directory at this given path.
        """
        if self._closed:
            self._raise_closed()
        try:
>           self._accessor.mkdir(self, mode)
E           FileNotFoundError: [WinError 3] The system cannot find the path specified: 'C:\\Users\\john_doe\\AppData\\Local\\Temp\\pytest-of-contoso\\john_doe'

C:\Python38\lib\pathlib.py:1266: FileNotFoundError
```

I could also reproduce this without the complicated ssh/windows setup with pytest 6.2.2 using the following commands from a `cmd`:
```bat
echo def test_tmpdir(tmpdir):>test_tmp.py
echo   pass>>test_tmp.py
set LOGNAME=contoso\john_doe
py.test test_tmp.py
```

Thanks for having a look at this!
Wrong path to test file when directory changed in fixture
Files are shown as relative to new directory when working directory is changed in a fixture. This makes it impossible to jump to the error as the editor is unaware of the directory change. The displayed directory should stay relative to the original directory.

test_path_error.py:
```python
import os
import errno
import shutil

import pytest


@pytest.fixture
def private_dir():  # or (monkeypatch)
    out_dir = 'ddd'

    try:
        shutil.rmtree(out_dir)
    except OSError as ex:
        if ex.errno != errno.ENOENT:
            raise
    os.mkdir(out_dir)

    old_dir = os.getcwd()
    os.chdir(out_dir)
    yield out_dir
    os.chdir(old_dir)

    # Same issue if using:
    # monkeypatch.chdir(out_dir)


def test_show_wrong_path(private_dir):
    assert False
```

```diff
+ Expected: test_path_error.py:29: AssertionError
- Displayed: ../test_path_error.py:29: AssertionError
```

The full output is:
```
-*- mode: compilation; default-directory: "~/src/pytest_path_error/" -*-
Compilation started at Fri Jan 10 00:05:52

nox
nox > Running session test
nox > Creating virtual environment (virtualenv) using python3.7 in .nox/test
nox > pip install pytest>=5.3
nox > pip freeze
attrs==19.3.0
importlib-metadata==1.3.0
more-itertools==8.0.2
packaging==20.0
pluggy==0.13.1
py==1.8.1
pyparsing==2.4.6
pytest==5.3.2
six==1.13.0
wcwidth==0.1.8
zipp==0.6.0
nox > pytest 
================================= test session starts =================================
platform linux -- Python 3.7.5, pytest-5.3.2, py-1.8.1, pluggy-0.13.1
rootdir: /home/lhn/src/pytest_path_error
collected 1 item                                                                      

test_path_error.py F                                                            [100%]

====================================== FAILURES =======================================
________________________________ test_show_wrong_path _________________________________

private_dir = 'ddd'

    def test_show_wrong_path(private_dir):
>       assert False
E       assert False

../test_path_error.py:29: AssertionError
================================== 1 failed in 0.03s ==================================
nox > Command pytest  failed with exit code 1
nox > Session test failed.

Compilation exited abnormally with code 1 at Fri Jan 10 00:06:01
```

noxfile.py:
```python
import nox

@nox.session(python='3.7')
def test(session):
    session.install('pytest>=5.3')
    session.run('pip', 'freeze')
    session.run('pytest')
```
translation.E004 shouldn't be raised on sublanguages when a base language is available.
Description
	
According to Django documentation:
If a base language is available but the sublanguage specified is not, Django uses the base language. For example, if a user specifies de-at (Austrian German) but Django only has de available, Django uses de.
However, when using Django 3.0.2, if my settings.py has
LANGUAGE_CODE = "de-at"
I get this error message:
SystemCheckError: System check identified some issues:
ERRORS:
?: (translation.E004) You have provided a value for the LANGUAGE_CODE setting that is not in the LANGUAGES setting.
If using
LANGUAGE_CODE = "es-ar"
Django works fine (es-ar is one of the translations provided out of the box).
napoleon_use_param should also affect "other parameters" section
Subject: napoleon_use_param should also affect "other parameters" section

### Problem
Currently, napoleon always renders the Other parameters section as if napoleon_use_param was False, see source
```
    def _parse_other_parameters_section(self, section):
        # type: (unicode) -> List[unicode]
        return self._format_fields(_('Other Parameters'), self._consume_fields())

    def _parse_parameters_section(self, section):
        # type: (unicode) -> List[unicode]
        fields = self._consume_fields()
        if self._config.napoleon_use_param:
            return self._format_docutils_params(fields)
        else:
            return self._format_fields(_('Parameters'), fields)
```
whereas it would make sense that this section should follow the same formatting rules as the Parameters section.

#### Procedure to reproduce the problem
```
In [5]: print(str(sphinx.ext.napoleon.NumpyDocstring("""\ 
   ...: Parameters 
   ...: ---------- 
   ...: x : int 
   ...:  
   ...: Other parameters 
   ...: ---------------- 
   ...: y: float 
   ...: """)))                                                                                                                                                                                      
:param x:
:type x: int

:Other Parameters: **y** (*float*)
```

Note the difference in rendering.

#### Error logs / results
See above.

#### Expected results
```
:param x:
:type x: int

:Other Parameters:  // Or some other kind of heading.
:param: y
:type y: float
```

Alternatively another separate config value could be introduced, but that seems a bit overkill.

### Reproducible project / your project
N/A

### Environment info
- OS: Linux
- Python version: 3.7
- Sphinx version: 1.8.1
Log exceptions handled in Signal.send_robust()
Description
	
As pointed out by ​Haki Benita on Twitter, by default Signal.send_robust() doesn't have any log messages for exceptions raised in receivers. Since Django logs exceptions in other similar situations, such as missing template variables, I think it would be worth adding a logger.exception() call in the except clause of send_robust() . Users would then see such exceptions in their error handling tools, e.g. Sentry, and be able to figure out what action to take from there. Ultimately any *expected* exception should be caught with a try in the receiver function.
Add support for item_comments to syndication framework
Description
	
Add comments argument to feed.add_item() in syndication.views so that item_comments can be defined directly without having to take the detour via item_extra_kwargs .
Additionally, comments is already explicitly mentioned in the feedparser, but not implemented in the view.
Cannot parse Greek characters (and possibly others) in parse_mathematica
The old Mathematica parser `mathematica` in the package `sympy.parsing.mathematica` was able to parse e.g. Greek characters. Hence the following example works fine:
```
from sympy.parsing.mathematica import mathematica
mathematica('λ')
Out[]: 
λ
```

As of SymPy v. 1.11, the `mathematica` function is deprecated, and is replaced by `parse_mathematica`. This function, however, seems unable to handle the simple example above:
```
from sympy.parsing.mathematica import parse_mathematica
parse_mathematica('λ')
Traceback (most recent call last):
...
File "<string>", line unknown
SyntaxError: unable to create a single AST for the expression
```

This appears to be due to a bug in `parse_mathematica`, which is why I have opened this issue.

Thanks in advance!
Cannot parse Greek characters (and possibly others) in parse_mathematica
The old Mathematica parser `mathematica` in the package `sympy.parsing.mathematica` was able to parse e.g. Greek characters. Hence the following example works fine:
```
from sympy.parsing.mathematica import mathematica
mathematica('λ')
Out[]: 
λ
```

As of SymPy v. 1.11, the `mathematica` function is deprecated, and is replaced by `parse_mathematica`. This function, however, seems unable to handle the simple example above:
```
from sympy.parsing.mathematica import parse_mathematica
parse_mathematica('λ')
Traceback (most recent call last):
...
File "<string>", line unknown
SyntaxError: unable to create a single AST for the expression
```

This appears to be due to a bug in `parse_mathematica`, which is why I have opened this issue.

Thanks in advance!
Inconsistency when simplifying (-a)**x * a**(-x), a a positive integer
Compare:

```
>>> a = Symbol('a', integer=True, positive=True)
>>> e = (-a)**x * a**(-x)
>>> f = simplify(e)
>>> print(e)
a**(-x)*(-a)**x
>>> print(f)
(-1)**x
>>> t = -S(10)/3
>>> n1 = e.subs(x,t)
>>> n2 = f.subs(x,t)
>>> print(N(n1))
-0.5 + 0.866025403784439*I
>>> print(N(n2))
-0.5 + 0.866025403784439*I
```

vs

```
>>> a = S(2)
>>> e = (-a)**x * a**(-x)
>>> f = simplify(e)
>>> print(e)
(-2)**x*2**(-x)
>>> print(f)
(-1)**x
>>> t = -S(10)/3
>>> n1 = e.subs(x,t)
>>> n2 = f.subs(x,t)
>>> print(N(n1))
0.5 - 0.866025403784439*I
>>> print(N(n2))
-0.5 + 0.866025403784439*I
```
Allow lists in the dict values of the hooks argument
Currently the Request class has a .register_hook() method but it parses the dictionary it expects from it's hooks argument weirdly: the argument can only specify one hook function per hook.  If you pass in a list of hook functions per hook the code in Request.**init**() will wrap the list in a list which then fails when the hooks are consumed (since a list is not callable).  This is especially annoying since you can not use multiple hooks from a session.  The only way to get multiple hooks now is to create the request object without sending it, then call .register_hook() multiple times and then finally call .send().

This would all be much easier if Request.**init**() parsed the hooks parameter in a way that it accepts lists as it's values.
NCA fails in GridSearch due to too strict parameter checks
NCA checks its parameters to have a specific type, which can easily fail in a GridSearch due to how param grid is made.

Here is an example:
```python
import numpy as np

from sklearn.pipeline import Pipeline
from sklearn.model_selection import GridSearchCV
from sklearn.neighbors import NeighborhoodComponentsAnalysis
from sklearn.neighbors import KNeighborsClassifier

X = np.random.random_sample((100, 10))
y = np.random.randint(2, size=100)

nca = NeighborhoodComponentsAnalysis()
knn = KNeighborsClassifier()

pipe = Pipeline([('nca', nca),
                 ('knn', knn)])
                
params = {'nca__tol': [0.1, 0.5, 1],
          'nca__n_components': np.arange(1, 10)}
          
gs = GridSearchCV(estimator=pipe, param_grid=params, error_score='raise')
gs.fit(X,y)
```

The issue is that for `tol`: 1 is not a float, and for  `n_components`: np.int64 is not int

Before proposing a fix for this specific situation, I'd like to have your general opinion about parameter checking.  
I like this idea of common parameter checking tool introduced with the NCA PR. What do you think about extending it across the code-base (or at least for new or recent estimators) ?

Currently parameter checking is not always done or often partially done, and is quite redundant. For instance, here is the input validation of lda:
```python
def _check_params(self):
        """Check model parameters."""
        if self.n_components <= 0:
            raise ValueError("Invalid 'n_components' parameter: %r"
                             % self.n_components)

        if self.total_samples <= 0:
            raise ValueError("Invalid 'total_samples' parameter: %r"
                             % self.total_samples)

        if self.learning_offset < 0:
            raise ValueError("Invalid 'learning_offset' parameter: %r"
                             % self.learning_offset)

        if self.learning_method not in ("batch", "online"):
            raise ValueError("Invalid 'learning_method' parameter: %r"
                             % self.learning_method)
```
most params aren't checked and for those who are there's a lot of duplicated code.

A propose to be upgrade the new tool to be able to check open/closed intervals (currently only closed) and list membership.

The api would be something like that:
```
check_param(param, name, valid_options)
```
where valid_options would be a dict of `type: constraint`. e.g for the `beta_loss` param of `NMF`, it can be either a float or a string in a list, which would give
```
valid_options = {numbers.Real: None,  # None for no constraint
                 str: ['frobenius', 'kullback-leibler', 'itakura-saito']}
```
Sometimes a parameter can only be positive or within a given interval, e.g. `l1_ratio` of `LogisticRegression` must be between 0 and 1, which would give
```
valid_options = {numbers.Real: Interval(0, 1, closed='both')}
```
positivity of e.g. `max_iter` would be `numbers.Integral: Interval(left=1)`.
(-x/4 - S(1)/12)**x - 1 simplifies to an inequivalent expression
    >>> from sympy import *
    >>> x = Symbol('x')
    >>> e = (-x/4 - S(1)/12)**x - 1
    >>> e
    (-x/4 - 1/12)**x - 1
    >>> f = simplify(e)
    >>> f
    12**(-x)*(-12**x + (-3*x - 1)**x)
    >>> a = S(9)/5
    >>> simplify(e.subs(x,a))
    -1 - 32*15**(1/5)*2**(2/5)/225
    >>> simplify(f.subs(x,a))
    -1 - 32*(-1)**(4/5)*60**(1/5)/225
    >>> N(e.subs(x,a))
    -1.32255049319339
    >>> N(f.subs(x,a))
    -0.739051169462523 - 0.189590423018741*I
Possible bug in io.fits related to D exponents
I came across the following code in ``fitsrec.py``:

```python
        # Replace exponent separator in floating point numbers
        if 'D' in format:
            output_field.replace(encode_ascii('E'), encode_ascii('D'))
```

I think this may be incorrect because as far as I can tell ``replace`` is not an in-place operation for ``chararray`` (it returns a copy). Commenting out this code doesn't cause any tests to fail so I think this code isn't being tested anyway.
Two sections called Symbols in index
When using index entries with the following leading characters: _@_, _£_, and _←_ I get two sections called _Symbols_ in the HTML output, the first containing all _@_ entries before ”normal” words and the second containing _£_ and _←_ entries after the ”normal” words.  Both have the same anchor in HTML so the links at the top of the index page contain two _Symbols_ links, one before the letters and one after, but both lead to the first section.
Product pretty print could be improved
This is what the pretty printing for `Product` looks like:

```
>>> pprint(Product(1, (n, 1, oo)))
  ∞
┬───┬
│   │ 1
│   │
n = 1
>>> pprint(Product(1/n, (n, 1, oo)))
   ∞
┬──────┬
│      │ 1
│      │ ─
│      │ n
│      │
 n = 1
>>> pprint(Product(1/n**2, (n, 1, oo)))
    ∞
┬────────┬
│        │ 1
│        │ ──
│        │  2
│        │ n
│        │
  n = 1
>>> pprint(Product(1, (n, 1, oo)), use_unicode=False)
  oo
_____
|   | 1
|   |
n = 1
>>> pprint(Product(1/n, (n, 1, oo)), use_unicode=False)
   oo
________
|      | 1
|      | -
|      | n
|      |
 n = 1
>>> pprint(Product(1/n**2, (n, 1, oo)), use_unicode=False)
    oo
__________
|        | 1
|        | --
|        |  2
|        | n
|        |
  n = 1
```

(if those don't look good in your browser copy paste them into the terminal)

This could be improved:

- Why is there always an empty line at the bottom of the ∏? Keeping everything below the horizontal line is good, but the bottom looks asymmetric, and it makes the ∏ bigger than it needs to be.

- The ∏ is too fat IMO. 

- It might look better if we extended the top bar. I'm unsure about this. 

Compare this

```
    ∞
─┬─────┬─
 │     │  1
 │     │  ──
 │     │   2
 │     │  n
  n = 1
```

That's still almost twice as wide as the equivalent Sum, but if you make it much skinnier it starts to look bad.

```
  ∞
 ____
 ╲
  ╲   1
   ╲  ──
   ╱   2
  ╱   n
 ╱
 ‾‾‾‾
n = 1
```
Point.vel() should calculate the velocity if possible
If you specify the orientation of two reference frames and then ask for the angular velocity between the two reference frames the angular velocity will be calculated. But if you try to do the same thing with velocities, this doesn't work. See below:

```
In [1]: import sympy as sm                                                                               

In [2]: import sympy.physics.mechanics as me                                                             

In [3]: A = me.ReferenceFrame('A')                                                                       

In [5]: q = me.dynamicsymbols('q')                                                                       

In [6]: B = A.orientnew('B', 'Axis', (q, A.x))                                                           

In [7]: B.ang_vel_in(A)                                                                                  
Out[7]: q'*A.x

In [9]: P = me.Point('P')                                                                                

In [10]: Q = me.Point('Q')                                                                               

In [11]: r = q*A.x + 2*q*A.y                                                                             

In [12]: Q.set_pos(P, r)                                                                                 

In [13]: Q.vel(A)                                                                                        
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-13-0fc8041904cc> in <module>
----> 1 Q.vel(A)

~/miniconda3/lib/python3.6/site-packages/sympy/physics/vector/point.py in vel(self, frame)
    453         if not (frame in self._vel_dict):
    454             raise ValueError('Velocity of point ' + self.name + ' has not been'
--> 455                              ' defined in ReferenceFrame ' + frame.name)
    456         return self._vel_dict[frame]
    457 

ValueError: Velocity of point Q has not been defined in ReferenceFrame A
```

The expected result of the `Q.vel(A)` should be:

```
In [14]: r.dt(A)                                                                                         
Out[14]: q'*A.x + 2*q'*A.y
```

I think that this is possible. Maybe there is a reason it isn't implemented. But we should try to implement it because it is confusing why this works for orientations and not positions.
autodoc isn't able to resolve struct.Struct type annotations
**Describe the bug**
If `struct.Struct` is declared in any type annotations, I get `class reference target not found: Struct`

**To Reproduce**
Simple `index.rst`
```
Hello World
===========

code docs
=========

.. automodule:: helloworld.helloworld
```

Simple `helloworld.py`
```
import struct
import pathlib

def consume_struct(_: struct.Struct) -> None:
    pass

def make_struct() -> struct.Struct:
    mystruct = struct.Struct('HH')
    return mystruct

def make_path() -> pathlib.Path:
    return pathlib.Path()
```

Command line:
```
python3 -m sphinx -b html docs/ doc-out -nvWT
```

**Expected behavior**
If you comment out the 2 functions that have `Struct` type annotations, you'll see that `pathlib.Path` resolves fine and shows up in the resulting documentation. I'd expect that `Struct` would also resolve correctly.

**Your project**
n/a

**Screenshots**
n/a

**Environment info**
- OS: Ubuntu 18.04, 20.04
- Python version: 3.8.2
- Sphinx version: 3.2.1
- Sphinx extensions:  'sphinx.ext.autodoc',
              'sphinx.ext.autosectionlabel',
              'sphinx.ext.intersphinx',
              'sphinx.ext.doctest',
              'sphinx.ext.todo'
- Extra tools: 

**Additional context**


- [e.g. URL or Ticket]