internlm/SWE-Fixer-Train-110K huggingface dataset:
Repository: sagemath/sage

Issue:
Give an `algorithm` keyword to (some?) `simplify` methods/functions
<div id="comment:0"></div>

Case in point (many other examples exist...) :

```
sage: var("x", domain="positive")
x
sage: u = -1/2*I*x + 1/2*I*sqrt(x^2 - 1) + 1/2*I/(x - sqrt(x^2 - 1))
sage: u.simplify()
-1/2*I*x + 1/2*I*sqrt(x^2 - 1) + 1/2*I/(x - sqrt(x^2 - 1))
sage: u._giac_().simplify()._sage_()
I*sqrt(x^2 - 1)
sage: u._fricas_().simplify()._sage_()
-(I*x^2 - I*sqrt(x^2 - 1)*x - I)/(x - sqrt(x^2 - 1))
sage: u._sympy_().simplify()._sage_()
-I*(x^2 - sqrt(x^2 - 1)*x - 1)/(x - sqrt(x^2 - 1))
sage: mathematica.FullSimplify(u).sage()
I*sqrt(x^2 - 1)
```

Suggestion : give to the `simplify` method of symbolic expressions (and its wrapper function) an `algorithm` keyword selecting an alternative to our "default" (which is to send the expression to Maxima and accept whatever Maxima sends back to us...).

This might be also useful for the more specialized methods/functions (such as `simplify_trig`). Advice required...

Advice also required about adding it to `simplify_full`, which aims to be a useful helper in complicated cases, but often bites more than it can swallow...

CC:  @slel

Component: **symbolics**

Author: **Emmanuel Charpentier**

Branch/Commit: **[u/charpent/give_an__algorithm__keyword_to__some____simplify__methods_functions](https://github.com/sagemath/sagetrac-mirror/tree/u/charpent/give_an__algorithm__keyword_to__some____simplify__methods_functions) @ [`6472588`](https://github.com/sagemath/sagetrac-mirror/commit/6472588cc04b8a4cefc402a640aa09d947b114a7)**

_Issue created by migration from https://trac.sagemath.org/ticket/32472_




Discussion:

Resolving patch:
diff --git a/src/sage/calculus/functional.py b/src/sage/calculus/functional.py
--- a/src/sage/calculus/functional.py
+++ b/src/sage/calculus/functional.py
@@ -25,24 +25,40 @@
     sage: expand((x - a)^3)
     -a^3 + 3*a^2*x - 3*a*x^2 + x^3
 """
-
 from sage.structure.element import Expression
 
 
-def simplify(f):
+def simplify(f, algorithm="maxima", **kwds):
     r"""
     Simplify the expression `f`.
 
-    EXAMPLES: We simplify the expression `i + x - x`.
+    See the documentation of the
+    :meth:`~sage.symbolic.expression.Expression.simplify` method of symbolic
+    expressions for details on options.
 
-    ::
+    EXAMPLES:
+
+    We simplify the expression `i + x - x`::
 
         sage: f = I + x - x; simplify(f)
         I
 
     In fact, printing `f` yields the same thing - i.e., the
     simplified form.
+
+    Some simplifications are algorithm-specific::
+
+        sage: x, t = var("x, t")
+        sage: ex = 1/2*I*x + 1/2*I*sqrt(x^2 - 1) + 1/2/(I*x + I*sqrt(x^2 - 1))
+        sage: simplify(ex)
+        1/2*I*x + 1/2*I*sqrt(x^2 - 1) + 1/(2*I*x + 2*I*sqrt(x^2 - 1))
+        sage: simplify(ex, algorithm="giac")
+        I*sqrt(x^2 - 1)
     """
+    try:
+        return f.simplify(algorithm=algorithm, **kwds)
+    except (TypeError, AttributeError):
+        pass
     try:
         return f.simplify()
     except AttributeError:


Test patch:
Repository: sagemath/sage

Issue:
Non-homogeneous GradedModularFormElement multiplication and exponentiation is incorrect
### Steps To Reproduce

Code:

```python
sage: M = ModularFormsRing(1)
sage: E4, E6 = M.gens()
sage: E4 + M(1)
2 + 240*q + 2160*q^2 + 6720*q^3 + 17520*q^4 + 30240*q^5 + O(q^6)
sage: (E4 + M(1))^2
3 + 720*q + 64080*q^2 + 1056960*q^3 + 7943760*q^4 + 37530720*q^5 + O(q^6)
```

### Expected Behavior

Well, it should start with `4 + ...` since `E4 + M(1)` start with `2 + ...`. In particular, it should be `E4^2 + 2 * E4 + 1` instead of the current computed `E4^2 + E4 + 1`.

### Actual Behavior

I found the buggy line, so I will just report it (and make a PR soon): On line 3558 of `sage.modular.modform`, i.e. inside the `_mul_` method of `GradedModularFormElement`, it has the following incorrect line:

```python
        GM = self.__class__
        f_self = self._forms_dictionary
        f_other = other._forms_dictionary
        f_mul = {}
        for k_self in f_self.keys():
            for k_other in f_other.keys():
                f_mul[k_self + k_other] = f_self[k_self]*f_other[k_other]        # Line 3558
        return GM(self.parent(), f_mul)
```
It should be `+=` instead of `=`, just like normal polynomial multiplication.

### Additional Information

_No response_

### Environment

```markdown
- **Sage Version**: 10.0
```


### Checklist

- [X] I have searched the existing issues for a bug report that matches the one I want to file, without success.
- [X] I have read the documentation and troubleshoot guide


Discussion:
Is it possible for me to add labels (modular-forms) myself? Or can I not because I haven't made any contributions to the repo before?

Resolving patch:
diff --git a/src/sage/modular/modform/element.py b/src/sage/modular/modform/element.py
--- a/src/sage/modular/modform/element.py
+++ b/src/sage/modular/modform/element.py
@@ -3544,18 +3544,26 @@ def _mul_(self, other):
         TESTS::
 
             sage: M = ModularFormsRing(1)
-            sage: f4 = ModularForms(1, 4).0; f6 = ModularForms(1, 6).0;
-            sage: F4 = M(f4); F6 = M(f6);
+            sage: F4 = M.0; F6 = M.1;
             sage: F4*F6 # indirect doctest
             1 - 264*q - 135432*q^2 - 5196576*q^3 - 69341448*q^4 - 515625264*q^5 + O(q^6)
+
+        This shows that the issue at :issue:`35932` is fixed::
+
+            sage: (F4 + M(1))^2
+            4 + 960*q + 66240*q^2 + 1063680*q^3 + 7961280*q^4 + 37560960*q^5 + O(q^6)
         """
+        from collections import defaultdict
+
         GM = self.__class__
         f_self = self._forms_dictionary
         f_other = other._forms_dictionary
-        f_mul = {}
+        f_mul = defaultdict(int)
+
         for k_self in f_self.keys():
             for k_other in f_other.keys():
-                f_mul[k_self + k_other] = f_self[k_self]*f_other[k_other]
+                f_mul[k_self + k_other] += f_self[k_self] * f_other[k_other]
+
         return GM(self.parent(), f_mul)
 
     def _lmul_(self, c):


Test patch:
Repository: sagemath/sage

Issue:
Typo in documentation for congruence subgroups
### Steps To Reproduce

N/A

### Expected Behavior

N/A

### Actual Behavior

N/A

### Additional Information

Reported by Chengyang Bao via David Loeffler:

typo in the Sage reference manual: in the class docstring for sage.modular.arithgroup.congroup_gammaH.GammaH_class, the formula "a, b \in H" should say "a, d \in H". 

(See https://doc.sagemath.org/html/en/reference/arithgroup/sage/modular/arithgroup/congroup_gammaH.html#sage.modular.arithgroup.congroup_gammaH.GammaH_class).

### Environment

```markdown
- **OS**:
- **Sage Version**:
```


### Checklist

- [X] I have searched the existing issues for a bug report that matches the one I want to file, without success.
- [X] I have read the documentation and troubleshoot guide


Discussion:

Resolving patch:
diff --git a/src/sage/modular/arithgroup/congroup_gammaH.py b/src/sage/modular/arithgroup/congroup_gammaH.py
--- a/src/sage/modular/arithgroup/congroup_gammaH.py
+++ b/src/sage/modular/arithgroup/congroup_gammaH.py
@@ -40,7 +40,7 @@ def GammaH_constructor(level, H):
     r"""
     Return the congruence subgroup `\Gamma_H(N)`, which is the subgroup of
     `SL_2(\ZZ)` consisting of matrices of the form `\begin{pmatrix} a & b \\
-    c & d \end{pmatrix}` with `N | c` and `a, b \in H`, for `H` a specified
+    c & d \end{pmatrix}` with `N | c` and `a, d \in H`, for `H` a specified
     subgroup of `(\ZZ/N\ZZ)^\times`.
 
     INPUT:
@@ -163,7 +163,7 @@ class GammaH_class(CongruenceSubgroup):
     The congruence subgroup `\Gamma_H(N)` for some subgroup `H \trianglelefteq
     (\ZZ / N\ZZ)^\times`, which is the subgroup of `\SL_2(\ZZ)` consisting of
     matrices of the form `\begin{pmatrix} a &
-    b \\ c & d \end{pmatrix}` with `N \mid c` and `a, b \in H`.
+    b \\ c & d \end{pmatrix}` with `N \mid c` and `a, d \in H`.
 
     TESTS:
 


Test patch:
Repository: sagemath/sage

Issue:
Conrey number of trivial character
### Is there an existing issue for this?

- [X] I have searched the existing issues for a bug report that matches the one I want to file, without success.

### Did you read the documentation and troubleshoot guide?

- [X] I have read the documentation and troubleshoot guide

### Environment

```markdown
- **OS**: Ubuntu 20.04.5 LTS
- **Sage Version**: 9.7
```


### Steps To Reproduce

g=DirichletGroup(1)
[z.conrey_number() for z in g]


### Expected Behavior

Answer should be [1]

### Actual Behavior

Sage give
[0]

### Additional Information

 0 is not a valid Conrey number of a Dirichlet character


Discussion:
This calls pari function `znconreyexp`  on the character converted to pari.

So either a bug in the conversion to pari, or a bug in pari. Please investigate.
Seems to be a bug in pari.
If so,  please report upstream and put a link here to the discussion there
upstream is https://pari.math.u-bordeaux.fr/cgi-bin/bugreport.cgi?bug=2479
The pari function does not claim to produce the Conrey number as defined in the LMFDB whereas the Sage documentation does specifically reference the LMFDB definition.  I think sage should make the small adjustment.

Resolving patch:
diff --git a/src/sage/modular/dirichlet.py b/src/sage/modular/dirichlet.py
--- a/src/sage/modular/dirichlet.py
+++ b/src/sage/modular/dirichlet.py
@@ -1201,7 +1201,12 @@ def conrey_number(self):
             sage: eps2 = DirichletGroup(5,QQ)([-1])
             sage: eps1.conrey_number() == eps2.conrey_number()
             True
+            sage: chi = DirichletGroup(1)[0]
+            sage: chi.conrey_number()
+            1
         """
+        if self.modulus() == 1:
+            return 1
         G, v = self._pari_init_()
         return pari.znconreyexp(G, v).sage()
 


Test patch:
Repository: sagemath/sage

Issue:
Reducing Gamma(N) cusps does not always reduce
### Steps To Reproduce

In Sage-10.1:

sage: Gamma(7).reduce_cusp(Cusp(6,7))
6/7
sage: Gamma(7).reduce_cusp(Cusp(1,0))
Infinity
sage: Gamma(7).are_equivalent(Cusp(1,0), Cusp(6,7))
True


### Expected Behavior


Both 6/7 and 1/0 should reduce to Infinity = 1/0 since 6/7 and 1/0 are equivalent modulo Gamma(7), and according to the definition of a reduced cusp for Gamma(N).  So we should see

sage: Gamma(7).reduce_cusp(Cusp(6,7))
Infinity

### Actual Behavior

instead of 

sage: Gamma(7).reduce_cusp(Cusp(6,7))
6/7


### Additional Information

The code reduces both u and v mod N (where the cusp is u/v and the level is N) and then calls the hidden function _lift_pair(u,v,N).  But that function assumes that its input u,v are coprime, which in this case they are not.

To fix this it suffices to change _lift_pair() to return Cusp(1,0), i.e. Infinity, when v%N==0 and u%N is either +1 or N-1; the second case was being missed.

### Environment

```markdown
- **OS**: Ubuntu 22.04.3 LTS
- **Sage Version**: 10.1
```


### Checklist

- [X] I have searched the existing issues for a bug report that matches the one I want to file, without success.
- [X] I have read the documentation and troubleshoot guide


Discussion:

Resolving patch:
diff --git a/src/sage/modular/arithgroup/congroup_gamma.py b/src/sage/modular/arithgroup/congroup_gamma.py
--- a/src/sage/modular/arithgroup/congroup_gamma.py
+++ b/src/sage/modular/arithgroup/congroup_gamma.py
@@ -240,6 +240,12 @@ def reduce_cusp(self, c):
             sage: G = Gamma(50)
             sage: all(c == G.reduce_cusp(c) for c in G.cusps())
             True
+
+        We test that :trac:`36163` is fixed::
+
+            sage: Gamma(7).reduce_cusp(Cusp(6,7))
+            Infinity
+
         """
         N = self.level()
         c = Cusp(c)
@@ -341,7 +347,7 @@ def _lift_pair(U,V,N):
     u = U % N
     v = V % N
     if v == 0:
-        if u == 1:
+        if u == 1 or u == N-1:
             return (1,0)
         else:
             v = N


Test patch:
Repository: sagemath/sage

Issue:
Unoptimal memory complexity of `sage.matrix.berlekamp`
The code here is unoptimal:

https://github.com/sagemath/sage/blob/6695becb762aebab78ef47d0fb12eae52be5d79d/src/sage/matrix/berlekamp_massey.py#L90-L98

For example, the following code uses a lot of memory:

```python
sage: from sage.matrix.berlekamp_massey import berlekamp_massey
sage: p = next_prime(2**64)
sage: ls = [GF(p).random_element() for _ in range(20000)]
sage: berlekamp_massey(ls);
```

To be more specific, the dictionaries are not necessarily and only `f[j - 2]` and `f[j - 1]` are used every time, same for `s`. So they can be stored as temporary variables.

### Additional Information

I am fixing it.

### Checklist

- [X] I have searched the existing issues for a bug report that matches the one I want to file, without success.
- [X] I have read the documentation and troubleshoot guide


Discussion:

Resolving patch:
diff --git a/src/sage/matrix/berlekamp_massey.py b/src/sage/matrix/berlekamp_massey.py
--- a/src/sage/matrix/berlekamp_massey.py
+++ b/src/sage/matrix/berlekamp_massey.py
@@ -84,15 +84,11 @@ def berlekamp_massey(a):
         K = a[0].parent().fraction_field()
     except AttributeError:
         K = sage.rings.rational_field.RationalField()
-    R = K['x']
-    x = R.gen()
-
-    f = {-1: R(a), 0: x**(2 * M)}
-    s = {-1: 1, 0: 0}
-    j = 0
-    while f[j].degree() >= M:
-        j += 1
-        qj, f[j] = f[j - 2].quo_rem(f[j - 1])
-        s[j] = s[j - 2] - qj * s[j - 1]
-    t = s[j].reverse()
-    return ~(t[t.degree()]) * t  # make monic  (~ is inverse in python)
+
+    R, x = K['x'].objgen()
+    f0, f1 = R(a), x**(2 * M)
+    s0, s1 = 1, 0
+    while f1.degree() >= M:
+        f0, (q, f1) = f1, f0.quo_rem(f1)
+        s0, s1 = s1, s0 - q * s1
+    return s1.reverse().monic()


Test patch:
Repository: sagemath/sage

Issue:
toml package is obsolete
### Steps To Reproduce

_No response_

### Expected Behavior

toml is not installed

### Actual Behavior

toml is installed

### Additional Information

I think our `toml` package is obsolete. The only other package listing it as a requirement is tox, but tox only needs it with ancient pythons: https://github.com/tox-dev/tox/blob/3.27.1/setup.cfg#L45

I think our dependency can be replaced with tomli at which point toml can go.


### Environment

```markdown
Gentoo / git develop
```


### Checklist

- [X] I have searched the existing issues for a bug report that matches the one I want to file, without success.
- [X] I have read the documentation and troubleshoot guide


Discussion:
Our tox needs to be updated to 4.x anyway - #34840 

Resolving patch:
diff --git a/build/sage_bootstrap/creator.py b/build/sage_bootstrap/creator.py
--- a/build/sage_bootstrap/creator.py
+++ b/build/sage_bootstrap/creator.py
@@ -94,7 +94,7 @@ def set_python_data_and_scripts(self, pypi_package_name=None, source='normal'):
         if pypi_package_name is None:
             pypi_package_name = self.package_name
         with open(os.path.join(self.path, 'dependencies'), 'w+') as f:
-            f.write('$(PYTHON) | $(PYTHON_TOOLCHAIN)\n\n')
+            f.write(' | $(PYTHON_TOOLCHAIN) $(PYTHON)\n\n')
             f.write('----------\nAll lines of this file are ignored except the first.\n')
         if source == 'normal':
             with open(os.path.join(self.path, 'spkg-install.in'), 'w+') as f:


Test patch:
Repository: sagemath/sage

Issue:
build/pkgs/toml doesn't have install info - remove?
### Steps To Reproduce

that's all it has:

```
$ ls -R build/pkgs/toml/
build/pkgs/toml/:
distros

build/pkgs/toml/distros:
arch.txt  debian.txt  fedora.txt  gentoo.txt  opensuse.txt
```

### Expected Behavior

it should not be there

### Actual Behavior

it is there. Remove?

### Additional Information

_No response_

### Environment

```markdown
all
```


### Checklist

- [X] I have searched the existing issues for a bug report that matches the one I want to file, without success.
- [X] I have read the documentation and troubleshoot guide


Discussion:

Resolving patch:
diff --git a/src/sage/plot/contour_plot.py b/src/sage/plot/contour_plot.py
--- a/src/sage/plot/contour_plot.py
+++ b/src/sage/plot/contour_plot.py
@@ -1394,8 +1394,7 @@ def f(x,y):
 @options(plot_points=100, incol='blue', outcol=None, bordercol=None,
          borderstyle=None, borderwidth=None, frame=False, axes=True,
          legend_label=None, aspect_ratio=1, alpha=1)
-def region_plot(f, xrange, yrange, plot_points, incol, outcol, bordercol,
-                borderstyle, borderwidth, alpha, **options):
+def region_plot(f, xrange, yrange, **options):
     r"""
     ``region_plot`` takes a boolean function of two variables, `f(x, y)`
     and plots the region where f is True over the specified
@@ -1659,6 +1658,14 @@ def region_plot(f, xrange, yrange, plot_points, incol, outcol, bordercol,
     from warnings import warn
     import numpy
 
+    plot_points = options['plot_points']
+    incol = options.pop('incol')
+    outcol = options.pop('outcol')
+    bordercol = options.pop('bordercol')
+    borderstyle = options.pop('borderstyle')
+    borderwidth = options.pop('borderwidth')
+    alpha = options.pop('alpha')
+
     if not isinstance(f, (list, tuple)):
         f = [f]
 
@@ -1677,9 +1684,9 @@ def region_plot(f, xrange, yrange, plot_points, incol, outcol, bordercol,
     if neqs and not bordercol:
         bordercol = incol
     if not f:
-        return implicit_plot(feqs[0], xrange, yrange, plot_points=plot_points,
-                             fill=False, linewidth=borderwidth,
-                             linestyle=borderstyle, color=bordercol, **options)
+        return implicit_plot(feqs[0], xrange, yrange, fill=False,
+                             linewidth=borderwidth, linestyle=borderstyle,
+                             color=bordercol, **options)
     f_all, ranges = setup_for_eval_on_grid(feqs + f,
                                            [xrange, yrange],
                                            plot_points)


Test patch:
Repository: sagemath/sage

Issue:
`func_persist` fails with Python 3.11
```sage
@func_persist
def test(n):
    return n*n
```

fails with

```python
AttributeError                            Traceback (most recent call last)
Cell In[1], line 1
----> 1 @func_persist
      2 def test(n):
      3     return n*n

File /usr/lib/python3.11/site-packages/sage/misc/func_persist.py:60, in func_persist.__init__(self, f, dir)
     56 self.__dir = dir
     57 os.makedirs(dir, exist_ok=True)
     58 self.__doc__ = '%s%s%s' % (
     59     f.__name__,
---> 60     inspect.formatargspec(*inspect.getargs(f.__code__)),
     61     f.__doc__)

AttributeError: module 'inspect' has no attribute 'formatargspec'
```

This is because `inspect.formatargspec` has been [deprecated in Python 3.5 and removed in 3.11](https://docs.python.org/3/whatsnew/3.11.html#removed). Probably related to #33842.



Discussion:

Resolving patch:
diff --git a/src/sage/misc/func_persist.py b/src/sage/misc/func_persist.py
--- a/src/sage/misc/func_persist.py
+++ b/src/sage/misc/func_persist.py
@@ -45,7 +45,6 @@ def bern(n):
 
 from . import persist
 
-
 class func_persist:
     r"""
     Put ``@func_persist`` right before your function
@@ -57,7 +56,7 @@ def __init__(self, f, dir='func_persist'):
         os.makedirs(dir, exist_ok=True)
         self.__doc__ = '%s%s%s' % (
             f.__name__,
-            inspect.formatargspec(*inspect.getargs(f.__code__)),
+            inspect.signature(f),
             f.__doc__)
 
     def __call__(self, *args, **kwds):


Test patch:
Repository: sagemath/sage

Issue:
build.yml: Report failures (e.g. from incremental test) earlier
as suggested in https://github.com/sagemath/sage/pull/35652#issuecomment-1603365433

possibly using https://github.com/LouisBrunner/checks-action

and/or problem matchers for:
- sphinx (see https://github.com/python/cpython/pull/20325/files)
- linter errors
- doctest failures



Discussion:

Resolving patch:
diff --git a/src/sage/doctest/reporting.py b/src/sage/doctest/reporting.py
--- a/src/sage/doctest/reporting.py
+++ b/src/sage/doctest/reporting.py
@@ -145,7 +145,8 @@ def were_doctests_with_optional_tag_run(self, tag):
         When latex is available, doctests marked with optional tag
         ``latex`` are run by default since :issue:`32174`::
 
-            sage: filename = os.path.join(SAGE_SRC,'sage','misc','latex.py')
+            sage: # needs SAGE_SRC
+            sage: filename = os.path.join(SAGE_SRC, 'sage', 'misc', 'latex.py')
             sage: DC = DocTestController(DocTestDefaults(), [filename])
             sage: DTR = DocTestReporter(DC)
             sage: DTR.were_doctests_with_optional_tag_run('latex')   # optional - latex
diff --git a/src/sage/features/__init__.py b/src/sage/features/__init__.py
--- a/src/sage/features/__init__.py
+++ b/src/sage/features/__init__.py
@@ -948,7 +948,10 @@ def _is_present(self):
             # Available since https://setuptools.pypa.io/en/latest/history.html#v59-0-0
             from setuptools.errors import CCompilerError
         except ImportError:
-            from distutils.errors import CCompilerError
+            try:
+                from distutils.errors import CCompilerError
+            except ImportError:
+                CCompilerError = ()
         with open(tmp_filename(ext=".pyx"), 'w') as pyx:
             pyx.write(self.test_code)
         try:
diff --git a/src/sage/misc/package.py b/src/sage/misc/package.py
--- a/src/sage/misc/package.py
+++ b/src/sage/misc/package.py
@@ -178,16 +178,16 @@ def pip_installed_packages(normalization=None):
         sage: # optional - sage_spkg
         sage: from sage.misc.package import pip_installed_packages
         sage: d = pip_installed_packages()
-        sage: 'scipy' in d or 'SciPy' in d
+        sage: 'scipy' in d or 'SciPy' in d                                              # needs scipy
+        True
+        sage: 'beautifulsoup4' in d                             # needs beautifulsoup4
+        True
+        sage: 'prompt-toolkit' in d or 'prompt_toolkit' in d    # whether - or _ appears in the name depends on the setuptools version used for building the package
         True
-        sage: d['beautifulsoup4']                               # optional - beautifulsoup4
-        '...'
-        sage: d['prompt-toolkit']
-        '...'
         sage: d = pip_installed_packages(normalization='spkg')
         sage: d['prompt_toolkit']
         '...'
-        sage: d['scipy']
+        sage: d['scipy']                                                                # needs scipy
         '...'
     """
     with open(os.devnull, 'w') as devnull:


Test patch: