instance_id
stringlengths 10
57
| base_commit
stringlengths 40
40
| created_at
stringdate 2014-04-30 14:58:36
2025-04-30 20:14:11
| environment_setup_commit
stringlengths 40
40
| hints_text
stringlengths 0
273k
| patch
stringlengths 251
7.06M
| problem_statement
stringlengths 11
52.5k
| repo
stringlengths 7
53
| test_patch
stringlengths 231
997k
| meta
dict | version
stringclasses 864
values | install_config
dict | requirements
stringlengths 93
34.2k
⌀ | environment
stringlengths 760
20.5k
⌀ | FAIL_TO_PASS
sequencelengths 1
9.39k
| FAIL_TO_FAIL
sequencelengths 0
2.69k
| PASS_TO_PASS
sequencelengths 0
7.87k
| PASS_TO_FAIL
sequencelengths 0
192
| license_name
stringclasses 56
values | __index_level_0__
int64 0
21.4k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
cdent__gabbi-61 | 081a75f5f0ddfdc31c4bab62db2f084a50c9ee99 | 2015-07-19 11:29:17 | 081a75f5f0ddfdc31c4bab62db2f084a50c9ee99 | diff --git a/gabbi/handlers.py b/gabbi/handlers.py
index d39a987..0b7a71d 100644
--- a/gabbi/handlers.py
+++ b/gabbi/handlers.py
@@ -128,9 +128,9 @@ class HeadersResponseHandler(ResponseHandler):
try:
response_value = response[header]
except KeyError:
- # Reform KeyError to something more debuggable.
- raise KeyError("'%s' header not available in response keys: %s"
- % (header, response.keys()))
+ raise AssertionError(
+ "'%s' header not present in response: %s" % (
+ header, response.keys()))
if header_value.startswith('/') and header_value.endswith('/'):
header_value = header_value.strip('/').rstrip('/')
| missing response header raises error rather than failure
The following reports an error when it should report a failure instead:
```yaml
tests:
- name: failure
url: http://google.com
status: 302
response_headers:
x-foo: bar
```
AFAICT that's because internally a `KeyError` is raised ("'x-foo' header not available in response keys: dict_keys(...)"): `testtools.TestCase`'s default `exception_handlers` doesn't have a mapping for that particular exception, so it defaults to `_report_error` rather than using `_report_failure`.
| cdent/gabbi | diff --git a/gabbi/tests/test_handlers.py b/gabbi/tests/test_handlers.py
index b647e80..af27359 100644
--- a/gabbi/tests/test_handlers.py
+++ b/gabbi/tests/test_handlers.py
@@ -133,9 +133,9 @@ class HandlersTest(unittest.TestCase):
'location': '/somewhere',
}}
self.test.response = {'content-type': 'application/json'}
- with self.assertRaises(KeyError) as failure:
+ with self.assertRaises(AssertionError) as failure:
self._assert_handler(handler)
- self.assertIn("'location' header not available in response keys:",
+ self.assertIn("'location' header not present in response:",
str(failure.exception))
def _assert_handler(self, handler):
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_hyperlinks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 0,
"issue_text_score": 0,
"test_score": 0
},
"num_modified_files": 1
} | 1.1 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest",
"pytest-cov",
"pytest-xdist",
"pytest-mock",
"pytest-asyncio"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.9",
"reqs_path": [
"requirements.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | coverage==7.8.0
decorator==5.2.1
exceptiongroup==1.2.2
execnet==2.1.1
-e git+https://github.com/cdent/gabbi.git@081a75f5f0ddfdc31c4bab62db2f084a50c9ee99#egg=gabbi
httplib2==0.22.0
iniconfig==2.1.0
jsonpath-rw==1.4.0
packaging==24.2
pbr==6.1.1
pluggy==1.5.0
ply==3.11
pyparsing==3.2.3
pytest==8.3.5
pytest-asyncio==0.26.0
pytest-cov==6.0.0
pytest-mock==3.14.0
pytest-xdist==3.6.1
PyYAML==6.0.2
six==1.17.0
testtools==2.7.2
tomli==2.2.1
typing_extensions==4.13.0
wsgi_intercept==1.13.1
| name: gabbi
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=3.0.16=h5eee18b_0
- pip=25.0=py39h06a4308_0
- python=3.9.21=he870216_1
- readline=8.2=h5eee18b_0
- setuptools=75.8.0=py39h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- tzdata=2025a=h04d1e81_0
- wheel=0.45.1=py39h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- coverage==7.8.0
- decorator==5.2.1
- exceptiongroup==1.2.2
- execnet==2.1.1
- httplib2==0.22.0
- iniconfig==2.1.0
- jsonpath-rw==1.4.0
- packaging==24.2
- pbr==6.1.1
- pluggy==1.5.0
- ply==3.11
- pyparsing==3.2.3
- pytest==8.3.5
- pytest-asyncio==0.26.0
- pytest-cov==6.0.0
- pytest-mock==3.14.0
- pytest-xdist==3.6.1
- pyyaml==6.0.2
- six==1.17.0
- testtools==2.7.2
- tomli==2.2.1
- typing-extensions==4.13.0
- wsgi-intercept==1.13.1
prefix: /opt/conda/envs/gabbi
| [
"gabbi/tests/test_handlers.py::HandlersTest::test_response_headers_fail_header"
] | [] | [
"gabbi/tests/test_handlers.py::HandlersTest::test_response_headers",
"gabbi/tests/test_handlers.py::HandlersTest::test_response_headers_fail_data",
"gabbi/tests/test_handlers.py::HandlersTest::test_response_headers_regex",
"gabbi/tests/test_handlers.py::HandlersTest::test_response_json_paths",
"gabbi/tests/test_handlers.py::HandlersTest::test_response_json_paths_fail_data",
"gabbi/tests/test_handlers.py::HandlersTest::test_response_json_paths_fail_path",
"gabbi/tests/test_handlers.py::HandlersTest::test_response_strings",
"gabbi/tests/test_handlers.py::HandlersTest::test_response_strings_fail"
] | [] | Apache License 2.0 | 200 |
|
sympy__sympy-9736 | 116988f268500c478cf77b0eb9b4968c4d2fb106 | 2015-07-27 03:20:40 | 0241b35cae5f2adc04dc37b25f7dc9c5f00bd746 | diff --git a/sympy/solvers/solveset.py b/sympy/solvers/solveset.py
index ff1683e1b1..f141ebb1d4 100644
--- a/sympy/solvers/solveset.py
+++ b/sympy/solvers/solveset.py
@@ -221,7 +221,7 @@ def _invert_complex(f, g_ys, symbol):
if isinstance(g_ys, FiniteSet):
exp_invs = Union(*[imageset(Lambda(n, I*(2*n*pi + arg(g_y)) +
log(Abs(g_y))), S.Integers)
- for g_y in g_ys])
+ for g_y in g_ys if g_y != 0])
return _invert_complex(f.args[0], exp_invs, symbol)
return (f, g_ys)
| `solveset(sinh(x).rewrite(exp), x)` returns ImageSet containing `nan`
```
>>> x = Symbol('x')
>>> solveset(sinh(x).rewrite(exp), x)
ImageSet(Lambda(_n, nan), Integers()) U ImageSet(Lambda(_n, _n*I*pi), Integers())
```
The `ImageSet(Lambda(_n, nan))` should not be there | sympy/sympy | diff --git a/sympy/solvers/tests/test_solveset.py b/sympy/solvers/tests/test_solveset.py
index 7c4c6dedd9..27116b4430 100644
--- a/sympy/solvers/tests/test_solveset.py
+++ b/sympy/solvers/tests/test_solveset.py
@@ -647,6 +647,9 @@ def test_solveset_complex_exp():
imageset(Lambda(n, I*2*n*pi), S.Integers)
assert solveset_complex(exp(x) - I, x) == \
imageset(Lambda(n, I*(2*n*pi + pi/2)), S.Integers)
+ assert solveset_complex(1/exp(x), x) == S.EmptySet
+ assert solveset_complex(sinh(x).rewrite(exp), x) == \
+ imageset(Lambda(n, n*pi*I), S.Integers)
def test_solve_complex_log():
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_short_problem_statement"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 0,
"issue_text_score": 0,
"test_score": 3
},
"num_modified_files": 1
} | 0.7 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[dev]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "pytest",
"pip_packages": [
"mpmath>=0.19",
"pytest"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.7",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | attrs @ file:///croot/attrs_1668696182826/work
certifi @ file:///croot/certifi_1671487769961/work/certifi
flit_core @ file:///opt/conda/conda-bld/flit-core_1644941570762/work/source/flit_core
importlib-metadata @ file:///tmp/build/80754af9/importlib-metadata_1648562407465/work
iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work
mpmath==1.3.0
packaging @ file:///croot/packaging_1671697413597/work
pluggy @ file:///tmp/build/80754af9/pluggy_1648042572264/work
py @ file:///opt/conda/conda-bld/py_1644396412707/work
pytest==7.1.2
-e git+https://github.com/sympy/sympy.git@116988f268500c478cf77b0eb9b4968c4d2fb106#egg=sympy
tomli @ file:///opt/conda/conda-bld/tomli_1657175507142/work
typing_extensions @ file:///croot/typing_extensions_1669924550328/work
zipp @ file:///croot/zipp_1672387121353/work
| name: sympy
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- attrs=22.1.0=py37h06a4308_0
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2022.12.7=py37h06a4308_0
- flit-core=3.6.0=pyhd3eb1b0_0
- importlib-metadata=4.11.3=py37h06a4308_0
- importlib_metadata=4.11.3=hd3eb1b0_0
- iniconfig=1.1.1=pyhd3eb1b0_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- packaging=22.0=py37h06a4308_0
- pip=22.3.1=py37h06a4308_0
- pluggy=1.0.0=py37h06a4308_1
- py=1.11.0=pyhd3eb1b0_0
- pytest=7.1.2=py37h06a4308_0
- python=3.7.16=h7a1cb2a_0
- readline=8.2=h5eee18b_0
- setuptools=65.6.3=py37h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- tomli=2.0.1=py37h06a4308_0
- typing_extensions=4.4.0=py37h06a4308_0
- wheel=0.38.4=py37h06a4308_0
- xz=5.6.4=h5eee18b_1
- zipp=3.11.0=py37h06a4308_0
- zlib=1.2.13=h5eee18b_1
- pip:
- mpmath==1.3.0
prefix: /opt/conda/envs/sympy
| [
"sympy/solvers/tests/test_solveset.py::test_solveset_complex_exp"
] | [] | [
"sympy/solvers/tests/test_solveset.py::test_invert_real",
"sympy/solvers/tests/test_solveset.py::test_invert_complex",
"sympy/solvers/tests/test_solveset.py::test_domain_check",
"sympy/solvers/tests/test_solveset.py::test_is_function_class_equation",
"sympy/solvers/tests/test_solveset.py::test_garbage_input",
"sympy/solvers/tests/test_solveset.py::test_solve_mul",
"sympy/solvers/tests/test_solveset.py::test_solve_invert",
"sympy/solvers/tests/test_solveset.py::test_errorinverses",
"sympy/solvers/tests/test_solveset.py::test_solve_polynomial",
"sympy/solvers/tests/test_solveset.py::test_return_root_of",
"sympy/solvers/tests/test_solveset.py::test__has_rational_power",
"sympy/solvers/tests/test_solveset.py::test_solveset_sqrt_1",
"sympy/solvers/tests/test_solveset.py::test_solveset_sqrt_2",
"sympy/solvers/tests/test_solveset.py::test_solve_sqrt_3",
"sympy/solvers/tests/test_solveset.py::test_solve_polynomial_symbolic_param",
"sympy/solvers/tests/test_solveset.py::test_solve_rational",
"sympy/solvers/tests/test_solveset.py::test_solveset_real_gen_is_pow",
"sympy/solvers/tests/test_solveset.py::test_no_sol",
"sympy/solvers/tests/test_solveset.py::test_sol_zero_real",
"sympy/solvers/tests/test_solveset.py::test_no_sol_rational_extragenous",
"sympy/solvers/tests/test_solveset.py::test_solve_polynomial_cv_1a",
"sympy/solvers/tests/test_solveset.py::test_solveset_real_rational",
"sympy/solvers/tests/test_solveset.py::test_solveset_real_log",
"sympy/solvers/tests/test_solveset.py::test_poly_gens",
"sympy/solvers/tests/test_solveset.py::test_solve_abs",
"sympy/solvers/tests/test_solveset.py::test_real_imag_splitting",
"sympy/solvers/tests/test_solveset.py::test_units",
"sympy/solvers/tests/test_solveset.py::test_solve_only_exp_1",
"sympy/solvers/tests/test_solveset.py::test_atan2",
"sympy/solvers/tests/test_solveset.py::test_piecewise",
"sympy/solvers/tests/test_solveset.py::test_solveset_complex_polynomial",
"sympy/solvers/tests/test_solveset.py::test_sol_zero_complex",
"sympy/solvers/tests/test_solveset.py::test_solveset_complex_rational",
"sympy/solvers/tests/test_solveset.py::test_solve_complex_log",
"sympy/solvers/tests/test_solveset.py::test_solve_complex_sqrt",
"sympy/solvers/tests/test_solveset.py::test_solveset_complex_tan",
"sympy/solvers/tests/test_solveset.py::test_solve_trig",
"sympy/solvers/tests/test_solveset.py::test_solve_invalid_sol",
"sympy/solvers/tests/test_solveset.py::test_solve_complex_unsolvable",
"sympy/solvers/tests/test_solveset.py::test_solveset",
"sympy/solvers/tests/test_solveset.py::test_improve_coverage",
"sympy/solvers/tests/test_solveset.py::test_issue_9522",
"sympy/solvers/tests/test_solveset.py::test_linear_eq_to_matrix",
"sympy/solvers/tests/test_solveset.py::test_linsolve",
"sympy/solvers/tests/test_solveset.py::test_issue_9556",
"sympy/solvers/tests/test_solveset.py::test_issue_9611",
"sympy/solvers/tests/test_solveset.py::test_issue_9557"
] | [] | BSD | 201 |
|
colour-science__colour-213 | d09934a0cf3d851ce15b3a7556ec24673a9ddb35 | 2015-07-27 10:51:51 | 3cd6ab8d4c3483bcdeb2d7ef33967160808c0bb2 | diff --git a/colour/algebra/__init__.py b/colour/algebra/__init__.py
index f46d14502..77bfc6f5e 100644
--- a/colour/algebra/__init__.py
+++ b/colour/algebra/__init__.py
@@ -6,17 +6,19 @@ from __future__ import absolute_import
from .coordinates import * # noqa
from . import coordinates
from .extrapolation import Extrapolator1d
-from .interpolation import (LinearInterpolator1d,
- SplineInterpolator,
- SpragueInterpolator)
+from .interpolation import (LinearInterpolator,
+ SpragueInterpolator,
+ CubicSplineInterpolator,
+ PchipInterpolator)
from .matrix import is_identity
from .random import random_triplet_generator
__all__ = []
__all__ += coordinates.__all__
__all__ += ['Extrapolator1d']
-__all__ += ['LinearInterpolator1d',
- 'SplineInterpolator',
- 'SpragueInterpolator']
+__all__ += ['LinearInterpolator',
+ 'SpragueInterpolator',
+ 'CubicSplineInterpolator',
+ 'PchipInterpolator']
__all__ += ['is_identity']
__all__ += ['random_triplet_generator']
diff --git a/colour/algebra/extrapolation.py b/colour/algebra/extrapolation.py
index 148074866..3e60ad80a 100644
--- a/colour/algebra/extrapolation.py
+++ b/colour/algebra/extrapolation.py
@@ -74,10 +74,10 @@ class Extrapolator1d(object):
--------
Extrapolating a single numeric variable:
- >>> from colour.algebra import LinearInterpolator1d
+ >>> from colour.algebra import LinearInterpolator
>>> x = np.array([3, 4, 5])
>>> y = np.array([1, 2, 3])
- >>> interpolator = LinearInterpolator1d(x, y)
+ >>> interpolator = LinearInterpolator(x, y)
>>> extrapolator = Extrapolator1d(interpolator)
>>> extrapolator(1)
-1.0
@@ -91,7 +91,7 @@ class Extrapolator1d(object):
>>> x = np.array([3, 4, 5])
>>> y = np.array([1, 2, 3])
- >>> interpolator = LinearInterpolator1d(x, y)
+ >>> interpolator = LinearInterpolator(x, y)
>>> extrapolator = Extrapolator1d(interpolator, method='Constant')
>>> extrapolator(np.array([0.1, 0.2, 8, 9]))
array([ 1., 1., 3., 3.])
@@ -100,7 +100,7 @@ class Extrapolator1d(object):
>>> x = np.array([3, 4, 5])
>>> y = np.array([1, 2, 3])
- >>> interpolator = LinearInterpolator1d(x, y)
+ >>> interpolator = LinearInterpolator(x, y)
>>> extrapolator = Extrapolator1d(interpolator, method='Constant', left=0)
>>> extrapolator(np.array([0.1, 0.2, 8, 9]))
array([ 0., 0., 3., 3.])
diff --git a/colour/algebra/interpolation.py b/colour/algebra/interpolation.py
index 83aa98bb4..4830120da 100644
--- a/colour/algebra/interpolation.py
+++ b/colour/algebra/interpolation.py
@@ -7,10 +7,12 @@ Interpolation
Defines classes for interpolating variables.
-- :class:`LinearInterpolator1d`: 1-D function linear interpolation.
-- :class:`SplineInterpolator`: 1-D function cubic spline interpolation.
+- :class:`LinearInterpolator`: 1-D function linear interpolation.
- :class:`SpragueInterpolator`: 1-D function fifth-order polynomial
interpolation.
+- :class:`CubicSplineInterpolator`: 1-D function cubic spline interpolation.
+- :class:`PchipInterpolator`: 1-D function piecewise cube Hermite
+ interpolation.
"""
from __future__ import division, unicode_literals
@@ -32,12 +34,13 @@ __maintainer__ = 'Colour Developers'
__email__ = '[email protected]'
__status__ = 'Production'
-__all__ = ['LinearInterpolator1d',
- 'SplineInterpolator',
- 'SpragueInterpolator']
+__all__ = ['LinearInterpolator',
+ 'SpragueInterpolator',
+ 'CubicSplineInterpolator',
+ 'PchipInterpolator']
-class LinearInterpolator1d(object):
+class LinearInterpolator(object):
"""
Linearly interpolates a 1-D function.
@@ -74,7 +77,7 @@ class LinearInterpolator1d(object):
... 27.8007,
... 86.0500])
>>> x = np.arange(len(y))
- >>> f = LinearInterpolator1d(x, y)
+ >>> f = LinearInterpolator(x, y)
>>> # Doctests ellipsis for Python 2.x compatibility.
>>> f(0.5) # doctest: +ELLIPSIS
7.64...
@@ -225,31 +228,6 @@ class LinearInterpolator1d(object):
raise ValueError('"{0}" is above interpolation range.'.format(x))
-if is_scipy_installed():
- from scipy.interpolate import interp1d
-
- class SplineInterpolator(interp1d):
- """
- Interpolates a 1-D function using cubic spline interpolation.
-
- Notes
- -----
- This class is a wrapper around *scipy.interpolate.interp1d* class.
- """
-
- def __init__(self, *args, **kwargs):
- # TODO: Implements proper wrapper to ensure return values
- # consistency and avoid having to cast to numeric in
- # :meth:`SpectralPowerDistribution.interpolate` method.
- super(SplineInterpolator, self).__init__(
- kind='cubic', *args, **kwargs)
-else:
- warning(('"scipy.interpolate.interp1d" interpolator is unavailable, using '
- '"LinearInterpolator1d" instead!'))
-
- SplineInterpolator = LinearInterpolator1d
-
-
class SpragueInterpolator(object):
"""
Constructs a fifth-order polynomial that passes through :math:`y` dependent
@@ -273,7 +251,7 @@ class SpragueInterpolator(object):
See Also
--------
- LinearInterpolator1d
+ LinearInterpolator
Notes
-----
@@ -523,3 +501,29 @@ class SpragueInterpolator(object):
if above_interpolation_range.any():
raise ValueError('"{0}" is above interpolation range.'.format(x))
+
+
+if is_scipy_installed():
+ from scipy.interpolate import PchipInterpolator, interp1d
+
+ class CubicSplineInterpolator(interp1d):
+ """
+ Interpolates a 1-D function using cubic spline interpolation.
+
+ Notes
+ -----
+ This class is a wrapper around *scipy.interpolate.interp1d* class.
+ """
+
+ def __init__(self, *args, **kwargs):
+ # TODO: Implements proper wrapper to ensure return values
+ # consistency and avoid having to cast to numeric in
+ # :meth:`SpectralPowerDistribution.interpolate` method.
+ super(CubicSplineInterpolator, self).__init__(
+ kind='cubic', *args, **kwargs)
+else:
+ warning(('"scipy.interpolate.PchipInterpolator" and '
+ '"scipy.interpolate.interp1d" interpolators are not available, '
+ 'using "LinearInterpolator" instead!'))
+
+ PchipInterpolator = CubicSplineInterpolator = LinearInterpolator
diff --git a/colour/colorimetry/spectrum.py b/colour/colorimetry/spectrum.py
index 37412d73f..bff22dd7d 100644
--- a/colour/colorimetry/spectrum.py
+++ b/colour/colorimetry/spectrum.py
@@ -26,9 +26,10 @@ import numpy as np
from colour.algebra import (
Extrapolator1d,
- LinearInterpolator1d,
- SplineInterpolator,
- SpragueInterpolator)
+ LinearInterpolator,
+ SpragueInterpolator,
+ CubicSplineInterpolator,
+ PchipInterpolator)
from colour.utilities import (
ArbitraryPrecisionMapping,
is_iterable,
@@ -1587,11 +1588,8 @@ class SpectralPowerDistribution(object):
"""
extrapolator = Extrapolator1d(
- LinearInterpolator1d(self.wavelengths,
- self.values),
- method=method,
- left=left,
- right=right)
+ LinearInterpolator(self.wavelengths, self.values),
+ method=method, left=left, right=right)
spd_shape = self.shape
for i in np.arange(spd_shape.start,
@@ -1618,7 +1616,7 @@ class SpectralPowerDistribution(object):
shape : SpectralShape, optional
Spectral shape used for interpolation.
method : unicode, optional
- {None, 'Sprague', 'Cubic Spline', 'Linear'},
+ {None, 'Cubic Spline', 'Linear', 'Pchip', 'Sprague'},
Enforce given interpolation method.
Returns
@@ -1651,9 +1649,11 @@ class SpectralPowerDistribution(object):
-------
- If *scipy* is not unavailable the *Cubic Spline* method will
fallback to legacy *Linear* interpolation.
+ - *Cubic Spline* interpolator requires at least 3 wavelengths
+ :math:`\lambda_n` for interpolation.
- *Linear* interpolator requires at least 2 wavelengths
:math:`\lambda_n` for interpolation.
- - *Cubic Spline* interpolator requires at least 3 wavelengths
+ - *Pchip* interpolator requires at least 2 wavelengths
:math:`\lambda_n` for interpolation.
- Sprague (1880) interpolator requires at least 6 wavelengths
:math:`\lambda_n` for interpolation.
@@ -1683,13 +1683,6 @@ class SpectralPowerDistribution(object):
Non uniform data is using *Cubic Spline* interpolation by default:
- >>> data = {
- ... 510: 49.67,
- ... 520: 69.59,
- ... 530: 81.73,
- ... 540: 88.19,
- ... 550: 86.26,
- ... 560: 77.18}
>>> spd = SpectralPowerDistribution('Spd', data)
>>> spd[511] = 31.41
>>> spd.interpolate(SpectralShape(steps=1)) # doctest: +ELLIPSIS
@@ -1699,18 +1692,23 @@ class SpectralPowerDistribution(object):
Enforcing *Linear* interpolation:
- >>> data = {
- ... 510: 49.67,
- ... 520: 69.59,
- ... 530: 81.73,
- ... 540: 88.19,
- ... 550: 86.26,
- ... 560: 77.18}
>>> spd = SpectralPowerDistribution('Spd', data)
- >>> spd.interpolate(SpectralShape(steps=1), method='Linear') # noqa # doctest: +ELLIPSIS
+ >>> spd.interpolate( # doctest: +ELLIPSIS
+ ... SpectralShape(steps=1),
+ ... method='Linear')
<...SpectralPowerDistribution object at 0x...>
>>> spd[515] # doctest: +ELLIPSIS
array(59.63...)
+
+ Enforcing *Pchip* interpolation:
+
+ >>> spd = SpectralPowerDistribution('Spd', data)
+ >>> spd.interpolate( # doctest: +ELLIPSIS
+ ... SpectralShape(steps=1),
+ ... method='Pchip')
+ <...SpectralPowerDistribution object at 0x...>
+ >>> spd[515] # doctest: +ELLIPSIS
+ array(58.8173260...)
"""
spd_shape = self.shape
@@ -1732,25 +1730,28 @@ class SpectralPowerDistribution(object):
if method is None:
if is_uniform:
- interpolator = SpragueInterpolator(wavelengths, values)
+ interpolator = SpragueInterpolator
else:
- interpolator = SplineInterpolator(wavelengths, values)
+ interpolator = CubicSplineInterpolator
+ elif method == 'cubic spline':
+ interpolator = CubicSplineInterpolator
+ elif method == 'linear':
+ interpolator = LinearInterpolator
+ elif method == 'pchip':
+ interpolator = PchipInterpolator
elif method == 'sprague':
if is_uniform:
- interpolator = SpragueInterpolator(wavelengths, values)
+ interpolator = SpragueInterpolator
else:
raise RuntimeError(
('"Sprague" interpolator can only be used for '
'interpolating functions having a uniformly spaced '
'independent variable!'))
- elif method == 'cubic spline':
- interpolator = SplineInterpolator(wavelengths, values)
- elif method == 'linear':
- interpolator = LinearInterpolator1d(wavelengths, values)
else:
raise ValueError(
'Undefined "{0}" interpolator!'.format(method))
+ interpolator = interpolator(wavelengths, values)
self.__data = SpectralMapping(
[(wavelength, float(interpolator(wavelength)))
for wavelength in shape])
@@ -3351,7 +3352,7 @@ class TriSpectralPowerDistribution(object):
shape : SpectralShape, optional
Spectral shape used for interpolation.
method : unicode, optional
- {None, 'Sprague', 'Cubic Spline', 'Linear'},
+ {None, 'Cubic Spline', 'Linear', 'Pchip', 'Sprague'},
Enforce given interpolation method.
Returns
@@ -3403,71 +3404,43 @@ class TriSpectralPowerDistribution(object):
>>> tri_spd = TriSpectralPowerDistribution('Tri Spd', data, mapping)
>>> tri_spd.interpolate(SpectralShape(steps=1)) # doctest: +ELLIPSIS
<...TriSpectralPowerDistribution object at 0x...>
- >>> tri_spd[515]
- array([ 60.30332087, 93.27163315, 13.86051361])
+ >>> tri_spd[515] # doctest: +ELLIPSIS
+ array([ 60.3033208..., 93.2716331..., 13.8605136...])
Non uniform data is using *Cubic Spline* interpolation by default:
- >>> x_bar = {
- ... 510: 49.67,
- ... 520: 69.59,
- ... 530: 81.73,
- ... 540: 88.19,
- ... 550: 89.76,
- ... 560: 90.28}
- >>> y_bar = {
- ... 510: 90.56,
- ... 520: 87.34,
- ... 530: 45.76,
- ... 540: 23.45,
- ... 550: 15.34,
- ... 560: 10.11}
- >>> z_bar = {
- ... 510: 12.43,
- ... 520: 23.15,
- ... 530: 67.98,
- ... 540: 90.28,
- ... 550: 91.61,
- ... 560: 98.24}
>>> data = {'x_bar': x_bar, 'y_bar': y_bar, 'z_bar': z_bar}
>>> mapping = {'x': 'x_bar', 'y': 'y_bar', 'z': 'z_bar'}
>>> tri_spd = TriSpectralPowerDistribution('Tri Spd', data, mapping)
>>> tri_spd[511] = np.array([31.41, 95.27, 15.06])
>>> tri_spd.interpolate(SpectralShape(steps=1)) # doctest: +ELLIPSIS
<...TriSpectralPowerDistribution object at 0x...>
- >>> tri_spd[515]
- array([ 21.47104053, 100.64300155, 18.8165196 ])
+ >>> tri_spd[515] # doctest: +ELLIPSIS
+ array([ 21.4710405..., 100.6430015..., 18.8165196...])
Enforcing *Linear* interpolation:
- >>> x_bar = {
- ... 510: 49.67,
- ... 520: 69.59,
- ... 530: 81.73,
- ... 540: 88.19,
- ... 550: 89.76,
- ... 560: 90.28}
- >>> y_bar = {
- ... 510: 90.56,
- ... 520: 87.34,
- ... 530: 45.76,
- ... 540: 23.45,
- ... 550: 15.34,
- ... 560: 10.11}
- >>> z_bar = {
- ... 510: 12.43,
- ... 520: 23.15,
- ... 530: 67.98,
- ... 540: 90.28,
- ... 550: 91.61,
- ... 560: 98.24}
>>> data = {'x_bar': x_bar, 'y_bar': y_bar, 'z_bar': z_bar}
>>> mapping = {'x': 'x_bar', 'y': 'y_bar', 'z': 'z_bar'}
>>> tri_spd = TriSpectralPowerDistribution('Tri Spd', data, mapping)
- >>> tri_spd.interpolate(SpectralShape(steps=1), method='Linear') # noqa # doctest: +ELLIPSIS
+ >>> tri_spd.interpolate( # doctest: +ELLIPSIS
+ ... SpectralShape(steps=1),
+ ... method='Linear')
+ <...TriSpectralPowerDistribution object at 0x...>
+ >>> tri_spd[515] # doctest: +ELLIPSIS
+ array([ 59.63..., 88.95..., 17.79...])
+
+ Enforcing *Pchip* interpolation:
+
+ >>> data = {'x_bar': x_bar, 'y_bar': y_bar, 'z_bar': z_bar}
+ >>> mapping = {'x': 'x_bar', 'y': 'y_bar', 'z': 'z_bar'}
+ >>> tri_spd = TriSpectralPowerDistribution('Tri Spd', data, mapping)
+ >>> tri_spd.interpolate( # doctest: +ELLIPSIS
+ ... SpectralShape(steps=1),
+ ... method='Pchip')
<...TriSpectralPowerDistribution object at 0x...>
- >>> tri_spd[515]
- array([ 59.63, 88.95, 17.79])
+ >>> tri_spd[515] # doctest: +ELLIPSIS
+ array([ 58.8173260..., 89.4355596..., 16.4545683...])
"""
for i in self.__mapping.keys():
diff --git a/colour/colorimetry/tristimulus.py b/colour/colorimetry/tristimulus.py
index e3d3eaa32..a901fc0cc 100644
--- a/colour/colorimetry/tristimulus.py
+++ b/colour/colorimetry/tristimulus.py
@@ -19,8 +19,13 @@ from __future__ import division, unicode_literals
import numpy as np
-from colour.algebra import SplineInterpolator, SpragueInterpolator
+from colour.algebra import (
+ CubicSplineInterpolator,
+ LinearInterpolator,
+ PchipInterpolator,
+ SpragueInterpolator)
from colour.colorimetry import STANDARD_OBSERVERS_CMFS, ones_spd
+from colour.utilities import is_string
__author__ = 'Colour Developers'
__copyright__ = 'Copyright (C) 2013 - 2015 - Colour Developers'
@@ -111,7 +116,8 @@ def spectral_to_XYZ(spd,
def wavelength_to_XYZ(wavelength,
cmfs=STANDARD_OBSERVERS_CMFS.get(
- 'CIE 1931 2 Degree Standard Observer')):
+ 'CIE 1931 2 Degree Standard Observer'),
+ method=None):
"""
Converts given wavelength :math:`\lambda` to *CIE XYZ* tristimulus values
using given colour matching functions.
@@ -128,6 +134,9 @@ def wavelength_to_XYZ(wavelength,
Wavelength :math:`\lambda` in nm.
cmfs : XYZ_ColourMatchingFunctions, optional
Standard observer colour matching functions.
+ method : unicode, optional
+ {None, 'Cubic Spline', 'Linear', 'Pchip', 'Sprague'},
+ Enforce given interpolation method.
Returns
-------
@@ -136,22 +145,60 @@ def wavelength_to_XYZ(wavelength,
Raises
------
+ RuntimeError
+ If Sprague (1880) interpolation method is forced with a
+ non-uniformly spaced independent variable.
ValueError
- If wavelength :math:`\lambda` is not contained in the colour matching
- functions domain.
+ If the interpolation method is not defined or if wavelength
+ :math:`\lambda` is not contained in the colour matching functions
+ domain.
Notes
-----
- Output *CIE XYZ* tristimulus values are in domain [0, 1].
- If *scipy* is not unavailable the *Cubic Spline* method will fallback
to legacy *Linear* interpolation.
+ - Sprague (1880) interpolator cannot be used for interpolating
+ functions having a non-uniformly spaced independent variable.
+
+ Warning
+ -------
+ - If *scipy* is not unavailable the *Cubic Spline* method will fallback
+ to legacy *Linear* interpolation.
+ - *Cubic Spline* interpolator requires at least 3 wavelengths
+ :math:`\lambda_n` for interpolation.
+ - *Linear* interpolator requires at least 2 wavelengths :math:`\lambda_n`
+ for interpolation.
+ - *Pchip* interpolator requires at least 2 wavelengths :math:`\lambda_n`
+ for interpolation.
+ - Sprague (1880) interpolator requires at least 6 wavelengths
+ :math:`\lambda_n` for interpolation.
Examples
--------
+ Uniform data is using Sprague (1880) interpolation by default:
+
>>> from colour import CMFS
>>> cmfs = CMFS.get('CIE 1931 2 Degree Standard Observer')
- >>> wavelength_to_XYZ(480) # doctest: +ELLIPSIS
+ >>> wavelength_to_XYZ(480, cmfs) # doctest: +ELLIPSIS
array([ 0.09564 , 0.13902 , 0.812950...])
+ >>> wavelength_to_XYZ(480.5, cmfs) # doctest: +ELLIPSIS
+ array([ 0.0914287..., 0.1418350..., 0.7915726...])
+
+ Enforcing *Cubic Spline* interpolation:
+
+ >>> wavelength_to_XYZ(480.5, cmfs, 'Cubic Spline') # doctest: +ELLIPSIS
+ array([ 0.0914288..., 0.1418351..., 0.7915729...])
+
+ Enforcing *Linear* interpolation:
+
+ >>> wavelength_to_XYZ(480.5, cmfs, 'Linear') # doctest: +ELLIPSIS
+ array([ 0.0914697..., 0.1418482..., 0.7917337...])
+
+ Enforcing *Pchip* interpolation:
+
+ >>> wavelength_to_XYZ(480.5, cmfs, 'Pchip') # doctest: +ELLIPSIS
+ array([ 0.0914280..., 0.1418341..., 0.7915711...])
"""
cmfs_shape = cmfs.shape
@@ -163,9 +210,34 @@ def wavelength_to_XYZ(wavelength,
if wavelength not in cmfs:
wavelengths, values, = cmfs.wavelengths, cmfs.values
- interpolator = (SpragueInterpolator
- if cmfs.is_uniform() else
- SplineInterpolator)
+
+ if is_string(method):
+ method = method.lower()
+
+ is_uniform = cmfs.is_uniform()
+
+ if method is None:
+ if is_uniform:
+ interpolator = SpragueInterpolator
+ else:
+ interpolator = CubicSplineInterpolator
+ elif method == 'cubic spline':
+ interpolator = CubicSplineInterpolator
+ elif method == 'linear':
+ interpolator = LinearInterpolator
+ elif method == 'pchip':
+ interpolator = PchipInterpolator
+ elif method == 'sprague':
+ if is_uniform:
+ interpolator = SpragueInterpolator
+ else:
+ raise RuntimeError(
+ ('"Sprague" interpolator can only be used for '
+ 'interpolating functions having a uniformly spaced '
+ 'independent variable!'))
+ else:
+ raise ValueError(
+ 'Undefined "{0}" interpolator!'.format(method))
interpolators = [interpolator(wavelengths, values[..., i])
for i in range(values.shape[-1])]
diff --git a/colour/examples/algebra/examples_interpolation.py b/colour/examples/algebra/examples_interpolation.py
index 9f94f50e4..d2edba760 100644
--- a/colour/examples/algebra/examples_interpolation.py
+++ b/colour/examples/algebra/examples_interpolation.py
@@ -16,7 +16,7 @@ from colour.utilities.verbose import message_box
message_box('Interpolation Computations')
message_box(('Comparing Sprague (1880) and "Cubic Spline" recommended '
- 'interpolation methods.'))
+ 'interpolation methods to "Pchip" method.'))
uniform_spd_data = {
340: 0.0000,
@@ -78,11 +78,16 @@ base_spd = colour.SpectralPowerDistribution(
uniform_interpolated_spd = colour.SpectralPowerDistribution(
'Uniform - Sprague Interpolation',
uniform_spd_data)
+uniform_pchip_interpolated_spd = colour.SpectralPowerDistribution(
+ 'Uniform - Pchip Interpolation',
+ uniform_spd_data)
non_uniform_interpolated_spd = colour.SpectralPowerDistribution(
'Non Uniform - Cubic Spline Interpolation',
non_uniform_spd_data)
uniform_interpolated_spd.interpolate(colour.SpectralShape(steps=1))
+uniform_pchip_interpolated_spd.interpolate(colour.SpectralShape(steps=1),
+ method='Pchip')
non_uniform_interpolated_spd.interpolate(colour.SpectralShape(steps=1))
shape = base_spd.shape
@@ -97,6 +102,10 @@ pylab.plot(uniform_interpolated_spd.wavelengths,
uniform_interpolated_spd.values,
label=uniform_interpolated_spd.name,
linewidth=2)
+pylab.plot(uniform_pchip_interpolated_spd.wavelengths,
+ uniform_pchip_interpolated_spd.values,
+ label=uniform_pchip_interpolated_spd.name,
+ linewidth=2)
pylab.plot(non_uniform_interpolated_spd.wavelengths,
non_uniform_interpolated_spd.values,
label=non_uniform_interpolated_spd.name,
diff --git a/colour/notation/munsell.py b/colour/notation/munsell.py
index 9a39cc6f7..93106af11 100644
--- a/colour/notation/munsell.py
+++ b/colour/notation/munsell.py
@@ -53,7 +53,7 @@ except ImportError:
from colour.algebra import (
Extrapolator1d,
- LinearInterpolator1d,
+ LinearInterpolator,
cartesian_to_cylindrical)
from colour.colorimetry import ILLUMINANTS, luminance_ASTMD153508
from colour.constants import (
@@ -197,7 +197,7 @@ def _munsell_value_ASTMD153508_interpolator():
munsell_values = np.arange(0, 10, 0.001)
if _MUNSELL_VALUE_ASTM_D1535_08_INTERPOLATOR_CACHE is None:
_MUNSELL_VALUE_ASTM_D1535_08_INTERPOLATOR_CACHE = Extrapolator1d(
- LinearInterpolator1d(
+ LinearInterpolator(
luminance_ASTMD153508(munsell_values),
munsell_values))
@@ -624,8 +624,8 @@ def munsell_specification_to_xyY(specification):
else:
Y_minus = luminance_ASTMD153508(value_minus)
Y_plus = luminance_ASTMD153508(value_plus)
- x = LinearInterpolator1d((Y_minus, Y_plus), (x_minus, x_plus))(Y)
- y = LinearInterpolator1d((Y_minus, Y_plus), (y_minus, y_plus))(Y)
+ x = LinearInterpolator((Y_minus, Y_plus), (x_minus, x_plus))(Y)
+ y = LinearInterpolator((Y_minus, Y_plus), (y_minus, y_plus))(Y)
return np.array([x, y, Y / 100])
@@ -826,7 +826,7 @@ def xyY_to_munsell_specification(xyY):
theta_differences_indexes]
hue_angle_difference_new = Extrapolator1d(
- LinearInterpolator1d(
+ LinearInterpolator(
theta_differences,
hue_angles_differences))(0) % 360
hue_angle_new = (hue_angle_current + hue_angle_difference_new) % 360
@@ -891,7 +891,7 @@ def xyY_to_munsell_specification(xyY):
rho_bounds = rho_bounds[rhos_bounds_indexes]
chroma_bounds = chroma_bounds[rhos_bounds_indexes]
- chroma_new = LinearInterpolator1d(rho_bounds, chroma_bounds)(rho_input)
+ chroma_new = LinearInterpolator(rho_bounds, chroma_bounds)(rho_input)
specification_current = [hue_current, value, chroma_new, code_current]
x_current, y_current, Y_current = np.ravel(
@@ -1305,7 +1305,7 @@ def hue_to_hue_angle(hue, code):
"""
single_hue = ((17 - code) % 10 + (hue / 10) - 0.5) % 10
- return LinearInterpolator1d(
+ return LinearInterpolator(
(0, 2, 3, 4, 5, 6, 8, 9, 10),
(0, 45, 70, 135, 160, 225, 255, 315, 360))(single_hue)
@@ -1339,7 +1339,7 @@ def hue_angle_to_hue(hue_angle):
(3.2160000..., 4)
"""
- single_hue = LinearInterpolator1d(
+ single_hue = LinearInterpolator(
(0, 45, 70, 135, 160, 225, 255, 315, 360),
(0, 2, 3, 4, 5, 6, 8, 9, 10))(hue_angle)
@@ -1826,15 +1826,15 @@ def xy_from_renotation_ovoid(specification):
specification).lower()
if interpolation_method == 'linear':
- x = LinearInterpolator1d((lower_hue_angle, upper_hue_angle),
- (x_minus, x_plus))(hue_angle)
- y = LinearInterpolator1d((lower_hue_angle, upper_hue_angle),
- (y_minus, y_plus))(hue_angle)
+ x = LinearInterpolator((lower_hue_angle, upper_hue_angle),
+ (x_minus, x_plus))(hue_angle)
+ y = LinearInterpolator((lower_hue_angle, upper_hue_angle),
+ (y_minus, y_plus))(hue_angle)
elif interpolation_method == 'radial':
- theta = LinearInterpolator1d((lower_hue_angle, upper_hue_angle),
- (theta_minus, theta_plus))(hue_angle)
- rho = LinearInterpolator1d((lower_hue_angle, upper_hue_angle),
- (rho_minus, rho_plus))(hue_angle)
+ theta = LinearInterpolator((lower_hue_angle, upper_hue_angle),
+ (theta_minus, theta_plus))(hue_angle)
+ rho = LinearInterpolator((lower_hue_angle, upper_hue_angle),
+ (rho_minus, rho_plus))(hue_angle)
x = rho * np.cos(np.radians(theta)) + x_grey
y = rho * np.sin(np.radians(theta)) + y_grey
@@ -1903,7 +1903,7 @@ def LCHab_to_munsell_specification(LCHab):
else:
code = 8
- hue = LinearInterpolator1d((0, 36), (0, 10))(Hab % 36)
+ hue = LinearInterpolator((0, 36), (0, 10))(Hab % 36)
if hue == 0:
hue = 10
@@ -1986,8 +1986,8 @@ def maximum_chroma_from_renotation(hue, value, code):
L9 = luminance_ASTMD153508(9)
L10 = luminance_ASTMD153508(10)
- max_chroma = min(LinearInterpolator1d((L9, L10), (ma_limit_mcw, 0))(L),
- LinearInterpolator1d((L9, L10), (ma_limit_mccw, 0))(
+ max_chroma = min(LinearInterpolator((L9, L10), (ma_limit_mcw, 0))(L),
+ LinearInterpolator((L9, L10), (ma_limit_mccw, 0))(
L))
return max_chroma
@@ -2065,9 +2065,9 @@ def munsell_specification_to_xy(specification):
x = x_minus
y = y_minus
else:
- x = LinearInterpolator1d((chroma_minus, chroma_plus),
- (x_minus, x_plus))(chroma)
- y = LinearInterpolator1d((chroma_minus, chroma_plus),
- (y_minus, y_plus))(chroma)
+ x = LinearInterpolator((chroma_minus, chroma_plus),
+ (x_minus, x_plus))(chroma)
+ y = LinearInterpolator((chroma_minus, chroma_plus),
+ (y_minus, y_plus))(chroma)
return x, y
diff --git a/colour/plotting/__init__.py b/colour/plotting/__init__.py
index 04dbb252b..0686b6164 100644
--- a/colour/plotting/__init__.py
+++ b/colour/plotting/__init__.py
@@ -12,9 +12,9 @@ from .common import (
DEFAULT_FIGURE_HEIGHT,
DEFAULT_FIGURE_SIZE,
DEFAULT_FONT_SIZE,
- DEFAULT_PARAMETERS,
DEFAULT_COLOUR_CYCLE,
DEFAULT_HATCH_PATTERNS,
+ DEFAULT_PARAMETERS,
DEFAULT_PLOTTING_ILLUMINANT,
DEFAULT_PLOTTING_OECF,
ColourParameter,
@@ -91,9 +91,9 @@ __all__ += [
'DEFAULT_FIGURE_HEIGHT',
'DEFAULT_FIGURE_SIZE',
'DEFAULT_FONT_SIZE',
- 'DEFAULT_PARAMETERS',
'DEFAULT_COLOUR_CYCLE',
'DEFAULT_HATCH_PATTERNS',
+ 'DEFAULT_PARAMETERS',
'DEFAULT_PLOTTING_ILLUMINANT',
'DEFAULT_PLOTTING_OECF',
'ColourParameter',
diff --git a/colour/plotting/colorimetry.py b/colour/plotting/colorimetry.py
index 049493214..730c22501 100644
--- a/colour/plotting/colorimetry.py
+++ b/colour/plotting/colorimetry.py
@@ -256,8 +256,6 @@ def multi_spd_plot(spds,
y_limit_min.append(min(values))
y_limit_max.append(max(values))
- matplotlib.pyplot.rc("axes", color_cycle=["r", "g", "b", "y"])
-
if use_spds_colours:
XYZ = spectral_to_XYZ(spd, cmfs, illuminant) / 100
if normalise_spds_colours:
diff --git a/colour/plotting/common.py b/colour/plotting/common.py
index 1b0eae504..4dd9bfd4e 100644
--- a/colour/plotting/common.py
+++ b/colour/plotting/common.py
@@ -53,9 +53,9 @@ __all__ = ['PLOTTING_RESOURCES_DIRECTORY',
'DEFAULT_FIGURE_HEIGHT',
'DEFAULT_FIGURE_SIZE',
'DEFAULT_FONT_SIZE',
- 'DEFAULT_PARAMETERS',
'DEFAULT_COLOUR_CYCLE',
'DEFAULT_HATCH_PATTERNS',
+ 'DEFAULT_PARAMETERS',
'DEFAULT_PLOTTING_ILLUMINANT',
'DEFAULT_PLOTTING_OECF',
'ColourParameter',
@@ -123,22 +123,6 @@ DEFAULT_FONT_SIZE : numeric
if 'Qt4Agg' in matplotlib.get_backend():
DEFAULT_FONT_SIZE = 10
-DEFAULT_PARAMETERS = {
- 'figure.figsize': DEFAULT_FIGURE_SIZE,
- 'font.size': DEFAULT_FONT_SIZE,
- 'axes.titlesize': DEFAULT_FONT_SIZE * 1.25,
- 'axes.labelsize': DEFAULT_FONT_SIZE * 1.25,
- 'legend.fontsize': DEFAULT_FONT_SIZE * 0.9,
- 'xtick.labelsize': DEFAULT_FONT_SIZE,
- 'ytick.labelsize': DEFAULT_FONT_SIZE}
-"""
-Default plotting parameters.
-
-DEFAULT_PARAMETERS : dict
-"""
-
-pylab.rcParams.update(DEFAULT_PARAMETERS)
-
DEFAULT_COLOUR_CYCLE = ('r', 'g', 'b', 'c', 'm', 'y', 'k')
"""
Default colour cycle for plots.
@@ -155,6 +139,23 @@ DEFAULT_HATCH_PATTERNS : tuple
{'\\\\', 'o', 'x', '.', '*', '//'}
"""
+DEFAULT_PARAMETERS = {
+ 'figure.figsize': DEFAULT_FIGURE_SIZE,
+ 'font.size': DEFAULT_FONT_SIZE,
+ 'axes.titlesize': DEFAULT_FONT_SIZE * 1.25,
+ 'axes.labelsize': DEFAULT_FONT_SIZE * 1.25,
+ 'legend.fontsize': DEFAULT_FONT_SIZE * 0.9,
+ 'xtick.labelsize': DEFAULT_FONT_SIZE,
+ 'ytick.labelsize': DEFAULT_FONT_SIZE,
+ 'axes.color_cycle': DEFAULT_COLOUR_CYCLE}
+"""
+Default plotting parameters.
+
+DEFAULT_PARAMETERS : dict
+"""
+
+pylab.rcParams.update(DEFAULT_PARAMETERS)
+
DEFAULT_PLOTTING_ILLUMINANT = ILLUMINANTS.get(
'CIE 1931 2 Degree Standard Observer').get('D65')
"""
| Implement support for spectral data "Piecewise Cubic Hermite Interpolation". | colour-science/colour | diff --git a/colour/algebra/tests/tests_extrapolation.py b/colour/algebra/tests/tests_extrapolation.py
index 9565bb613..00f7a4262 100644
--- a/colour/algebra/tests/tests_extrapolation.py
+++ b/colour/algebra/tests/tests_extrapolation.py
@@ -16,7 +16,7 @@ else:
import unittest
from itertools import permutations
-from colour.algebra import Extrapolator1d, LinearInterpolator1d
+from colour.algebra import Extrapolator1d, LinearInterpolator
from colour.utilities import ignore_numpy_errors
__author__ = 'Colour Developers'
@@ -62,14 +62,14 @@ class TestExtrapolator1d(unittest.TestCase):
"""
extrapolator = Extrapolator1d(
- LinearInterpolator1d(
+ LinearInterpolator(
np.array([5, 6, 7]),
np.array([5, 6, 7])))
np.testing.assert_almost_equal(extrapolator((4, 8)), (4., 8.))
self.assertEqual(extrapolator(4), 4.)
extrapolator = Extrapolator1d(
- LinearInterpolator1d(
+ LinearInterpolator(
np.array([3, 4, 5]),
np.array([1, 2, 3])),
method='Constant')
@@ -78,7 +78,7 @@ class TestExtrapolator1d(unittest.TestCase):
self.assertEqual(extrapolator(0.1), 1.)
extrapolator = Extrapolator1d(
- LinearInterpolator1d(
+ LinearInterpolator(
np.array([3, 4, 5]),
np.array([1, 2, 3])),
method='Constant',
@@ -88,7 +88,7 @@ class TestExtrapolator1d(unittest.TestCase):
self.assertEqual(extrapolator(0.1), 0.)
extrapolator = Extrapolator1d(
- LinearInterpolator1d(
+ LinearInterpolator(
np.array([3, 4, 5]),
np.array([1, 2, 3])),
method='Constant',
@@ -108,7 +108,7 @@ class TestExtrapolator1d(unittest.TestCase):
cases = set(permutations(cases * 3, r=3))
for case in cases:
extrapolator = Extrapolator1d(
- LinearInterpolator1d(np.array(case), np.array(case)))
+ LinearInterpolator(np.array(case), np.array(case)))
extrapolator(case[0])
diff --git a/colour/algebra/tests/tests_interpolation.py b/colour/algebra/tests/tests_interpolation.py
index ba5113322..0b85c20f8 100644
--- a/colour/algebra/tests/tests_interpolation.py
+++ b/colour/algebra/tests/tests_interpolation.py
@@ -17,7 +17,7 @@ else:
from itertools import permutations
from colour.algebra import (
- LinearInterpolator1d,
+ LinearInterpolator,
SpragueInterpolator)
from colour.utilities import ignore_numpy_errors
@@ -362,7 +362,7 @@ SPRAGUE_INTERPOLATED_POINTS_DATA_A_10_SAMPLES = (
class TestLinearInterpolator1d(unittest.TestCase):
"""
Defines
- :func:`colour.algebra.interpolation.LinearInterpolator1d` class units
+ :func:`colour.algebra.interpolation.LinearInterpolator` class units
tests methods.
"""
@@ -375,7 +375,7 @@ class TestLinearInterpolator1d(unittest.TestCase):
'y')
for attribute in required_attributes:
- self.assertIn(attribute, dir(LinearInterpolator1d))
+ self.assertIn(attribute, dir(LinearInterpolator))
def test_required_methods(self):
"""
@@ -385,18 +385,18 @@ class TestLinearInterpolator1d(unittest.TestCase):
required_methods = ()
for method in required_methods:
- self.assertIn(method, dir(LinearInterpolator1d))
+ self.assertIn(method, dir(LinearInterpolator))
def test___call__(self):
"""
Tests
- :func:`colour.algebra.interpolation.LinearInterpolator1d.__call__`
+ :func:`colour.algebra.interpolation.LinearInterpolator.__call__`
method.
"""
steps = 0.1
x = np.arange(len(POINTS_DATA_A))
- linear_interpolator = LinearInterpolator1d(x, POINTS_DATA_A)
+ linear_interpolator = LinearInterpolator(x, POINTS_DATA_A)
for i, value in enumerate(
np.arange(0, len(POINTS_DATA_A) - 1 + steps, steps)):
@@ -414,7 +414,7 @@ class TestLinearInterpolator1d(unittest.TestCase):
def test_nan__call__(self):
"""
Tests
- :func:`colour.algebra.interpolation.LinearInterpolator1d.__call__`
+ :func:`colour.algebra.interpolation.LinearInterpolator.__call__`
method nan support.
"""
@@ -422,7 +422,7 @@ class TestLinearInterpolator1d(unittest.TestCase):
cases = set(permutations(cases * 3, r=3))
for case in cases:
try:
- linear_interpolator = LinearInterpolator1d(
+ linear_interpolator = LinearInterpolator(
np.array(case), np.array(case))
linear_interpolator(case[0])
except ValueError:
diff --git a/colour/colorimetry/tests/tests_spectrum.py b/colour/colorimetry/tests/tests_spectrum.py
index f32ef44ce..5677a5226 100644
--- a/colour/colorimetry/tests/tests_spectrum.py
+++ b/colour/colorimetry/tests/tests_spectrum.py
@@ -2434,6 +2434,20 @@ class TestSpectralPowerDistribution(unittest.TestCase):
rtol=0.0000001,
atol=0.0000001)
+ np.testing.assert_almost_equal(
+ self.__spd.clone().interpolate(
+ SpectralShape(steps=1),
+ method='Linear')[410],
+ np.array(0.0643),
+ decimal=7)
+
+ np.testing.assert_almost_equal(
+ self.__spd.clone().interpolate(
+ SpectralShape(steps=1),
+ method='Pchip')[410],
+ np.array(0.06439937984496125),
+ decimal=7)
+
def test_align(self):
"""
Tests
@@ -2971,6 +2985,20 @@ class TestTriSpectralPowerDistribution(unittest.TestCase):
rtol=0.0000001,
atol=0.0000001)
+ np.testing.assert_almost_equal(
+ self.__tri_spd.clone().interpolate(
+ SpectralShape(steps=1),
+ method='Linear')[411],
+ np.array([0.050334, 0.001404, 0.24018]),
+ decimal=7)
+
+ np.testing.assert_almost_equal(
+ self.__tri_spd.clone().interpolate(
+ SpectralShape(steps=1),
+ method='Pchip')[411],
+ np.array([0.04895501, 0.00136229, 0.23349933]),
+ decimal=7)
+
def test_align(self):
"""
Tests
diff --git a/colour/colorimetry/tests/tests_tristimulus.py b/colour/colorimetry/tests/tests_tristimulus.py
index 33fecf517..97a72d384 100644
--- a/colour/colorimetry/tests/tests_tristimulus.py
+++ b/colour/colorimetry/tests/tests_tristimulus.py
@@ -208,6 +208,30 @@ class TestWavelength_to_XYZ(unittest.TestCase):
np.array([0.44575583, 0.18184213, 0.]),
decimal=7)
+ np.testing.assert_almost_equal(
+ wavelength_to_XYZ(
+ 480.5,
+ CMFS.get('CIE 2012 2 Degree Standard Observer'),
+ 'Cubic Spline'),
+ np.array([0.07773422, 0.18148028, 0.7337162]),
+ decimal=7)
+
+ np.testing.assert_almost_equal(
+ wavelength_to_XYZ(
+ 480.5,
+ CMFS.get('CIE 2012 2 Degree Standard Observer'),
+ 'Linear'),
+ np.array([0.07779856, 0.18149335, 0.7340129]),
+ decimal=7)
+
+ np.testing.assert_almost_equal(
+ wavelength_to_XYZ(
+ 480.5,
+ CMFS.get('CIE 2012 2 Degree Standard Observer'),
+ 'Pchip'),
+ np.array([0.07773515, 0.18148048, 0.73372294]),
+ decimal=7)
+
def test_n_dimensional_wavelength_to_XYZ(self):
"""
Tests
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 2,
"issue_text_score": 2,
"test_score": 2
},
"num_modified_files": 10
} | 0.3 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[tests]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.4",
"reqs_path": [
"requirements/base.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | attrs==22.2.0
certifi==2021.5.30
-e git+https://github.com/colour-science/colour.git@d09934a0cf3d851ce15b3a7556ec24673a9ddb35#egg=colour_science
coverage==6.2
flake8==5.0.4
importlib-metadata==4.2.0
iniconfig==1.1.1
mccabe==0.7.0
nose==1.3.7
numpy==1.19.5
packaging==21.3
pluggy==1.0.0
py==1.11.0
pycodestyle==2.9.1
pyflakes==2.5.0
pyparsing==3.1.4
pytest==7.0.1
tomli==1.2.3
typing_extensions==4.1.1
zipp==3.6.0
| name: colour
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2021.5.30=py36h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.3=he6710b0_2
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- pip=21.2.2=py36h06a4308_0
- python=3.6.13=h12debd9_1
- readline=8.2=h5eee18b_0
- setuptools=58.0.4=py36h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- wheel=0.37.1=pyhd3eb1b0_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- attrs==22.2.0
- coverage==6.2
- flake8==5.0.4
- importlib-metadata==4.2.0
- iniconfig==1.1.1
- mccabe==0.7.0
- nose==1.3.7
- numpy==1.19.5
- packaging==21.3
- pluggy==1.0.0
- py==1.11.0
- pycodestyle==2.9.1
- pyflakes==2.5.0
- pyparsing==3.1.4
- pytest==7.0.1
- tomli==1.2.3
- typing-extensions==4.1.1
- zipp==3.6.0
prefix: /opt/conda/envs/colour
| [
"colour/algebra/tests/tests_extrapolation.py::TestExtrapolator1d::test___call__",
"colour/algebra/tests/tests_extrapolation.py::TestExtrapolator1d::test_nan__call__",
"colour/algebra/tests/tests_extrapolation.py::TestExtrapolator1d::test_required_attributes",
"colour/algebra/tests/tests_extrapolation.py::TestExtrapolator1d::test_required_methods",
"colour/algebra/tests/tests_interpolation.py::TestLinearInterpolator1d::test___call__",
"colour/algebra/tests/tests_interpolation.py::TestLinearInterpolator1d::test_nan__call__",
"colour/algebra/tests/tests_interpolation.py::TestLinearInterpolator1d::test_required_attributes",
"colour/algebra/tests/tests_interpolation.py::TestLinearInterpolator1d::test_required_methods",
"colour/algebra/tests/tests_interpolation.py::TestSpragueInterpolator::test___call__",
"colour/algebra/tests/tests_interpolation.py::TestSpragueInterpolator::test_nan__call__",
"colour/algebra/tests/tests_interpolation.py::TestSpragueInterpolator::test_required_attributes",
"colour/algebra/tests/tests_interpolation.py::TestSpragueInterpolator::test_required_methods",
"colour/colorimetry/tests/tests_spectrum.py::TestSpectralMapping::test_required_attributes",
"colour/colorimetry/tests/tests_spectrum.py::TestSpectralMapping::test_required_methods",
"colour/colorimetry/tests/tests_spectrum.py::TestSpectralShape::test__contains__",
"colour/colorimetry/tests/tests_spectrum.py::TestSpectralShape::test__eq__",
"colour/colorimetry/tests/tests_spectrum.py::TestSpectralShape::test__iter__",
"colour/colorimetry/tests/tests_spectrum.py::TestSpectralShape::test__len__",
"colour/colorimetry/tests/tests_spectrum.py::TestSpectralShape::test__ne__",
"colour/colorimetry/tests/tests_spectrum.py::TestSpectralShape::test_end",
"colour/colorimetry/tests/tests_spectrum.py::TestSpectralShape::test_range",
"colour/colorimetry/tests/tests_spectrum.py::TestSpectralShape::test_required_attributes",
"colour/colorimetry/tests/tests_spectrum.py::TestSpectralShape::test_required_methods",
"colour/colorimetry/tests/tests_spectrum.py::TestSpectralShape::test_start",
"colour/colorimetry/tests/tests_spectrum.py::TestSpectralShape::test_steps",
"colour/colorimetry/tests/tests_spectrum.py::TestSpectralPowerDistribution::test__add__",
"colour/colorimetry/tests/tests_spectrum.py::TestSpectralPowerDistribution::test__contains__",
"colour/colorimetry/tests/tests_spectrum.py::TestSpectralPowerDistribution::test__div__",
"colour/colorimetry/tests/tests_spectrum.py::TestSpectralPowerDistribution::test__eq__",
"colour/colorimetry/tests/tests_spectrum.py::TestSpectralPowerDistribution::test__getitem__",
"colour/colorimetry/tests/tests_spectrum.py::TestSpectralPowerDistribution::test__iter__",
"colour/colorimetry/tests/tests_spectrum.py::TestSpectralPowerDistribution::test__len__",
"colour/colorimetry/tests/tests_spectrum.py::TestSpectralPowerDistribution::test__mul__",
"colour/colorimetry/tests/tests_spectrum.py::TestSpectralPowerDistribution::test__ne__",
"colour/colorimetry/tests/tests_spectrum.py::TestSpectralPowerDistribution::test__pow__",
"colour/colorimetry/tests/tests_spectrum.py::TestSpectralPowerDistribution::test__setitem__",
"colour/colorimetry/tests/tests_spectrum.py::TestSpectralPowerDistribution::test__sub__",
"colour/colorimetry/tests/tests_spectrum.py::TestSpectralPowerDistribution::test_align",
"colour/colorimetry/tests/tests_spectrum.py::TestSpectralPowerDistribution::test_clone",
"colour/colorimetry/tests/tests_spectrum.py::TestSpectralPowerDistribution::test_extrapolate",
"colour/colorimetry/tests/tests_spectrum.py::TestSpectralPowerDistribution::test_get",
"colour/colorimetry/tests/tests_spectrum.py::TestSpectralPowerDistribution::test_is_uniform",
"colour/colorimetry/tests/tests_spectrum.py::TestSpectralPowerDistribution::test_normalise",
"colour/colorimetry/tests/tests_spectrum.py::TestSpectralPowerDistribution::test_required_attributes",
"colour/colorimetry/tests/tests_spectrum.py::TestSpectralPowerDistribution::test_required_methods",
"colour/colorimetry/tests/tests_spectrum.py::TestSpectralPowerDistribution::test_shape",
"colour/colorimetry/tests/tests_spectrum.py::TestSpectralPowerDistribution::test_values",
"colour/colorimetry/tests/tests_spectrum.py::TestSpectralPowerDistribution::test_wavelengths",
"colour/colorimetry/tests/tests_spectrum.py::TestSpectralPowerDistribution::test_zeros",
"colour/colorimetry/tests/tests_spectrum.py::TestTriSpectralPowerDistribution::test__add__",
"colour/colorimetry/tests/tests_spectrum.py::TestTriSpectralPowerDistribution::test__contains__",
"colour/colorimetry/tests/tests_spectrum.py::TestTriSpectralPowerDistribution::test__div__",
"colour/colorimetry/tests/tests_spectrum.py::TestTriSpectralPowerDistribution::test__eq__",
"colour/colorimetry/tests/tests_spectrum.py::TestTriSpectralPowerDistribution::test__getitem__",
"colour/colorimetry/tests/tests_spectrum.py::TestTriSpectralPowerDistribution::test__iter__",
"colour/colorimetry/tests/tests_spectrum.py::TestTriSpectralPowerDistribution::test__len__",
"colour/colorimetry/tests/tests_spectrum.py::TestTriSpectralPowerDistribution::test__mul__",
"colour/colorimetry/tests/tests_spectrum.py::TestTriSpectralPowerDistribution::test__ne__",
"colour/colorimetry/tests/tests_spectrum.py::TestTriSpectralPowerDistribution::test__pow__",
"colour/colorimetry/tests/tests_spectrum.py::TestTriSpectralPowerDistribution::test__setitem__",
"colour/colorimetry/tests/tests_spectrum.py::TestTriSpectralPowerDistribution::test__sub__",
"colour/colorimetry/tests/tests_spectrum.py::TestTriSpectralPowerDistribution::test_align",
"colour/colorimetry/tests/tests_spectrum.py::TestTriSpectralPowerDistribution::test_clone",
"colour/colorimetry/tests/tests_spectrum.py::TestTriSpectralPowerDistribution::test_extrapolate",
"colour/colorimetry/tests/tests_spectrum.py::TestTriSpectralPowerDistribution::test_get",
"colour/colorimetry/tests/tests_spectrum.py::TestTriSpectralPowerDistribution::test_is_uniform",
"colour/colorimetry/tests/tests_spectrum.py::TestTriSpectralPowerDistribution::test_normalise",
"colour/colorimetry/tests/tests_spectrum.py::TestTriSpectralPowerDistribution::test_required_attributes",
"colour/colorimetry/tests/tests_spectrum.py::TestTriSpectralPowerDistribution::test_required_methods",
"colour/colorimetry/tests/tests_spectrum.py::TestTriSpectralPowerDistribution::test_shape",
"colour/colorimetry/tests/tests_spectrum.py::TestTriSpectralPowerDistribution::test_values",
"colour/colorimetry/tests/tests_spectrum.py::TestTriSpectralPowerDistribution::test_wavelengths",
"colour/colorimetry/tests/tests_spectrum.py::TestTriSpectralPowerDistribution::test_zeros",
"colour/colorimetry/tests/tests_spectrum.py::TestConstantSpd::test_constant_spd",
"colour/colorimetry/tests/tests_spectrum.py::TestZerosSpd::test_zeros_spd",
"colour/colorimetry/tests/tests_spectrum.py::TestOnes_spd::test_ones_spd",
"colour/colorimetry/tests/tests_tristimulus.py::TestSpectral_to_XYZ::test_spectral_to_XYZ",
"colour/colorimetry/tests/tests_tristimulus.py::TestWavelength_to_XYZ::test_n_dimensional_wavelength_to_XYZ"
] | [
"colour/colorimetry/tests/tests_spectrum.py::TestSpectralPowerDistribution::test_interpolate",
"colour/colorimetry/tests/tests_spectrum.py::TestTriSpectralPowerDistribution::test_interpolate",
"colour/colorimetry/tests/tests_tristimulus.py::TestWavelength_to_XYZ::test_wavelength_to_XYZ"
] | [] | [] | BSD 3-Clause "New" or "Revised" License | 202 |
|
sigmavirus24__github3.py-421 | 95b8f36b296dc58954b053f88fe34a408944a921 | 2015-07-27 17:02:15 | 05ed0c6a02cffc6ddd0e82ce840c464e1c5fd8c4 | sigmavirus24: 2 things:
1. This is failing flake8 checks
2. This needs unittests | diff --git a/github3/github.py b/github3/github.py
index be5f5aab..9c61e4b9 100644
--- a/github3/github.py
+++ b/github3/github.py
@@ -78,6 +78,26 @@ class GitHub(GitHubCore):
url = self._build_url('events')
return self._iter(int(number), url, Event, etag=etag)
+ def all_organizations(self, number=-1, since=None, etag=None,
+ per_page=None):
+ """Iterate over every organization in the order they were created.
+
+ :param int number: (optional), number of organizations to return.
+ Default: -1, returns all of them
+ :param int since: (optional), last organization id seen (allows
+ restarting this iteration)
+ :param str etag: (optional), ETag from a previous request to the same
+ endpoint
+ :param int per_page: (optional), number of organizations to list per
+ request
+ :returns: generator of :class:`Organization
+ <github3.orgs.Organization>`
+ """
+ url = self._build_url('organizations')
+ return self._iter(int(number), url, Organization,
+ params={'since': since, 'per_page': per_page},
+ etag=etag)
+
def all_repositories(self, number=-1, since=None, etag=None,
per_page=None):
"""Iterate over every repository in the order they were created.
| Need a method to list all organizations on GitHub
https://developer.github.com/v3/orgs/#list-all-organizations was added recently. As a result we need to add `GitHub#all_organizations` to correspond with `GitHub#all_users`, `GitHub#all_events`, and `GitHub#all_repositories`. | sigmavirus24/github3.py | diff --git a/tests/cassettes/GitHub_all_organizations.json b/tests/cassettes/GitHub_all_organizations.json
new file mode 100644
index 00000000..d379a91d
--- /dev/null
+++ b/tests/cassettes/GitHub_all_organizations.json
@@ -0,0 +1,1 @@
+{"http_interactions": [{"request": {"uri": "https://api.github.com/organizations?per_page=25", "method": "GET", "headers": {"Accept": "application/vnd.github.v3.full+json", "Accept-Charset": "utf-8", "Content-Type": "application/json", "Accept-Encoding": "gzip, deflate", "Connection": "keep-alive", "User-Agent": "github3.py/1.0.0a2"}, "body": {"string": "", "encoding": "utf-8"}}, "recorded_at": "2015-07-27T16:50:16", "response": {"url": "https://api.github.com/organizations?per_page=25", "headers": {"x-github-media-type": "github.v3; param=full; format=json", "content-type": "application/json; charset=utf-8", "x-github-request-id": "3EBD09C7:4121:BE664F4:55B66147", "x-served-by": "065b43cd9674091fec48a221b420fbb3", "x-ratelimit-remaining": "58", "transfer-encoding": "chunked", "access-control-expose-headers": "ETag, Link, X-GitHub-OTP, X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset, X-OAuth-Scopes, X-Accepted-OAuth-Scopes, X-Poll-Interval", "x-frame-options": "deny", "content-security-policy": "default-src 'none'", "status": "200 OK", "x-xss-protection": "1; mode=block", "date": "Mon, 27 Jul 2015 16:50:16 GMT", "x-ratelimit-limit": "60", "etag": "W/\"467f85325c09d7c93ffa03581d0b7de5\"", "cache-control": "public, max-age=60, s-maxage=60", "content-encoding": "gzip", "access-control-allow-origin": "*", "link": "<https://api.github.com/organizations?per_page=25&since=2595>; rel=\"next\", <https://api.github.com/organizations{?since}>; rel=\"first\"", "x-ratelimit-reset": "1438017277", "access-control-allow-credentials": "true", "vary": "Accept", "x-content-type-options": "nosniff", "server": "GitHub.com", "strict-transport-security": "max-age=31536000; includeSubdomains; preload"}, "status": {"message": "OK", "code": 200}, "body": {"base64_string": "H4sIAAAAAAAAA63ay27jNhSA4VcR1G0QX+JbAhRdzKqLAsV00UVRDGiZlomhRIGi7BqDefceySJFyRrMIXF2gyD/yYQfaElU/vmWSpWLMv1IudZnzXn6kopT+rHZvKSNlvD1izFV/bFYsEq85sJcmuNrpoqF0nm9GBrNK1V/QReL7vvhZ/ErL01I+AigLHhx5Dok7Ytvi8c/vsOQqjlKkX0JnzUO/ZHsygzT06Xovlj3C9jUXGeqNPCrd2vZLDab366/vsF/6MTrTIvKCAUmZSPl9xePqAQqfmf61CsdViglP0NDuSjCamhjuIaaRGwYR4x2WM2hpalPVohS1EbfM7Dmmlu41eodIzdTY/2mabji04QIy6cZFKJPQ4ldAWcOdrobMyUlz4y4cnHirN+Rq/UBA/vUYlnHYTjqpI8gnUygAJ2MpOZcH+Y40795cmyEPCW1Opsb0zwxCv4trzzRnMmk0uooeVG/jja0yjNLjbtGPgKsL3x3OGobRUi2GQVfO4faDHdBrNvf+ia0vWtZbZeY3ednWBjXhPMMaQTSEFNQDdOowbbLuU02/cyEq6C+39jdbqHdHuPlVVgum4RruTICy7UUVm4YNdVuj6EquD72TOsd6mmgL7BE7beH83RVBE3XUbB0g4hJYIFRJAru/uvqfuK6l3nb4u4jRyEaaKginLw4hsvLSdS8ecR4YIDBq+F+ojHCWLk9ak95FZbNJuFmrowAcy2FlhtGTbVH7bOb5mV2kezYnlB0pyEH1DYbdViuIQoH89oIMq+mQPPGEbPB8mN2mKiu8CSmCqa/ciPKs+r1ttst5i5jLsciPrXhls8jIkifh1DIPk8lBgahOeDxUYqG9ZCsOxl77Mo97ll71GFBhyhc0msjCL2aws4bR4wGyz+HNr3l10zIWqqre0Zb4m76/Q6tZn9WBJpLY8xcTELmphGLrWDp0WQnldunNORpZSf2yILAIIn0astYrrYl02qHUWP94Bgy/QSnU0bpOlHn5K8KXtkkrDwl5sKTX1b9Fz6pAh5TMp78DqfOue4+NJM/mTYlPDn4x9MlN3mjGwe92WGulEOFde6LcGYbRijblALZziI33uzmNmT6uTneEzD73G6pzrdQRyF5cmovgqoq4HAguSh4kTTivPHjRdWgPYCiDlj8DkvqmnDUIY1gHWIK2GEaPS3qs7ZmTV0JLq3YdoV6p+dlWDCbhHu5MoLLtRRabhg1Fqz63D6c3svcLvAOL5Oqce/xDhvck6EfYsGGnxZO5rURaF5NweaNo4aD9Z+DGz85GA0v6bo/N2gf5lfvuOeGocKC9UW4lg0jqGxK4WRnUSPBgs8hTXeXFCW8CSylUpWjwp08j0ssl1eFk/lxBJufU9D588j55k+n0z/YV/gDnPY29CLyS1JxfVa6YCXcd8JlNWFVBX9b0917Tt6hlspkl0NvvF4eUCehLsLyPoJw2b6LQO1LCs9+FDFlu9ZzO3H8cclPOc8Y3Fo+Pi/Xb0vUNc7LsEQ2CUdyZQSTaymg3DBqKlj1n1PlTLL/7rDJ7MVtvd2g/gBlFGK5higczGsjyLyaAs0bR80G6/9zttrAIx28DbI7bPuOOqH2MiyZTcLBXBnB5VoKLDeMnOp99tS5uy3593+CzYb+GisAAA==", "string": "", "encoding": "utf-8"}}}], "recorded_with": "betamax/0.4.2"}
\ No newline at end of file
diff --git a/tests/integration/test_github.py b/tests/integration/test_github.py
index 11067a7f..d27eb229 100644
--- a/tests/integration/test_github.py
+++ b/tests/integration/test_github.py
@@ -169,6 +169,13 @@ class TestGitHub(IntegrationHelper):
assert isinstance(i, github3.issues.Issue)
+ def test_all_organizations(self):
+ """Test the ability to iterate over all of the organizations."""
+ cassette_name = self.cassette_name('all_organizations')
+ with self.recorder.use_cassette(cassette_name):
+ for r in self.gh.all_organizations(number=25):
+ assert isinstance(r, github3.orgs.Organization)
+
def test_all_repositories(self):
"""Test the ability to iterate over all of the repositories."""
cassette_name = self.cassette_name('iter_all_repos')
diff --git a/tests/unit/test_github.py b/tests/unit/test_github.py
index dd98da37..8c7e10ca 100644
--- a/tests/unit/test_github.py
+++ b/tests/unit/test_github.py
@@ -317,6 +317,40 @@ class TestGitHubIterators(UnitIteratorHelper):
headers={}
)
+ def test_all_organizations(self):
+ """Show that one can iterate over all organizations."""
+ i = self.instance.all_organizations()
+ self.get_next(i)
+
+ self.session.get.assert_called_once_with(
+ url_for('organizations'),
+ params={'per_page': 100},
+ headers={}
+ )
+
+ def test_all_organizations_per_page(self):
+ """Show that one can iterate over all organizations with per_page."""
+ i = self.instance.all_organizations(per_page=25)
+ self.get_next(i)
+
+ self.session.get.assert_called_once_with(
+ url_for('organizations'),
+ params={'per_page': 25},
+ headers={}
+ )
+
+ def test_all_organizations_since(self):
+ """Show that one can limit the organizations returned."""
+ since = 100000
+ i = self.instance.all_organizations(since=since)
+ self.get_next(i)
+
+ self.session.get.assert_called_once_with(
+ url_for('organizations'),
+ params={'per_page': 100, 'since': since},
+ headers={}
+ )
+
def test_all_repositories(self):
"""Show that one can iterate over all repositories."""
i = self.instance.all_repositories()
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_short_problem_statement",
"has_hyperlinks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 0,
"issue_text_score": 0,
"test_score": 2
},
"num_modified_files": 1
} | 1.0 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[test]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest",
"pytest-cov",
"pytest-xdist",
"pytest-mock",
"pytest-asyncio"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.9",
"reqs_path": [
"requirements.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | betamax==0.9.0
betamax-matchers==0.4.0
certifi==2025.1.31
charset-normalizer==3.4.1
coverage==7.8.0
exceptiongroup==1.2.2
execnet==2.1.1
-e git+https://github.com/sigmavirus24/github3.py.git@95b8f36b296dc58954b053f88fe34a408944a921#egg=github3.py
idna==3.10
iniconfig==2.1.0
packaging==24.2
pluggy==1.5.0
pytest==8.3.5
pytest-asyncio==0.26.0
pytest-cov==6.0.0
pytest-mock==3.14.0
pytest-xdist==3.6.1
requests==2.32.3
requests-toolbelt==1.0.0
tomli==2.2.1
typing_extensions==4.13.0
uritemplate==4.1.1
uritemplate.py==3.0.2
urllib3==2.3.0
| name: github3.py
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=3.0.16=h5eee18b_0
- pip=25.0=py39h06a4308_0
- python=3.9.21=he870216_1
- readline=8.2=h5eee18b_0
- setuptools=75.8.0=py39h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- tzdata=2025a=h04d1e81_0
- wheel=0.45.1=py39h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- betamax==0.9.0
- betamax-matchers==0.4.0
- certifi==2025.1.31
- charset-normalizer==3.4.1
- coverage==7.8.0
- exceptiongroup==1.2.2
- execnet==2.1.1
- idna==3.10
- iniconfig==2.1.0
- packaging==24.2
- pluggy==1.5.0
- pytest==8.3.5
- pytest-asyncio==0.26.0
- pytest-cov==6.0.0
- pytest-mock==3.14.0
- pytest-xdist==3.6.1
- requests==2.32.3
- requests-toolbelt==1.0.0
- tomli==2.2.1
- typing-extensions==4.13.0
- uritemplate==4.1.1
- uritemplate-py==3.0.2
- urllib3==2.3.0
prefix: /opt/conda/envs/github3.py
| [
"tests/integration/test_github.py::TestGitHub::test_all_organizations",
"tests/unit/test_github.py::TestGitHubIterators::test_all_organizations",
"tests/unit/test_github.py::TestGitHubIterators::test_all_organizations_per_page",
"tests/unit/test_github.py::TestGitHubIterators::test_all_organizations_since"
] | [
"tests/integration/test_github.py::TestGitHub::test_update_me"
] | [
"tests/integration/test_github.py::TestGitHub::test_all_events",
"tests/integration/test_github.py::TestGitHub::test_all_repositories",
"tests/integration/test_github.py::TestGitHub::test_all_users",
"tests/integration/test_github.py::TestGitHub::test_authorize",
"tests/integration/test_github.py::TestGitHub::test_create_gist",
"tests/integration/test_github.py::TestGitHub::test_create_issue",
"tests/integration/test_github.py::TestGitHub::test_create_key",
"tests/integration/test_github.py::TestGitHub::test_create_repository",
"tests/integration/test_github.py::TestGitHub::test_emojis",
"tests/integration/test_github.py::TestGitHub::test_feeds",
"tests/integration/test_github.py::TestGitHub::test_followers",
"tests/integration/test_github.py::TestGitHub::test_followers_of",
"tests/integration/test_github.py::TestGitHub::test_gist",
"tests/integration/test_github.py::TestGitHub::test_gitignore_template",
"tests/integration/test_github.py::TestGitHub::test_gitignore_templates",
"tests/integration/test_github.py::TestGitHub::test_is_following",
"tests/integration/test_github.py::TestGitHub::test_is_starred",
"tests/integration/test_github.py::TestGitHub::test_issue",
"tests/integration/test_github.py::TestGitHub::test_me",
"tests/integration/test_github.py::TestGitHub::test_meta",
"tests/integration/test_github.py::TestGitHub::test_non_existent_gitignore_template",
"tests/integration/test_github.py::TestGitHub::test_notifications",
"tests/integration/test_github.py::TestGitHub::test_notifications_all",
"tests/integration/test_github.py::TestGitHub::test_octocat",
"tests/integration/test_github.py::TestGitHub::test_organization",
"tests/integration/test_github.py::TestGitHub::test_pull_request",
"tests/integration/test_github.py::TestGitHub::test_rate_limit",
"tests/integration/test_github.py::TestGitHub::test_repositories",
"tests/integration/test_github.py::TestGitHub::test_repositories_by",
"tests/integration/test_github.py::TestGitHub::test_repository",
"tests/integration/test_github.py::TestGitHub::test_repository_with_id",
"tests/integration/test_github.py::TestGitHub::test_search_code",
"tests/integration/test_github.py::TestGitHub::test_search_code_with_text_match",
"tests/integration/test_github.py::TestGitHub::test_search_issues",
"tests/integration/test_github.py::TestGitHub::test_search_repositories",
"tests/integration/test_github.py::TestGitHub::test_search_repositories_with_text_match",
"tests/integration/test_github.py::TestGitHub::test_search_users",
"tests/integration/test_github.py::TestGitHub::test_search_users_with_text_match",
"tests/integration/test_github.py::TestGitHub::test_user",
"tests/integration/test_github.py::TestGitHub::test_user_teams",
"tests/integration/test_github.py::TestGitHub::test_user_with_id",
"tests/integration/test_github.py::TestGitHub::test_zen",
"tests/unit/test_github.py::TestGitHub::test_authorization",
"tests/unit/test_github.py::TestGitHub::test_authorize",
"tests/unit/test_github.py::TestGitHub::test_can_login_without_two_factor_callback",
"tests/unit/test_github.py::TestGitHub::test_check_authorization",
"tests/unit/test_github.py::TestGitHub::test_create_gist",
"tests/unit/test_github.py::TestGitHub::test_create_key",
"tests/unit/test_github.py::TestGitHub::test_create_key_requires_a_key",
"tests/unit/test_github.py::TestGitHub::test_create_key_requires_a_title",
"tests/unit/test_github.py::TestGitHub::test_create_repository",
"tests/unit/test_github.py::TestGitHub::test_emojis",
"tests/unit/test_github.py::TestGitHub::test_follow",
"tests/unit/test_github.py::TestGitHub::test_follow_requires_a_username",
"tests/unit/test_github.py::TestGitHub::test_gist",
"tests/unit/test_github.py::TestGitHub::test_gitignore_template",
"tests/unit/test_github.py::TestGitHub::test_gitignore_templates",
"tests/unit/test_github.py::TestGitHub::test_is_following",
"tests/unit/test_github.py::TestGitHub::test_is_starred",
"tests/unit/test_github.py::TestGitHub::test_is_starred_requires_a_repo",
"tests/unit/test_github.py::TestGitHub::test_is_starred_requires_an_owner",
"tests/unit/test_github.py::TestGitHub::test_issue",
"tests/unit/test_github.py::TestGitHub::test_issue_requires_positive_issue_id",
"tests/unit/test_github.py::TestGitHub::test_issue_requires_repository",
"tests/unit/test_github.py::TestGitHub::test_issue_requires_username",
"tests/unit/test_github.py::TestGitHub::test_me",
"tests/unit/test_github.py::TestGitHub::test_repository",
"tests/unit/test_github.py::TestGitHub::test_repository_with_id",
"tests/unit/test_github.py::TestGitHub::test_repository_with_id_accepts_a_string",
"tests/unit/test_github.py::TestGitHub::test_repository_with_id_requires_a_positive_id",
"tests/unit/test_github.py::TestGitHub::test_repository_with_invalid_repo",
"tests/unit/test_github.py::TestGitHub::test_repository_with_invalid_user",
"tests/unit/test_github.py::TestGitHub::test_repository_with_invalid_user_and_repo",
"tests/unit/test_github.py::TestGitHub::test_two_factor_login",
"tests/unit/test_github.py::TestGitHub::test_update_me",
"tests/unit/test_github.py::TestGitHub::test_user",
"tests/unit/test_github.py::TestGitHub::test_user_with_id",
"tests/unit/test_github.py::TestGitHub::test_user_with_id_accepts_a_string",
"tests/unit/test_github.py::TestGitHub::test_user_with_id_requires_a_positive_id",
"tests/unit/test_github.py::TestGitHubIterators::test_all_events",
"tests/unit/test_github.py::TestGitHubIterators::test_all_repositories",
"tests/unit/test_github.py::TestGitHubIterators::test_all_repositories_per_page",
"tests/unit/test_github.py::TestGitHubIterators::test_all_repositories_since",
"tests/unit/test_github.py::TestGitHubIterators::test_all_users",
"tests/unit/test_github.py::TestGitHubIterators::test_all_users_per_page",
"tests/unit/test_github.py::TestGitHubIterators::test_all_users_since",
"tests/unit/test_github.py::TestGitHubIterators::test_authorizations",
"tests/unit/test_github.py::TestGitHubIterators::test_emails",
"tests/unit/test_github.py::TestGitHubIterators::test_followed_by",
"tests/unit/test_github.py::TestGitHubIterators::test_followers",
"tests/unit/test_github.py::TestGitHubIterators::test_followers_of",
"tests/unit/test_github.py::TestGitHubIterators::test_followers_require_auth",
"tests/unit/test_github.py::TestGitHubIterators::test_following",
"tests/unit/test_github.py::TestGitHubIterators::test_following_require_auth",
"tests/unit/test_github.py::TestGitHubIterators::test_gists",
"tests/unit/test_github.py::TestGitHubIterators::test_gists_by",
"tests/unit/test_github.py::TestGitHubIterators::test_issues",
"tests/unit/test_github.py::TestGitHubIterators::test_issues_on",
"tests/unit/test_github.py::TestGitHubIterators::test_issues_on_with_params",
"tests/unit/test_github.py::TestGitHubIterators::test_issues_with_params",
"tests/unit/test_github.py::TestGitHubIterators::test_keys",
"tests/unit/test_github.py::TestGitHubIterators::test_notifications",
"tests/unit/test_github.py::TestGitHubIterators::test_notifications_all",
"tests/unit/test_github.py::TestGitHubIterators::test_notifications_participating_in",
"tests/unit/test_github.py::TestGitHubIterators::test_organization_issues",
"tests/unit/test_github.py::TestGitHubIterators::test_organization_issues_with_params",
"tests/unit/test_github.py::TestGitHubIterators::test_organizations",
"tests/unit/test_github.py::TestGitHubIterators::test_organizations_with",
"tests/unit/test_github.py::TestGitHubIterators::test_public_gists",
"tests/unit/test_github.py::TestGitHubIterators::test_repositories_by",
"tests/unit/test_github.py::TestGitHubIterators::test_repositories_by_with_type",
"tests/unit/test_github.py::TestGitHubIterators::test_respositories",
"tests/unit/test_github.py::TestGitHubIterators::test_respositories_accepts_params",
"tests/unit/test_github.py::TestGitHubIterators::test_starred",
"tests/unit/test_github.py::TestGitHubIterators::test_starred_by",
"tests/unit/test_github.py::TestGitHubIterators::test_subscriptions",
"tests/unit/test_github.py::TestGitHubIterators::test_subscriptions_for",
"tests/unit/test_github.py::TestGitHubIterators::test_user_issues",
"tests/unit/test_github.py::TestGitHubIterators::test_user_issues_with_parameters",
"tests/unit/test_github.py::TestGitHubRequiresAuthentication::test_authorization",
"tests/unit/test_github.py::TestGitHubRequiresAuthentication::test_authorizations",
"tests/unit/test_github.py::TestGitHubRequiresAuthentication::test_create_issue",
"tests/unit/test_github.py::TestGitHubRequiresAuthentication::test_create_key",
"tests/unit/test_github.py::TestGitHubRequiresAuthentication::test_create_repository",
"tests/unit/test_github.py::TestGitHubRequiresAuthentication::test_emails",
"tests/unit/test_github.py::TestGitHubRequiresAuthentication::test_follow",
"tests/unit/test_github.py::TestGitHubRequiresAuthentication::test_gists",
"tests/unit/test_github.py::TestGitHubRequiresAuthentication::test_is_following",
"tests/unit/test_github.py::TestGitHubRequiresAuthentication::test_is_starred",
"tests/unit/test_github.py::TestGitHubRequiresAuthentication::test_issues",
"tests/unit/test_github.py::TestGitHubRequiresAuthentication::test_keys",
"tests/unit/test_github.py::TestGitHubRequiresAuthentication::test_me",
"tests/unit/test_github.py::TestGitHubRequiresAuthentication::test_notifications",
"tests/unit/test_github.py::TestGitHubRequiresAuthentication::test_organization_issues",
"tests/unit/test_github.py::TestGitHubRequiresAuthentication::test_organizations",
"tests/unit/test_github.py::TestGitHubRequiresAuthentication::test_repositories",
"tests/unit/test_github.py::TestGitHubRequiresAuthentication::test_starred",
"tests/unit/test_github.py::TestGitHubRequiresAuthentication::test_user_issues",
"tests/unit/test_github.py::TestGitHubAuthorizations::test_revoke_authorization",
"tests/unit/test_github.py::TestGitHubAuthorizations::test_revoke_authorizations"
] | [] | BSD 3-Clause "New" or "Revised" License | 203 |
PennChopMicrobiomeProgram__PhylogeneticProfiler-4 | fc368fcef164305e45513d27d592f0118229ec0e | 2015-07-29 20:38:42 | fc368fcef164305e45513d27d592f0118229ec0e | diff --git a/phyloprofilerlib/main.py b/phyloprofilerlib/main.py
index c7ba473..4105c14 100644
--- a/phyloprofilerlib/main.py
+++ b/phyloprofilerlib/main.py
@@ -52,7 +52,25 @@ class Metaphlan(object):
def run(self, R1, R2, out_dir):
command = self.make_command(R1, R2)
- subprocess.check_call(command, stdout=self.make_output_handle(R1, out_dir))
+ output = subprocess.check_output(command)
+ revised_output = self.revise_output(output)
+ with self.make_output_handle(R1, out_dir) as f:
+ f.write(revised_output)
+
+ @staticmethod
+ def revise_output(output):
+ output_lines = output.splitlines(True)
+ if len(output_lines) < 2:
+ raise ValueError("Output has fewer than 2 lines.")
+ elif len(output_lines) == 2:
+ return output
+ else:
+ header = output_lines.pop(0)
+ revised_output_lines = [header]
+ for line in output_lines:
+ if ("s__" in line) and not ("t__" in line):
+ revised_output_lines.append(line)
+ return "".join(revised_output_lines)
def main(argv=None):
| Sum of proportions should equal 1
MetaPhlan prints the proportions for each level of the taxonomy, which results in the sum of proportions being (number of ranks) * 100. This kind of output is difficult for us to use downstream. It would be better for us to have the full taxonomic assignment at the species level only. If we want to summarize at a higher rank of the taxonomy, we can compute this downstream.
One complication is that, if no reads are assigned for a sample, no species-level output is generated. We will have to deal with this as a special case. | PennChopMicrobiomeProgram/PhylogeneticProfiler | diff --git a/test/test_main.py b/test/test_main.py
index 935b6e5..12ebbd8 100644
--- a/test/test_main.py
+++ b/test/test_main.py
@@ -19,6 +19,15 @@ class MetaphlanWrapperTest(unittest.TestCase):
self.r2 = "fake_genome1-R2.fastq"
self.out = "out"
+ def test_revise_output(self):
+ observed = Metaphlan.revise_output(ANELLO_FULL_OUTPUT)
+ self.assertEqual(observed, ANELLO_OUTPUT)
+
+ def test_revise_no_assignments(self):
+ """revise_output should not adjust output if no assignments are made."""
+ self.assertEqual(
+ Metaphlan.revise_output(UNCLASSIFIED_OUTPUT), UNCLASSIFIED_OUTPUT)
+
def test_main(self):
app = Metaphlan(self.config)
observed = app.make_command(self.r1, self.r2)
@@ -872,7 +881,7 @@ TCGTTGTAGTAAATACTGCGTGTCCCGGCAGATCACGCAGTATTTACTACAACGAAGGGGACATTTGAAGCCTATTTTGA
BC@A@GGGEGGGGFFG>CDF/;E=CD<E/CEEE@FB<D>CGGGGCEGGGGGDECEGGGGG/EDGECCFGGEGGGG00FGG>CFGGEGBGGDG0BFGGGGGGGGGDACDGGG...68.@
"""
-ANELLO_OUTPUT = """\
+ANELLO_FULL_OUTPUT = """\
#SampleID Metaphlan2_Analysis
k__Viruses 100.0
k__Viruses|p__Viruses_noname 100.0
@@ -883,3 +892,13 @@ k__Viruses|p__Viruses_noname|c__Viruses_noname|o__Viruses_noname|f__Anellovirida
k__Viruses|p__Viruses_noname|c__Viruses_noname|o__Viruses_noname|f__Anelloviridae|g__Alphatorquevirus|s__Torque_teno_virus_1 100.0
k__Viruses|p__Viruses_noname|c__Viruses_noname|o__Viruses_noname|f__Anelloviridae|g__Alphatorquevirus|s__Torque_teno_virus_1|t__PRJNA15247 100.0
"""
+
+UNCLASSIFIED_OUTPUT = """\
+#SampleID Metaphlan2_Analysis
+unclassified 100.0
+"""
+
+ANELLO_OUTPUT = """\
+#SampleID Metaphlan2_Analysis
+k__Viruses|p__Viruses_noname|c__Viruses_noname|o__Viruses_noname|f__Anelloviridae|g__Alphatorquevirus|s__Torque_teno_virus_1 100.0
+"""
| {
"commit_name": "head_commit",
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true,
"llm_score": {
"difficulty_score": 0,
"issue_text_score": 0,
"test_score": 2
},
"num_modified_files": 1
} | unknown | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "",
"pip_packages": [
"numpy>=1.16.0",
"pandas>=1.0.0",
"pytest"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.9",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | exceptiongroup==1.2.2
iniconfig==2.1.0
numpy==2.0.2
packaging==24.2
pandas==2.2.3
-e git+https://github.com/PennChopMicrobiomeProgram/PhylogeneticProfiler.git@fc368fcef164305e45513d27d592f0118229ec0e#egg=PhyloProfiler
pluggy==1.5.0
pytest==8.3.5
python-dateutil==2.9.0.post0
pytz==2025.2
six==1.17.0
tomli==2.2.1
tzdata==2025.2
| name: PhylogeneticProfiler
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=3.0.16=h5eee18b_0
- pip=25.0=py39h06a4308_0
- python=3.9.21=he870216_1
- readline=8.2=h5eee18b_0
- setuptools=75.8.0=py39h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- wheel=0.45.1=py39h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- exceptiongroup==1.2.2
- iniconfig==2.1.0
- numpy==2.0.2
- packaging==24.2
- pandas==2.2.3
- pluggy==1.5.0
- pytest==8.3.5
- python-dateutil==2.9.0.post0
- pytz==2025.2
- six==1.17.0
- tomli==2.2.1
- tzdata==2025.2
prefix: /opt/conda/envs/PhylogeneticProfiler
| [
"test/test_main.py::MetaphlanWrapperTest::test_revise_no_assignments",
"test/test_main.py::MetaphlanWrapperTest::test_revise_output"
] | [
"test/test_main.py::MainTests::test_main_function"
] | [
"test/test_main.py::MetaphlanWrapperTest::test_main"
] | [] | null | 204 |
|
scrapinghub__shub-53 | 7d6eb64b6bfa5de78f20629bfd92922489bd187d | 2015-08-05 17:06:56 | 7e4919dba6005af10818ce087a19239454c04699 | diff --git a/shub/login.py b/shub/login.py
index af5f8aa..4699e07 100644
--- a/shub/login.py
+++ b/shub/login.py
@@ -10,7 +10,8 @@ from six.moves import input
@click.pass_context
def cli(context):
if auth.get_key_netrc():
- context.fail('Already logged in. To logout use: shub logout')
+ log("You're already logged in. To change credentials, use 'shub logout' first.")
+ return 0
cfg_key = _find_cfg_key()
key = _prompt_for_key(suggestion=cfg_key)
| login while already logged-in shows error
If one is already logged in, `shub login` throws an error, while it could say something less "dramatic"
Current behavior:
```
$ shub login
Usage: shub login [OPTIONS]
Error: Already logged in. To logout use: shub logout
```
- no need to show "Usage" as it's correct
- "Error" is misleading. it could say "You're already logged in. Nothing to do. If you want to login with another API key, use `logout` first", or something along those lines | scrapinghub/shub | diff --git a/tests/test_login.py b/tests/test_login.py
index 48ba3b9..00c195e 100644
--- a/tests/test_login.py
+++ b/tests/test_login.py
@@ -65,3 +65,17 @@ username = KEY_SUGGESTION
# then
self.assertEqual(0, result.exit_code, result.exception)
+
+ def test_login_attempt_after_login_doesnt_lead_to_an_error(self):
+ with self.runner.isolated_filesystem() as fs:
+ login.auth.NETRC_FILE = os.path.join(fs, '.netrc')
+
+ # given
+ self.runner.invoke(login.cli, input=self.VALID_KEY)
+
+ # when
+ result = self.runner.invoke(login.cli, input=self.VALID_KEY)
+
+ # then
+ self.assertEqual(0, result.exit_code)
+ self.assertTrue('already logged in' in result.output)
| {
"commit_name": "head_commit",
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true,
"llm_score": {
"difficulty_score": 0,
"issue_text_score": 0,
"test_score": 3
},
"num_modified_files": 1
} | 1.3 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest",
"mock",
"scrapy"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.9",
"reqs_path": [
"requirements.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | attrs==25.3.0
Automat==24.8.1
certifi==2025.1.31
cffi==1.17.1
charset-normalizer==3.4.1
click==8.1.8
constantly==23.10.4
cryptography==44.0.2
cssselect==1.3.0
defusedxml==0.7.1
exceptiongroup==1.2.2
filelock==3.18.0
hyperlink==21.0.0
idna==3.10
incremental==24.7.2
iniconfig==2.1.0
itemadapter==0.11.0
itemloaders==1.3.2
jmespath==1.0.1
lxml==5.3.1
mock==5.2.0
packaging==24.2
parsel==1.10.0
pluggy==1.5.0
Protego==0.4.0
pyasn1==0.6.1
pyasn1_modules==0.4.2
pycparser==2.22
PyDispatcher==2.0.7
pyOpenSSL==25.0.0
pytest==8.3.5
queuelib==1.7.0
requests==2.32.3
requests-file==2.1.0
Scrapy==2.12.0
service-identity==24.2.0
-e git+https://github.com/scrapinghub/shub.git@7d6eb64b6bfa5de78f20629bfd92922489bd187d#egg=shub
six==1.17.0
tldextract==5.1.3
tomli==2.2.1
Twisted==24.11.0
typing_extensions==4.13.0
urllib3==2.3.0
w3lib==2.3.1
zope.interface==7.2
| name: shub
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=3.0.16=h5eee18b_0
- pip=25.0=py39h06a4308_0
- python=3.9.21=he870216_1
- readline=8.2=h5eee18b_0
- setuptools=75.8.0=py39h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- tzdata=2025a=h04d1e81_0
- wheel=0.45.1=py39h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- attrs==25.3.0
- automat==24.8.1
- certifi==2025.1.31
- cffi==1.17.1
- charset-normalizer==3.4.1
- click==8.1.8
- constantly==23.10.4
- cryptography==44.0.2
- cssselect==1.3.0
- defusedxml==0.7.1
- exceptiongroup==1.2.2
- filelock==3.18.0
- hyperlink==21.0.0
- idna==3.10
- incremental==24.7.2
- iniconfig==2.1.0
- itemadapter==0.11.0
- itemloaders==1.3.2
- jmespath==1.0.1
- lxml==5.3.1
- mock==5.2.0
- packaging==24.2
- parsel==1.10.0
- pluggy==1.5.0
- protego==0.4.0
- pyasn1==0.6.1
- pyasn1-modules==0.4.2
- pycparser==2.22
- pydispatcher==2.0.7
- pyopenssl==25.0.0
- pytest==8.3.5
- queuelib==1.7.0
- requests==2.32.3
- requests-file==2.1.0
- scrapy==2.12.0
- service-identity==24.2.0
- six==1.17.0
- tldextract==5.1.3
- tomli==2.2.1
- twisted==24.11.0
- typing-extensions==4.13.0
- urllib3==2.3.0
- w3lib==2.3.1
- zope-interface==7.2
prefix: /opt/conda/envs/shub
| [
"tests/test_login.py::LoginTest::test_login_attempt_after_login_doesnt_lead_to_an_error"
] | [] | [
"tests/test_login.py::LoginTest::test_login_can_handle_invalid_scrapy_cfg",
"tests/test_login.py::LoginTest::test_login_suggests_scrapy_cfg_username_as_key",
"tests/test_login.py::LoginTest::test_login_suggests_shub_apikey_as_key",
"tests/test_login.py::LoginTest::test_login_validates_api_key",
"tests/test_login.py::LoginTest::test_login_writes_input_key_to_netrc_file"
] | [] | BSD 3-Clause "New" or "Revised" License | 205 |
|
DataDog__datadogpy-76 | 2c49469f45e6f84f17ba72875a97976277ce1a14 | 2015-08-06 18:16:53 | 2c49469f45e6f84f17ba72875a97976277ce1a14 | diff --git a/datadog/__init__.py b/datadog/__init__.py
index 92c4d55..2dbe54e 100644
--- a/datadog/__init__.py
+++ b/datadog/__init__.py
@@ -7,14 +7,17 @@ It contains:
without hindering performance.
* datadog.dogshell: a command-line tool, wrapping datadog.api, to interact with Datadog REST API.
"""
+# stdlib
from pkg_resources import get_distribution, DistributionNotFound
import os
import os.path
+# datadog
from datadog import api
from datadog.dogstatsd import statsd
from datadog.threadstats import ThreadStats # noqa
from datadog.util.hostname import get_hostname
+from datadog.util.compat import iteritems
try:
@@ -32,7 +35,7 @@ else:
def initialize(api_key=None, app_key=None, host_name=None, api_host=None,
- proxies=None, statsd_host=None, statsd_port=None, cacert=True):
+ statsd_host=None, statsd_port=None, **kwargs):
"""
Initialize and configure Datadog.api and Datadog.statsd modules
@@ -58,17 +61,23 @@ def initialize(api_key=None, app_key=None, host_name=None, api_host=None,
certificates. Can also be set to True (default) to use the systems
certificate store, or False to skip SSL verification
:type cacert: path or boolean
+
+ :param mute: Mute any exceptions before they escape from the library (default: True).
+ :type mute: boolean
"""
- # Configure api
+ # API configuration
api._api_key = api_key if api_key is not None else os.environ.get('DATADOG_API_KEY')
api._application_key = app_key if app_key is not None else os.environ.get('DATADOG_APP_KEY')
api._host_name = host_name if host_name is not None else get_hostname()
api._api_host = api_host if api_host is not None else \
os.environ.get('DATADOG_HOST', 'https://app.datadoghq.com')
- api._proxies = proxies
- api._cacert = cacert
- # Given statsd_host and statsd_port, overrides statsd instance
+ # Statsd configuration -overrides default statsd instance attributes-
if statsd_host and statsd_port:
statsd.host = statsd_host
statsd.port = int(statsd_port)
+
+ # HTTP client and API options
+ for key, value in iteritems(kwargs):
+ attribute = "_{0}".format(key)
+ setattr(api, attribute, value)
diff --git a/datadog/api/__init__.py b/datadog/api/__init__.py
index 9570eff..3ce7b85 100644
--- a/datadog/api/__init__.py
+++ b/datadog/api/__init__.py
@@ -14,7 +14,7 @@ _timeout = 3
_max_timeouts = 3
_max_retries = 3
_backoff_period = 300
-_swallow = True
+_mute = True
# Resources
from datadog.api.comments import Comment
diff --git a/datadog/api/base.py b/datadog/api/base.py
index 4c312ff..b618186 100644
--- a/datadog/api/base.py
+++ b/datadog/api/base.py
@@ -61,7 +61,7 @@ class HTTPClient(object):
# Import API, User and HTTP settings
from datadog.api import _api_key, _application_key, _api_host, \
- _swallow, _host_name, _proxies, _max_retries, _timeout, \
+ _mute, _host_name, _proxies, _max_retries, _timeout, \
_cacert
# Check keys and add then to params
@@ -124,6 +124,7 @@ class HTTPClient(object):
raise HttpTimeout('%s %s timed out after %d seconds.' % (method, url, _timeout))
except requests.exceptions.HTTPError as e:
if e.response.status_code in (400, 403, 404):
+ # This gets caught afterwards and raises an ApiError exception
pass
else:
raise
@@ -160,7 +161,7 @@ class HTTPClient(object):
return response_formatter(response_obj)
except ClientError as e:
- if _swallow:
+ if _mute:
log.error(str(e))
if error_formatter is None:
return {'errors': e.args[0]}
@@ -169,7 +170,7 @@ class HTTPClient(object):
else:
raise
except ApiError as e:
- if _swallow:
+ if _mute:
for error in e.args[0]['errors']:
log.error(str(error))
if error_formatter is None:
| Error handling: APIError is never raised
This library never returns the status code of the http request.
Instead, when the status code is 400, 403 or 404, it is supposed to raise an APIError exception with the content of the errors field received from the dispatcher.(https://github.com/DataDog/datadogpy/blob/master/datadog/api/base.py#L152).
For all other 3, 4, 5** status codes, an HTTPError is raised.
So catching errors and interacting with the API should be a matter of catching APIError and HTTPError exceptions.
BUT, the `_swallow` attribute prevents APIError to be raised (https://github.com/DataDog/datadogpy/blob/master/datadog/api/base.py#L171-L172). It's set to True in api/__init__.py and is not modifiable at the moment.
A temporary workaround is to use `from datadog import api api._swallow = False`.
We could evaluate the impact of a potential transition to swallow being True by default and also being set up when initializing the api. | DataDog/datadogpy | diff --git a/tests/unit/api/helper.py b/tests/unit/api/helper.py
index 6db98ca..624c160 100644
--- a/tests/unit/api/helper.py
+++ b/tests/unit/api/helper.py
@@ -5,6 +5,7 @@ import unittest
from datadog import initialize, api
from datadog.api.base import CreateableAPIResource, UpdatableAPIResource, DeletableAPIResource,\
GetableAPIResource, ListableAPIResource, ActionAPIResource
+from datadog.api.exceptions import ApiError
from datadog.util.compat import iteritems, json
# 3p
@@ -20,11 +21,16 @@ FAKE_PROXY = {
}
-class MockReponse(requests.Response):
- content = None
+class MockResponse(requests.Response):
+
+ def __init__(self, raise_for_status=False):
+ super(MockResponse, self).__init__()
+ self._raise_for_status = raise_for_status
def raise_for_status(self):
- pass
+ if not self._raise_for_status:
+ return
+ raise ApiError({'errors': ""})
# A few API Resources
@@ -68,32 +74,42 @@ class DatadogAPITestCase(unittest.TestCase):
self.request_patcher = patch('requests.Session')
request_class_mock = self.request_patcher.start()
self.request_mock = request_class_mock.return_value
- self.request_mock.request = Mock(return_value=MockReponse())
+ self.request_mock.request = Mock(return_value=MockResponse())
- def get_request_data(self):
+ def tearDown(self):
+ self.request_patcher.stop()
+
+ def arm_requests_to_raise(self):
"""
+ Arm the mocked request to raise for status.
+ """
+ self.request_mock.request = Mock(return_value=MockResponse(raise_for_status=True))
+ def get_request_data(self):
+ """
+ Returns JSON formatted data from the submitted `requests`.
"""
_, kwargs = self.request_mock.request.call_args
return json.loads(kwargs['data'])
def request_called_with(self, method, url, data=None, params=None):
(req_method, req_url), others = self.request_mock.request.call_args
- assert method == req_method, req_method
- assert url == req_url, req_url
+ self.assertEquals(method, req_method, req_method)
+ self.assertEquals(url, req_url, req_url)
if data:
- assert 'data' in others
- assert json.dumps(data) == others['data'], others['data']
+ self.assertIn('data', others)
+ self.assertEquals(json.dumps(data), others['data'], others['data'])
if params:
- assert 'params' in others
+ self.assertIn('params', others)
for (k, v) in iteritems(params):
- assert k in others['params'], others['params']
- assert v == others['params'][k]
+ self.assertIn(k, others['params'], others['params'])
+ self.assertEquals(v, others['params'][k])
- def tearDown(self):
- self.request_patcher.stop()
+ def assertIn(self, first, second, msg=None):
+ msg = msg or "{0} not in {1}".format(first, second)
+ self.assertTrue(first in second, msg)
class DatadogAPINoInitialization(DatadogAPITestCase):
diff --git a/tests/unit/api/test_api.py b/tests/unit/api/test_api.py
index b34a49a..c2566f7 100644
--- a/tests/unit/api/test_api.py
+++ b/tests/unit/api/test_api.py
@@ -7,12 +7,11 @@ from time import time
# 3p
import mock
-from nose.tools import assert_raises, assert_true, assert_false
# datadog
from datadog import initialize, api
from datadog.api import Metric
-from datadog.api.exceptions import ApiNotInitialized
+from datadog.api.exceptions import ApiError, ApiNotInitialized
from datadog.util.compat import is_p3k
from tests.unit.api.helper import (
DatadogAPIWithInitialization,
@@ -51,21 +50,27 @@ def preserve_environ_datadog(func):
class TestInitialization(DatadogAPINoInitialization):
- def test_no_initialization_fails(self, test='sisi'):
- assert_raises(ApiNotInitialized, MyCreatable.create)
+ def test_no_initialization_fails(self):
+ """
+ Raise ApiNotInitialized exception when `initialize` has not ran or no API key was set.
+ """
+ self.assertRaises(ApiNotInitialized, MyCreatable.create)
# No API key => only stats in statsd mode should work
initialize()
api._api_key = None
- assert_raises(ApiNotInitialized, MyCreatable.create)
+ self.assertRaises(ApiNotInitialized, MyCreatable.create)
# Finally, initialize with an API key
initialize(api_key=API_KEY, api_host=API_HOST)
MyCreatable.create()
- assert self.request_mock.request.call_count == 1
+ self.assertEquals(self.request_mock.request.call_count, 1)
@mock.patch('datadog.util.config.get_config_path')
def test_get_hostname(self, mock_config_path):
+ """
+ API hostname parameter fallback with Datadog Agent hostname when available.
+ """
# Generate a fake agent config
tmpfilepath = os.path.join(tempfile.gettempdir(), "tmp-agentconfig")
with open(tmpfilepath, "wb") as f:
@@ -79,31 +84,64 @@ class TestInitialization(DatadogAPINoInitialization):
mock_config_path.return_value = tmpfilepath
initialize()
- assert api._host_name == HOST_NAME, api._host_name
+ self.assertEquals(api._host_name, HOST_NAME, api._host_name)
def test_request_parameters(self):
- # Test API, application keys, API host and proxies
- initialize(api_key=API_KEY, app_key=APP_KEY, api_host=API_HOST, proxies=FAKE_PROXY)
+ """
+ API parameters are set with `initialize` method.
+ """
+ # Test API, application keys, API host, and some HTTP client options
+ initialize(api_key=API_KEY, app_key=APP_KEY, api_host=API_HOST)
# Make a simple API call
MyCreatable.create()
_, options = self.request_mock.request.call_args
- assert 'params' in options
+ # Assert `requests` parameters
+ self.assertIn('params', options)
- assert 'api_key' in options['params']
- assert options['params']['api_key'] == API_KEY
- assert 'application_key' in options['params']
- assert options['params']['application_key'] == APP_KEY
+ self.assertIn('api_key', options['params'])
+ self.assertEquals(options['params']['api_key'], API_KEY)
+ self.assertIn('application_key', options['params'])
+ self.assertEquals(options['params']['application_key'], APP_KEY)
- assert 'proxies' in options
- assert options['proxies'] == FAKE_PROXY
+ self.assertIn('headers', options)
+ self.assertEquals(options['headers'], {'Content-Type': 'application/json'})
- assert 'headers' in options
- assert options['headers'] == {'Content-Type': 'application/json'}
+ def test_initialize_options(self):
+ """
+ HTTP client and API options are set with `initialize` method.
+ """
+ initialize(api_key=API_KEY, app_key=APP_KEY, api_host=API_HOST,
+ proxies=FAKE_PROXY, cacert=False)
+
+ # Make a simple API call
+ MyCreatable.create()
+
+ _, options = self.request_mock.request.call_args
+
+ # Assert `requests` parameters
+ self.assertIn('proxies', options)
+ self.assertEquals(options['proxies'], FAKE_PROXY)
+
+ self.assertIn('verify', options)
+ self.assertEquals(options['verify'], False)
+
+ # Arm the `requests` to raise
+ self.arm_requests_to_raise()
+
+ # No exception should be raised (mute=True by default)
+ MyCreatable.create()
+
+ # Repeat with mute to False
+ initialize(api_key=API_KEY, mute=False)
+ self.assertRaises(ApiError, MyCreatable.create)
def test_initialization_from_env(self):
+ """
+ Set API parameters in `initialize` from environment variables.
+ """
@preserve_environ_datadog
def test_api_params_from_env(env_name, attr_name, env_value):
"""
@@ -156,6 +194,9 @@ class TestInitialization(DatadogAPINoInitialization):
class TestResources(DatadogAPIWithInitialization):
def test_creatable(self):
+ """
+ Creatable resource logic.
+ """
MyCreatable.create(mydata="val")
self.request_called_with('POST', "host/api/v1/creatables", data={'mydata': "val"})
@@ -164,28 +205,43 @@ class TestResources(DatadogAPIWithInitialization):
data={'mydata': "val", 'host': api._host_name})
def test_getable(self):
+ """
+ Getable resource logic.
+ """
getable_object_id = 123
MyGetable.get(getable_object_id, otherparam="val")
self.request_called_with('GET', "host/api/v1/getables/" + str(getable_object_id),
params={'otherparam': "val"})
def test_listable(self):
+ """
+ Listable resource logic.
+ """
MyListable.get_all(otherparam="val")
self.request_called_with('GET', "host/api/v1/listables", params={'otherparam': "val"})
def test_updatable(self):
+ """
+ Updatable resource logic.
+ """
updatable_object_id = 123
MyUpdatable.update(updatable_object_id, params={'myparam': "val1"}, mydata="val2")
self.request_called_with('PUT', "host/api/v1/updatables/" + str(updatable_object_id),
params={'myparam': "val1"}, data={'mydata': "val2"})
def test_detalable(self):
+ """
+ Deletable resource logic.
+ """
deletable_object_id = 123
MyDeletable.delete(deletable_object_id, otherparam="val")
self.request_called_with('DELETE', "host/api/v1/deletables/" + str(deletable_object_id),
params={'otherparam': "val"})
def test_actionable(self):
+ """
+ Actionable resource logic.
+ """
actionable_object_id = 123
MyActionable.trigger_class_action('POST', "actionname", id=actionable_object_id,
mydata="val")
@@ -214,17 +270,18 @@ class TestMetricResource(DatadogAPIWithInitialization):
payload = self.get_request_data()
for i, metric in enumerate(payload['series']):
- assert set(metric.keys()) == set(['metric', 'points', 'host'])
+ self.assertEquals(set(metric.keys()), set(['metric', 'points', 'host']))
- assert metric['metric'] == serie[i]['metric']
- assert metric['host'] == api._host_name
+ self.assertEquals(metric['metric'], serie[i]['metric'])
+ self.assertEquals(metric['host'], api._host_name)
# points is a list of 1 point
- assert isinstance(metric['points'], list) and len(metric['points']) == 1
+ self.assertTrue(isinstance(metric['points'], list))
+ self.assertEquals(len(metric['points']), 1)
# it consists of a [time, value] pair
- assert len(metric['points'][0]) == 2
+ self.assertEquals(len(metric['points'][0]), 2)
# its value == value we sent
- assert metric['points'][0][1] == serie[i]['points']
+ self.assertEquals(metric['points'][0][1], serie[i]['points'])
# it's time not so far from current time
assert now - 1 < metric['points'][0][0] < now + 1
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 2,
"issue_text_score": 1,
"test_score": 2
},
"num_modified_files": 3
} | 0.8 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"nose",
"six",
"mock",
"pytest"
],
"pre_install": [],
"python": "3.9",
"reqs_path": [
"requirements/base.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | certifi==2025.1.31
charset-normalizer==3.4.1
-e git+https://github.com/DataDog/datadogpy.git@2c49469f45e6f84f17ba72875a97976277ce1a14#egg=datadog
decorator==5.2.1
exceptiongroup==1.2.2
idna==3.10
iniconfig==2.1.0
mock==5.2.0
nose==1.3.7
packaging==24.2
pluggy==1.5.0
pytest==8.3.5
requests==2.32.3
six==1.17.0
tomli==2.2.1
urllib3==2.3.0
| name: datadogpy
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=3.0.16=h5eee18b_0
- pip=25.0=py39h06a4308_0
- python=3.9.21=he870216_1
- readline=8.2=h5eee18b_0
- setuptools=75.8.0=py39h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- tzdata=2025a=h04d1e81_0
- wheel=0.45.1=py39h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- certifi==2025.1.31
- charset-normalizer==3.4.1
- decorator==5.2.1
- exceptiongroup==1.2.2
- idna==3.10
- iniconfig==2.1.0
- mock==5.2.0
- nose==1.3.7
- packaging==24.2
- pluggy==1.5.0
- pytest==8.3.5
- requests==2.32.3
- six==1.17.0
- tomli==2.2.1
- urllib3==2.3.0
prefix: /opt/conda/envs/datadogpy
| [
"tests/unit/api/test_api.py::TestInitialization::test_initialize_options"
] | [] | [
"tests/unit/api/test_api.py::TestInitialization::test_get_hostname",
"tests/unit/api/test_api.py::TestInitialization::test_initialization_from_env",
"tests/unit/api/test_api.py::TestInitialization::test_no_initialization_fails",
"tests/unit/api/test_api.py::TestInitialization::test_request_parameters",
"tests/unit/api/test_api.py::TestResources::test_actionable",
"tests/unit/api/test_api.py::TestResources::test_creatable",
"tests/unit/api/test_api.py::TestResources::test_detalable",
"tests/unit/api/test_api.py::TestResources::test_getable",
"tests/unit/api/test_api.py::TestResources::test_listable",
"tests/unit/api/test_api.py::TestResources::test_updatable",
"tests/unit/api/test_api.py::TestMetricResource::test_metric_submit_query_switch",
"tests/unit/api/test_api.py::TestMetricResource::test_points_submission"
] | [] | BSD-3-Clause | 206 |
|
zalando-stups__pierone-cli-15 | 49f45a29f0890a35a6e53754f9cdcadd5924ab21 | 2015-08-07 11:15:04 | 49f45a29f0890a35a6e53754f9cdcadd5924ab21 | diff --git a/pierone/cli.py b/pierone/cli.py
index 786b144..436bacd 100644
--- a/pierone/cli.py
+++ b/pierone/cli.py
@@ -208,5 +208,31 @@ def scm_source(config, team, artifact, tag, output):
max_column_widths={'revision': 10})
[email protected]('image')
[email protected]('image')
+@output_option
[email protected]_obj
+def image(config, image, output):
+ '''List tags that point to this image'''
+ token = get_token()
+
+ resp = request(config.get('url'), '/tags/{}'.format(image), token['access_token'])
+
+ if resp.status_code == 404:
+ click.echo('Image {} not found'.format(image))
+ return
+
+ if resp.status_code == 412:
+ click.echo('Prefix {} matches more than one image.'.format(image))
+ return
+
+ tags = resp.json()
+
+ with OutputFormat(output):
+ print_table(['team', 'artifact', 'name'],
+ tags,
+ titles={'name': 'Tag', 'artifact': 'Artifact', 'team': 'Team'})
+
+
def main():
cli()
| Support reverse image search
As soon as https://github.com/zalando-stups/pierone/issues/33 is done. | zalando-stups/pierone-cli | diff --git a/tests/test_cli.py b/tests/test_cli.py
index f2b360c..b319cb3 100644
--- a/tests/test_cli.py
+++ b/tests/test_cli.py
@@ -49,3 +49,20 @@ def test_scm_source(monkeypatch, tmpdir):
result = runner.invoke(cli, ['scm-source', 'myteam', 'myart', '1.0'], catch_exceptions=False)
assert 'myrev123' in result.output
assert 'git:somerepo' in result.output
+
+def test_image(monkeypatch, tmpdir):
+ response = MagicMock()
+ response.json.return_value = [{'name': '1.0', 'team': 'stups', 'artifact': 'kio'}]
+
+ runner = CliRunner()
+ monkeypatch.setattr('pierone.cli.CONFIG_FILE_PATH', 'config.yaml')
+ monkeypatch.setattr('pierone.cli.get_named_token', MagicMock(return_value={'access_token': 'tok123'}))
+ monkeypatch.setattr('os.path.expanduser', lambda x: x.replace('~', str(tmpdir)))
+ monkeypatch.setattr('requests.get', MagicMock(return_value=response))
+ with runner.isolated_filesystem():
+ with open('config.yaml', 'w') as fd:
+ fd.write('')
+ result = runner.invoke(cli, ['image', 'abcd'], catch_exceptions=False)
+ assert 'kio' in result.output
+ assert 'stups' in result.output
+ assert '1.0' in result.output
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_short_problem_statement",
"has_hyperlinks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 2,
"issue_text_score": 3,
"test_score": 2
},
"num_modified_files": 1
} | 0.16 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest",
"pytest-cov"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.9",
"reqs_path": [
"requirements.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | backports.tarfile==1.2.0
certifi==2025.1.31
cffi==1.17.1
charset-normalizer==3.4.1
click==8.1.8
clickclick==20.10.2
coverage==7.8.0
cryptography==44.0.2
dnspython==2.7.0
exceptiongroup==1.2.2
idna==3.10
importlib_metadata==8.6.1
iniconfig==2.1.0
jaraco.classes==3.4.0
jaraco.context==6.0.1
jaraco.functools==4.1.0
jeepney==0.9.0
keyring==25.6.0
more-itertools==10.6.0
packaging==24.2
pluggy==1.5.0
pycparser==2.22
pytest==8.3.5
pytest-cov==6.0.0
PyYAML==6.0.2
requests==2.32.3
SecretStorage==3.3.3
stups-cli-support==1.1.22
-e git+https://github.com/zalando-stups/pierone-cli.git@49f45a29f0890a35a6e53754f9cdcadd5924ab21#egg=stups_pierone
stups-tokens==1.1.19
stups-zign==1.2
tomli==2.2.1
urllib3==2.3.0
zipp==3.21.0
| name: pierone-cli
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=3.0.16=h5eee18b_0
- pip=25.0=py39h06a4308_0
- python=3.9.21=he870216_1
- readline=8.2=h5eee18b_0
- setuptools=75.8.0=py39h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- tzdata=2025a=h04d1e81_0
- wheel=0.45.1=py39h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- backports-tarfile==1.2.0
- certifi==2025.1.31
- cffi==1.17.1
- charset-normalizer==3.4.1
- click==8.1.8
- clickclick==20.10.2
- coverage==7.8.0
- cryptography==44.0.2
- dnspython==2.7.0
- exceptiongroup==1.2.2
- idna==3.10
- importlib-metadata==8.6.1
- iniconfig==2.1.0
- jaraco-classes==3.4.0
- jaraco-context==6.0.1
- jaraco-functools==4.1.0
- jeepney==0.9.0
- keyring==25.6.0
- more-itertools==10.6.0
- packaging==24.2
- pluggy==1.5.0
- pycparser==2.22
- pytest==8.3.5
- pytest-cov==6.0.0
- pyyaml==6.0.2
- requests==2.32.3
- secretstorage==3.3.3
- stups-cli-support==1.1.22
- stups-tokens==1.1.19
- stups-zign==1.2
- tomli==2.2.1
- urllib3==2.3.0
- zipp==3.21.0
prefix: /opt/conda/envs/pierone-cli
| [
"tests/test_cli.py::test_image"
] | [] | [
"tests/test_cli.py::test_version",
"tests/test_cli.py::test_login",
"tests/test_cli.py::test_scm_source"
] | [] | Apache License 2.0 | 207 |
|
sympy__sympy-9790 | a91ba26c6d639980a4b3351a443548c629447cf9 | 2015-08-07 18:49:25 | 0241b35cae5f2adc04dc37b25f7dc9c5f00bd746 | diff --git a/sympy/sets/conditionset.py b/sympy/sets/conditionset.py
index c1ce9993f6..c3627b9486 100644
--- a/sympy/sets/conditionset.py
+++ b/sympy/sets/conditionset.py
@@ -33,5 +33,10 @@ def __new__(cls, condition, base_set):
condition = property(lambda self: self.args[0])
base_set = property(lambda self: self.args[1])
+ def _intersect(self, other):
+ if not isinstance(other, ConditionSet):
+ return ConditionSet(self.condition,
+ Intersection(self.base_set, other))
+
def contains(self, other):
return And(self.condition(other), self.base_set.contains(other))
diff --git a/sympy/solvers/solveset.py b/sympy/solvers/solveset.py
index 05fe51b83c..ce0b8dc70c 100644
--- a/sympy/solvers/solveset.py
+++ b/sympy/solvers/solveset.py
@@ -18,7 +18,7 @@
from sympy.functions.elementary.trigonometric import (TrigonometricFunction,
HyperbolicFunction)
from sympy.sets import (FiniteSet, EmptySet, imageset, Interval, Intersection,
- Union)
+ Union, ConditionSet)
from sympy.matrices import Matrix
from sympy.polys import (roots, Poly, degree, together, PolynomialError,
RootOf)
@@ -355,6 +355,8 @@ def solveset_real(f, symbol):
Set
A set of values for `symbol` for which `f` is equal to
zero. An `EmptySet` is returned if no solution is found.
+ A `ConditionSet` is returned as unsolved object if algorithms
+ to evaluate complete solutions are not yet implemented.
`solveset_real` claims to be complete in the set of the solution it
returns.
@@ -363,7 +365,7 @@ def solveset_real(f, symbol):
======
NotImplementedError
- The algorithms for to find the solution of the given equation are
+ Algorithms to solve inequalities in complex domain are
not yet implemented.
ValueError
The input is not valid.
@@ -464,7 +466,7 @@ def solveset_real(f, symbol):
else:
result += solveset_real(equation, symbol)
else:
- raise NotImplementedError
+ result = ConditionSet(Lambda(symbol, Eq(f, 0)), S.Reals)
if isinstance(result, FiniteSet):
result = [s for s in result
@@ -497,7 +499,7 @@ def _solve_real_trig(f, symbol):
g, h = g.expand(), h.expand()
g, h = g.subs(exp(I*symbol), y), h.subs(exp(I*symbol), y)
if g.has(symbol) or h.has(symbol):
- raise NotImplementedError
+ return ConditionSet(Lambda(symbol, Eq(f, 0)), S.Reals)
solns = solveset_complex(g, y) - solveset_complex(h, y)
@@ -507,7 +509,7 @@ def _solve_real_trig(f, symbol):
elif solns is S.EmptySet:
return S.EmptySet
else:
- raise NotImplementedError
+ return ConditionSet(Lambda(symbol, Eq(f, 0)), S.Reals)
def _solve_as_poly(f, symbol, solveset_solver, invert_func):
@@ -529,12 +531,11 @@ def _solve_as_poly(f, symbol, solveset_solver, invert_func):
if poly.degree() <= len(solns):
result = FiniteSet(*solns)
else:
- raise NotImplementedError("Couldn't find all roots "
- "of the equation %s" % f)
+ result = ConditionSet(Lambda(symbol, Eq(f, 0)), S.Complexes)
else:
poly = Poly(f)
if poly is None:
- raise NotImplementedError("Could not convert %s to Poly" % f)
+ result = ConditionSet(Lambda(symbol, Eq(f, 0)), S.Complexes)
gens = [g for g in poly.gens if g.has(symbol)]
if len(gens) == 1:
@@ -546,8 +547,7 @@ def _solve_as_poly(f, symbol, solveset_solver, invert_func):
quintics=True).keys())
if len(poly_solns) < deg:
- raise NotImplementedError("Couldn't find all the roots of "
- "the equation %s" % f)
+ result = ConditionSet(Lambda(symbol, Eq(f, 0)), S.Complexes)
if gen != symbol:
y = Dummy('y')
@@ -555,11 +555,9 @@ def _solve_as_poly(f, symbol, solveset_solver, invert_func):
if lhs is symbol:
result = Union(*[rhs_s.subs(y, s) for s in poly_solns])
else:
- raise NotImplementedError(
- "inversion of %s not handled" % gen)
+ result = ConditionSet(Lambda(symbol, Eq(f, 0)), S.Complexes)
else:
- raise NotImplementedError("multiple generators not handled"
- " by solveset")
+ result = ConditionSet(Lambda(symbol, Eq(f, 0)), S.Complexes)
if result is not None:
if isinstance(result, FiniteSet):
@@ -573,7 +571,7 @@ def _solve_as_poly(f, symbol, solveset_solver, invert_func):
result = imageset(Lambda(s, expand_complex(s)), result)
return result
else:
- raise NotImplementedError
+ return ConditionSet(Lambda(symbol, Eq(f, 0)), S.Complexes)
def _solve_as_poly_real(f, symbol):
@@ -672,7 +670,7 @@ def _solve_abs(f, symbol):
symbol).intersect(q_neg_cond)
return Union(sols_q_pos, sols_q_neg)
else:
- raise NotImplementedError
+ return ConditionSet(Lambda(symbol, Eq(f, 0)), S.Complexes)
def solveset_complex(f, symbol):
@@ -692,6 +690,8 @@ def solveset_complex(f, symbol):
Set
A set of values for `symbol` for which `f` equal to
zero. An `EmptySet` is returned if no solution is found.
+ A `ConditionSet` is returned as an unsolved object if algorithms
+ to evaluate complete solutions are not yet implemented.
`solveset_complex` claims to be complete in the solution set that
it returns.
@@ -700,7 +700,7 @@ def solveset_complex(f, symbol):
======
NotImplementedError
- The algorithms for to find the solution of the given equation are
+ The algorithms to solve inequalities in complex domain are
not yet implemented.
ValueError
The input is not valid.
@@ -770,7 +770,7 @@ def solveset_complex(f, symbol):
else:
result += solveset_complex(equation, symbol)
else:
- raise NotImplementedError
+ result = ConditionSet(Lambda(symbol, Eq(f, 0)), S.Complexes)
if isinstance(result, FiniteSet):
result = [s for s in result
@@ -800,6 +800,8 @@ def solveset(f, symbol=None, domain=S.Complexes):
Set
A set of values for `symbol` for which `f` is True or is equal to
zero. An `EmptySet` is returned if no solution is found.
+ A `ConditionSet` is returned as unsolved object if algorithms
+ to evaluatee complete solution are not yet implemented.
`solveset` claims to be complete in the solution set that it returns.
@@ -807,7 +809,7 @@ def solveset(f, symbol=None, domain=S.Complexes):
======
NotImplementedError
- The algorithms for to find the solution of the given equation are
+ The algorithms to solve inequalities in complex domain are
not yet implemented.
ValueError
The input is not valid.
@@ -889,8 +891,12 @@ def solveset(f, symbol=None, domain=S.Complexes):
raise NotImplementedError("Inequalities in the complex domain are "
"not supported. Try the real domain by"
"setting domain=S.Reals")
- return solve_univariate_inequality(
+ try:
+ result = solve_univariate_inequality(
f, symbol, relational=False).intersection(domain)
+ except NotImplementedError:
+ result = ConditionSet(Lambda(symbol, f), domain)
+ return result
if isinstance(f, (Expr, Number)):
if domain is S.Reals:
| Use ConditionSet as an unsolved object for solveset
In https://github.com/sympy/sympy/pull/9696 we implemented a `ConditionSet` object which can be used to represent unsolved equations and inequalities as a Set object. We need to use it as an unsolved object in solveset. | sympy/sympy | diff --git a/sympy/sets/tests/test_conditionset.py b/sympy/sets/tests/test_conditionset.py
index 5786e91e3a..c7ba55c399 100644
--- a/sympy/sets/tests/test_conditionset.py
+++ b/sympy/sets/tests/test_conditionset.py
@@ -1,4 +1,4 @@
-from sympy.sets import ConditionSet
+from sympy.sets import (ConditionSet, Intersection)
from sympy import (Symbol, Eq, S, sin, pi, Lambda, Interval)
x = Symbol('x')
@@ -12,3 +12,10 @@ def test_CondSet():
assert 3*pi not in sin_sols_principal
assert 5 in ConditionSet(Lambda(x, x**2 > 4), S.Reals)
assert 1 not in ConditionSet(Lambda(x, x**2 > 4), S.Reals)
+
+
+def test_CondSet_intersect():
+ input_conditionset = ConditionSet(Lambda(x, x**2 > 4), Interval(1, 4, False, False))
+ other_domain = Interval(0, 3, False, False)
+ output_conditionset = ConditionSet(Lambda(x, x**2 > 4), Interval(1, 3, False, False))
+ assert Intersection(input_conditionset, other_domain) == output_conditionset
diff --git a/sympy/solvers/tests/test_solveset.py b/sympy/solvers/tests/test_solveset.py
index afb659e205..004509eea5 100644
--- a/sympy/solvers/tests/test_solveset.py
+++ b/sympy/solvers/tests/test_solveset.py
@@ -14,7 +14,7 @@
from sympy.polys.rootoftools import RootOf
-from sympy.sets import FiniteSet
+from sympy.sets import (FiniteSet, ConditionSet)
from sympy.utilities.pytest import XFAIL, raises, skip
from sympy.utilities.randtest import verify_numerically as tn
@@ -409,7 +409,8 @@ def test_solve_sqrt_3():
eq = -sqrt((m - q)**2 + (-m/(2*q) + S(1)/2)**2) + sqrt((-m**2/2 - sqrt(
4*m**4 - 4*m**2 + 8*m + 1)/4 - S(1)/4)**2 + (m**2/2 - m - sqrt(
4*m**4 - 4*m**2 + 8*m + 1)/4 - S(1)/4)**2)
- raises(NotImplementedError, lambda: solveset_real(eq, q))
+ unsolved_object = ConditionSet(Lambda(q, Eq((-2*sqrt(4*q**2*(m - q)**2 + (-m + q)**2) + sqrt((-2*m**2 - sqrt(4*m**4 - 4*m**2 + 8*m + 1) - 1)**2 + (2*m**2 - 4*m - sqrt(4*m**4 - 4*m**2 + 8*m + 1) - 1)**2)*Abs(q))/Abs(q), 0)), S.Reals)
+ assert solveset_real(eq, q) == unsolved_object
def test_solve_polynomial_symbolic_param():
@@ -683,7 +684,9 @@ def test_solve_invalid_sol():
def test_solve_complex_unsolvable():
- raises(NotImplementedError, lambda: solveset_complex(cos(x) - S.Half, x))
+ unsolved_object = ConditionSet(Lambda(x, Eq(2*cos(x) - 1, 0)), S.Complexes)
+ solution = solveset_complex(cos(x) - S.Half, x)
+ assert solution == unsolved_object
@XFAIL
@@ -808,6 +811,29 @@ def test_solveset():
S.Integers)
+def test_conditonset():
+ assert solveset(Eq(sin(x)**2 + cos(x)**2, 1), x, domain=S.Reals) == \
+ ConditionSet(Lambda(x, True), S.Reals)
+
+ assert solveset(Eq(x**2 + x*sin(x), 1), x, domain=S.Reals) == \
+ ConditionSet(Lambda(x, Eq(x*(x + sin(x)) - 1, 0)), S.Reals)
+
+ assert solveset(Eq(sin(Abs(x)), 1), x, domain=S.Reals) == \
+ ConditionSet(Lambda(x, Eq(sin(Abs(x)) - 1, 0)), S.Reals)
+
+ assert solveset(Eq(-I*(exp(I*x) - exp(-I*x))/2, 1), x) == \
+ imageset(Lambda(n, 2*n*pi + pi/2), S.Integers)
+
+ assert solveset(x + sin(x) > 1, x, domain=S.Reals) == \
+ ConditionSet(Lambda(x, x + sin(x) > 1), S.Reals)
+
+
+@XFAIL
+def test_conditionset_equality():
+ ''' Checking equality of different representations of ConditionSet'''
+ assert solveset(Eq(tan(x), y), x) == ConditionSet(Lambda(x, Eq(tan(x), y)), S.Complexes)
+
+
def test_solveset_domain():
x = Symbol('x')
@@ -820,7 +846,9 @@ def test_improve_coverage():
from sympy.solvers.solveset import _has_rational_power
x = Symbol('x')
y = exp(x+1/x**2)
- raises(NotImplementedError, lambda: solveset(y**2+y, x, S.Reals))
+ solution = solveset(y**2+y, x, S.Reals)
+ unsolved_object = ConditionSet(Lambda(x, Eq((exp((x**3 + 1)/x**2) + 1)*exp((x**3 + 1)/x**2), 0)), S.Reals)
+ assert solution == unsolved_object
assert _has_rational_power(sin(x)*exp(x) + 1, x) == (False, S.One)
assert _has_rational_power((sin(x)**2)*(exp(x) + 1)**3, x) == (False, S.One)
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 2,
"issue_text_score": 1,
"test_score": 3
},
"num_modified_files": 2
} | 0.7 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "pytest",
"pip_packages": [
"pytest"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.4",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | attrs @ file:///opt/conda/conda-bld/attrs_1642510447205/work
certifi==2021.5.30
importlib-metadata @ file:///tmp/build/80754af9/importlib-metadata_1631916693255/work
iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work
more-itertools @ file:///tmp/build/80754af9/more-itertools_1637733554872/work
mpmath==1.3.0
packaging @ file:///tmp/build/80754af9/packaging_1637314298585/work
pluggy @ file:///tmp/build/80754af9/pluggy_1615976315926/work
py @ file:///opt/conda/conda-bld/py_1644396412707/work
pyparsing @ file:///tmp/build/80754af9/pyparsing_1635766073266/work
pytest==6.2.4
-e git+https://github.com/sympy/sympy.git@a91ba26c6d639980a4b3351a443548c629447cf9#egg=sympy
toml @ file:///tmp/build/80754af9/toml_1616166611790/work
typing_extensions @ file:///opt/conda/conda-bld/typing_extensions_1647553014482/work
zipp @ file:///tmp/build/80754af9/zipp_1633618647012/work
| name: sympy
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- attrs=21.4.0=pyhd3eb1b0_0
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2021.5.30=py36h06a4308_0
- importlib-metadata=4.8.1=py36h06a4308_0
- importlib_metadata=4.8.1=hd3eb1b0_0
- iniconfig=1.1.1=pyhd3eb1b0_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.3=he6710b0_2
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- more-itertools=8.12.0=pyhd3eb1b0_0
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- packaging=21.3=pyhd3eb1b0_0
- pip=21.2.2=py36h06a4308_0
- pluggy=0.13.1=py36h06a4308_0
- py=1.11.0=pyhd3eb1b0_0
- pyparsing=3.0.4=pyhd3eb1b0_0
- pytest=6.2.4=py36h06a4308_2
- python=3.6.13=h12debd9_1
- readline=8.2=h5eee18b_0
- setuptools=58.0.4=py36h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- toml=0.10.2=pyhd3eb1b0_0
- typing_extensions=4.1.1=pyh06a4308_0
- wheel=0.37.1=pyhd3eb1b0_0
- xz=5.6.4=h5eee18b_1
- zipp=3.6.0=pyhd3eb1b0_0
- zlib=1.2.13=h5eee18b_1
- pip:
- mpmath==1.3.0
prefix: /opt/conda/envs/sympy
| [
"sympy/sets/tests/test_conditionset.py::test_CondSet_intersect",
"sympy/solvers/tests/test_solveset.py::test_solve_sqrt_3",
"sympy/solvers/tests/test_solveset.py::test_solve_complex_unsolvable",
"sympy/solvers/tests/test_solveset.py::test_conditonset",
"sympy/solvers/tests/test_solveset.py::test_improve_coverage"
] | [] | [
"sympy/sets/tests/test_conditionset.py::test_CondSet",
"sympy/solvers/tests/test_solveset.py::test_invert_real",
"sympy/solvers/tests/test_solveset.py::test_invert_complex",
"sympy/solvers/tests/test_solveset.py::test_domain_check",
"sympy/solvers/tests/test_solveset.py::test_is_function_class_equation",
"sympy/solvers/tests/test_solveset.py::test_garbage_input",
"sympy/solvers/tests/test_solveset.py::test_solve_mul",
"sympy/solvers/tests/test_solveset.py::test_solve_invert",
"sympy/solvers/tests/test_solveset.py::test_errorinverses",
"sympy/solvers/tests/test_solveset.py::test_solve_polynomial",
"sympy/solvers/tests/test_solveset.py::test_return_root_of",
"sympy/solvers/tests/test_solveset.py::test__has_rational_power",
"sympy/solvers/tests/test_solveset.py::test_solveset_sqrt_1",
"sympy/solvers/tests/test_solveset.py::test_solveset_sqrt_2",
"sympy/solvers/tests/test_solveset.py::test_solve_polynomial_symbolic_param",
"sympy/solvers/tests/test_solveset.py::test_solve_rational",
"sympy/solvers/tests/test_solveset.py::test_solveset_real_gen_is_pow",
"sympy/solvers/tests/test_solveset.py::test_no_sol",
"sympy/solvers/tests/test_solveset.py::test_sol_zero_real",
"sympy/solvers/tests/test_solveset.py::test_no_sol_rational_extragenous",
"sympy/solvers/tests/test_solveset.py::test_solve_polynomial_cv_1a",
"sympy/solvers/tests/test_solveset.py::test_solveset_real_rational",
"sympy/solvers/tests/test_solveset.py::test_solveset_real_log",
"sympy/solvers/tests/test_solveset.py::test_poly_gens",
"sympy/solvers/tests/test_solveset.py::test_solve_abs",
"sympy/solvers/tests/test_solveset.py::test_real_imag_splitting",
"sympy/solvers/tests/test_solveset.py::test_units",
"sympy/solvers/tests/test_solveset.py::test_solve_only_exp_1",
"sympy/solvers/tests/test_solveset.py::test_atan2",
"sympy/solvers/tests/test_solveset.py::test_piecewise",
"sympy/solvers/tests/test_solveset.py::test_solveset_complex_polynomial",
"sympy/solvers/tests/test_solveset.py::test_sol_zero_complex",
"sympy/solvers/tests/test_solveset.py::test_solveset_complex_rational",
"sympy/solvers/tests/test_solveset.py::test_solveset_complex_exp",
"sympy/solvers/tests/test_solveset.py::test_solve_complex_log",
"sympy/solvers/tests/test_solveset.py::test_solve_complex_sqrt",
"sympy/solvers/tests/test_solveset.py::test_solveset_complex_tan",
"sympy/solvers/tests/test_solveset.py::test_solve_trig",
"sympy/solvers/tests/test_solveset.py::test_solve_invalid_sol",
"sympy/solvers/tests/test_solveset.py::test_solveset",
"sympy/solvers/tests/test_solveset.py::test_solveset_domain",
"sympy/solvers/tests/test_solveset.py::test_issue_9522",
"sympy/solvers/tests/test_solveset.py::test_linear_eq_to_matrix",
"sympy/solvers/tests/test_solveset.py::test_linsolve",
"sympy/solvers/tests/test_solveset.py::test_issue_9556",
"sympy/solvers/tests/test_solveset.py::test_issue_9611",
"sympy/solvers/tests/test_solveset.py::test_issue_9557"
] | [] | BSD | 208 |
|
softlayer__softlayer-python-602 | 1195b2020ef6efc40462d59eb079f26e5f39a6d8 | 2015-08-10 15:51:18 | 1195b2020ef6efc40462d59eb079f26e5f39a6d8 | diff --git a/SoftLayer/CLI/server/detail.py b/SoftLayer/CLI/server/detail.py
index 1b9d588e..9fc76c5d 100644
--- a/SoftLayer/CLI/server/detail.py
+++ b/SoftLayer/CLI/server/detail.py
@@ -62,14 +62,11 @@ def cli(env, identifier, passwords, price):
table.add_row(
['created', result['provisionDate'] or formatting.blank()])
- if utils.lookup(result, 'billingItem') != []:
- table.add_row(['owner', formatting.FormattedItem(
- utils.lookup(result, 'billingItem', 'orderItem',
- 'order', 'userRecord',
- 'username') or formatting.blank(),
- )])
- else:
- table.add_row(['owner', formatting.blank()])
+ table.add_row(['owner', formatting.FormattedItem(
+ utils.lookup(result, 'billingItem', 'orderItem',
+ 'order', 'userRecord',
+ 'username') or formatting.blank()
+ )])
vlan_table = formatting.Table(['type', 'number', 'id'])
diff --git a/SoftLayer/CLI/virt/detail.py b/SoftLayer/CLI/virt/detail.py
index b003e413..4fc115ce 100644
--- a/SoftLayer/CLI/virt/detail.py
+++ b/SoftLayer/CLI/virt/detail.py
@@ -67,14 +67,11 @@ def cli(self, identifier, passwords=False, price=False):
table.add_row(['private_cpu', result['dedicatedAccountHostOnlyFlag']])
table.add_row(['created', result['createDate']])
table.add_row(['modified', result['modifyDate']])
- if utils.lookup(result, 'billingItem') != []:
- table.add_row(['owner', formatting.FormattedItem(
- utils.lookup(result, 'billingItem', 'orderItem',
- 'order', 'userRecord',
- 'username') or formatting.blank(),
- )])
- else:
- table.add_row(['owner', formatting.blank()])
+ table.add_row(['owner', formatting.FormattedItem(
+ utils.lookup(result, 'billingItem', 'orderItem',
+ 'order', 'userRecord',
+ 'username') or formatting.blank(),
+ )])
vlan_table = formatting.Table(['type', 'number', 'id'])
for vlan in result['networkVlans']:
diff --git a/SoftLayer/managers/vs.py b/SoftLayer/managers/vs.py
index 30de90b3..40ea9925 100644
--- a/SoftLayer/managers/vs.py
+++ b/SoftLayer/managers/vs.py
@@ -423,6 +423,7 @@ def verify_create_instance(self, **kwargs):
Without actually placing an order.
See :func:`create_instance` for a list of available options.
"""
+ kwargs.pop('tags', None)
create_options = self._generate_create_dict(**kwargs)
return self.guest.generateOrderTemplate(create_options)
| got an unexpected keyword argument 'tags'
Hi there
I came across an error when creating VS and providing tags either in the form of -g or --tag
C:\Python34\Scripts>slcli vs create --test --hostname OS --domain vm.local --cpu 1 --memory 1024 --os WIN_LATEST_64 --datacenter lon02 --tag 1234
An unexpected error has occured:
Traceback (most recent call last):
File "C:\Python34\lib\site-packages\SoftLayer\CLI\core.py", line 181, in main
cli.main()
File "C:\Python34\lib\site-packages\click\core.py", line 644, in main
rv = self.invoke(ctx)
File "C:\Python34\lib\site-packages\click\core.py", line 991, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "C:\Python34\lib\site-packages\click\core.py", line 991, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "C:\Python34\lib\site-packages\click\core.py", line 837, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "C:\Python34\lib\site-packages\click\core.py", line 464, in invoke
return callback(*args, **kwargs)
File "C:\Python34\lib\site-packages\click\decorators.py", line 64, in new_func
return ctx.invoke(f, obj, *args[1:], **kwargs)
File "C:\Python34\lib\site-packages\click\core.py", line 464, in invoke
return callback(*args, **kwargs)
File "C:\Python34\lib\site-packages\SoftLayer\CLI\virt\create.py", line 92, in cli
result = vsi.verify_create_instance(**data)
File "C:\Python34\lib\site-packages\SoftLayer\managers\vs.py", line 426, in verify_create_instance
create_options = self._generate_create_dict(**kwargs)
TypeError: _generate_create_dict() got an unexpected keyword argument 'tags' | softlayer/softlayer-python | diff --git a/SoftLayer/tests/managers/vs_tests.py b/SoftLayer/tests/managers/vs_tests.py
index 3a179b46..9bdb3459 100644
--- a/SoftLayer/tests/managers/vs_tests.py
+++ b/SoftLayer/tests/managers/vs_tests.py
@@ -141,7 +141,7 @@ def test_reload_instance(self):
def test_create_verify(self, create_dict):
create_dict.return_value = {'test': 1, 'verify': 1}
- self.vs.verify_create_instance(test=1, verify=1)
+ self.vs.verify_create_instance(test=1, verify=1, tags=['test', 'tags'])
create_dict.assert_called_once_with(test=1, verify=1)
self.assert_called_with('SoftLayer_Virtual_Guest',
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 1,
"issue_text_score": 1,
"test_score": 2
},
"num_modified_files": 3
} | 4.0 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[dev]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.6",
"reqs_path": [
"tools/test-requirements.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | alabaster==0.7.13
attrs==22.2.0
Babel==2.11.0
certifi==2021.5.30
charset-normalizer==2.0.12
click==8.0.4
coverage==6.2
distlib==0.3.9
docutils==0.18.1
filelock==3.4.1
fixtures==4.0.1
idna==3.10
imagesize==1.4.1
importlib-metadata==4.8.3
importlib-resources==5.4.0
iniconfig==1.1.1
Jinja2==3.0.3
MarkupSafe==2.0.1
mock==5.2.0
nose==1.3.7
packaging==21.3
pbr==6.1.1
platformdirs==2.4.0
pluggy==1.0.0
prettytable==2.5.0
py==1.11.0
Pygments==2.14.0
pyparsing==3.1.4
pytest==7.0.1
pytz==2025.2
requests==2.27.1
six==1.17.0
snowballstemmer==2.2.0
-e git+https://github.com/softlayer/softlayer-python.git@1195b2020ef6efc40462d59eb079f26e5f39a6d8#egg=SoftLayer
Sphinx==5.3.0
sphinxcontrib-applehelp==1.0.2
sphinxcontrib-devhelp==1.0.2
sphinxcontrib-htmlhelp==2.0.0
sphinxcontrib-jsmath==1.0.1
sphinxcontrib-qthelp==1.0.3
sphinxcontrib-serializinghtml==1.1.5
testtools==2.6.0
toml==0.10.2
tomli==1.2.3
tox==3.28.0
typing_extensions==4.1.1
urllib3==1.26.20
virtualenv==20.17.1
wcwidth==0.2.13
zipp==3.6.0
| name: softlayer-python
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2021.5.30=py36h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.3=he6710b0_2
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- pip=21.2.2=py36h06a4308_0
- python=3.6.13=h12debd9_1
- readline=8.2=h5eee18b_0
- setuptools=58.0.4=py36h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- wheel=0.37.1=pyhd3eb1b0_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- alabaster==0.7.13
- attrs==22.2.0
- babel==2.11.0
- charset-normalizer==2.0.12
- click==8.0.4
- coverage==6.2
- distlib==0.3.9
- docutils==0.18.1
- filelock==3.4.1
- fixtures==4.0.1
- idna==3.10
- imagesize==1.4.1
- importlib-metadata==4.8.3
- importlib-resources==5.4.0
- iniconfig==1.1.1
- jinja2==3.0.3
- markupsafe==2.0.1
- mock==5.2.0
- nose==1.3.7
- packaging==21.3
- pbr==6.1.1
- platformdirs==2.4.0
- pluggy==1.0.0
- prettytable==2.5.0
- py==1.11.0
- pygments==2.14.0
- pyparsing==3.1.4
- pytest==7.0.1
- pytz==2025.2
- requests==2.27.1
- six==1.17.0
- snowballstemmer==2.2.0
- sphinx==5.3.0
- sphinxcontrib-applehelp==1.0.2
- sphinxcontrib-devhelp==1.0.2
- sphinxcontrib-htmlhelp==2.0.0
- sphinxcontrib-jsmath==1.0.1
- sphinxcontrib-qthelp==1.0.3
- sphinxcontrib-serializinghtml==1.1.5
- testtools==2.6.0
- toml==0.10.2
- tomli==1.2.3
- tox==3.28.0
- typing-extensions==4.1.1
- urllib3==1.26.20
- virtualenv==20.17.1
- wcwidth==0.2.13
- zipp==3.6.0
prefix: /opt/conda/envs/softlayer-python
| [
"SoftLayer/tests/managers/vs_tests.py::VSTests::test_create_verify"
] | [] | [
"SoftLayer/tests/managers/vs_tests.py::VSTests::test_cancel_instance",
"SoftLayer/tests/managers/vs_tests.py::VSTests::test_capture_additional_disks",
"SoftLayer/tests/managers/vs_tests.py::VSTests::test_captures",
"SoftLayer/tests/managers/vs_tests.py::VSTests::test_change_port_speed_private",
"SoftLayer/tests/managers/vs_tests.py::VSTests::test_change_port_speed_public",
"SoftLayer/tests/managers/vs_tests.py::VSTests::test_create_instance",
"SoftLayer/tests/managers/vs_tests.py::VSTests::test_create_instances",
"SoftLayer/tests/managers/vs_tests.py::VSTests::test_edit_blank",
"SoftLayer/tests/managers/vs_tests.py::VSTests::test_edit_full",
"SoftLayer/tests/managers/vs_tests.py::VSTests::test_edit_metadata",
"SoftLayer/tests/managers/vs_tests.py::VSTests::test_edit_tags",
"SoftLayer/tests/managers/vs_tests.py::VSTests::test_edit_tags_blank",
"SoftLayer/tests/managers/vs_tests.py::VSTests::test_generate_basic",
"SoftLayer/tests/managers/vs_tests.py::VSTests::test_generate_datacenter",
"SoftLayer/tests/managers/vs_tests.py::VSTests::test_generate_dedicated",
"SoftLayer/tests/managers/vs_tests.py::VSTests::test_generate_image_id",
"SoftLayer/tests/managers/vs_tests.py::VSTests::test_generate_missing",
"SoftLayer/tests/managers/vs_tests.py::VSTests::test_generate_monthly",
"SoftLayer/tests/managers/vs_tests.py::VSTests::test_generate_multi_disk",
"SoftLayer/tests/managers/vs_tests.py::VSTests::test_generate_network",
"SoftLayer/tests/managers/vs_tests.py::VSTests::test_generate_no_disks",
"SoftLayer/tests/managers/vs_tests.py::VSTests::test_generate_os_and_image",
"SoftLayer/tests/managers/vs_tests.py::VSTests::test_generate_post_uri",
"SoftLayer/tests/managers/vs_tests.py::VSTests::test_generate_private_network_only",
"SoftLayer/tests/managers/vs_tests.py::VSTests::test_generate_private_vlan",
"SoftLayer/tests/managers/vs_tests.py::VSTests::test_generate_public_vlan",
"SoftLayer/tests/managers/vs_tests.py::VSTests::test_generate_single_disk",
"SoftLayer/tests/managers/vs_tests.py::VSTests::test_generate_sshkey",
"SoftLayer/tests/managers/vs_tests.py::VSTests::test_generate_userdata",
"SoftLayer/tests/managers/vs_tests.py::VSTests::test_get_create_options",
"SoftLayer/tests/managers/vs_tests.py::VSTests::test_get_instance",
"SoftLayer/tests/managers/vs_tests.py::VSTests::test_get_item_id_for_upgrade",
"SoftLayer/tests/managers/vs_tests.py::VSTests::test_list_instances",
"SoftLayer/tests/managers/vs_tests.py::VSTests::test_list_instances_hourly",
"SoftLayer/tests/managers/vs_tests.py::VSTests::test_list_instances_monthly",
"SoftLayer/tests/managers/vs_tests.py::VSTests::test_list_instances_neither",
"SoftLayer/tests/managers/vs_tests.py::VSTests::test_list_instances_with_filters",
"SoftLayer/tests/managers/vs_tests.py::VSTests::test_reload_instance",
"SoftLayer/tests/managers/vs_tests.py::VSTests::test_rescue",
"SoftLayer/tests/managers/vs_tests.py::VSTests::test_resolve_ids_hostname",
"SoftLayer/tests/managers/vs_tests.py::VSTests::test_resolve_ids_ip",
"SoftLayer/tests/managers/vs_tests.py::VSTests::test_resolve_ids_ip_invalid",
"SoftLayer/tests/managers/vs_tests.py::VSTests::test_resolve_ids_ip_private",
"SoftLayer/tests/managers/vs_tests.py::VSTests::test_upgrade",
"SoftLayer/tests/managers/vs_tests.py::VSTests::test_upgrade_blank",
"SoftLayer/tests/managers/vs_tests.py::VSTests::test_upgrade_full",
"SoftLayer/tests/managers/vs_tests.py::VSWaitReadyGoTests::test_active_and_provisiondate",
"SoftLayer/tests/managers/vs_tests.py::VSWaitReadyGoTests::test_active_not_provisioned",
"SoftLayer/tests/managers/vs_tests.py::VSWaitReadyGoTests::test_active_provision_pending",
"SoftLayer/tests/managers/vs_tests.py::VSWaitReadyGoTests::test_active_reload",
"SoftLayer/tests/managers/vs_tests.py::VSWaitReadyGoTests::test_iter_four_complete",
"SoftLayer/tests/managers/vs_tests.py::VSWaitReadyGoTests::test_iter_once_complete",
"SoftLayer/tests/managers/vs_tests.py::VSWaitReadyGoTests::test_iter_ten_incomplete",
"SoftLayer/tests/managers/vs_tests.py::VSWaitReadyGoTests::test_iter_two_incomplete",
"SoftLayer/tests/managers/vs_tests.py::VSWaitReadyGoTests::test_ready_iter_once_incomplete",
"SoftLayer/tests/managers/vs_tests.py::VSWaitReadyGoTests::test_reload_no_pending",
"SoftLayer/tests/managers/vs_tests.py::VSWaitReadyGoTests::test_reload_pending",
"SoftLayer/tests/managers/vs_tests.py::VSWaitReadyGoTests::test_wait_interface"
] | [] | MIT License | 209 |
|
sympy__sympy-9814 | 690558757292f69b90f39ce22523ce2daa755538 | 2015-08-12 11:33:51 | 0241b35cae5f2adc04dc37b25f7dc9c5f00bd746 | gxyd: Are the tests-failures related to this ? | diff --git a/sympy/series/order.py b/sympy/series/order.py
index d3dd991efe..e5a153dc1f 100644
--- a/sympy/series/order.py
+++ b/sympy/series/order.py
@@ -6,6 +6,7 @@
from sympy.core.compatibility import default_sort_key, is_sequence
from sympy.core.containers import Tuple
from sympy.utilities.iterables import uniq
+from sympy.sets.sets import Complement
class Order(Expr):
@@ -415,6 +416,10 @@ def _eval_subs(self, old, new):
from sympy.solvers.solveset import solveset
d = Dummy()
sol = solveset(old - new.subs(var, d), d)
+ if isinstance(sol, Complement):
+ e1 = sol.args[0]
+ e2 = sol.args[1]
+ sol = set(e1) - set(e2)
res = [dict(zip((d, ), sol))]
point = d.subs(res[0]).limit(old, self.point[i])
newvars[i] = var
diff --git a/sympy/sets/sets.py b/sympy/sets/sets.py
index fc3411d6ec..a748db622c 100644
--- a/sympy/sets/sets.py
+++ b/sympy/sets/sets.py
@@ -1784,6 +1784,12 @@ def _complement(self, other):
elif nums == []:
return None
+ elif isinstance(other, FiniteSet):
+ elms_unknown = FiniteSet(*[el for el in self if other.contains(el) not in (True, False)])
+ if elms_unknown == self:
+ return
+ return Complement(FiniteSet(*[el for el in other if self.contains(el) != True]), elms_unknown)
+
return Set._complement(self, other)
| Complements with symbols should remain unevaluated
Complements with symbols should remain unevaluated for the same reason Intersections with symbols should remain unevaluated i.e., we don't know what the complement is unless we the value of the symbol. Our current behaviour is:
```python
In [14]: Complement(FiniteSet(y), FiniteSet(1))
Out[14]: {y} # should be {y}\{1}
``` | sympy/sympy | diff --git a/sympy/sets/tests/test_sets.py b/sympy/sets/tests/test_sets.py
index 8ad2b79745..b841e4be20 100644
--- a/sympy/sets/tests/test_sets.py
+++ b/sympy/sets/tests/test_sets.py
@@ -888,3 +888,9 @@ def test_issue_9637():
Complement(Union(Interval(1, 2, False, True), Interval(2, 3, True, False)), a)
assert Complement(a, S.Reals) == Complement(a, S.Reals, evaluate=False)
assert Complement(a, Interval(1, 3)) == Complement(a, Interval(1, 3), evaluate=False)
+
+
+def test_issue_9808():
+ assert Complement(FiniteSet(y), FiniteSet(1)) == Complement(FiniteSet(y), FiniteSet(1), evaluate=False)
+ assert Complement(FiniteSet(1, 2, x), FiniteSet(x, y, 2, 3)) == \
+ Complement(FiniteSet(1), FiniteSet(y), evaluate=False)
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 2,
"issue_text_score": 0,
"test_score": 0
},
"num_modified_files": 2
} | 0.7 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "pytest",
"pip_packages": [
"pytest",
"pytest-cov",
"pytest-xdist",
"pytest-mock",
"pytest-asyncio"
],
"pre_install": [],
"python": "3.7",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | attrs @ file:///croot/attrs_1668696182826/work
certifi @ file:///croot/certifi_1671487769961/work/certifi
coverage==7.2.7
execnet==2.0.2
flit_core @ file:///opt/conda/conda-bld/flit-core_1644941570762/work/source/flit_core
importlib-metadata @ file:///tmp/build/80754af9/importlib-metadata_1648562407465/work
iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work
mpmath==1.3.0
packaging @ file:///croot/packaging_1671697413597/work
pluggy @ file:///tmp/build/80754af9/pluggy_1648042572264/work
py @ file:///opt/conda/conda-bld/py_1644396412707/work
pytest==7.1.2
pytest-asyncio==0.21.2
pytest-cov==4.1.0
pytest-mock==3.11.1
pytest-xdist==3.5.0
-e git+https://github.com/sympy/sympy.git@690558757292f69b90f39ce22523ce2daa755538#egg=sympy
tomli @ file:///opt/conda/conda-bld/tomli_1657175507142/work
typing_extensions @ file:///croot/typing_extensions_1669924550328/work
zipp @ file:///croot/zipp_1672387121353/work
| name: sympy
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- attrs=22.1.0=py37h06a4308_0
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2022.12.7=py37h06a4308_0
- flit-core=3.6.0=pyhd3eb1b0_0
- importlib-metadata=4.11.3=py37h06a4308_0
- importlib_metadata=4.11.3=hd3eb1b0_0
- iniconfig=1.1.1=pyhd3eb1b0_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- packaging=22.0=py37h06a4308_0
- pip=22.3.1=py37h06a4308_0
- pluggy=1.0.0=py37h06a4308_1
- py=1.11.0=pyhd3eb1b0_0
- pytest=7.1.2=py37h06a4308_0
- python=3.7.16=h7a1cb2a_0
- readline=8.2=h5eee18b_0
- setuptools=65.6.3=py37h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- tomli=2.0.1=py37h06a4308_0
- typing_extensions=4.4.0=py37h06a4308_0
- wheel=0.38.4=py37h06a4308_0
- xz=5.6.4=h5eee18b_1
- zipp=3.11.0=py37h06a4308_0
- zlib=1.2.13=h5eee18b_1
- pip:
- coverage==7.2.7
- execnet==2.0.2
- mpmath==1.3.0
- pytest-asyncio==0.21.2
- pytest-cov==4.1.0
- pytest-mock==3.11.1
- pytest-xdist==3.5.0
prefix: /opt/conda/envs/sympy
| [
"sympy/sets/tests/test_sets.py::test_issue_9808"
] | [] | [
"sympy/sets/tests/test_sets.py::test_interval_arguments",
"sympy/sets/tests/test_sets.py::test_interval_symbolic_end_points",
"sympy/sets/tests/test_sets.py::test_union",
"sympy/sets/tests/test_sets.py::test_difference",
"sympy/sets/tests/test_sets.py::test_Complement",
"sympy/sets/tests/test_sets.py::test_complement",
"sympy/sets/tests/test_sets.py::test_intersect",
"sympy/sets/tests/test_sets.py::test_intersection",
"sympy/sets/tests/test_sets.py::test_issue_9623",
"sympy/sets/tests/test_sets.py::test_is_disjoint",
"sympy/sets/tests/test_sets.py::test_ProductSet_of_single_arg_is_arg",
"sympy/sets/tests/test_sets.py::test_interval_subs",
"sympy/sets/tests/test_sets.py::test_interval_to_mpi",
"sympy/sets/tests/test_sets.py::test_measure",
"sympy/sets/tests/test_sets.py::test_is_subset",
"sympy/sets/tests/test_sets.py::test_is_proper_subset",
"sympy/sets/tests/test_sets.py::test_is_superset",
"sympy/sets/tests/test_sets.py::test_is_proper_superset",
"sympy/sets/tests/test_sets.py::test_contains",
"sympy/sets/tests/test_sets.py::test_interval_symbolic",
"sympy/sets/tests/test_sets.py::test_union_contains",
"sympy/sets/tests/test_sets.py::test_is_number",
"sympy/sets/tests/test_sets.py::test_Interval_is_left_unbounded",
"sympy/sets/tests/test_sets.py::test_Interval_is_right_unbounded",
"sympy/sets/tests/test_sets.py::test_Interval_as_relational",
"sympy/sets/tests/test_sets.py::test_Finite_as_relational",
"sympy/sets/tests/test_sets.py::test_Union_as_relational",
"sympy/sets/tests/test_sets.py::test_Intersection_as_relational",
"sympy/sets/tests/test_sets.py::test_EmptySet",
"sympy/sets/tests/test_sets.py::test_finite_basic",
"sympy/sets/tests/test_sets.py::test_powerset",
"sympy/sets/tests/test_sets.py::test_product_basic",
"sympy/sets/tests/test_sets.py::test_real",
"sympy/sets/tests/test_sets.py::test_supinf",
"sympy/sets/tests/test_sets.py::test_universalset",
"sympy/sets/tests/test_sets.py::test_Union_of_ProductSets_shares",
"sympy/sets/tests/test_sets.py::test_Interval_free_symbols",
"sympy/sets/tests/test_sets.py::test_image_interval",
"sympy/sets/tests/test_sets.py::test_image_piecewise",
"sympy/sets/tests/test_sets.py::test_image_FiniteSet",
"sympy/sets/tests/test_sets.py::test_image_Union",
"sympy/sets/tests/test_sets.py::test_image_EmptySet",
"sympy/sets/tests/test_sets.py::test_issue_5724_7680",
"sympy/sets/tests/test_sets.py::test_boundary",
"sympy/sets/tests/test_sets.py::test_boundary_Union",
"sympy/sets/tests/test_sets.py::test_boundary_ProductSet",
"sympy/sets/tests/test_sets.py::test_boundary_ProductSet_line",
"sympy/sets/tests/test_sets.py::test_is_open",
"sympy/sets/tests/test_sets.py::test_is_closed",
"sympy/sets/tests/test_sets.py::test_closure",
"sympy/sets/tests/test_sets.py::test_interior",
"sympy/sets/tests/test_sets.py::test_issue_7841",
"sympy/sets/tests/test_sets.py::test_Eq",
"sympy/sets/tests/test_sets.py::test_SymmetricDifference",
"sympy/sets/tests/test_sets.py::test_issue_9536",
"sympy/sets/tests/test_sets.py::test_issue_9637"
] | [] | BSD | 210 |
SMART-Lab__smartlearner-31 | 0f11484800712ac92d6027754ab0a026193fa985 | 2015-08-13 18:37:49 | 0f11484800712ac92d6027754ab0a026193fa985 | diff --git a/smartlearner/__init__.py b/smartlearner/__init__.py
index 5159ac3..d6347f4 100644
--- a/smartlearner/__init__.py
+++ b/smartlearner/__init__.py
@@ -1,5 +1,10 @@
from .interfaces.model import Model
from .interfaces.dataset import Dataset
+from .interfaces.loss import Loss
+from .interfaces.task import Task
+
from .trainer import Trainer
from .tasks import tasks
+from .tasks import views
+from .tasks import stopping_criteria
diff --git a/smartlearner/batch_schedulers/__init__.py b/smartlearner/batch_schedulers/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/smartlearner/batch_schedulers/minibatch.py b/smartlearner/batch_schedulers/minibatch.py
new file mode 100644
index 0000000..54ea692
--- /dev/null
+++ b/smartlearner/batch_schedulers/minibatch.py
@@ -0,0 +1,46 @@
+import theano
+import numpy as np
+
+from ..interfaces.batch_scheduler import BatchScheduler
+
+
+class MiniBatchScheduler(BatchScheduler):
+ def __init__(self, dataset, batch_size):
+ super(MiniBatchScheduler, self).__init__(dataset)
+ self._shared_batch_size = theano.shared(np.array(0, dtype='i4'))
+ self.batch_size = batch_size
+ self.shared_batch_count = theano.shared(np.array(0, dtype='i4'))
+
+ @property
+ def batch_size(self):
+ return self._shared_batch_size.get_value()
+
+ @batch_size.setter
+ def batch_size(self, value):
+ self._shared_batch_size.set_value(np.array(value, dtype='i4'))
+ self.nb_updates_per_epoch = int(np.ceil(len(self.dataset)/self.batch_size))
+
+ @property
+ def updates(self):
+ return {} # No updates
+
+ @property
+ def givens(self):
+ start = self.shared_batch_count * self._shared_batch_size
+ end = (self.shared_batch_count + 1) * self._shared_batch_size
+
+ if self.dataset.targets is not None:
+ return {self.dataset.symb_inputs: self.dataset.inputs[start:end],
+ self.dataset.symb_targets: self.dataset.targets[start:end]}
+ else:
+ return {self.dataset.symb_inputs: self.dataset.inputs[start:end]}
+
+ def __iter__(self):
+ for batch_count in range(self.nb_updates_per_epoch):
+ self.shared_batch_count.set_value(batch_count)
+ yield batch_count + 1
+
+
+class FullBatchScheduler(MiniBatchScheduler):
+ def __init__(self, dataset):
+ super(FullBatchScheduler, self).__init__(dataset, batch_size=len(self.dataset))
diff --git a/smartlearner/update_rules/__init__.py b/smartlearner/direction_modifiers/__init__.py
similarity index 76%
rename from smartlearner/update_rules/__init__.py
rename to smartlearner/direction_modifiers/__init__.py
index f1121ac..33afb25 100644
--- a/smartlearner/update_rules/__init__.py
+++ b/smartlearner/direction_modifiers/__init__.py
@@ -1,3 +1,2 @@
-from .update_rule import UpdateRule
from .decreasing_learning_rate import DecreasingLearningRate
from .constant_learning_rate import ConstantLearningRate
diff --git a/smartlearner/update_rules/constant_learning_rate.py b/smartlearner/direction_modifiers/constant_learning_rate.py
similarity index 100%
rename from smartlearner/update_rules/constant_learning_rate.py
rename to smartlearner/direction_modifiers/constant_learning_rate.py
diff --git a/smartlearner/direction_modifiers/decreasing_learning_rate.py b/smartlearner/direction_modifiers/decreasing_learning_rate.py
new file mode 100644
index 0000000..eaca014
--- /dev/null
+++ b/smartlearner/direction_modifiers/decreasing_learning_rate.py
@@ -0,0 +1,44 @@
+from collections import OrderedDict
+
+import numpy as np
+
+from ..utils import sharedX
+from ..interfaces.direction_modifier import DirectionModifier
+
+
+class DecreasingLearningRate(DirectionModifier):
+ def __init__(self, lr, dc=0.):
+ """
+ Implements a decreasing learning rate update rule.
+
+ Parameters
+ ----------
+ lr: float
+ Learning rate.
+ dc: float in [0,1) (optional)
+ Decreasing constant (decay). Default: 0.
+ """
+ if dc < 0. or dc >= 1:
+ raise ValueError("`dc` ({}) must be between 0 (inclusive) and 1 (exclusive)!".format(dc))
+
+ super(DecreasingLearningRate, self).__init__()
+ self.lr = lr
+ self.dc = dc
+ self._updates = OrderedDict()
+
+ def _get_updates(self):
+ return self._updates
+
+ def apply(self, directions):
+ new_directions = OrderedDict()
+
+ for param, gparam in directions.items():
+ lr = sharedX(self.lr * np.ones_like(param.get_value()), name='lr_' + param.name)
+
+ if self.dc != 0.:
+ # Decrease the learning rate by a factor of `dc` after each update.
+ self._updates[lr] = self.dc * lr
+
+ new_directions[param] = lr * gparam
+
+ return new_directions
diff --git a/smartlearner/interfaces/__init__.py b/smartlearner/interfaces/__init__.py
index e69de29..889fe01 100644
--- a/smartlearner/interfaces/__init__.py
+++ b/smartlearner/interfaces/__init__.py
@@ -0,0 +1,7 @@
+from .batch_scheduler import BatchScheduler
+from .dataset import Dataset
+from .model import Model
+from .loss import Loss
+from .task import Task
+from .direction_modifier import DirectionModifier
+from .direction_modifier import ParamModifier
diff --git a/smartlearner/batch_scheduler.py b/smartlearner/interfaces/batch_scheduler.py
similarity index 84%
rename from smartlearner/batch_scheduler.py
rename to smartlearner/interfaces/batch_scheduler.py
index 99f33ec..2324f97 100644
--- a/smartlearner/batch_scheduler.py
+++ b/smartlearner/interfaces/batch_scheduler.py
@@ -1,4 +1,4 @@
-from abc import ABCMeta, abstractmethod
+from abc import ABCMeta, abstractmethod, abstractproperty
import numpy as np
import theano
@@ -11,8 +11,16 @@ class BatchScheduler(object):
self.dataset = dataset
@property
+ def tasks(self):
+ return []
+
+ @abstractproperty
+ def updates(self):
+ raise NotImplementedError("Subclass of 'BatchScheduler' must implement property 'updates'.")
+
+ @abstractproperty
def givens(self):
- raise NotImplementedError("Subclass of 'BatchScheduler' must implement 'givens'.")
+ raise NotImplementedError("Subclass of 'BatchScheduler' must implement property 'givens'.")
@abstractmethod
def __iter__(self):
@@ -40,6 +48,10 @@ class MiniBatchScheduler(BatchScheduler):
self._shared_batch_size.set_value(np.array(value, dtype='i4'))
self.nb_updates_per_epoch = int(np.ceil(len(self.dataset)/self.batch_size))
+ @property
+ def updates(self):
+ return {} # No updates
+
@property
def givens(self):
start = self.shared_batch_count * self._shared_batch_size
@@ -59,4 +71,4 @@ class MiniBatchScheduler(BatchScheduler):
class FullBatchScheduler(MiniBatchScheduler):
def __init__(self, dataset):
- super(FullBatchScheduler, self).__init__(dataset, batch_size=len(self.dataset))
\ No newline at end of file
+ super(FullBatchScheduler, self).__init__(dataset, batch_size=len(self.dataset))
diff --git a/smartlearner/interfaces/direction_modifier.py b/smartlearner/interfaces/direction_modifier.py
new file mode 100644
index 0000000..9823a42
--- /dev/null
+++ b/smartlearner/interfaces/direction_modifier.py
@@ -0,0 +1,41 @@
+from abc import ABCMeta, abstractmethod
+
+
+class DirectionModifier(object):
+ __metaclass__ = ABCMeta
+
+ @property
+ def tasks(self):
+ return []
+
+ @property
+ def updates(self):
+ return self._get_updates()
+
+ @abstractmethod
+ def _get_updates(self):
+ raise NotImplementedError("Subclass of 'DirectionModifier' must implement '_get_updates()'.")
+
+ @abstractmethod
+ def apply(self, directions):
+ raise NotImplementedError("Subclass of 'DirectionModifier' must implement 'apply(directions)'.")
+
+
+class ParamModifier(object):
+ __metaclass__ = ABCMeta
+
+ @property
+ def tasks(self):
+ return []
+
+ @property
+ def updates(self):
+ return self._get_updates()
+
+ @abstractmethod
+ def _get_updates(self):
+ raise NotImplementedError("Subclass of 'ParamModifier' must implement '_get_updates()'.")
+
+ @abstractmethod
+ def apply(self, params):
+ raise NotImplementedError("Subclass of 'ParamModifier' must implement 'apply(params)'.")
diff --git a/smartlearner/interfaces/loss.py b/smartlearner/interfaces/loss.py
index e9823e9..cd1742f 100644
--- a/smartlearner/interfaces/loss.py
+++ b/smartlearner/interfaces/loss.py
@@ -1,24 +1,53 @@
+from collections import OrderedDict
+
from theano import tensor as T
+from abc import ABCMeta, abstractmethod
+
class Loss(object):
+ __metaclass__ = ABCMeta
+
def __init__(self, model, dataset):
self.model = model
self.dataset = dataset
- self.target = dataset.symb_targets
self.consider_constant = [] # Part of the computational graph to be considered as a constant.
+ self._tasks = []
+ self._gradients = None
+
+ # Build the graph for the loss.
+ model_output = self.model.get_output(self.dataset.symb_inputs)
+ self._loss = self._compute_loss(model_output)
+
+ @abstractmethod
+ def _get_updates(self):
+ raise NotImplementedError("Subclass of 'Loss' must implement '_get_updates()'.")
- def get_graph_output(self):
- output, updates = self.model.get_model_output(self.dataset.symb_inputs)
- return self._loss_function(output), updates
+ @abstractmethod
+ def _compute_loss(self, model_output):
+ raise NotImplementedError("Subclass of 'Loss' must implement '_compute_loss(model_output)'.")
- def get_gradients(self):
- cost, updates = self.get_graph_output()
- gparams = T.grad(cost=cost,
+ @property
+ def gradients(self):
+ if self._gradients is None:
+ self._gradients = self._get_gradients()
+
+ return self._gradients
+
+ @property
+ def tasks(self):
+ return self.model.tasks + self._tasks
+
+ @property
+ def updates(self):
+ updates = OrderedDict()
+ updates.update(self.model.updates)
+ updates.update(self._get_updates())
+ return updates
+
+ def _get_gradients(self):
+ gparams = T.grad(cost=self._loss,
wrt=self.model.parameters,
consider_constant=self.consider_constant)
- gradients = dict(zip(self.model.parameters, gparams))
- return gradients, updates
-
- def _loss_function(self, model_output):
- raise NotImplementedError("Subclass of 'Loss' must implement '_loss_function(model_output)'.")
+ self._gradients = dict(zip(self.model.parameters, gparams))
+ return self.gradients
diff --git a/smartlearner/interfaces/model.py b/smartlearner/interfaces/model.py
index f72e79b..bad865b 100644
--- a/smartlearner/interfaces/model.py
+++ b/smartlearner/interfaces/model.py
@@ -1,5 +1,3 @@
-import theano.tensor as T
-from collections import OrderedDict
from abc import ABCMeta, abstractmethod, abstractproperty
@@ -14,9 +12,18 @@ class abstractclassmethod(classmethod):
class Model(object):
__metaclass__ = ABCMeta
- def get_model_output(self, inputs):
+ @property
+ def tasks(self):
+ return []
+
+ @abstractmethod
+ def get_output(self, inputs):
raise NotImplementedError("Subclass of 'Model' must define a model output (a theano graph)")
+ @abstractproperty
+ def updates(self):
+ raise NotImplementedError("Subclass of 'Model' must implement property 'updates'.")
+
@abstractproperty
def parameters(self):
raise NotImplementedError("Subclass of 'Model' must implement property 'parameters'.")
diff --git a/smartlearner/interfaces/optimizer.py b/smartlearner/interfaces/optimizer.py
new file mode 100644
index 0000000..13da9d1
--- /dev/null
+++ b/smartlearner/interfaces/optimizer.py
@@ -0,0 +1,81 @@
+from collections import OrderedDict
+
+from abc import ABCMeta, abstractmethod
+
+
+class Optimizer(object):
+ __metaclass__ = ABCMeta
+
+ def __init__(self, loss):
+ self.loss = loss
+ self._tasks = []
+
+ self._direction_modifiers = []
+ self._param_modifiers = []
+ self._directions = None
+
+ def append_direction_modifier(self, direction_modifier):
+ self._direction_modifiers.append(direction_modifier)
+
+ def append_param_modifier(self, param_modifier):
+ self._param_modifiers.append(param_modifier)
+
+ @abstractmethod
+ def _get_directions(self):
+ raise NotImplementedError("Subclass of 'Optimizer' must implement '_get_directions()'.")
+
+ @abstractmethod
+ def _get_updates(self):
+ raise NotImplementedError("Subclass of 'Optimizer' must implement private property '_updates'.")
+
+ @property
+ def directions(self):
+ if self._directions is None:
+ self._directions = self._get_directions()
+
+ return self._directions
+
+ @property
+ def tasks(self):
+ tasks = []
+ tasks.extend(self.loss.tasks)
+
+ for direction_modifier in self._direction_modifiers:
+ tasks.extend(direction_modifier.tasks)
+
+ for param_modifier in self._param_modifiers:
+ tasks.extend(param_modifier.tasks)
+
+ tasks.extend(self._tasks)
+ return tasks
+
+ @property
+ def updates(self):
+ updates = OrderedDict()
+
+ directions = self.directions
+ updates.update(self.loss.updates) # Gather updates from the loss.
+ updates.update(self._get_updates()) # Gather updates from the optimizer.
+
+ # Apply directions modifiers and gather updates from these modifiers.
+ updates.update(self._apply_modifiers(self._direction_modifiers, directions))
+
+ # Update parameters
+ params_updates = OrderedDict()
+ for param, direction in directions.items():
+ params_updates[param] = param + direction
+ updates.update(params_updates)
+
+ # Apply parameters modifiers and gather updates from these modifiers.
+ updates.update(self._apply_modifiers(self._param_modifiers, params_updates))
+
+ return updates
+
+ def _apply_modifiers(self, list_modifiers, objects_to_modify):
+ updates = OrderedDict()
+ for modifier in list_modifiers:
+ modified_objects = modifier.apply(objects_to_modify)
+ objects_to_modify.update(modified_objects)
+ updates.update(modifier.updates)
+
+ return updates
diff --git a/smartlearner/losses/classification_losses.py b/smartlearner/losses/classification_losses.py
index b5bfc74..738a899 100644
--- a/smartlearner/losses/classification_losses.py
+++ b/smartlearner/losses/classification_losses.py
@@ -4,13 +4,19 @@ import theano.tensor as T
class NegativeLogLikelihood(Loss):
- def _loss_function(self, model_output):
+ def _get_updates(self):
+ return {} # There is no updates for NegativeLogLikelihood.
+
+ def _compute_loss(self, model_output):
nll = -T.log(model_output)
- indices = T.cast(self.target[:, 0], dtype="int32") # Targets are floats.
- selected_nll = nll[T.arange(self.target.shape[0]), indices]
+ indices = T.cast(self.dataset.symb_targets[:, 0], dtype="int32") # Targets are floats.
+ selected_nll = nll[T.arange(self.dataset.symb_targets.shape[0]), indices]
return T.mean(selected_nll)
class CategoricalCrossEntropy(Loss):
- def _loss_function(self, model_output):
- return T.mean(T.nnet.categorical_crossentropy(model_output, self.target))
+ def _get_updates(self):
+ return {} # There is no updates for CategoricalCrossEntropy.
+
+ def _compute_loss(self, model_output):
+ return T.mean(T.nnet.categorical_crossentropy(model_output, self.dataset.symb_targets))
diff --git a/smartlearner/losses/distribution_losses.py b/smartlearner/losses/distribution_losses.py
index c20506b..97a99c7 100644
--- a/smartlearner/losses/distribution_losses.py
+++ b/smartlearner/losses/distribution_losses.py
@@ -4,5 +4,8 @@ import theano.tensor as T
class BinaryCrossEntropy(Loss):
- def _loss_function(self, model_output):
- return T.mean(T.nnet.binary_crossentropy(model_output, self.target))
+ def _get_updates(self):
+ return {} # There is no updates for BinaryCrossEntropy.
+
+ def _compute_loss(self, model_output):
+ return T.mean(T.nnet.binary_crossentropy(model_output, self.dataset.symb_targets))
diff --git a/smartlearner/losses/reconstruction_losses.py b/smartlearner/losses/reconstruction_losses.py
index 59f3e0e..19f5199 100644
--- a/smartlearner/losses/reconstruction_losses.py
+++ b/smartlearner/losses/reconstruction_losses.py
@@ -4,10 +4,16 @@ import theano.tensor as T
class L2Distance(Loss):
- def _loss_function(self, model_output):
- return T.mean((model_output - self.target)**2)
+ def _get_updates(self):
+ return {} # There is no updates for L2Distance.
+
+ def _compute_loss(self, model_output):
+ return T.mean((model_output - self.dataset.symb_targets)**2)
class L1Distance(Loss):
- def _loss_function(self, model_output):
- return T.mean(abs(model_output - self.target))
+ def _get_updates(self):
+ return {} # There is no updates for L1Distance.
+
+ def _compute_loss(self, model_output):
+ return T.mean(abs(model_output - self.dataset.symb_targets))
diff --git a/smartlearner/optimizers/__init__.py b/smartlearner/optimizers/__init__.py
index 3ddc3b4..d2baa34 100644
--- a/smartlearner/optimizers/__init__.py
+++ b/smartlearner/optimizers/__init__.py
@@ -1,2 +1,2 @@
-from .optimizer import Optimizer
from .sgd import SGD
+from .adagrad import AdaGrad
diff --git a/smartlearner/optimizers/adagrad.py b/smartlearner/optimizers/adagrad.py
new file mode 100644
index 0000000..c132e9d
--- /dev/null
+++ b/smartlearner/optimizers/adagrad.py
@@ -0,0 +1,58 @@
+from collections import OrderedDict
+import theano.tensor as T
+
+from . import SGD
+from ..utils import sharedX
+
+
+class AdaGrad(SGD):
+ """ Implements the AdaGrad optimizer [Duchi11]_.
+
+ References
+ ----------
+ .. [Duchi11] Duchi, J., Hazan, E., & Singer, Y., "Adaptive Subgradient
+ Methods for Online Learning and Stochastic Optimization",
+ Journal of Machine Learning Research, vol. 12, pp. 2121-2159,
+ 2011.
+ """
+ def __init__(self, loss, lr, eps=1e-6):
+ """
+ Parameters
+ ----------
+ loss: `smartlearner.interfaces.loss.Loss` object
+ Loss function from which to obtain the gradients.
+ lr: float
+ Initial learning rate.
+ eps: float (optional)
+ Epsilon needed to avoid division by zero.
+ """
+ super().__init__(loss)
+ self.lr = lr
+ self.eps = eps
+ self.parameters = {}
+ self._updates = OrderedDict()
+
+ def _get_updates(self):
+ return self._updates
+
+ def _get_directions(self):
+ """ Produces descending directions. """
+ directions = OrderedDict()
+
+ for i, (param, direction) in enumerate(super()._get_directions().items()):
+ # sum_squared_grad := \sum g_t^2
+ param_name = param.name if param.name is not None else str(i)
+ sum_squared_grad = sharedX(param.get_value() * 0., name='sum_squared_grad_' + param_name)
+ self.parameters[sum_squared_grad.name] = sum_squared_grad
+
+ # Accumulate gradient
+ new_sum_squared_grad = sum_squared_grad + T.sqr(direction)
+
+ # Compute update
+ root_sum_squared = T.sqrt(new_sum_squared_grad + self.eps)
+
+ # Apply update
+ self._updates[sum_squared_grad] = new_sum_squared_grad
+ directions[param] = (self.lr/root_sum_squared) * direction
+
+ return directions
diff --git a/smartlearner/optimizers/optimizer.py b/smartlearner/optimizers/optimizer.py
deleted file mode 100644
index 954a241..0000000
--- a/smartlearner/optimizers/optimizer.py
+++ /dev/null
@@ -1,49 +0,0 @@
-from collections import OrderedDict
-
-from abc import ABCMeta, abstractmethod
-
-
-class Optimizer(object):
- __metaclass__ = ABCMeta
-
- def __init__(self, loss):
- self.loss = loss
-
- self._update_rules = []
- self._param_modifiers = []
-
- def append_update_rule(self, update_rule):
- self._update_rules.append(update_rule)
-
- def append_param_modifier(self, param_modifier):
- self._param_modifiers.append(param_modifier)
-
- @abstractmethod
- def _get_directions(self):
- raise NotImplementedError("Subclass of 'Optimizer' must implement '_get_directions()'.")
-
- def gather_updates(self):
- updates = OrderedDict()
-
- self.directions, updates_from_get_directions = self._get_directions()
- updates.update(updates_from_get_directions)
-
- updates.update(self._apply_updates(self._update_rules, self.directions))
-
- # Update parameters
- params_updates = OrderedDict()
- for param, gparam in self.directions.items():
- params_updates[param] = param + self.directions[param]
- updates.update(params_updates)
-
- updates.update(self._apply_updates(self._param_modifiers, params_updates))
-
- return updates
-
- def _apply_updates(self, list_updates, object_to_update):
- update_dict = OrderedDict()
- for update in list_updates:
- modified_object, updates_to_add = update.apply(object_to_update)
- object_to_update.update(modified_object)
- update_dict.update(updates_to_add)
- return update_dict
\ No newline at end of file
diff --git a/smartlearner/optimizers/sgd.py b/smartlearner/optimizers/sgd.py
index 2130265..8f73365 100644
--- a/smartlearner/optimizers/sgd.py
+++ b/smartlearner/optimizers/sgd.py
@@ -1,16 +1,19 @@
-import numpy as np
-from . import Optimizer
+from collections import OrderedDict
+
+from ..interfaces.optimizer import Optimizer
class SGD(Optimizer):
def __init__(self, loss):
- super(SGD, self).__init__(loss)
+ super().__init__(loss)
- def _get_directions(self):
- self.gradients, updates_from_get_gradients = self.loss.get_gradients()
+ def _get_updates(self):
+ return {} # There is no updates for SGD.
- # Take the opposite of the gradient.
- for param, gparam in self.gradients.items():
- self.gradients[param] = -gparam
+ def _get_directions(self):
+ # Take the opposite of the gradients as directions.
+ directions = OrderedDict()
+ for param, gradient in self.loss.gradients.items():
+ directions[param] = -gradient
- return self.gradients, updates_from_get_gradients
+ return directions
diff --git a/smartlearner/tasks/tasks.py b/smartlearner/tasks/tasks.py
index cd6021f..75ba0c4 100644
--- a/smartlearner/tasks/tasks.py
+++ b/smartlearner/tasks/tasks.py
@@ -6,6 +6,16 @@ from time import time
from smartlearner.interfaces.task import Task, RecurrentTask
+class MonitorVariable(Task):
+ def __init__(self, var):
+ super().__init__()
+ self.var = self.track_variable(var)
+
+ @property
+ def value(self):
+ return self.var.get_value()
+
+
class PrintVariable(RecurrentTask):
def __init__(self, msg, *variables, **recurrent_options):
# TODO: docstring should include **recurrent_options.
diff --git a/smartlearner/trainer.py b/smartlearner/trainer.py
index c25770f..d9cfda0 100644
--- a/smartlearner/trainer.py
+++ b/smartlearner/trainer.py
@@ -1,9 +1,8 @@
from collections import OrderedDict
import theano
-from time import time
from .status import Status
-from smartlearner.tasks.stopping_criteria import TrainingExit
+from .tasks.stopping_criteria import TrainingExit
class Trainer(object):
@@ -11,8 +10,16 @@ class Trainer(object):
self.status = status if status is not None else Status(self)
self._optimizer = optimizer
self._batch_scheduler = batch_scheduler
- self._updates = OrderedDict()
+
+ # Gather updates from the optimizer and the batch scheduler.
+ self._graph_updates = OrderedDict()
+ self._graph_updates.update(self._optimizer.updates)
+ self._graph_updates.update(self._batch_scheduler.updates)
+
+ # Gather tasks from the optimizer and the batch scheduler.
self._tasks = []
+ self._tasks.extend(self._optimizer.tasks)
+ self._tasks.extend(self._batch_scheduler.tasks)
def train(self):
self._pre_learning()
@@ -20,16 +27,17 @@ class Trainer(object):
self._post_learning()
def append_task(self, task):
- self._updates.update(task.updates)
self._tasks.append(task)
def _build_theano_graph(self):
- updates = self._optimizer.gather_updates()
- updates.update(self._updates)
+ # Get updates from tasks.
+ for task in self._tasks:
+ self._graph_updates.update(task.updates)
+
self._learn = theano.function([],
- updates=updates,
- givens=self._batch_scheduler.givens,
- name="learn")
+ updates=self._graph_updates,
+ givens=self._batch_scheduler.givens,
+ name="learn")
def _pre_learning(self):
self._build_theano_graph()
diff --git a/smartlearner/update_rules/decreasing_learning_rate.py b/smartlearner/update_rules/decreasing_learning_rate.py
deleted file mode 100644
index f721726..0000000
--- a/smartlearner/update_rules/decreasing_learning_rate.py
+++ /dev/null
@@ -1,40 +0,0 @@
-from collections import OrderedDict
-
-import numpy as np
-
-from ..utils import sharedX
-from . import UpdateRule
-
-
-class DecreasingLearningRate(UpdateRule):
- def __init__(self, lr, dc=0.):
- """
- Implements a decreasing learning rate update rule.
-
- Parameters
- ----------
- lr: float
- learning rate
- dc: float
- decreasing constant (decay)
- """
- super(DecreasingLearningRate, self).__init__()
- assert dc <= 1.
- assert dc >= 0.
- self.lr = lr
- self.dc = dc
-
- def apply(self, gradients):
- updates = OrderedDict()
- new_gradients = OrderedDict()
-
- for param, gparam in gradients.items():
- lr = sharedX(self.lr * np.ones_like(param.get_value()), name='lr_' + param.name)
-
- if self.dc != 0.:
- # Decrease the learning rate by a factor of `dc` after each update.
- updates[lr] = self.dc * lr
-
- new_gradients[param] = lr * gparam
-
- return new_gradients, updates
diff --git a/smartlearner/update_rules/update_rule.py b/smartlearner/update_rules/update_rule.py
deleted file mode 100644
index e5933ad..0000000
--- a/smartlearner/update_rules/update_rule.py
+++ /dev/null
@@ -1,9 +0,0 @@
-from abc import ABCMeta, abstractmethod
-
-
-class UpdateRule(object):
- __metaclass__ = ABCMeta
-
- @abstractmethod
- def apply(self, gradients):
- raise NotImplementedError("Subclass of 'UpdateRule' must implement 'apply(gradients)'.")
| Refactor how the updates are handled
I suggest a global updates gatherer (either a module function or a singleton class if you feel fancy) that each parts would have access to. This way, everyone would be in charge of registering its updates.
Another solution is a chain call to gather the updates. This would have to be added in the interfaces of each abstract classes (`Model`, `Optimizer`, `Loss`?, `Tasks`?). | SMART-Lab/smartlearner | diff --git a/smartlearner/optimizers/tests/tests_optimizers.py b/smartlearner/optimizers/tests/tests_optimizers.py
new file mode 100644
index 0000000..7735fb9
--- /dev/null
+++ b/smartlearner/optimizers/tests/tests_optimizers.py
@@ -0,0 +1,110 @@
+import numpy as np
+
+import theano
+import theano.tensor as T
+
+from smartlearner.tasks import stopping_criteria
+from smartlearner.utils import sharedX
+
+from smartlearner import Trainer
+from smartlearner.optimizers import SGD, AdaGrad
+
+from smartlearner.tasks import tasks
+
+from numpy.testing import assert_array_almost_equal
+
+from smartlearner.testing import DummyLoss, DummyBatchScheduler
+
+floatX = theano.config.floatX
+
+
+class DummyLossWithGradient(DummyLoss):
+ def __init__(self, cost, param):
+ super().__init__()
+ self.cost = cost
+ self.param = param
+
+ def _get_gradients(self):
+ gparam = T.grad(cost=self.cost, wrt=self.param)
+ return {self.param: gparam}
+
+
+def test_sgd():
+ # Create simple Nd gaussian functions to optimize. These functions are
+ # (perfectly) well-conditioned so it should take only one gradient step
+ # to converge using 1/L, where L is the largest eigenvalue of the hessian.
+ max_epoch = 2
+ for N in range(1, 5):
+ center = np.arange(1, N+1)[None, :].astype(floatX)
+ param = sharedX(np.zeros((1, N)))
+ cost = T.sum(0.5*T.dot(T.dot((param-center), T.eye(N)), (param-center).T))
+ loss = DummyLossWithGradient(cost, param)
+
+ trainer = Trainer(SGD(loss), DummyBatchScheduler())
+ trainer.append_task(stopping_criteria.MaxEpochStopping(max_epoch))
+
+ # Monitor the gradient of `loss` w.r.t. to `param`.
+ gparam = tasks.MonitorVariable(loss.gradients[param])
+ trainer.append_task(gparam)
+ trainer.train()
+
+ # Since the problem is well-conditionned and we use an optimal gradient step 1/L,
+ # two epochs should be enough for `param` to be around `center` and the gradients near 0.
+ assert_array_almost_equal(param.get_value(), center)
+ assert_array_almost_equal(gparam.value, 0.)
+
+ # Create an Nd gaussian function to optimize. This function is not
+ # well-conditioned and there exists no perfect gradient step to converge in
+ # only one iteration.
+ #cost = T.sum(N*0.5*T.dot(T.dot((param-center), np.diag(1./np.arange(1, N+1))), ((param-center).T)))
+ max_epoch = 80
+ N = 4
+ center = 5*np.ones((1, N)).astype(floatX)
+ param = sharedX(np.zeros((1, N)))
+ cost = T.sum(0.5*T.dot(T.dot((param-center), np.diag(1./np.arange(1, N+1))), (param-center).T))
+ loss = DummyLossWithGradient(cost, param)
+
+ trainer = Trainer(SGD(loss), DummyBatchScheduler())
+ trainer.append_task(stopping_criteria.MaxEpochStopping(max_epoch))
+ #trainer.append_task(tasks.PrintVariable("Loss param : {}", param))
+ #trainer.append_task(tasks.PrintVariable("Loss gradient: {}", loss.gradients[param]))
+
+ # Monitor the gradient of `loss` w.r.t. to `param`.
+ gparam = tasks.MonitorVariable(loss.gradients[param])
+ trainer.append_task(gparam)
+ trainer.train()
+
+ # Since the problem is well-conditionned and we use an optimal gradient step 1/L,
+ # two epochs should be enough for `param` to be around `center` and the gradients near 0.
+ assert_array_almost_equal(param.get_value(), center, decimal=6)
+ assert_array_almost_equal(gparam.value, 0.)
+
+
+def test_adagrad():
+ max_epoch = 15
+
+ # Create an Nd gaussian functions to optimize. These functions are not
+ # well-conditioned and there exists no perfect gradient step to converge in
+ # only one iteration.
+ for N in range(1, 5):
+ center = 5*np.ones((1, N)).astype(floatX)
+ param = sharedX(np.zeros((1, N)))
+ cost = T.sum(0.5*T.dot(T.dot((param-center), np.diag(1./np.arange(1, N+1))), ((param-center).T)))
+ loss = DummyLossWithGradient(cost, param)
+
+ # Even with a really high gradient step, AdaGrad can still converge.
+ # Actually, it is faster than using the optimal gradient step with SGD.
+ optimizer = AdaGrad(loss, lr=100, eps=1e-1)
+ trainer = Trainer(optimizer, DummyBatchScheduler())
+ trainer.append_task(stopping_criteria.MaxEpochStopping(max_epoch))
+ #trainer.append_task(tasks.PrintVariable("Loss param : {}", param))
+ #trainer.append_task(tasks.PrintVariable("Loss gradient: {}", loss.gradients[param]))
+
+ # Monitor the gradient of `loss` w.r.t. to `param`.
+ gparam = tasks.MonitorVariable(loss.gradients[param])
+ trainer.append_task(gparam)
+ trainer.train()
+
+ # After 30 epochs, param should be around the center and gradients near 0.
+ assert_array_almost_equal(param.get_value(), center)
+ assert_array_almost_equal(gparam.value, 0.)
diff --git a/smartlearner/testing.py b/smartlearner/testing.py
index 4036c3a..5edf1ce 100644
--- a/smartlearner/testing.py
+++ b/smartlearner/testing.py
@@ -1,10 +1,10 @@
import numpy as np
-from smartlearner.interfaces.dataset import Dataset
-from smartlearner.interfaces.model import Model
-from smartlearner.interfaces.loss import Loss
-from smartlearner.optimizers.optimizer import Optimizer
-from smartlearner.batch_scheduler import BatchScheduler
+from .interfaces.dataset import Dataset
+from .interfaces.model import Model
+from .interfaces.loss import Loss
+from .interfaces.optimizer import Optimizer
+from .interfaces.batch_scheduler import BatchScheduler
class DummyDataset(Dataset):
@@ -21,8 +21,12 @@ class DummyModel(Model):
def parameters(self):
return self._parameters
- def get_model_output(self, inputs):
- pass
+ @property
+ def updates(self):
+ return {}
+
+ def get_output(self, inputs):
+ return inputs
def save(self, path):
pass
@@ -35,16 +39,22 @@ class DummyLoss(Loss):
def __init__(self):
super(DummyLoss, self).__init__(DummyModel(), DummyDataset())
- def _loss_function(self, model_output):
- pass
+ def _compute_loss(self, model_output):
+ return model_output
+
+ def _get_updates(self):
+ return {}
class DummyOptimizer(Optimizer):
def __init__(self):
super(DummyOptimizer, self).__init__(loss=DummyLoss())
+ def _get_updates(self):
+ return {}
+
def _get_directions(self):
- return {}, {}
+ return {}
class DummyBatchScheduler(BatchScheduler):
@@ -55,5 +65,9 @@ class DummyBatchScheduler(BatchScheduler):
def givens(self):
return {}
+ @property
+ def updates(self):
+ return {}
+
def __iter__(self):
return iter(range(1))
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_added_files",
"has_removed_files",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 3,
"issue_text_score": 2,
"test_score": 2
},
"num_modified_files": 12
} | unknown | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "theano numpy scipy nose pyparsing pip flake8 six pep8 pyflakes",
"pip_packages": [
"nose",
"nose-cov",
"pytest"
],
"pre_install": null,
"python": "3.9",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | cov-core==1.15.0
coverage==7.8.0
exceptiongroup==1.2.2
flake8 @ file:///croot/flake8_1726157165993/work
iniconfig==2.1.0
Mako @ file:///croot/mako_1665472421453/work
MarkupSafe @ file:///croot/markupsafe_1738584038848/work
mccabe @ file:///opt/conda/conda-bld/mccabe_1644221741721/work
nose @ file:///opt/conda/conda-bld/nose_1642704612149/work
nose-cov==1.6
numpy @ file:///opt/conda/conda-bld/numpy_and_numpy_base_1652801679809/work
packaging==24.2
pep8==1.7.1
pluggy==1.5.0
pycodestyle @ file:///croot/pycodestyle_1726150303809/work
pyflakes @ file:///croot/pyflakes_1708962956225/work
pygpu==0.7.6
pyparsing @ file:///croot/pyparsing_1731445506121/work
pytest==8.3.5
scipy @ file:///opt/conda/conda-bld/scipy_1661390393401/work
six @ file:///tmp/build/80754af9/six_1644875935023/work
-e git+https://github.com/SMART-Lab/smartlearner.git@0f11484800712ac92d6027754ab0a026193fa985#egg=smartlearner
Theano==1.0.5
tomli==2.2.1
| name: smartlearner
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- _sysroot_linux-64_curr_repodata_hack=3=haa98f57_10
- binutils_impl_linux-64=2.35.1=h27ae35d_9
- binutils_linux-64=2.35.1=h454624a_30
- blas=1.0=openblas
- ca-certificates=2025.2.25=h06a4308_0
- fftw=3.3.9=h5eee18b_2
- flake8=7.1.1=py39h06a4308_0
- gcc_impl_linux-64=7.5.0=h7105cf2_17
- gcc_linux-64=7.5.0=h8f34230_30
- gxx_impl_linux-64=7.5.0=h0a5bf11_17
- gxx_linux-64=7.5.0=hffc177d_30
- kernel-headers_linux-64=3.10.0=h57e8cba_10
- ld_impl_linux-64=2.35.1=h7274673_9
- libffi=3.4.4=h6a678d5_1
- libgcc-devel_linux-64=7.5.0=hbbeae57_17
- libgcc-ng=11.2.0=h1234567_1
- libgfortran-ng=11.2.0=h00389a5_1
- libgfortran5=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libgpuarray=0.7.6=h7f8727e_1
- libopenblas=0.3.21=h043d6bf_0
- libstdcxx-devel_linux-64=7.5.0=hf0c5c8d_17
- libstdcxx-ng=11.2.0=h1234567_1
- mako=1.2.3=py39h06a4308_0
- markupsafe=3.0.2=py39h5eee18b_0
- mccabe=0.7.0=pyhd3eb1b0_0
- ncurses=6.4=h6a678d5_0
- nose=1.3.7=pyhd3eb1b0_1008
- numpy=1.22.3=py39h7a5d4dd_0
- numpy-base=1.22.3=py39hb8be1f0_0
- openssl=3.0.16=h5eee18b_0
- pep8=1.7.1=py39h06a4308_1
- pip=25.0=py39h06a4308_0
- pycodestyle=2.12.1=py39h06a4308_0
- pyflakes=3.2.0=py39h06a4308_0
- pygpu=0.7.6=py39hce1f21e_1
- pyparsing=3.2.0=py39h06a4308_0
- python=3.9.21=he870216_1
- readline=8.2=h5eee18b_0
- scipy=1.7.3=py39hf838250_2
- setuptools=75.8.0=py39h06a4308_0
- six=1.16.0=pyhd3eb1b0_1
- sqlite=3.45.3=h5eee18b_0
- sysroot_linux-64=2.17=h57e8cba_10
- theano=1.0.5=py39h295c915_1
- tk=8.6.14=h39e8969_0
- tzdata=2025a=h04d1e81_0
- wheel=0.45.1=py39h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- cov-core==1.15.0
- coverage==7.8.0
- exceptiongroup==1.2.2
- iniconfig==2.1.0
- nose-cov==1.6
- packaging==24.2
- pluggy==1.5.0
- pytest==8.3.5
- tomli==2.2.1
prefix: /opt/conda/envs/smartlearner
| [
"smartlearner/optimizers/tests/tests_optimizers.py::test_sgd",
"smartlearner/optimizers/tests/tests_optimizers.py::test_adagrad"
] | [] | [] | [] | BSD 3-Clause "New" or "Revised" License | 211 |
|
SMART-Lab__smartlearner-35 | b0877d3b961deceb273139f064985e39239351a7 | 2015-08-16 16:29:00 | b0877d3b961deceb273139f064985e39239351a7 | diff --git a/smartlearner/batch_scheduler.py b/smartlearner/batch_scheduler.py
index 664cfb5..99f33ec 100644
--- a/smartlearner/batch_scheduler.py
+++ b/smartlearner/batch_scheduler.py
@@ -26,6 +26,11 @@ class MiniBatchScheduler(BatchScheduler):
self.batch_size = batch_size
self.shared_batch_count = theano.shared(np.array(0, dtype='i4'))
+ # Keep only `batch_size` examples as test values.
+ self.dataset.symb_inputs.tag.test_value = self.dataset.inputs.get_value()[:batch_size]
+ if self.dataset.has_targets:
+ self.dataset.symb_targets.tag.test_value = self.dataset.targets.get_value()[:batch_size]
+
@property
def batch_size(self):
return self._shared_batch_size.get_value()
diff --git a/smartlearner/interfaces/dataset.py b/smartlearner/interfaces/dataset.py
index d2d0a4c..c67da77 100644
--- a/smartlearner/interfaces/dataset.py
+++ b/smartlearner/interfaces/dataset.py
@@ -1,13 +1,48 @@
-import theano
+import numpy as np
+
+import theano.tensor as T
+
+from smartlearner.utils import sharedX
class Dataset(object):
+ """ Dataset interface.
+
+ Attributes
+ ----------
+ symb_inputs : `theano.tensor.TensorType` object
+ Symbolic variables representing the inputs.
+ symb_targets : `theano.tensor.TensorType` object or None
+ Symbolic variables representing the targets.
+
+ Notes
+ -----
+ `symb_inputs` and `symb_targets` have test value already tagged to them. Use
+ THEANO_FLAGS="compute_test_value=warn" to use them.
+ """
def __init__(self, inputs, targets=None, name="dataset"):
+ """
+ Parameters
+ ----------
+ inputs : ndarray
+ Training examples
+ targets : ndarray (optional)
+ Target for each training example.
+ name : str (optional)
+ The name of the dataset is used to name Theano variables. Default: 'dataset'.
+ """
self.name = name
self.inputs = inputs
self.targets = targets
- self.symb_inputs = theano.tensor.matrix(name=self.name+'_inputs')
- self.symb_targets = theano.tensor.matrix(name=self.name+'_targets')
+ self.symb_inputs = T.TensorVariable(type=T.TensorType("floatX", [False]*self.inputs.ndim),
+ name=self.name+'_symb_inputs')
+ self.symb_inputs.tag.test_value = self.inputs.get_value() # For debugging Theano graphs.
+
+ self.symb_targets = None
+ if self.has_targets:
+ self.symb_targets = T.TensorVariable(type=T.TensorType("floatX", [False]*self.targets.ndim),
+ name=self.name+'_symb_targets')
+ self.symb_targets.tag.test_value = self.targets.get_value() # For debugging Theano graphs.
@property
def inputs(self):
@@ -15,7 +50,7 @@ class Dataset(object):
@inputs.setter
def inputs(self, value):
- self._inputs_shared = theano.shared(value, name=self.name + "_inputs", borrow=True)
+ self._inputs_shared = sharedX(value, name=self.name+"_inputs")
@property
def targets(self):
@@ -24,20 +59,37 @@ class Dataset(object):
@targets.setter
def targets(self, value):
if value is not None:
- self._targets_shared = theano.shared(value, name=self.name + "_targets", borrow=True)
+ self._targets_shared = sharedX(np.array(value), name=self.name+"_targets")
else:
self._targets_shared = None
+ @property
+ def has_targets(self):
+ return self.targets is not None
+
+ @property
+ def input_shape(self):
+ return self.inputs.get_value().shape[1:]
+
+ @property
+ def target_shape(self):
+ if self.has_targets:
+ return self.targets.get_value().shape[1:]
+
+ return None
+
@property
def input_size(self):
- return self.inputs.get_value().shape[-1]
+ # TODO: is this property really useful? If needed one could just call directly `dataset.input_shape[-1]`.
+ return self.input_shape[-1]
@property
def target_size(self):
- if self.targets is None:
- return 0
- else:
- return self.targets.get_value().shape[-1]
+ # TODO: is this property really useful? If needed one could just call directly `dataset.target_shape[-1]`.
+ if self.has_targets:
+ return self.target_shape[-1]
+
+ return None
def __len__(self):
return len(self.inputs.get_value())
| Move tests at the root of the library.
That way test won't appear in the autocomplete of your preferred python IDE. | SMART-Lab/smartlearner | diff --git a/tests/interfaces/test_dataset.py b/tests/interfaces/test_dataset.py
new file mode 100644
index 0000000..6378b93
--- /dev/null
+++ b/tests/interfaces/test_dataset.py
@@ -0,0 +1,140 @@
+import numpy as np
+import theano
+import theano.tensor as T
+
+from nose.tools import assert_true
+from numpy.testing import assert_equal, assert_array_equal
+
+from smartlearner.interfaces.dataset import Dataset
+
+floatX = theano.config.floatX
+ALL_DTYPES = np.sctypes['int'] + np.sctypes['uint'] + np.sctypes['float']
+
+
+def test_dataset_used_in_theano_function():
+ rng = np.random.RandomState(1234)
+
+ nb_examples = 10
+
+ inputs = (rng.randn(nb_examples, 5) * 100).astype(floatX)
+ targets = (rng.randn(nb_examples, 1) > 0.5).astype(floatX)
+ dataset = Dataset(inputs, targets)
+
+ input_sqr_norm = T.sum(dataset.symb_inputs**2)
+ result = input_sqr_norm - dataset.symb_targets
+ f = theano.function([dataset.symb_inputs, dataset.symb_targets], result)
+
+ assert_array_equal(f(inputs, targets), np.sum(inputs**2)-targets)
+
+
+def test_dataset_without_targets():
+ rng = np.random.RandomState(1234)
+
+ nb_examples = 10
+ nb_features = 3
+ sequences_length = 4
+ nb_channels = 2
+ image_shape = (5, 5)
+
+ # Test creating dataset with different example shapes:
+ # scalar feature, vector features, sequence of vector features, multiple channels images features.
+ for example_shape in [(), (nb_features,), (sequences_length, nb_features), (nb_channels,)+image_shape]:
+ inputs_shape = (nb_examples,) + example_shape
+
+ for dtype in ALL_DTYPES:
+ inputs = (rng.randn(*inputs_shape) * 100).astype(dtype)
+ dataset = Dataset(inputs)
+
+ # Data should be converted into `floatX`.
+ assert_equal(dataset.inputs.dtype, floatX)
+ assert_equal(dataset.symb_inputs.dtype, floatX)
+ assert_equal(dataset.symb_inputs.ndim, inputs.ndim)
+ assert_equal(dataset.input_shape, example_shape)
+ assert_array_equal(dataset.inputs.get_value(), inputs.astype(floatX))
+
+ # Everything related to target should be None
+ assert_true(dataset.targets is None)
+ assert_true(dataset.symb_targets is None)
+ assert_true(dataset.target_shape is None)
+ assert_true(dataset.target_size is None)
+
+ # Create dataset from nested Pyton lists.
+ inputs = [[1, 2, 3]] * nb_examples
+ dataset = Dataset(inputs)
+ # Data should be converted into `floatX`.
+ assert_equal(dataset.inputs.dtype, floatX)
+ assert_equal(dataset.symb_inputs.dtype, floatX)
+ assert_equal(dataset.symb_inputs.ndim, 2)
+ assert_equal(dataset.input_shape, (3,))
+ assert_array_equal(dataset.inputs.get_value(), np.array(inputs, dtype=floatX))
+
+
+def test_dataset_with_targets():
+ rng = np.random.RandomState(1234)
+
+ nb_examples = 10
+ nb_features = 3
+ sequences_length = 4
+ nb_channels = 2
+ image_shape = (5, 5)
+
+ # Test creating dataset with different example shapes and target shapes:
+ # scalar feature, vector features, sequence of vector features, multiple channels images features.
+ for target_shape in [(), (nb_features,), (sequences_length, nb_features), (nb_channels,)+image_shape]:
+ for example_shape in [(), (nb_features,), (sequences_length, nb_features), (nb_channels,)+image_shape]:
+ inputs_shape = (nb_examples,) + example_shape
+ targets_shape = (nb_examples,) + target_shape
+
+ for example_dtype in ALL_DTYPES:
+ for target_dtype in ALL_DTYPES:
+ inputs = (rng.randn(*inputs_shape) * 100).astype(example_dtype)
+ targets = (rng.randn(*targets_shape) * 100).astype(target_dtype)
+ dataset = Dataset(inputs, targets)
+
+ # Data should be converted into `floatX`.
+ assert_equal(dataset.inputs.dtype, floatX)
+ assert_equal(dataset.symb_inputs.dtype, floatX)
+ assert_equal(dataset.symb_inputs.ndim, inputs.ndim)
+ assert_equal(dataset.input_shape, example_shape)
+ assert_array_equal(dataset.inputs.get_value(), inputs.astype(floatX))
+
+ assert_equal(dataset.targets.dtype, floatX)
+ assert_equal(dataset.symb_targets.dtype, floatX)
+ assert_equal(dataset.symb_targets.ndim, targets.ndim)
+ assert_equal(dataset.target_shape, target_shape)
+ assert_array_equal(dataset.targets.get_value(), targets.astype(floatX))
+
+ # Create dataset from nested Pyton lists.
+ inputs = [[1, 2, 3]] * nb_examples
+ targets = [[1, 2, 3]] * nb_examples
+ dataset = Dataset(inputs, targets)
+ # Data should be converted into `floatX`.
+ assert_equal(dataset.inputs.dtype, floatX)
+ assert_equal(dataset.symb_inputs.dtype, floatX)
+ assert_equal(dataset.symb_inputs.ndim, 2)
+ assert_equal(dataset.input_shape, (3,))
+ assert_array_equal(dataset.inputs.get_value(), np.array(inputs, dtype=floatX))
+
+ assert_equal(dataset.targets.dtype, floatX)
+ assert_equal(dataset.symb_targets.dtype, floatX)
+ assert_equal(dataset.symb_targets.ndim, 2)
+ assert_equal(dataset.target_shape, (3,))
+ assert_array_equal(dataset.targets.get_value(), np.array(targets, dtype=floatX))
+
+
+def test_dataset_with_test_value():
+ rng = np.random.RandomState(1234)
+
+ nb_examples = 10
+
+ theano.config.compute_test_value = 'warn'
+ try:
+ inputs = (rng.randn(nb_examples, 5) * 100).astype(floatX)
+ targets = (rng.randn(nb_examples, 1) > 0.5).astype(floatX)
+ dataset = Dataset(inputs, targets)
+
+ input_sqr_norm = T.sum(dataset.symb_inputs**2)
+ result = input_sqr_norm - dataset.symb_targets
+ assert_array_equal(result.tag.test_value, np.sum(inputs**2)-targets)
+ finally:
+ theano.config.compute_test_value = 'off'
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 2,
"issue_text_score": 2,
"test_score": 3
},
"num_modified_files": 2
} | unknown | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "theano numpy scipy nose pyparsing pip flake8 six pep8 pyflakes",
"pip_packages": [
"nose",
"nose-cov",
"pytest"
],
"pre_install": null,
"python": "3.9",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | cov-core==1.15.0
coverage==7.8.0
exceptiongroup==1.2.2
flake8 @ file:///croot/flake8_1726157165993/work
iniconfig==2.1.0
Mako @ file:///croot/mako_1665472421453/work
MarkupSafe @ file:///croot/markupsafe_1738584038848/work
mccabe @ file:///opt/conda/conda-bld/mccabe_1644221741721/work
nose @ file:///opt/conda/conda-bld/nose_1642704612149/work
nose-cov==1.6
numpy @ file:///opt/conda/conda-bld/numpy_and_numpy_base_1652801679809/work
packaging==24.2
pep8==1.7.1
pluggy==1.5.0
pycodestyle @ file:///croot/pycodestyle_1726150303809/work
pyflakes @ file:///croot/pyflakes_1708962956225/work
pygpu==0.7.6
pyparsing @ file:///croot/pyparsing_1731445506121/work
pytest==8.3.5
scipy @ file:///opt/conda/conda-bld/scipy_1661390393401/work
six @ file:///tmp/build/80754af9/six_1644875935023/work
-e git+https://github.com/SMART-Lab/smartlearner.git@b0877d3b961deceb273139f064985e39239351a7#egg=smartlearner
Theano==1.0.5
tomli==2.2.1
| name: smartlearner
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- _sysroot_linux-64_curr_repodata_hack=3=haa98f57_10
- binutils_impl_linux-64=2.35.1=h27ae35d_9
- binutils_linux-64=2.35.1=h454624a_30
- blas=1.0=openblas
- ca-certificates=2025.2.25=h06a4308_0
- fftw=3.3.9=h5eee18b_2
- flake8=7.1.1=py39h06a4308_0
- gcc_impl_linux-64=7.5.0=h7105cf2_17
- gcc_linux-64=7.5.0=h8f34230_30
- gxx_impl_linux-64=7.5.0=h0a5bf11_17
- gxx_linux-64=7.5.0=hffc177d_30
- kernel-headers_linux-64=3.10.0=h57e8cba_10
- ld_impl_linux-64=2.35.1=h7274673_9
- libffi=3.4.4=h6a678d5_1
- libgcc-devel_linux-64=7.5.0=hbbeae57_17
- libgcc-ng=11.2.0=h1234567_1
- libgfortran-ng=11.2.0=h00389a5_1
- libgfortran5=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libgpuarray=0.7.6=h7f8727e_1
- libopenblas=0.3.21=h043d6bf_0
- libstdcxx-devel_linux-64=7.5.0=hf0c5c8d_17
- libstdcxx-ng=11.2.0=h1234567_1
- mako=1.2.3=py39h06a4308_0
- markupsafe=3.0.2=py39h5eee18b_0
- mccabe=0.7.0=pyhd3eb1b0_0
- ncurses=6.4=h6a678d5_0
- nose=1.3.7=pyhd3eb1b0_1008
- numpy=1.22.3=py39h7a5d4dd_0
- numpy-base=1.22.3=py39hb8be1f0_0
- openssl=3.0.16=h5eee18b_0
- pep8=1.7.1=py39h06a4308_1
- pip=25.0=py39h06a4308_0
- pycodestyle=2.12.1=py39h06a4308_0
- pyflakes=3.2.0=py39h06a4308_0
- pygpu=0.7.6=py39hce1f21e_1
- pyparsing=3.2.0=py39h06a4308_0
- python=3.9.21=he870216_1
- readline=8.2=h5eee18b_0
- scipy=1.7.3=py39hf838250_2
- setuptools=75.8.0=py39h06a4308_0
- six=1.16.0=pyhd3eb1b0_1
- sqlite=3.45.3=h5eee18b_0
- sysroot_linux-64=2.17=h57e8cba_10
- theano=1.0.5=py39h295c915_1
- tk=8.6.14=h39e8969_0
- tzdata=2025a=h04d1e81_0
- wheel=0.45.1=py39h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- cov-core==1.15.0
- coverage==7.8.0
- exceptiongroup==1.2.2
- iniconfig==2.1.0
- nose-cov==1.6
- packaging==24.2
- pluggy==1.5.0
- pytest==8.3.5
- tomli==2.2.1
prefix: /opt/conda/envs/smartlearner
| [
"tests/interfaces/test_dataset.py::test_dataset_without_targets",
"tests/interfaces/test_dataset.py::test_dataset_with_targets"
] | [
"tests/interfaces/test_dataset.py::test_dataset_used_in_theano_function",
"tests/interfaces/test_dataset.py::test_dataset_with_test_value"
] | [] | [] | BSD 3-Clause "New" or "Revised" License | 212 |
|
Shopify__shopify_python_api-110 | 657517e9b83e0e99404d994047b3bfea3b73d310 | 2015-08-18 03:32:10 | c29e0ecbed9de67dd923f980a3ac053922dab75e | diff --git a/shopify/resources/image.py b/shopify/resources/image.py
index c5f9fd2..a0e82ef 100644
--- a/shopify/resources/image.py
+++ b/shopify/resources/image.py
@@ -8,6 +8,14 @@ import re
class Image(ShopifyResource):
_prefix_source = "/admin/products/$product_id/"
+ @classmethod
+ def _prefix(cls, options={}):
+ product_id = options.get("product_id")
+ if product_id:
+ return "/admin/products/%s" % (product_id)
+ else:
+ return "/admin"
+
def __getattr__(self, name):
if name in ["pico", "icon", "thumb", "small", "compact", "medium", "large", "grande", "original"]:
return re.sub(r"/(.*)\.(\w{2,4})", r"/\1_%s.\2" % (name), self.src)
@@ -24,3 +32,8 @@ class Image(ShopifyResource):
return []
query_params = { 'metafield[owner_id]': self.id, 'metafield[owner_resource]': 'product_image' }
return Metafield.find(from_ = '/admin/metafields.json?%s' % urllib.parse.urlencode(query_params))
+
+ def save(self):
+ if 'product_id' not in self._prefix_options:
+ self._prefix_options['product_id'] = self.product_id
+ return super(ShopifyResource, self).save()
| Support for independently creating/modifying product images.
Please correct me if I'm wrong, but at the moment the only way to create/update product images through the Python API is directly through a POST/PUT call to the product endpoint.
As per the [Shopify API documentation on product images](http://docs.shopify.com/api/product_image), we should be able to make POST and PUT calls directly to `/admin/products/#{id}/images.json` and `PUT /admin/products/#{id}/images/#{id}.json`. However, this doesn't seem to work currently with the API as the prefix for the `Image` class isn't properly being built. Thus, something like this...
```python
image = shopify.Image()
image.src = "http://example.com/example.png"
image.product_id = 123456789
image.save()
```
... tries to POST to `/admin/products//images.json` which returns a 406.
Looking at the source, I think a fix would be to implement the `prefix()` class method, similar to what's been done with the `Variant` class. Just wanted to run this by folks who might be more familiar with this to see if that might be a valid solution. | Shopify/shopify_python_api | diff --git a/test/image_test.py b/test/image_test.py
index 935f53b..1234898 100644
--- a/test/image_test.py
+++ b/test/image_test.py
@@ -13,6 +13,17 @@ class ImageTest(TestCase):
self.assertEqual('http://cdn.shopify.com/s/files/1/0006/9093/3842/products/ipod-nano.png?v=1389388540', image.src)
self.assertEqual(850703190, image.id)
+ def test_create_image_then_add_parent_id(self):
+ self.fake("products/632910392/images", method='POST', body=self.load_fixture('image'), headers={'Content-type': 'application/json'})
+ image = shopify.Image()
+ image.position = 1
+ image.product_id = 632910392
+ image.attachment = "R0lGODlhbgCMAPf/APbr48VySrxTO7IgKt2qmKQdJeK8lsFjROG5p/nz7Zg3MNmnd7Q1MLNVS9GId71hSJMZIuzTu4UtKbeEeakhKMl8U8WYjfr18YQaIbAf=="
+ image.save()
+
+ self.assertEqual('http://cdn.shopify.com/s/files/1/0006/9093/3842/products/ipod-nano.png?v=1389388540', image.src)
+ self.assertEqual(850703190, image.id)
+
def test_get_images(self):
self.fake("products/632910392/images", method='GET', body=self.load_fixture('images'))
image = shopify.Image.find(product_id=632910392)
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_hyperlinks",
"has_media"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 0,
"issue_text_score": 1,
"test_score": 0
},
"num_modified_files": 1
} | 2.1 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[dev]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest",
"pytest-cov"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.9",
"reqs_path": [
"requirements/base.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | coverage==7.8.0
exceptiongroup==1.2.2
iniconfig==2.1.0
packaging==24.2
pluggy==1.5.0
pyactiveresource==2.2.2
pytest==8.3.5
pytest-cov==6.0.0
PyYAML==6.0.2
-e git+https://github.com/Shopify/shopify_python_api.git@657517e9b83e0e99404d994047b3bfea3b73d310#egg=ShopifyAPI
six==1.17.0
tomli==2.2.1
| name: shopify_python_api
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=3.0.16=h5eee18b_0
- pip=25.0=py39h06a4308_0
- python=3.9.21=he870216_1
- readline=8.2=h5eee18b_0
- setuptools=75.8.0=py39h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- tzdata=2025a=h04d1e81_0
- wheel=0.45.1=py39h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- coverage==7.8.0
- exceptiongroup==1.2.2
- iniconfig==2.1.0
- packaging==24.2
- pluggy==1.5.0
- pyactiveresource==2.2.2
- pytest==8.3.5
- pytest-cov==6.0.0
- pyyaml==6.0.2
- six==1.17.0
- tomli==2.2.1
prefix: /opt/conda/envs/shopify_python_api
| [
"test/image_test.py::ImageTest::test_create_image_then_add_parent_id"
] | [] | [
"test/image_test.py::ImageTest::test_create_image",
"test/image_test.py::ImageTest::test_get_image",
"test/image_test.py::ImageTest::test_get_images",
"test/image_test.py::ImageTest::test_get_metafields_for_image"
] | [] | MIT License | 213 |
|
marshmallow-code__marshmallow-262 | b8ad05b5342914e857c442d75e8abe9ea8f867fb | 2015-08-19 17:33:46 | b8ad05b5342914e857c442d75e8abe9ea8f867fb | diff --git a/AUTHORS.rst b/AUTHORS.rst
index b9a42126..26fc232f 100644
--- a/AUTHORS.rst
+++ b/AUTHORS.rst
@@ -40,3 +40,4 @@ Contributors (chronological)
- Kelvin Hammond `@kelvinhammond <https://github.com/kelvinhammond>`_
- Matt Stobo `@mwstobo <https://github.com/mwstobo>`_
- Max Orhai `@max-orhai <https://github.com/max-orhai>`_
+- Praveen `@praveen-p <https://github.com/praveen-p>`_
diff --git a/CHANGELOG.rst b/CHANGELOG.rst
index 5090a42a..f1c43987 100644
--- a/CHANGELOG.rst
+++ b/CHANGELOG.rst
@@ -1,10 +1,7 @@
Changelog
---------
-2.0.0x (unreleased)
-+++++++++++++++++++
-
-2.0.0b5 (2015-08-23)
+2.0.0b5 (unreleased)
++++++++++++++++++++
Features:
@@ -17,11 +14,9 @@ Features:
Bug fixes:
- `make_object` is only called after all validators and postprocessors have finished (:issue:`253`). Thanks :user:`sunsongxp` for reporting.
-- If an invalid type is passed to ``Schema`` and ``strict=False``, store a ``_schema`` error in the errors dict rather than raise an exception (:issue:`261`). Thanks :user:`density` for reporting.
Other changes:
-- ``make_object`` is only called when input data are completely valid (:issue:`243`). Thanks :user:`kissgyorgy` for reporting.
- Change default error messages for ``URL`` and ``Email`` validators so that they don't include user input (:issue:`255`).
- ``Email`` validator permits email addresses with non-ASCII characters, as per RFC 6530 (:issue:`221`). Thanks :user:`lextoumbourou` for reporting and :user:`mwstobo` for sending the patch.
diff --git a/MANIFEST.in b/MANIFEST.in
index f6857893..b7f36481 100644
--- a/MANIFEST.in
+++ b/MANIFEST.in
@@ -1,11 +1,1 @@
-include *.rst LICENSE NOTICE
-recursive-include tests *
-recursive-include examples *
-recursive-include docs *
-recursive-exclude docs *.pyc
-recursive-exclude docs *.pyo
-recursive-exclude tests *.pyc
-recursive-exclude tests *.pyo
-recursive-exclude examples *.pyc
-recursive-exclude examples *.pyo
-prune docs/_build
+include *.rst LICENSE
\ No newline at end of file
diff --git a/docs/extending.rst b/docs/extending.rst
index 606c246c..fdae3460 100644
--- a/docs/extending.rst
+++ b/docs/extending.rst
@@ -184,7 +184,6 @@ Schema-level Validation
You can register schema-level validation functions for a :class:`Schema` using the :meth:`marshmallow.validates_schema <marshmallow.decorators.validates_schema>` decorator. Schema-level validation errors will be stored on the ``_schema`` key of the errors dictonary.
.. code-block:: python
- :emphasize-lines: 7
from marshmallow import Schema, fields, validates_schema, ValidationError
@@ -269,15 +268,16 @@ However, if you want to specify how values are accessed from an object, you can
return obj.get(key, default)
-Error Handlers and Accessors as Class Members
----------------------------------------------
+Handler Functions as Class Members
+----------------------------------
-You can register a Schema's error handler and accessor as optional class members. This might be useful for defining an abstract `Schema` class.
+You can register a Schema's error handler, validators, and accessor as optional class members. This might be useful for defining an abstract `Schema` class.
.. code-block:: python
class BaseSchema(Schema):
__error_handler__ = handle_errors # A function
+ __validators__ = [validate_schema] # List of functions
__accessor__ = get_from_dict # A function
@@ -362,15 +362,3 @@ Our application schemas can now inherit from our custom schema class.
result = ser.dump(user)
result.data # {"user": {"name": "Keith", "email": "[email protected]"}}
-Using Context
--------------
-
-The ``context`` attribute of a `Schema` is a general-purpose store for extra information that may be needed for (de)serialization. It may be used in both ``Schema`` and ``Field`` methods.
-
-.. code-block:: python
-
- schema = UserSchema()
- # Make current HTTP request available to
- # custom fields, schema methods, schema validators, etc.
- schema.context['request'] = request
- schema.dump(user)
diff --git a/marshmallow/__init__.py b/marshmallow/__init__.py
index fc41de39..b8581d21 100644
--- a/marshmallow/__init__.py
+++ b/marshmallow/__init__.py
@@ -13,7 +13,7 @@ from marshmallow.decorators import (
from marshmallow.utils import pprint, missing
from marshmallow.exceptions import MarshallingError, UnmarshallingError, ValidationError
-__version__ = '2.0.0.dev'
+__version__ = '2.0.0b5-dev'
__author__ = 'Steven Loria'
__license__ = 'MIT'
diff --git a/marshmallow/fields.py b/marshmallow/fields.py
index 0990f115..b45afb9b 100755
--- a/marshmallow/fields.py
+++ b/marshmallow/fields.py
@@ -810,6 +810,11 @@ class DateTime(Field):
return func(value)
except (TypeError, AttributeError, ValueError):
raise err
+ elif self.dateformat:
+ try:
+ return dt.datetime.strptime(value, self.dateformat)
+ except (TypeError, AttributeError, ValueError):
+ raise err
elif utils.dateutil_available:
try:
return utils.from_datestring(value)
diff --git a/marshmallow/marshalling.py b/marshmallow/marshalling.py
index 8bbb42dd..630c51f5 100644
--- a/marshmallow/marshalling.py
+++ b/marshmallow/marshalling.py
@@ -248,20 +248,13 @@ class Unmarshaller(ErrorStore):
key = fields_dict[attr_name].attribute or attr_name
try:
raw_value = data.get(attr_name, missing)
- except AttributeError: # Input data is not a dict
+ except AttributeError:
msg = 'Data must be a dict, got a {0}'.format(data.__class__.__name__)
- errors = self.get_errors(index=index)
- if strict:
- raise ValidationError(
- msg,
- field_names=[SCHEMA],
- fields=[]
- )
- else:
- errors = self.get_errors()
- errors.setdefault(SCHEMA, []).append(msg)
- # Input data type is incorrect, so we can bail out early
- break
+ raise ValidationError(
+ msg,
+ field_names=[attr_name],
+ fields=[field_obj]
+ )
field_name = attr_name
if raw_value is missing and field_obj.load_from:
field_name = field_obj.load_from
diff --git a/marshmallow/schema.py b/marshmallow/schema.py
index 950fce69..8b1e8f92 100644
--- a/marshmallow/schema.py
+++ b/marshmallow/schema.py
@@ -257,6 +257,8 @@ class BaseSchema(base.SchemaABC):
instead of failing silently and storing the errors.
:param bool many: Should be set to `True` if ``obj`` is a collection
so that the object will be serialized to a list.
+ :param bool skip_missing: If `True`, don't include key:value pairs in
+ serialized results if ``value`` is `None`.
:param dict context: Optional context passed to :class:`fields.Method` and
:class:`fields.Function` fields.
:param tuple load_only: A list or tuple of fields to skip during serialization
@@ -596,15 +598,9 @@ class BaseSchema(base.SchemaABC):
"""Override-able method that defines how to create the final deserialization
output. Defaults to noop (i.e. just return ``data`` as is).
- .. note::
-
- This method will only be invoked if when the input data are completely valid.
-
:param dict data: The deserialized data.
.. versionadded:: 1.0.0
- .. versionchanged:: 2.0.0
- Only invoked when data are valid.
"""
return data
@@ -656,7 +652,7 @@ class BaseSchema(base.SchemaABC):
result = self._invoke_load_processors(POST_LOAD, result, many)
- if not errors and postprocess:
+ if postprocess:
if many:
result = [self.make_object(each) for each in result]
else:
diff --git a/marshmallow/validate.py b/marshmallow/validate.py
index 4f8f7a26..680c9019 100644
--- a/marshmallow/validate.py
+++ b/marshmallow/validate.py
@@ -97,7 +97,7 @@ class Email(Validator):
"""
USER_REGEX = re.compile(
- r"(^[-!#$%&'*+/=?^`{}|~\w]+(\.[-!#$%&'*+/=?^`{}|~\w]+)*$" # dot-atom
+ r"(^[-!#$%&'*+/=?^_`{}|~0-9\w]+(\.[-!#$%&'*+/=?^_`{}|~0-9\w]+)*$" # dot-atom
# quoted-string
r'|^"([\001-\010\013\014\016-\037!#-\[\]-\177]'
r'|\\[\001-\011\013\014\016-\177])*"$)', re.IGNORECASE | re.UNICODE)
diff --git a/tasks.py b/tasks.py
index b1b20780..04eab04a 100644
--- a/tasks.py
+++ b/tasks.py
@@ -12,7 +12,7 @@ build_dir = os.path.join(docs_dir, '_build')
def test():
"""Run the tests."""
flake()
- run('python setup.py test', echo=True)
+ run('python setup.py test', echo=True, pty=True)
@task
def flake():
@@ -48,7 +48,7 @@ def docs(clean=False, browse=False, watch=False):
"""Build the docs."""
if clean:
clean_docs()
- run("sphinx-build %s %s" % (docs_dir, build_dir), echo=True)
+ run("sphinx-build %s %s" % (docs_dir, build_dir), pty=True)
if browse:
browse_docs()
if watch:
@@ -69,7 +69,7 @@ def watch_docs():
@task
def readme(browse=False):
- run("rst2html.py README.rst > README.html")
+ run("rst2html.py README.rst > README.html", pty=True)
if browse:
webbrowser.open_new_tab('README.html')
| DateTime ignores date formatting string
The documentation for the `marshmallow.fields.DateTime` says:
Parameters:
* format (str) – Either "rfc" (for RFC822), "iso" (for ISO8601), or a date format string. If None, defaults to “iso”.
But the part `or a date format string` is not true. I would've expected this to accept date formatting strings as defined in the [`time` module](https://docs.python.org/2/library/time.html#time.strftime), however, if the `format` parameter is a date formatting string, it is ignored and the parsing is done using `dateutil` (I noticed this [here in the source code](https://github.com/marshmallow-code/marshmallow/blob/dev/marshmallow/fields.py#L771).
It looks like the documentation is not consistent with the code here. I think it would be very valuable if you could indeed provide a date formatting string and that marshmallow will use it with (`time.strptime`](https://docs.python.org/2/library/time.html#time.strptime) to parse it instead of letting `dateutil` do a guess about the format.
I am willing to edit this in the source code, but I would like to discuss the desired behaviour first.
Cheers | marshmallow-code/marshmallow | diff --git a/tests/test_deserialization.py b/tests/test_deserialization.py
index 356f759d..d7c66630 100644
--- a/tests/test_deserialization.py
+++ b/tests/test_deserialization.py
@@ -288,6 +288,26 @@ class TestFieldDeserialization:
msg = 'Could not deserialize {0!r} to a datetime object.'.format(in_value)
assert msg in str(excinfo)
+ def test_custom_date_format_datetime_field_deserialization(self):
+
+ dtime = dt.datetime.now()
+ datestring = dtime.strftime('%H:%M:%S %Y-%m-%d')
+
+ field = fields.DateTime(format='%d-%m-%Y %H:%M:%S')
+ #deserialization should fail when datestring is not of same format
+ with pytest.raises(ValidationError) as excinfo:
+ field.deserialize(datestring)
+ msg = 'Could not deserialize {0!r} to a datetime object.'.format(datestring)
+ assert msg in str(excinfo)
+ field = fields.DateTime(format='%H:%M:%S %Y-%m-%d')
+ assert_datetime_equal(field.deserialize(datestring), dtime)
+
+ field = fields.DateTime()
+ if utils.dateutil_available:
+ assert_datetime_equal(field.deserialize(datestring), dtime)
+ else:
+ assert msg in str(excinfo)
+
@pytest.mark.parametrize('fmt', ['rfc', 'rfc822'])
def test_rfc_datetime_field_deserialization(self, fmt):
dtime = dt.datetime.now()
@@ -741,16 +761,6 @@ class TestSchemaDeserialization:
assert result.name == 'Monty'
assert_almost_equal(result.age, 42.3)
- # https://github.com/marshmallow-code/marshmallow/issues/243
- def test_make_object_not_called_if_data_are_invalid(self):
- class MySchema(Schema):
- email = fields.Email()
-
- def make_object(self, data):
- assert False, 'make_object should not have been called'
- result, errors = MySchema().load({'email': 'invalid'})
- assert 'email' in errors
-
# Regression test for https://github.com/marshmallow-code/marshmallow/issues/253
def test_validators_run_before_make_object(self):
class UserSchema(Schema):
@@ -1168,24 +1178,3 @@ def test_required_message_can_be_changed(message):
expected = [message] if isinstance(message, basestring) else message
assert expected == errs['age']
assert data == {}
-
-# Regression test for https://github.com/marshmallow-code/marshmallow/issues/261
-def test_deserialize_doesnt_raise_exception_if_strict_is_false_and_input_type_is_incorrect():
- class MySchema(Schema):
- foo = fields.Field()
- bar = fields.Field()
- data, errs = MySchema().load([])
- assert '_schema' in errs
- assert errs['_schema'] == ['Data must be a dict, got a list']
-
-
-def test_deserialize_raises_exception_if_strict_is_true_and_input_type_is_incorrect():
- class MySchema(Schema):
- foo = fields.Field()
- bar = fields.Field()
- with pytest.raises(ValidationError) as excinfo:
- MySchema(strict=True).load([])
- assert 'Data must be a dict, got a list' in str(excinfo)
- exc = excinfo.value
- assert exc.field_names == ['_schema']
- assert exc.fields == []
diff --git a/tests/test_schema.py b/tests/test_schema.py
index 0fda3b71..bfbf5dad 100644
--- a/tests/test_schema.py
+++ b/tests/test_schema.py
@@ -1706,7 +1706,7 @@ class TestNestedSchema:
schema = OuterSchema()
_, errors = schema.load({'inner': 1})
- assert errors['inner']['_schema'] == ['Data must be a dict, got a int']
+ assert errors['inner'] == ['Data must be a dict, got a int']
def test_missing_required_nested_field(self):
class Inner(Schema):
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_hyperlinks",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 1,
"issue_text_score": 0,
"test_score": 2
},
"num_modified_files": 10
} | 2.0 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[dev]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest"
],
"pre_install": null,
"python": "3.9",
"reqs_path": [
"dev-requirements.txt",
"docs/requirements.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | alabaster @ git+https://github.com/sloria/alabaster.git@667b1b676c6bf7226db057f098ec826d84d3ae40
babel==2.17.0
cachetools==5.5.2
certifi==2025.1.31
chardet==5.2.0
charset-normalizer==3.4.1
colorama==0.4.6
distlib==0.3.9
docutils==0.20.1
exceptiongroup==1.2.2
filelock==3.18.0
flake8==2.4.0
idna==3.10
imagesize==1.4.1
importlib_metadata==8.6.1
iniconfig==2.1.0
invoke==2.2.0
Jinja2==3.1.6
MarkupSafe==3.0.2
-e git+https://github.com/marshmallow-code/marshmallow.git@b8ad05b5342914e857c442d75e8abe9ea8f867fb#egg=marshmallow
mccabe==0.3.1
packaging==24.2
pep8==1.5.7
platformdirs==4.3.7
pluggy==1.5.0
pyflakes==0.8.1
Pygments==2.19.1
pyproject-api==1.9.0
pytest==8.3.5
python-dateutil==2.9.0.post0
pytz==2025.2
requests==2.32.3
six==1.17.0
snowballstemmer==2.2.0
Sphinx==7.2.6
sphinx-issues==0.2.0
sphinxcontrib-applehelp==2.0.0
sphinxcontrib-devhelp==2.0.0
sphinxcontrib-htmlhelp==2.1.0
sphinxcontrib-jsmath==1.0.1
sphinxcontrib-qthelp==2.0.0
sphinxcontrib-serializinghtml==2.0.0
tomli==2.2.1
tox==4.25.0
typing_extensions==4.13.0
urllib3==2.3.0
virtualenv==20.29.3
zipp==3.21.0
| name: marshmallow
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=3.0.16=h5eee18b_0
- pip=25.0=py39h06a4308_0
- python=3.9.21=he870216_1
- readline=8.2=h5eee18b_0
- setuptools=75.8.0=py39h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- tzdata=2025a=h04d1e81_0
- wheel=0.45.1=py39h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- alabaster==0.7.11+sloria0
- babel==2.17.0
- cachetools==5.5.2
- certifi==2025.1.31
- chardet==5.2.0
- charset-normalizer==3.4.1
- colorama==0.4.6
- distlib==0.3.9
- docutils==0.20.1
- exceptiongroup==1.2.2
- filelock==3.18.0
- flake8==2.4.0
- idna==3.10
- imagesize==1.4.1
- importlib-metadata==8.6.1
- iniconfig==2.1.0
- invoke==2.2.0
- jinja2==3.1.6
- markupsafe==3.0.2
- mccabe==0.3.1
- packaging==24.2
- pep8==1.5.7
- platformdirs==4.3.7
- pluggy==1.5.0
- pyflakes==0.8.1
- pygments==2.19.1
- pyproject-api==1.9.0
- pytest==8.3.5
- python-dateutil==2.9.0.post0
- pytz==2025.2
- requests==2.32.3
- six==1.17.0
- snowballstemmer==2.2.0
- sphinx==7.2.6
- sphinx-issues==0.2.0
- sphinxcontrib-applehelp==2.0.0
- sphinxcontrib-devhelp==2.0.0
- sphinxcontrib-htmlhelp==2.1.0
- sphinxcontrib-jsmath==1.0.1
- sphinxcontrib-qthelp==2.0.0
- sphinxcontrib-serializinghtml==2.0.0
- tomli==2.2.1
- tox==4.25.0
- typing-extensions==4.13.0
- urllib3==2.3.0
- virtualenv==20.29.3
- zipp==3.21.0
prefix: /opt/conda/envs/marshmallow
| [
"tests/test_deserialization.py::TestFieldDeserialization::test_custom_date_format_datetime_field_deserialization",
"tests/test_schema.py::TestNestedSchema::test_invalid_type_passed_to_nested_field"
] | [] | [
"tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[String]",
"tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Integer]",
"tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Boolean]",
"tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Float]",
"tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Number]",
"tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[DateTime]",
"tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[LocalDateTime]",
"tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Time]",
"tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Date]",
"tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[TimeDelta]",
"tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Fixed]",
"tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Url]",
"tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Email]",
"tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[FormattedString]",
"tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[UUID]",
"tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Select]",
"tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Decimal]",
"tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[String]",
"tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Integer]",
"tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Boolean]",
"tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Float]",
"tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Number]",
"tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[DateTime]",
"tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[LocalDateTime]",
"tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Time]",
"tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Date]",
"tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[TimeDelta]",
"tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Fixed]",
"tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Url]",
"tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Email]",
"tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[FormattedString]",
"tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[UUID]",
"tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Select]",
"tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Decimal]",
"tests/test_deserialization.py::TestDeserializingNone::test_list_field_deserialize_none_to_empty_list",
"tests/test_deserialization.py::TestFieldDeserialization::test_float_field_deserialization",
"tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[bad]",
"tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[]",
"tests/test_deserialization.py::TestFieldDeserialization::test_integer_field_deserialization",
"tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_deserialization",
"tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_with_places",
"tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_with_places_and_rounding",
"tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_deserialization_string",
"tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_special_values",
"tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_special_values_not_permitted",
"tests/test_deserialization.py::TestFieldDeserialization::test_string_field_deserialization",
"tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization",
"tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values",
"tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values_invalid[notvalid]",
"tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values_invalid[123]",
"tests/test_deserialization.py::TestFieldDeserialization::test_arbitrary_field_deserialization",
"tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[not-a-datetime]",
"tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[42]",
"tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[]",
"tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[in_value3]",
"tests/test_deserialization.py::TestFieldDeserialization::test_rfc_datetime_field_deserialization[rfc]",
"tests/test_deserialization.py::TestFieldDeserialization::test_rfc_datetime_field_deserialization[rfc822]",
"tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[iso]",
"tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[iso8601]",
"tests/test_deserialization.py::TestFieldDeserialization::test_localdatetime_field_deserialization",
"tests/test_deserialization.py::TestFieldDeserialization::test_time_field_deserialization",
"tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[badvalue]",
"tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[]",
"tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[in_data2]",
"tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[42]",
"tests/test_deserialization.py::TestFieldDeserialization::test_fixed_field_deserialization",
"tests/test_deserialization.py::TestFieldDeserialization::test_fixed_field_deserialize_invalid_value",
"tests/test_deserialization.py::TestFieldDeserialization::test_timedelta_field_deserialization",
"tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[]",
"tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[badvalue]",
"tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[in_value2]",
"tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[9999999999]",
"tests/test_deserialization.py::TestFieldDeserialization::test_date_field_deserialization",
"tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[]",
"tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[123]",
"tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[in_value2]",
"tests/test_deserialization.py::TestFieldDeserialization::test_price_field_deserialization",
"tests/test_deserialization.py::TestFieldDeserialization::test_url_field_deserialization",
"tests/test_deserialization.py::TestFieldDeserialization::test_relative_url_field_deserialization",
"tests/test_deserialization.py::TestFieldDeserialization::test_email_field_deserialization",
"tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_is_noop_by_default",
"tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_with_callable",
"tests/test_deserialization.py::TestFieldDeserialization::test_uuid_field_deserialization",
"tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[malformed]",
"tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[123]",
"tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[in_value2]",
"tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_function_must_be_callable",
"tests/test_deserialization.py::TestFieldDeserialization::test_method_field_deserialization_is_noop_by_default",
"tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_method",
"tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_method_must_be_a_method",
"tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_deserialization",
"tests/test_deserialization.py::TestFieldDeserialization::test_query_select_field_func_key_deserialization",
"tests/test_deserialization.py::TestFieldDeserialization::test_query_select_field_string_key_deserialization",
"tests/test_deserialization.py::TestFieldDeserialization::test_query_select_list_field_func_key_deserialization",
"tests/test_deserialization.py::TestFieldDeserialization::test_query_select_list_field_string_key_deserialization",
"tests/test_deserialization.py::TestFieldDeserialization::test_fixed_list_field_deserialization",
"tests/test_deserialization.py::TestFieldDeserialization::test_datetime_list_field_deserialization",
"tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_single_value",
"tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_invalid_value",
"tests/test_deserialization.py::TestFieldDeserialization::test_constant_field_deserialization",
"tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_function",
"tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_class_that_returns_bool",
"tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_that_raises_error_with_list",
"tests/test_deserialization.py::TestFieldDeserialization::test_validator_must_return_false_to_raise_error",
"tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_validator_with_nonascii_input",
"tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validators",
"tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_custom_error_message",
"tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_to_dict",
"tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_values",
"tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_many",
"tests/test_deserialization.py::TestSchemaDeserialization::test_make_object",
"tests/test_deserialization.py::TestSchemaDeserialization::test_validators_run_before_make_object",
"tests/test_deserialization.py::TestSchemaDeserialization::test_make_object_many",
"tests/test_deserialization.py::TestSchemaDeserialization::test_exclude",
"tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_deserialization_to_dict",
"tests/test_deserialization.py::TestSchemaDeserialization::test_nested_list_deserialization_to_dict",
"tests/test_deserialization.py::TestSchemaDeserialization::test_none_deserialization",
"tests/test_deserialization.py::TestSchemaDeserialization::test_nested_none_deserialization",
"tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param",
"tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_error_returns_field_name_not_attribute_name",
"tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_error_returns_load_from_not_attribute_name",
"tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_load_from_param",
"tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_dump_only_param",
"tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_value",
"tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_callable",
"tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_none",
"tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_returns_errors",
"tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_returns_errors_with_multiple_validators",
"tests/test_deserialization.py::TestSchemaDeserialization::test_strict_mode_deserialization",
"tests/test_deserialization.py::TestSchemaDeserialization::test_strict_mode_many",
"tests/test_deserialization.py::TestSchemaDeserialization::test_strict_mode_deserialization_with_multiple_validators",
"tests/test_deserialization.py::TestSchemaDeserialization::test_uncaught_validation_errors_are_stored",
"tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_a_field",
"tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_an_email_field",
"tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_a_url_field",
"tests/test_deserialization.py::TestSchemaDeserialization::test_required_value_only_passed_to_validators_if_provided",
"tests/test_deserialization.py::TestValidation::test_integer_with_validator",
"tests/test_deserialization.py::TestValidation::test_integer_with_validators[field0]",
"tests/test_deserialization.py::TestValidation::test_integer_with_validators[field1]",
"tests/test_deserialization.py::TestValidation::test_integer_with_validators[field2]",
"tests/test_deserialization.py::TestValidation::test_float_with_validators[field0]",
"tests/test_deserialization.py::TestValidation::test_float_with_validators[field1]",
"tests/test_deserialization.py::TestValidation::test_float_with_validators[field2]",
"tests/test_deserialization.py::TestValidation::test_string_validator",
"tests/test_deserialization.py::TestValidation::test_function_validator",
"tests/test_deserialization.py::TestValidation::test_function_validators[field0]",
"tests/test_deserialization.py::TestValidation::test_function_validators[field1]",
"tests/test_deserialization.py::TestValidation::test_function_validators[field2]",
"tests/test_deserialization.py::TestValidation::test_method_validator",
"tests/test_deserialization.py::test_required_field_failure[String]",
"tests/test_deserialization.py::test_required_field_failure[Integer]",
"tests/test_deserialization.py::test_required_field_failure[Boolean]",
"tests/test_deserialization.py::test_required_field_failure[Float]",
"tests/test_deserialization.py::test_required_field_failure[Number]",
"tests/test_deserialization.py::test_required_field_failure[DateTime]",
"tests/test_deserialization.py::test_required_field_failure[LocalDateTime]",
"tests/test_deserialization.py::test_required_field_failure[Time]",
"tests/test_deserialization.py::test_required_field_failure[Date]",
"tests/test_deserialization.py::test_required_field_failure[TimeDelta]",
"tests/test_deserialization.py::test_required_field_failure[Fixed]",
"tests/test_deserialization.py::test_required_field_failure[Url]",
"tests/test_deserialization.py::test_required_field_failure[Email]",
"tests/test_deserialization.py::test_required_field_failure[UUID]",
"tests/test_deserialization.py::test_required_field_failure[Decimal]",
"tests/test_deserialization.py::test_required_enum",
"tests/test_deserialization.py::test_required_message_can_be_changed[My",
"tests/test_deserialization.py::test_required_message_can_be_changed[message1]",
"tests/test_deserialization.py::test_required_message_can_be_changed[message2]",
"tests/test_schema.py::test_serializing_basic_object[UserSchema]",
"tests/test_schema.py::test_serializing_basic_object[UserMetaSchema]",
"tests/test_schema.py::test_serializer_dump",
"tests/test_schema.py::test_dump_returns_dict_of_errors",
"tests/test_schema.py::test_dump_with_strict_mode_raises_error[UserSchema]",
"tests/test_schema.py::test_dump_with_strict_mode_raises_error[UserMetaSchema]",
"tests/test_schema.py::test_dump_resets_errors",
"tests/test_schema.py::test_load_resets_errors",
"tests/test_schema.py::test_dump_resets_error_fields",
"tests/test_schema.py::test_load_resets_error_fields",
"tests/test_schema.py::test_errored_fields_do_not_appear_in_output",
"tests/test_schema.py::test_load_many_stores_error_indices",
"tests/test_schema.py::test_dump_many",
"tests/test_schema.py::test_multiple_errors_can_be_stored_for_a_given_index",
"tests/test_schema.py::test_dump_many_stores_error_indices",
"tests/test_schema.py::test_dump_many_doesnt_stores_error_indices_when_index_errors_is_false",
"tests/test_schema.py::test_dump_returns_a_marshalresult",
"tests/test_schema.py::test_dumps_returns_a_marshalresult",
"tests/test_schema.py::test_dumping_single_object_with_collection_schema",
"tests/test_schema.py::test_loading_single_object_with_collection_schema",
"tests/test_schema.py::test_dumps_many",
"tests/test_schema.py::test_load_returns_an_unmarshalresult",
"tests/test_schema.py::test_load_many",
"tests/test_schema.py::test_loads_returns_an_unmarshalresult",
"tests/test_schema.py::test_loads_many",
"tests/test_schema.py::test_loads_deserializes_from_json",
"tests/test_schema.py::test_serializing_none",
"tests/test_schema.py::test_default_many_symmetry",
"tests/test_schema.py::TestValidate::test_validate_returns_errors_dict",
"tests/test_schema.py::TestValidate::test_validate_many",
"tests/test_schema.py::TestValidate::test_validate_many_doesnt_store_index_if_index_errors_option_is_false",
"tests/test_schema.py::TestValidate::test_validate_strict",
"tests/test_schema.py::TestValidate::test_validate_required",
"tests/test_schema.py::test_fields_are_not_copies[UserSchema]",
"tests/test_schema.py::test_fields_are_not_copies[UserMetaSchema]",
"tests/test_schema.py::test_dumps_returns_json",
"tests/test_schema.py::test_naive_datetime_field",
"tests/test_schema.py::test_datetime_formatted_field",
"tests/test_schema.py::test_datetime_iso_field",
"tests/test_schema.py::test_tz_datetime_field",
"tests/test_schema.py::test_local_datetime_field",
"tests/test_schema.py::test_class_variable",
"tests/test_schema.py::test_serialize_many[UserSchema]",
"tests/test_schema.py::test_serialize_many[UserMetaSchema]",
"tests/test_schema.py::test_inheriting_schema",
"tests/test_schema.py::test_custom_field",
"tests/test_schema.py::test_url_field",
"tests/test_schema.py::test_relative_url_field",
"tests/test_schema.py::test_stores_invalid_url_error[UserSchema]",
"tests/test_schema.py::test_stores_invalid_url_error[UserMetaSchema]",
"tests/test_schema.py::test_email_field[UserSchema]",
"tests/test_schema.py::test_email_field[UserMetaSchema]",
"tests/test_schema.py::test_stored_invalid_email",
"tests/test_schema.py::test_integer_field",
"tests/test_schema.py::test_fixed_field",
"tests/test_schema.py::test_as_string",
"tests/test_schema.py::test_decimal_field",
"tests/test_schema.py::test_price_field",
"tests/test_schema.py::test_extra",
"tests/test_schema.py::test_extra_many",
"tests/test_schema.py::test_method_field[UserSchema]",
"tests/test_schema.py::test_method_field[UserMetaSchema]",
"tests/test_schema.py::test_function_field",
"tests/test_schema.py::test_prefix[UserSchema]",
"tests/test_schema.py::test_prefix[UserMetaSchema]",
"tests/test_schema.py::test_fields_must_be_declared_as_instances",
"tests/test_schema.py::test_serializing_generator[UserSchema]",
"tests/test_schema.py::test_serializing_generator[UserMetaSchema]",
"tests/test_schema.py::test_serializing_empty_list_returns_empty_list",
"tests/test_schema.py::test_serializing_dict",
"tests/test_schema.py::test_serializing_dict_with_meta_fields",
"tests/test_schema.py::test_exclude_in_init[UserSchema]",
"tests/test_schema.py::test_exclude_in_init[UserMetaSchema]",
"tests/test_schema.py::test_only_in_init[UserSchema]",
"tests/test_schema.py::test_only_in_init[UserMetaSchema]",
"tests/test_schema.py::test_invalid_only_param",
"tests/test_schema.py::test_can_serialize_uuid",
"tests/test_schema.py::test_can_serialize_time",
"tests/test_schema.py::test_invalid_time",
"tests/test_schema.py::test_invalid_date",
"tests/test_schema.py::test_invalid_email",
"tests/test_schema.py::test_invalid_url",
"tests/test_schema.py::test_invalid_selection",
"tests/test_schema.py::test_custom_json",
"tests/test_schema.py::test_custom_error_message",
"tests/test_schema.py::test_load_errors_with_many",
"tests/test_schema.py::test_error_raised_if_fields_option_is_not_list",
"tests/test_schema.py::test_error_raised_if_additional_option_is_not_list",
"tests/test_schema.py::test_only_and_exclude",
"tests/test_schema.py::test_only_with_invalid_attribute",
"tests/test_schema.py::test_nested_only_and_exclude",
"tests/test_schema.py::test_nested_with_sets",
"tests/test_schema.py::test_meta_serializer_fields",
"tests/test_schema.py::test_meta_fields_mapping",
"tests/test_schema.py::test_meta_field_not_on_obj_raises_attribute_error",
"tests/test_schema.py::test_exclude_fields",
"tests/test_schema.py::test_fields_option_must_be_list_or_tuple",
"tests/test_schema.py::test_exclude_option_must_be_list_or_tuple",
"tests/test_schema.py::test_dateformat_option",
"tests/test_schema.py::test_default_dateformat",
"tests/test_schema.py::test_inherit_meta",
"tests/test_schema.py::test_inherit_meta_override",
"tests/test_schema.py::test_additional",
"tests/test_schema.py::test_cant_set_both_additional_and_fields",
"tests/test_schema.py::test_serializing_none_meta",
"tests/test_schema.py::TestErrorHandler::test_dump_with_custom_error_handler",
"tests/test_schema.py::TestErrorHandler::test_load_with_custom_error_handler",
"tests/test_schema.py::TestErrorHandler::test_validate_with_custom_error_handler",
"tests/test_schema.py::TestErrorHandler::test_multiple_serializers_with_same_error_handler",
"tests/test_schema.py::TestErrorHandler::test_setting_error_handler_class_attribute",
"tests/test_schema.py::TestSchemaValidator::test_validator_decorator_is_deprecated",
"tests/test_schema.py::TestSchemaValidator::test_validator_defined_on_class",
"tests/test_schema.py::TestSchemaValidator::test_validator_that_raises_error_with_dict",
"tests/test_schema.py::TestSchemaValidator::test_validator_that_raises_error_with_list",
"tests/test_schema.py::TestSchemaValidator::test_mixed_schema_validators",
"tests/test_schema.py::TestSchemaValidator::test_registered_validators_are_not_shared_with_ancestors",
"tests/test_schema.py::TestSchemaValidator::test_registered_validators_are_not_shared_with_children",
"tests/test_schema.py::TestSchemaValidator::test_inheriting_then_registering_validator",
"tests/test_schema.py::TestSchemaValidator::test_multiple_schema_errors_can_be_stored",
"tests/test_schema.py::TestSchemaValidator::test_schema_validation_error_with_stict_stores_correct_field_name",
"tests/test_schema.py::TestSchemaValidator::test_schema_validation_error_with_strict_when_field_is_specified",
"tests/test_schema.py::TestSchemaValidator::test_schema_validation_error_stored_on_multiple_fields",
"tests/test_schema.py::TestSchemaValidator::test_validator_with_strict",
"tests/test_schema.py::TestSchemaValidator::test_validator_defined_by_decorator",
"tests/test_schema.py::TestSchemaValidator::test_validators_are_inherited",
"tests/test_schema.py::TestSchemaValidator::test_uncaught_validation_errors_are_stored",
"tests/test_schema.py::TestSchemaValidator::test_validation_error_with_error_parameter",
"tests/test_schema.py::TestSchemaValidator::test_store_schema_validation_errors_on_specified_field",
"tests/test_schema.py::TestSchemaValidator::test_errors_are_cleared_on_load",
"tests/test_schema.py::TestSchemaValidator::test_errors_are_cleared_after_loading_collection",
"tests/test_schema.py::TestSchemaValidator::test_raises_error_with_list",
"tests/test_schema.py::TestSchemaValidator::test_raises_error_with_dict",
"tests/test_schema.py::TestSchemaValidator::test_nested_schema_validators",
"tests/test_schema.py::TestPreprocessors::test_preprocessor_decorator_is_deprecated",
"tests/test_schema.py::TestPreprocessors::test_preprocessors_defined_on_class",
"tests/test_schema.py::TestPreprocessors::test_registered_preprocessors_are_not_shared_with_ancestors",
"tests/test_schema.py::TestPreprocessors::test_registered_preprocessors_are_not_shared_with_children",
"tests/test_schema.py::TestPreprocessors::test_preprocessors_defined_by_decorator",
"tests/test_schema.py::TestDataHandler::test_data_handler_is_deprecated",
"tests/test_schema.py::TestDataHandler::test_schema_with_custom_data_handler",
"tests/test_schema.py::TestDataHandler::test_registered_data_handlers_are_not_shared_with_ancestors",
"tests/test_schema.py::TestDataHandler::test_registered_data_handlers_are_not_shared_with_children",
"tests/test_schema.py::TestDataHandler::test_serializer_with_multiple_data_handlers",
"tests/test_schema.py::TestDataHandler::test_setting_data_handlers_class_attribute",
"tests/test_schema.py::TestDataHandler::test_root_data_handler",
"tests/test_schema.py::test_schema_repr",
"tests/test_schema.py::TestNestedSchema::test_flat_nested",
"tests/test_schema.py::TestNestedSchema::test_nested_many_with_missing_attribute",
"tests/test_schema.py::TestNestedSchema::test_nested_with_attribute_none",
"tests/test_schema.py::TestNestedSchema::test_flat_nested2",
"tests/test_schema.py::TestNestedSchema::test_nested_field_does_not_validate_required",
"tests/test_schema.py::TestNestedSchema::test_nested_none",
"tests/test_schema.py::TestNestedSchema::test_nested",
"tests/test_schema.py::TestNestedSchema::test_nested_many_fields",
"tests/test_schema.py::TestNestedSchema::test_nested_meta_many",
"tests/test_schema.py::TestNestedSchema::test_nested_only",
"tests/test_schema.py::TestNestedSchema::test_exclude",
"tests/test_schema.py::TestNestedSchema::test_list_field",
"tests/test_schema.py::TestNestedSchema::test_list_field_parent",
"tests/test_schema.py::TestNestedSchema::test_nested_load_many",
"tests/test_schema.py::TestNestedSchema::test_nested_errors",
"tests/test_schema.py::TestNestedSchema::test_nested_strict",
"tests/test_schema.py::TestNestedSchema::test_nested_method_field",
"tests/test_schema.py::TestNestedSchema::test_nested_function_field",
"tests/test_schema.py::TestNestedSchema::test_nested_prefixed_field",
"tests/test_schema.py::TestNestedSchema::test_nested_prefixed_many_field",
"tests/test_schema.py::TestNestedSchema::test_invalid_float_field",
"tests/test_schema.py::TestNestedSchema::test_serializer_meta_with_nested_fields",
"tests/test_schema.py::TestNestedSchema::test_serializer_with_nested_meta_fields",
"tests/test_schema.py::TestNestedSchema::test_nested_fields_must_be_passed_a_serializer",
"tests/test_schema.py::TestNestedSchema::test_missing_required_nested_field",
"tests/test_schema.py::TestSelfReference::test_nesting_schema_within_itself",
"tests/test_schema.py::TestSelfReference::test_nesting_schema_by_passing_class_name",
"tests/test_schema.py::TestSelfReference::test_nesting_within_itself_meta",
"tests/test_schema.py::TestSelfReference::test_nested_self_with_only_param",
"tests/test_schema.py::TestSelfReference::test_multiple_nested_self_fields",
"tests/test_schema.py::TestSelfReference::test_nested_many",
"tests/test_schema.py::test_serialization_with_required_field",
"tests/test_schema.py::test_deserialization_with_required_field",
"tests/test_schema.py::test_deserialization_with_required_field_and_custom_validator",
"tests/test_schema.py::TestContext::test_context_method",
"tests/test_schema.py::TestContext::test_context_method_function",
"tests/test_schema.py::TestContext::test_function_field_raises_error_when_context_not_available",
"tests/test_schema.py::TestContext::test_fields_context",
"tests/test_schema.py::TestContext::test_nested_fields_inherit_context",
"tests/test_schema.py::test_serializer_can_specify_nested_object_as_attribute",
"tests/test_schema.py::TestFieldInheritance::test_inherit_fields_from_schema_subclass",
"tests/test_schema.py::TestFieldInheritance::test_inherit_fields_from_non_schema_subclass",
"tests/test_schema.py::TestFieldInheritance::test_inheritance_follows_mro",
"tests/test_schema.py::TestAccessor::test_accessor_is_used",
"tests/test_schema.py::TestAccessor::test_accessor_with_many",
"tests/test_schema.py::TestAccessor::test_accessor_decorator",
"tests/test_schema.py::TestRequiredFields::test_required_string_field_missing",
"tests/test_schema.py::TestRequiredFields::test_required_string_field_failure",
"tests/test_schema.py::TestRequiredFields::test_allow_none_param",
"tests/test_schema.py::TestRequiredFields::test_allow_none_custom_message",
"tests/test_schema.py::TestDefaults::test_missing_inputs_are_excluded_from_dump_output",
"tests/test_schema.py::TestDefaults::test_none_is_serialized_to_none",
"tests/test_schema.py::TestDefaults::test_default_and_value_missing",
"tests/test_schema.py::TestDefaults::test_loading_none",
"tests/test_schema.py::TestDefaults::test_missing_inputs_are_excluded_from_load_output",
"tests/test_schema.py::TestLoadOnly::test_load_only",
"tests/test_schema.py::TestLoadOnly::test_dump_only"
] | [] | MIT License | 214 |
|
sympy__sympy-9850 | 3bec1824f7732752e1f400d7248b10d3dbfc9b32 | 2015-08-22 17:11:17 | 0241b35cae5f2adc04dc37b25f7dc9c5f00bd746 | diff --git a/sympy/printing/latex.py b/sympy/printing/latex.py
index 8f9c35051d..31dce95a55 100644
--- a/sympy/printing/latex.py
+++ b/sympy/printing/latex.py
@@ -1575,6 +1575,13 @@ def _print_ConditionSet(self, s):
self._print(s.base_set),
self._print(s.condition.expr))
+ def _print_ComplexPlane(self, s):
+ vars_print = ', '.join([self._print(var) for var in s.args[0].variables])
+ return r"\left\{%s\; |\; %s \in %s \right\}" % (
+ self._print(s.args[0].expr),
+ vars_print,
+ self._print(s.sets))
+
def _print_Contains(self, e):
return r"%s \in %s" % tuple(self._print(a) for a in e.args)
diff --git a/sympy/printing/pretty/pretty.py b/sympy/printing/pretty/pretty.py
index cfbe49f915..e1f457c622 100644
--- a/sympy/printing/pretty/pretty.py
+++ b/sympy/printing/pretty/pretty.py
@@ -1530,6 +1530,18 @@ def _print_ConditionSet(self, ts):
return self._print_seq((variables, bar, variables, inn,
base, _and, cond), "{", "}", ' ')
+ def _print_ComplexPlane(self, ts):
+ if self._use_unicode:
+ inn = u("\N{SMALL ELEMENT OF}")
+ else:
+ inn = 'in'
+ variables = self._print_seq(ts.args[0].variables)
+ expr = self._print(ts.args[0].expr)
+ bar = self._print("|")
+ prodsets = self._print(ts.sets)
+
+ return self._print_seq((expr, bar, variables, inn, prodsets), "{", "}", ' ')
+
def _print_Contains(self, e):
var, set = e.args
if self._use_unicode:
| Printer for ComplexPlane for custom Intervals
Since ComplexSets have been implemented here #9463 , the printer for Singleton Complex class `S.Complex` is present, but the printer for `ComplexPlane` class doesn't exists.
This is there:
```python
In [3]: S.Complex
Out[3]: ℂ
```
Printer for the following needs to be added:
```python
In [4]: ComplexPlane(Interval(1, 5)*Interval(2, 7))
Out[4]: ComplexPlane(Lambda((x, y), x + I*y), [1, 5] x [2, 7])
In [5]: ComplexPlane(Interval(0, 1)*Interval(0, 2*pi), polar=True)
Out[5]: ComplexPlane(Lambda((r, theta), r*(I*sin(theta) + cos(theta))), [0, 1] x [0, 2*pi))
```
| sympy/sympy | diff --git a/sympy/printing/pretty/tests/test_pretty.py b/sympy/printing/pretty/tests/test_pretty.py
index 52f0ae3517..d2ad29306a 100644
--- a/sympy/printing/pretty/tests/test_pretty.py
+++ b/sympy/printing/pretty/tests/test_pretty.py
@@ -3108,6 +3108,15 @@ def test_pretty_ConditionSet():
assert upretty(ConditionSet(Lambda(x, Eq(sin(x), 0)), S.Reals)) == ucode_str
+def test_pretty_ComplexPlane():
+ from sympy import ComplexPlane
+ ucode_str = u('{x + ⅈ⋅y | x, y ∊ [3, 5] × [4, 6]}')
+ assert upretty(ComplexPlane(Interval(3, 5)*Interval(4, 6))) == ucode_str
+
+ ucode_str = u('{r⋅(ⅈ⋅sin(θ) + cos(θ)) | r, θ ∊ [0, 1] × [0, 2⋅π)}')
+ assert upretty(ComplexPlane(Interval(0, 1)*Interval(0, 2*pi), polar=True)) == ucode_str
+
+
def test_ProductSet_paranthesis():
from sympy import Interval, Union, FiniteSet
ucode_str = u('([4, 7] × {1, 2}) ∪ ([2, 3] × [4, 7])')
diff --git a/sympy/printing/tests/test_latex.py b/sympy/printing/tests/test_latex.py
index e758ae8783..a397db0c96 100644
--- a/sympy/printing/tests/test_latex.py
+++ b/sympy/printing/tests/test_latex.py
@@ -15,7 +15,7 @@
uppergamma, zeta, subfactorial, totient, elliptic_k, elliptic_f,
elliptic_e, elliptic_pi, cos, tan, Wild, true, false, Equivalent, Not,
Contains, divisor_sigma, SymmetricDifference, SeqPer, SeqFormula,
- SeqAdd, SeqMul, fourier_series, pi, ConditionSet, fps)
+ SeqAdd, SeqMul, fourier_series, pi, ConditionSet, ComplexPlane, fps)
from sympy.ntheory.factor_ import udivisor_sigma
@@ -609,6 +609,13 @@ def test_latex_ConditionSet():
r"\left\{x\; |\; x \in \mathbb{R} \wedge x^{2} = 1 \right\}"
+def test_latex_ComplexPlane():
+ assert latex(ComplexPlane(Interval(3, 5)*Interval(4, 6))) == \
+ r"\left\{x + i y\; |\; x, y \in \left[3, 5\right] \times \left[4, 6\right] \right\}"
+ assert latex(ComplexPlane(Interval(0, 1)*Interval(0, 2*pi), polar=True)) == \
+ r"\left\{r \left(i \sin{\left (\theta \right )} + \cos{\left (\theta \right )}\right)\; |\; r, \theta \in \left[0, 1\right] \times \left[0, 2 \pi\right) \right\}"
+
+
def test_latex_Contains():
x = Symbol('x')
assert latex(Contains(x, S.Naturals)) == r"x \in \mathbb{N}"
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 0,
"issue_text_score": 0,
"test_score": 0
},
"num_modified_files": 2
} | 0.7 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "pytest",
"pip_packages": [
"mpmath>=0.19",
"pytest"
],
"pre_install": null,
"python": "3.6",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | attrs @ file:///opt/conda/conda-bld/attrs_1642510447205/work
certifi==2021.5.30
importlib-metadata @ file:///tmp/build/80754af9/importlib-metadata_1631916693255/work
iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work
more-itertools @ file:///tmp/build/80754af9/more-itertools_1637733554872/work
mpmath==1.3.0
packaging @ file:///tmp/build/80754af9/packaging_1637314298585/work
pluggy @ file:///tmp/build/80754af9/pluggy_1615976315926/work
py @ file:///opt/conda/conda-bld/py_1644396412707/work
pyparsing @ file:///tmp/build/80754af9/pyparsing_1635766073266/work
pytest==6.2.4
-e git+https://github.com/sympy/sympy.git@3bec1824f7732752e1f400d7248b10d3dbfc9b32#egg=sympy
toml @ file:///tmp/build/80754af9/toml_1616166611790/work
typing_extensions @ file:///opt/conda/conda-bld/typing_extensions_1647553014482/work
zipp @ file:///tmp/build/80754af9/zipp_1633618647012/work
| name: sympy
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- attrs=21.4.0=pyhd3eb1b0_0
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2021.5.30=py36h06a4308_0
- importlib-metadata=4.8.1=py36h06a4308_0
- importlib_metadata=4.8.1=hd3eb1b0_0
- iniconfig=1.1.1=pyhd3eb1b0_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.3=he6710b0_2
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- more-itertools=8.12.0=pyhd3eb1b0_0
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- packaging=21.3=pyhd3eb1b0_0
- pip=21.2.2=py36h06a4308_0
- pluggy=0.13.1=py36h06a4308_0
- py=1.11.0=pyhd3eb1b0_0
- pyparsing=3.0.4=pyhd3eb1b0_0
- pytest=6.2.4=py36h06a4308_2
- python=3.6.13=h12debd9_1
- readline=8.2=h5eee18b_0
- setuptools=58.0.4=py36h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- toml=0.10.2=pyhd3eb1b0_0
- typing_extensions=4.1.1=pyh06a4308_0
- wheel=0.37.1=pyhd3eb1b0_0
- xz=5.6.4=h5eee18b_1
- zipp=3.6.0=pyhd3eb1b0_0
- zlib=1.2.13=h5eee18b_1
- pip:
- mpmath==1.3.0
prefix: /opt/conda/envs/sympy
| [
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_ComplexPlane",
"sympy/printing/tests/test_latex.py::test_latex_ComplexPlane"
] | [] | [
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_ascii_str",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_unicode_str",
"sympy/printing/pretty/tests/test_pretty.py::test_upretty_greek",
"sympy/printing/pretty/tests/test_pretty.py::test_upretty_multiindex",
"sympy/printing/pretty/tests/test_pretty.py::test_upretty_sub_super",
"sympy/printing/pretty/tests/test_pretty.py::test_upretty_subs_missing_in_24",
"sympy/printing/pretty/tests/test_pretty.py::test_upretty_modifiers",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_basic",
"sympy/printing/pretty/tests/test_pretty.py::test_negative_fractions",
"sympy/printing/pretty/tests/test_pretty.py::test_issue_5524",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_ordering",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_relational",
"sympy/printing/pretty/tests/test_pretty.py::test_issue_7117",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_rational",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_functions",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_sqrt",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_sqrt_char_knob",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_sqrt_longsymbol_no_sqrt_char",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_KroneckerDelta",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_product",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_lambda",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_order",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_derivatives",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_integrals",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_matrix",
"sympy/printing/pretty/tests/test_pretty.py::test_Adjoint",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_piecewise",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_seq",
"sympy/printing/pretty/tests/test_pretty.py::test_any_object_in_sequence",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_sets",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_ConditionSet",
"sympy/printing/pretty/tests/test_pretty.py::test_ProductSet_paranthesis",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_sequences",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_FourierSeries",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_FormalPowerSeries",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_limits",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_RootOf",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_RootSum",
"sympy/printing/pretty/tests/test_pretty.py::test_GroebnerBasis",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_Boolean",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_Domain",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_prec",
"sympy/printing/pretty/tests/test_pretty.py::test_pprint",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_class",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_no_wrap_line",
"sympy/printing/pretty/tests/test_pretty.py::test_settings",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_sum",
"sympy/printing/pretty/tests/test_pretty.py::test_units",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_Subs",
"sympy/printing/pretty/tests/test_pretty.py::test_gammas",
"sympy/printing/pretty/tests/test_pretty.py::test_hyper",
"sympy/printing/pretty/tests/test_pretty.py::test_meijerg",
"sympy/printing/pretty/tests/test_pretty.py::test_noncommutative",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_special_functions",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_geometry",
"sympy/printing/pretty/tests/test_pretty.py::test_expint",
"sympy/printing/pretty/tests/test_pretty.py::test_elliptic_functions",
"sympy/printing/pretty/tests/test_pretty.py::test_RandomDomain",
"sympy/printing/pretty/tests/test_pretty.py::test_PrettyPoly",
"sympy/printing/pretty/tests/test_pretty.py::test_issue_6285",
"sympy/printing/pretty/tests/test_pretty.py::test_issue_6359",
"sympy/printing/pretty/tests/test_pretty.py::test_issue_6739",
"sympy/printing/pretty/tests/test_pretty.py::test_complicated_symbol_unchanged",
"sympy/printing/pretty/tests/test_pretty.py::test_categories",
"sympy/printing/pretty/tests/test_pretty.py::test_PrettyModules",
"sympy/printing/pretty/tests/test_pretty.py::test_QuotientRing",
"sympy/printing/pretty/tests/test_pretty.py::test_Homomorphism",
"sympy/printing/pretty/tests/test_pretty.py::test_Tr",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_Add",
"sympy/printing/pretty/tests/test_pretty.py::test_issue_7179",
"sympy/printing/pretty/tests/test_pretty.py::test_issue_7180",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_Complement",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_SymmetricDifference",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_Contains",
"sympy/printing/pretty/tests/test_pretty.py::test_issue_8292",
"sympy/printing/pretty/tests/test_pretty.py::test_issue_4335",
"sympy/printing/pretty/tests/test_pretty.py::test_issue_8344",
"sympy/printing/pretty/tests/test_pretty.py::test_issue_6324",
"sympy/printing/pretty/tests/test_pretty.py::test_issue_7927",
"sympy/printing/pretty/tests/test_pretty.py::test_issue_6134",
"sympy/printing/tests/test_latex.py::test_printmethod",
"sympy/printing/tests/test_latex.py::test_latex_basic",
"sympy/printing/tests/test_latex.py::test_latex_builtins",
"sympy/printing/tests/test_latex.py::test_latex_Float",
"sympy/printing/tests/test_latex.py::test_latex_symbols",
"sympy/printing/tests/test_latex.py::test_latex_functions",
"sympy/printing/tests/test_latex.py::test_hyper_printing",
"sympy/printing/tests/test_latex.py::test_latex_bessel",
"sympy/printing/tests/test_latex.py::test_latex_fresnel",
"sympy/printing/tests/test_latex.py::test_latex_brackets",
"sympy/printing/tests/test_latex.py::test_latex_indexed",
"sympy/printing/tests/test_latex.py::test_latex_derivatives",
"sympy/printing/tests/test_latex.py::test_latex_subs",
"sympy/printing/tests/test_latex.py::test_latex_integrals",
"sympy/printing/tests/test_latex.py::test_latex_sets",
"sympy/printing/tests/test_latex.py::test_latex_Range",
"sympy/printing/tests/test_latex.py::test_latex_sequences",
"sympy/printing/tests/test_latex.py::test_latex_FourierSeries",
"sympy/printing/tests/test_latex.py::test_latex_FormalPowerSeries",
"sympy/printing/tests/test_latex.py::test_latex_intervals",
"sympy/printing/tests/test_latex.py::test_latex_emptyset",
"sympy/printing/tests/test_latex.py::test_latex_union",
"sympy/printing/tests/test_latex.py::test_latex_symmetric_difference",
"sympy/printing/tests/test_latex.py::test_latex_Complement",
"sympy/printing/tests/test_latex.py::test_latex_Complexes",
"sympy/printing/tests/test_latex.py::test_latex_productset",
"sympy/printing/tests/test_latex.py::test_latex_Naturals",
"sympy/printing/tests/test_latex.py::test_latex_ImageSet",
"sympy/printing/tests/test_latex.py::test_latex_ConditionSet",
"sympy/printing/tests/test_latex.py::test_latex_Contains",
"sympy/printing/tests/test_latex.py::test_latex_sum",
"sympy/printing/tests/test_latex.py::test_latex_product",
"sympy/printing/tests/test_latex.py::test_latex_limits",
"sympy/printing/tests/test_latex.py::test_issue_3568",
"sympy/printing/tests/test_latex.py::test_latex",
"sympy/printing/tests/test_latex.py::test_latex_dict",
"sympy/printing/tests/test_latex.py::test_latex_list",
"sympy/printing/tests/test_latex.py::test_latex_rational",
"sympy/printing/tests/test_latex.py::test_latex_inverse",
"sympy/printing/tests/test_latex.py::test_latex_DiracDelta",
"sympy/printing/tests/test_latex.py::test_latex_Heaviside",
"sympy/printing/tests/test_latex.py::test_latex_KroneckerDelta",
"sympy/printing/tests/test_latex.py::test_latex_LeviCivita",
"sympy/printing/tests/test_latex.py::test_mode",
"sympy/printing/tests/test_latex.py::test_latex_Piecewise",
"sympy/printing/tests/test_latex.py::test_latex_Matrix",
"sympy/printing/tests/test_latex.py::test_latex_matrix_with_functions",
"sympy/printing/tests/test_latex.py::test_latex_mul_symbol",
"sympy/printing/tests/test_latex.py::test_latex_issue_4381",
"sympy/printing/tests/test_latex.py::test_latex_issue_4576",
"sympy/printing/tests/test_latex.py::test_latex_pow_fraction",
"sympy/printing/tests/test_latex.py::test_noncommutative",
"sympy/printing/tests/test_latex.py::test_latex_order",
"sympy/printing/tests/test_latex.py::test_latex_Lambda",
"sympy/printing/tests/test_latex.py::test_latex_PolyElement",
"sympy/printing/tests/test_latex.py::test_latex_FracElement",
"sympy/printing/tests/test_latex.py::test_latex_Poly",
"sympy/printing/tests/test_latex.py::test_latex_RootOf",
"sympy/printing/tests/test_latex.py::test_latex_RootSum",
"sympy/printing/tests/test_latex.py::test_settings",
"sympy/printing/tests/test_latex.py::test_latex_numbers",
"sympy/printing/tests/test_latex.py::test_lamda",
"sympy/printing/tests/test_latex.py::test_custom_symbol_names",
"sympy/printing/tests/test_latex.py::test_matAdd",
"sympy/printing/tests/test_latex.py::test_matMul",
"sympy/printing/tests/test_latex.py::test_latex_MatrixSlice",
"sympy/printing/tests/test_latex.py::test_latex_RandomDomain",
"sympy/printing/tests/test_latex.py::test_PrettyPoly",
"sympy/printing/tests/test_latex.py::test_integral_transforms",
"sympy/printing/tests/test_latex.py::test_PolynomialRingBase",
"sympy/printing/tests/test_latex.py::test_categories",
"sympy/printing/tests/test_latex.py::test_Modules",
"sympy/printing/tests/test_latex.py::test_QuotientRing",
"sympy/printing/tests/test_latex.py::test_Tr",
"sympy/printing/tests/test_latex.py::test_Adjoint",
"sympy/printing/tests/test_latex.py::test_Hadamard",
"sympy/printing/tests/test_latex.py::test_ZeroMatrix",
"sympy/printing/tests/test_latex.py::test_boolean_args_order",
"sympy/printing/tests/test_latex.py::test_imaginary",
"sympy/printing/tests/test_latex.py::test_builtins_without_args",
"sympy/printing/tests/test_latex.py::test_latex_greek_functions",
"sympy/printing/tests/test_latex.py::test_translate",
"sympy/printing/tests/test_latex.py::test_other_symbols",
"sympy/printing/tests/test_latex.py::test_modifiers",
"sympy/printing/tests/test_latex.py::test_greek_symbols",
"sympy/printing/tests/test_latex.py::test_builtin_no_args",
"sympy/printing/tests/test_latex.py::test_issue_6853",
"sympy/printing/tests/test_latex.py::test_Mul",
"sympy/printing/tests/test_latex.py::test_Pow",
"sympy/printing/tests/test_latex.py::test_issue_7180",
"sympy/printing/tests/test_latex.py::test_issue_8409",
"sympy/printing/tests/test_latex.py::test_issue_8470",
"sympy/printing/tests/test_latex.py::test_issue_7117",
"sympy/printing/tests/test_latex.py::test_issue_2934"
] | [] | BSD | 215 |
|
sympy__sympy-9854 | dffa488a34d68ccf5b09a08ff2753c408990c344 | 2015-08-23 21:44:20 | 0241b35cae5f2adc04dc37b25f7dc9c5f00bd746 | diff --git a/sympy/functions/combinatorial/factorials.py b/sympy/functions/combinatorial/factorials.py
index 4ed7582a76..99bd6dff9e 100644
--- a/sympy/functions/combinatorial/factorials.py
+++ b/sympy/functions/combinatorial/factorials.py
@@ -498,54 +498,40 @@ def _sage_(self):
class FallingFactorial(CombinatorialFunction):
"""Falling factorial (related to rising factorial) is a double valued
- function arising in concrete mathematics, hypergeometric functions
- and series expansions. It is defined by
+ function arising in concrete mathematics, hypergeometric functions
+ and series expansions. It is defined by
- ff(x, k) = x * (x-1) * ... * (x - k+1)
+ ff(x, k) = x * (x-1) * ... * (x - k+1)
- where 'x' can be arbitrary expression and 'k' is an integer. For
- more information check "Concrete mathematics" by Graham, pp. 66
- or visit http://mathworld.wolfram.com/FallingFactorial.html page.
+ where 'x' can be arbitrary expression and 'k' is an integer. For
+ more information check "Concrete mathematics" by Graham, pp. 66
+ or visit http://mathworld.wolfram.com/FallingFactorial.html page.
- When x is a polynomial f of a single variable y of order >= 1,
- ff(x,k) = f(y) * f(y-1) * ... * f(x-k+1) as described in
- Peter Paule, "Greatest Factorial Factorization and Symbolic Summation",
- Journal of Symbolic Computation, vol. 20, pp. 235-268, 1995.
+ When x is a polynomial f of a single variable y of order >= 1,
+ ff(x,k) = f(y) * f(y-1) * ... * f(x-k+1) as described in
+ Peter Paule, "Greatest Factorial Factorization and Symbolic Summation",
+ Journal of Symbolic Computation, vol. 20, pp. 235-268, 1995.
- >>> from sympy import ff, factorial, rf, gamma, polygamma, binomial, symbols
- >>> from sympy.abc import x, k
- >>> n, m = symbols('n m', integer=True)
- >>> ff(x, 0)
- 1
- >>> ff(5, 5)
- 120
- >>> ff(x, 5) == x*(x-1)*(x-2)*(x-3)*(x-4)
- True
- >>> ff(x**2, 2)
- Poly(x**4 - 2*x**3 + x**2, x, domain='ZZ')
- >>> ff(n, n)
- factorial(n)
-
- Rewrite
-
- >>> ff(x, k).rewrite(gamma)
- (-1)**k*gamma(k - x)/gamma(-x)
- >>> ff(x, k).rewrite(rf)
- RisingFactorial(-k + x + 1, k)
- >>> ff(x, m).rewrite(binomial)
- binomial(x, m)*factorial(m)
- >>> ff(n, m).rewrite(factorial)
- factorial(n)/factorial(-m + n)
+ >>> from sympy import ff
+ >>> from sympy.abc import x
- See Also
- ========
+ >>> ff(x, 0)
+ 1
- factorial, factorial2, RisingFactorial
+ >>> ff(5, 5)
+ 120
- References
- ==========
+ >>> ff(x, 5) == x*(x-1)*(x-2)*(x-3)*(x-4)
+ True
+
+ >>> ff(x**2, 2)
+ Poly(x**4 - 2*x**3 + x**2, x, domain='ZZ')
- .. [1] http://mathworld.wolfram.com/FallingFactorial.html
+
+ See Also
+ ========
+
+ factorial, factorial2, RisingFactorial
"""
@classmethod
@@ -553,12 +539,12 @@ def eval(cls, x, k):
x = sympify(x)
k = sympify(k)
- if x is S.NaN or k is S.NaN:
+ if x is S.NaN:
return S.NaN
- elif k.is_integer and x == k:
- return factorial(x)
elif k.is_Integer:
- if k is S.Zero:
+ if k is S.NaN:
+ return S.NaN
+ elif k is S.Zero:
return S.One
else:
if k.is_positive:
@@ -573,16 +559,12 @@ def eval(cls, x, k):
try:
F, opt = poly_from_expr(x)
except PolificationFailed:
- return reduce(lambda r, i: r*(x - i),
- range(0, int(k)), 1)
+ return reduce(lambda r, i: r*(x - i), range(0, int(k)), 1)
if len(opt.gens) > 1 or F.degree() <= 1:
- return reduce(lambda r, i: r*(x - i),
- range(0, int(k)), 1)
+ return reduce(lambda r, i: r*(x - i), range(0, int(k)), 1)
else:
v = opt.gens[0]
- return reduce(lambda r, i:
- r*(F.subs(v, v - i).expand()),
- range(0, int(k)), 1)
+ return reduce(lambda r, i: r*(F.subs(v, v - i).expand()), range(0, int(k)), 1)
else:
if x is S.Infinity:
return S.Infinity
@@ -592,31 +574,16 @@ def eval(cls, x, k):
try:
F, opt = poly_from_expr(x)
except PolificationFailed:
- return 1/reduce(lambda r, i: r*(x + i),
- range(1, abs(int(k)) + 1), 1)
+ return 1/reduce(lambda r, i: r*(x + i), range(1, abs(int(k)) + 1), 1)
if len(opt.gens) > 1 or F.degree() <= 1:
- return 1/reduce(lambda r, i: r*(x + i),
- range(1, abs(int(k)) + 1), 1)
+ return 1/reduce(lambda r, i: r*(x + i), range(1, abs(int(k)) + 1), 1)
else:
v = opt.gens[0]
- return 1/reduce(lambda r, i:
- r*(F.subs(v, v + i).expand()),
- range(1, abs(int(k)) + 1), 1)
+ return 1/reduce(lambda r, i: r*(F.subs(v, v + i).expand()), range(1, abs(int(k)) + 1), 1)
def _eval_rewrite_as_gamma(self, x, k):
from sympy import gamma
- return (-1)**k*gamma(k - x) / gamma(-x)
-
- def _eval_rewrite_as_RisingFactorial(self, x, k):
- return rf(x - k + 1, k)
-
- def _eval_rewrite_as_binomial(self, x, k):
- if k.is_integer:
- return factorial(k) * binomial(x, k)
-
- def _eval_rewrite_as_factorial(self, x, k):
- if x.is_integer and k.is_integer:
- return factorial(x) / factorial(x - k)
+ return (-1)**k * gamma(-x + k) / gamma(-x)
def _eval_is_integer(self):
return fuzzy_and((self.args[0].is_integer, self.args[1].is_integer,
@@ -624,8 +591,7 @@ def _eval_is_integer(self):
def _sage_(self):
import sage.all as sage
- return sage.falling_factorial(self.args[0]._sage_(),
- self.args[1]._sage_())
+ return sage.falling_factorial(self.args[0]._sage_(), self.args[1]._sage_())
rf = RisingFactorial
@@ -817,10 +783,6 @@ def _eval_rewrite_as_gamma(self, n, k):
from sympy import gamma
return gamma(n + 1)/(gamma(k + 1)*gamma(n - k + 1))
- def _eval_rewrite_as_FallingFactorial(self, n, k):
- if k.is_integer:
- return ff(n, k) / factorial(k)
-
def _eval_is_integer(self):
n, k = self.args
if n.is_integer and k.is_integer:
diff --git a/sympy/printing/latex.py b/sympy/printing/latex.py
index 31dce95a55..8b92a8be78 100644
--- a/sympy/printing/latex.py
+++ b/sympy/printing/latex.py
@@ -1552,6 +1552,9 @@ def _print_EmptySet(self, e):
def _print_Naturals(self, n):
return r"\mathbb{N}"
+ def _print_Naturals0(self, n):
+ return r"\mathbb{N_0}"
+
def _print_Integers(self, i):
return r"\mathbb{Z}"
@@ -1575,13 +1578,6 @@ def _print_ConditionSet(self, s):
self._print(s.base_set),
self._print(s.condition.expr))
- def _print_ComplexPlane(self, s):
- vars_print = ', '.join([self._print(var) for var in s.args[0].variables])
- return r"\left\{%s\; |\; %s \in %s \right\}" % (
- self._print(s.args[0].expr),
- vars_print,
- self._print(s.sets))
-
def _print_Contains(self, e):
return r"%s \in %s" % tuple(self._print(a) for a in e.args)
diff --git a/sympy/printing/pretty/pretty.py b/sympy/printing/pretty/pretty.py
index e1f457c622..7300ba464d 100644
--- a/sympy/printing/pretty/pretty.py
+++ b/sympy/printing/pretty/pretty.py
@@ -93,6 +93,7 @@ def _print_Atom(self, e):
_print_NegativeInfinity = _print_Atom
_print_EmptySet = _print_Atom
_print_Naturals = _print_Atom
+ _print_Naturals0 = _print_Atom
_print_Integers = _print_Atom
_print_Reals = _print_Atom
_print_Complexes = _print_Atom
@@ -1530,18 +1531,6 @@ def _print_ConditionSet(self, ts):
return self._print_seq((variables, bar, variables, inn,
base, _and, cond), "{", "}", ' ')
- def _print_ComplexPlane(self, ts):
- if self._use_unicode:
- inn = u("\N{SMALL ELEMENT OF}")
- else:
- inn = 'in'
- variables = self._print_seq(ts.args[0].variables)
- expr = self._print(ts.args[0].expr)
- bar = self._print("|")
- prodsets = self._print(ts.sets)
-
- return self._print_seq((expr, bar, variables, inn, prodsets), "{", "}", ' ')
-
def _print_Contains(self, e):
var, set = e.args
if self._use_unicode:
diff --git a/sympy/printing/pretty/pretty_symbology.py b/sympy/printing/pretty/pretty_symbology.py
index 3701dd5fad..36ff6bbac9 100644
--- a/sympy/printing/pretty/pretty_symbology.py
+++ b/sympy/printing/pretty/pretty_symbology.py
@@ -468,6 +468,9 @@ def xsym(sym):
'ImaginaryUnit': U('DOUBLE-STRUCK ITALIC SMALL I'),
'EmptySet': U('EMPTY SET'),
'Naturals': U('DOUBLE-STRUCK CAPITAL N'),
+ 'Naturals0': (U('DOUBLE-STRUCK CAPITAL N') and
+ (U('DOUBLE-STRUCK CAPITAL N') +
+ U('SUBSCRIPT ZERO'))),
'Integers': U('DOUBLE-STRUCK CAPITAL Z'),
'Reals': U('DOUBLE-STRUCK CAPITAL R'),
'Complexes': U('DOUBLE-STRUCK CAPITAL C'),
| Defining printing for `S.Naturals0`
```
>>> init_printing(use_unicode=True)
>>> S.Naturals
ℕ
>>> S.Naturals0
ℕ
```
There should should be some difference in their printing may be putting a `N0`(0 in subscript) for `S.Naturals0`. | sympy/sympy | diff --git a/sympy/functions/combinatorial/tests/test_comb_factorials.py b/sympy/functions/combinatorial/tests/test_comb_factorials.py
index 5baf0bf434..31ec8b7a81 100644
--- a/sympy/functions/combinatorial/tests/test_comb_factorials.py
+++ b/sympy/functions/combinatorial/tests/test_comb_factorials.py
@@ -50,11 +50,8 @@ def test_rf_eval_apply():
def test_ff_eval_apply():
x, y = symbols('x,y')
- n, k = symbols('n k', integer=True)
- m = Symbol('m', integer=True, nonnegative=True)
assert ff(nan, y) == nan
- assert ff(x, nan) == nan
assert ff(x, y) == ff(x, y)
@@ -82,6 +79,9 @@ def test_ff_eval_apply():
assert ff(2*x**2 - 5*x, 2) == 4*x**4 - 28*x**3 + 59*x**2 - 35*x
assert ff(x**2 + 3*x, -2) == 1/(x**4 + 12*x**3 + 49*x**2 + 78*x + 40)
+ n = Symbol('n', integer=True)
+ k = Symbol('k', integer=True)
+ m = Symbol('m', integer=True, nonnegative=True)
assert ff(x, m).is_integer is None
assert ff(n, k).is_integer is None
assert ff(n, m).is_integer is True
@@ -89,14 +89,6 @@ def test_ff_eval_apply():
assert ff(n, m + pi).is_integer is False
assert ff(pi, m).is_integer is False
- assert isinstance(ff(x, x), ff)
- assert ff(n, n) == factorial(n)
-
- assert ff(x, k).rewrite(rf) == rf(x - k + 1, k)
- assert ff(x, k).rewrite(gamma) == (-1)**k*gamma(k - x) / gamma(-x)
- assert ff(n, k).rewrite(factorial) == factorial(n) / factorial(n - k)
- assert ff(x, k).rewrite(binomial) == factorial(k) * binomial(x, k)
-
def test_factorial():
x = Symbol('x')
@@ -314,7 +306,6 @@ def test_binomial_rewrite():
factorial) == factorial(n)/(factorial(k)*factorial(n - k))
assert binomial(
n, k).rewrite(gamma) == gamma(n + 1)/(gamma(k + 1)*gamma(n - k + 1))
- assert binomial(n, k).rewrite(ff) == ff(n, k) / factorial(k)
@XFAIL
diff --git a/sympy/printing/pretty/tests/test_pretty.py b/sympy/printing/pretty/tests/test_pretty.py
index d2ad29306a..3ac278343d 100644
--- a/sympy/printing/pretty/tests/test_pretty.py
+++ b/sympy/printing/pretty/tests/test_pretty.py
@@ -3108,15 +3108,6 @@ def test_pretty_ConditionSet():
assert upretty(ConditionSet(Lambda(x, Eq(sin(x), 0)), S.Reals)) == ucode_str
-def test_pretty_ComplexPlane():
- from sympy import ComplexPlane
- ucode_str = u('{x + ⅈ⋅y | x, y ∊ [3, 5] × [4, 6]}')
- assert upretty(ComplexPlane(Interval(3, 5)*Interval(4, 6))) == ucode_str
-
- ucode_str = u('{r⋅(ⅈ⋅sin(θ) + cos(θ)) | r, θ ∊ [0, 1] × [0, 2⋅π)}')
- assert upretty(ComplexPlane(Interval(0, 1)*Interval(0, 2*pi), polar=True)) == ucode_str
-
-
def test_ProductSet_paranthesis():
from sympy import Interval, Union, FiniteSet
ucode_str = u('([4, 7] × {1, 2}) ∪ ([2, 3] × [4, 7])')
@@ -5052,6 +5043,8 @@ def test_issue_7180():
def test_pretty_Complement():
assert pretty(S.Reals - S.Naturals) == '(-oo, oo) \ Naturals()'
assert upretty(S.Reals - S.Naturals) == u('ℝ \ ℕ')
+ assert pretty(S.Reals - S.Naturals0) == '(-oo, oo) \ Naturals0()'
+ assert upretty(S.Reals - S.Naturals0) == u('ℝ \ ℕ₀')
def test_pretty_SymmetricDifference():
diff --git a/sympy/printing/tests/test_latex.py b/sympy/printing/tests/test_latex.py
index a397db0c96..9bb886d199 100644
--- a/sympy/printing/tests/test_latex.py
+++ b/sympy/printing/tests/test_latex.py
@@ -15,7 +15,7 @@
uppergamma, zeta, subfactorial, totient, elliptic_k, elliptic_f,
elliptic_e, elliptic_pi, cos, tan, Wild, true, false, Equivalent, Not,
Contains, divisor_sigma, SymmetricDifference, SeqPer, SeqFormula,
- SeqAdd, SeqMul, fourier_series, pi, ConditionSet, ComplexPlane, fps)
+ SeqAdd, SeqMul, fourier_series, pi, ConditionSet, fps)
from sympy.ntheory.factor_ import udivisor_sigma
@@ -594,6 +594,13 @@ def test_latex_productset():
def test_latex_Naturals():
assert latex(S.Naturals) == r"\mathbb{N}"
+
+
+def test_latex_Naturals0():
+ assert latex(S.Naturals0) == r"\mathbb{N_0}"
+
+
+def test_latex_Integers():
assert latex(S.Integers) == r"\mathbb{Z}"
@@ -609,13 +616,6 @@ def test_latex_ConditionSet():
r"\left\{x\; |\; x \in \mathbb{R} \wedge x^{2} = 1 \right\}"
-def test_latex_ComplexPlane():
- assert latex(ComplexPlane(Interval(3, 5)*Interval(4, 6))) == \
- r"\left\{x + i y\; |\; x, y \in \left[3, 5\right] \times \left[4, 6\right] \right\}"
- assert latex(ComplexPlane(Interval(0, 1)*Interval(0, 2*pi), polar=True)) == \
- r"\left\{r \left(i \sin{\left (\theta \right )} + \cos{\left (\theta \right )}\right)\; |\; r, \theta \in \left[0, 1\right] \times \left[0, 2 \pi\right) \right\}"
-
-
def test_latex_Contains():
x = Symbol('x')
assert latex(Contains(x, S.Naturals)) == r"x \in \mathbb{N}"
diff --git a/sympy/solvers/tests/test_solveset.py b/sympy/solvers/tests/test_solveset.py
index 44f3548acc..64062b4d33 100644
--- a/sympy/solvers/tests/test_solveset.py
+++ b/sympy/solvers/tests/test_solveset.py
@@ -603,7 +603,6 @@ def test_atan2():
def test_piecewise():
eq = Piecewise((x - 2, Gt(x, 2)), (2 - x, True)) - 3
- f = Piecewise(((x - 2)**2, x >= 0), (0, True))
assert set(solveset_real(eq, x)) == set(FiniteSet(-1, 5))
absxm3 = Piecewise(
(x - 3, S(0) <= x - 3),
@@ -611,7 +610,6 @@ def test_piecewise():
)
y = Symbol('y', positive=True)
assert solveset_real(absxm3 - y, x) == FiniteSet(-y + 3, y + 3)
- assert solveset(f, x, domain=S.Reals) == Union(FiniteSet(2), Interval(-oo, 0, True, True))
def test_solveset_complex_polynomial():
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 0,
"issue_text_score": 2,
"test_score": 0
},
"num_modified_files": 4
} | 0.7 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "pytest",
"pip_packages": [
"pytest"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.7",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | attrs @ file:///croot/attrs_1668696182826/work
certifi @ file:///croot/certifi_1671487769961/work/certifi
flit_core @ file:///opt/conda/conda-bld/flit-core_1644941570762/work/source/flit_core
importlib-metadata @ file:///tmp/build/80754af9/importlib-metadata_1648562407465/work
iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work
mpmath==1.3.0
packaging @ file:///croot/packaging_1671697413597/work
pluggy @ file:///tmp/build/80754af9/pluggy_1648042572264/work
py @ file:///opt/conda/conda-bld/py_1644396412707/work
pytest==7.1.2
-e git+https://github.com/sympy/sympy.git@dffa488a34d68ccf5b09a08ff2753c408990c344#egg=sympy
tomli @ file:///opt/conda/conda-bld/tomli_1657175507142/work
typing_extensions @ file:///croot/typing_extensions_1669924550328/work
zipp @ file:///croot/zipp_1672387121353/work
| name: sympy
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- attrs=22.1.0=py37h06a4308_0
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2022.12.7=py37h06a4308_0
- flit-core=3.6.0=pyhd3eb1b0_0
- importlib-metadata=4.11.3=py37h06a4308_0
- importlib_metadata=4.11.3=hd3eb1b0_0
- iniconfig=1.1.1=pyhd3eb1b0_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- packaging=22.0=py37h06a4308_0
- pip=22.3.1=py37h06a4308_0
- pluggy=1.0.0=py37h06a4308_1
- py=1.11.0=pyhd3eb1b0_0
- pytest=7.1.2=py37h06a4308_0
- python=3.7.16=h7a1cb2a_0
- readline=8.2=h5eee18b_0
- setuptools=65.6.3=py37h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- tomli=2.0.1=py37h06a4308_0
- typing_extensions=4.4.0=py37h06a4308_0
- wheel=0.38.4=py37h06a4308_0
- xz=5.6.4=h5eee18b_1
- zipp=3.11.0=py37h06a4308_0
- zlib=1.2.13=h5eee18b_1
- pip:
- mpmath==1.3.0
prefix: /opt/conda/envs/sympy
| [
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_Complement",
"sympy/printing/tests/test_latex.py::test_latex_Naturals0"
] | [] | [
"sympy/functions/combinatorial/tests/test_comb_factorials.py::test_rf_eval_apply",
"sympy/functions/combinatorial/tests/test_comb_factorials.py::test_ff_eval_apply",
"sympy/functions/combinatorial/tests/test_comb_factorials.py::test_factorial",
"sympy/functions/combinatorial/tests/test_comb_factorials.py::test_factorial_diff",
"sympy/functions/combinatorial/tests/test_comb_factorials.py::test_factorial_series",
"sympy/functions/combinatorial/tests/test_comb_factorials.py::test_factorial_rewrite",
"sympy/functions/combinatorial/tests/test_comb_factorials.py::test_factorial2",
"sympy/functions/combinatorial/tests/test_comb_factorials.py::test_binomial",
"sympy/functions/combinatorial/tests/test_comb_factorials.py::test_binomial_diff",
"sympy/functions/combinatorial/tests/test_comb_factorials.py::test_binomial_rewrite",
"sympy/functions/combinatorial/tests/test_comb_factorials.py::test_subfactorial",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_ascii_str",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_unicode_str",
"sympy/printing/pretty/tests/test_pretty.py::test_upretty_greek",
"sympy/printing/pretty/tests/test_pretty.py::test_upretty_multiindex",
"sympy/printing/pretty/tests/test_pretty.py::test_upretty_sub_super",
"sympy/printing/pretty/tests/test_pretty.py::test_upretty_subs_missing_in_24",
"sympy/printing/pretty/tests/test_pretty.py::test_upretty_modifiers",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_basic",
"sympy/printing/pretty/tests/test_pretty.py::test_negative_fractions",
"sympy/printing/pretty/tests/test_pretty.py::test_issue_5524",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_ordering",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_relational",
"sympy/printing/pretty/tests/test_pretty.py::test_issue_7117",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_rational",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_functions",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_sqrt",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_sqrt_char_knob",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_sqrt_longsymbol_no_sqrt_char",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_KroneckerDelta",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_product",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_lambda",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_order",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_derivatives",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_integrals",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_matrix",
"sympy/printing/pretty/tests/test_pretty.py::test_Adjoint",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_piecewise",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_seq",
"sympy/printing/pretty/tests/test_pretty.py::test_any_object_in_sequence",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_sets",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_ConditionSet",
"sympy/printing/pretty/tests/test_pretty.py::test_ProductSet_paranthesis",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_sequences",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_FourierSeries",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_FormalPowerSeries",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_limits",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_RootOf",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_RootSum",
"sympy/printing/pretty/tests/test_pretty.py::test_GroebnerBasis",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_Boolean",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_Domain",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_prec",
"sympy/printing/pretty/tests/test_pretty.py::test_pprint",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_class",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_no_wrap_line",
"sympy/printing/pretty/tests/test_pretty.py::test_settings",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_sum",
"sympy/printing/pretty/tests/test_pretty.py::test_units",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_Subs",
"sympy/printing/pretty/tests/test_pretty.py::test_gammas",
"sympy/printing/pretty/tests/test_pretty.py::test_hyper",
"sympy/printing/pretty/tests/test_pretty.py::test_meijerg",
"sympy/printing/pretty/tests/test_pretty.py::test_noncommutative",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_special_functions",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_geometry",
"sympy/printing/pretty/tests/test_pretty.py::test_expint",
"sympy/printing/pretty/tests/test_pretty.py::test_elliptic_functions",
"sympy/printing/pretty/tests/test_pretty.py::test_RandomDomain",
"sympy/printing/pretty/tests/test_pretty.py::test_PrettyPoly",
"sympy/printing/pretty/tests/test_pretty.py::test_issue_6285",
"sympy/printing/pretty/tests/test_pretty.py::test_issue_6359",
"sympy/printing/pretty/tests/test_pretty.py::test_issue_6739",
"sympy/printing/pretty/tests/test_pretty.py::test_complicated_symbol_unchanged",
"sympy/printing/pretty/tests/test_pretty.py::test_categories",
"sympy/printing/pretty/tests/test_pretty.py::test_PrettyModules",
"sympy/printing/pretty/tests/test_pretty.py::test_QuotientRing",
"sympy/printing/pretty/tests/test_pretty.py::test_Homomorphism",
"sympy/printing/pretty/tests/test_pretty.py::test_Tr",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_Add",
"sympy/printing/pretty/tests/test_pretty.py::test_issue_7179",
"sympy/printing/pretty/tests/test_pretty.py::test_issue_7180",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_SymmetricDifference",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_Contains",
"sympy/printing/pretty/tests/test_pretty.py::test_issue_8292",
"sympy/printing/pretty/tests/test_pretty.py::test_issue_4335",
"sympy/printing/pretty/tests/test_pretty.py::test_issue_8344",
"sympy/printing/pretty/tests/test_pretty.py::test_issue_6324",
"sympy/printing/pretty/tests/test_pretty.py::test_issue_7927",
"sympy/printing/pretty/tests/test_pretty.py::test_issue_6134",
"sympy/printing/tests/test_latex.py::test_printmethod",
"sympy/printing/tests/test_latex.py::test_latex_basic",
"sympy/printing/tests/test_latex.py::test_latex_builtins",
"sympy/printing/tests/test_latex.py::test_latex_Float",
"sympy/printing/tests/test_latex.py::test_latex_symbols",
"sympy/printing/tests/test_latex.py::test_latex_functions",
"sympy/printing/tests/test_latex.py::test_hyper_printing",
"sympy/printing/tests/test_latex.py::test_latex_bessel",
"sympy/printing/tests/test_latex.py::test_latex_fresnel",
"sympy/printing/tests/test_latex.py::test_latex_brackets",
"sympy/printing/tests/test_latex.py::test_latex_indexed",
"sympy/printing/tests/test_latex.py::test_latex_derivatives",
"sympy/printing/tests/test_latex.py::test_latex_subs",
"sympy/printing/tests/test_latex.py::test_latex_integrals",
"sympy/printing/tests/test_latex.py::test_latex_sets",
"sympy/printing/tests/test_latex.py::test_latex_Range",
"sympy/printing/tests/test_latex.py::test_latex_sequences",
"sympy/printing/tests/test_latex.py::test_latex_FourierSeries",
"sympy/printing/tests/test_latex.py::test_latex_FormalPowerSeries",
"sympy/printing/tests/test_latex.py::test_latex_intervals",
"sympy/printing/tests/test_latex.py::test_latex_emptyset",
"sympy/printing/tests/test_latex.py::test_latex_union",
"sympy/printing/tests/test_latex.py::test_latex_symmetric_difference",
"sympy/printing/tests/test_latex.py::test_latex_Complement",
"sympy/printing/tests/test_latex.py::test_latex_Complexes",
"sympy/printing/tests/test_latex.py::test_latex_productset",
"sympy/printing/tests/test_latex.py::test_latex_Naturals",
"sympy/printing/tests/test_latex.py::test_latex_Integers",
"sympy/printing/tests/test_latex.py::test_latex_ImageSet",
"sympy/printing/tests/test_latex.py::test_latex_ConditionSet",
"sympy/printing/tests/test_latex.py::test_latex_Contains",
"sympy/printing/tests/test_latex.py::test_latex_sum",
"sympy/printing/tests/test_latex.py::test_latex_product",
"sympy/printing/tests/test_latex.py::test_latex_limits",
"sympy/printing/tests/test_latex.py::test_issue_3568",
"sympy/printing/tests/test_latex.py::test_latex",
"sympy/printing/tests/test_latex.py::test_latex_dict",
"sympy/printing/tests/test_latex.py::test_latex_list",
"sympy/printing/tests/test_latex.py::test_latex_rational",
"sympy/printing/tests/test_latex.py::test_latex_inverse",
"sympy/printing/tests/test_latex.py::test_latex_DiracDelta",
"sympy/printing/tests/test_latex.py::test_latex_Heaviside",
"sympy/printing/tests/test_latex.py::test_latex_KroneckerDelta",
"sympy/printing/tests/test_latex.py::test_latex_LeviCivita",
"sympy/printing/tests/test_latex.py::test_mode",
"sympy/printing/tests/test_latex.py::test_latex_Piecewise",
"sympy/printing/tests/test_latex.py::test_latex_Matrix",
"sympy/printing/tests/test_latex.py::test_latex_matrix_with_functions",
"sympy/printing/tests/test_latex.py::test_latex_mul_symbol",
"sympy/printing/tests/test_latex.py::test_latex_issue_4381",
"sympy/printing/tests/test_latex.py::test_latex_issue_4576",
"sympy/printing/tests/test_latex.py::test_latex_pow_fraction",
"sympy/printing/tests/test_latex.py::test_noncommutative",
"sympy/printing/tests/test_latex.py::test_latex_order",
"sympy/printing/tests/test_latex.py::test_latex_Lambda",
"sympy/printing/tests/test_latex.py::test_latex_PolyElement",
"sympy/printing/tests/test_latex.py::test_latex_FracElement",
"sympy/printing/tests/test_latex.py::test_latex_Poly",
"sympy/printing/tests/test_latex.py::test_latex_RootOf",
"sympy/printing/tests/test_latex.py::test_latex_RootSum",
"sympy/printing/tests/test_latex.py::test_settings",
"sympy/printing/tests/test_latex.py::test_latex_numbers",
"sympy/printing/tests/test_latex.py::test_lamda",
"sympy/printing/tests/test_latex.py::test_custom_symbol_names",
"sympy/printing/tests/test_latex.py::test_matAdd",
"sympy/printing/tests/test_latex.py::test_matMul",
"sympy/printing/tests/test_latex.py::test_latex_MatrixSlice",
"sympy/printing/tests/test_latex.py::test_latex_RandomDomain",
"sympy/printing/tests/test_latex.py::test_PrettyPoly",
"sympy/printing/tests/test_latex.py::test_integral_transforms",
"sympy/printing/tests/test_latex.py::test_PolynomialRingBase",
"sympy/printing/tests/test_latex.py::test_categories",
"sympy/printing/tests/test_latex.py::test_Modules",
"sympy/printing/tests/test_latex.py::test_QuotientRing",
"sympy/printing/tests/test_latex.py::test_Tr",
"sympy/printing/tests/test_latex.py::test_Adjoint",
"sympy/printing/tests/test_latex.py::test_Hadamard",
"sympy/printing/tests/test_latex.py::test_ZeroMatrix",
"sympy/printing/tests/test_latex.py::test_boolean_args_order",
"sympy/printing/tests/test_latex.py::test_imaginary",
"sympy/printing/tests/test_latex.py::test_builtins_without_args",
"sympy/printing/tests/test_latex.py::test_latex_greek_functions",
"sympy/printing/tests/test_latex.py::test_translate",
"sympy/printing/tests/test_latex.py::test_other_symbols",
"sympy/printing/tests/test_latex.py::test_modifiers",
"sympy/printing/tests/test_latex.py::test_greek_symbols",
"sympy/printing/tests/test_latex.py::test_builtin_no_args",
"sympy/printing/tests/test_latex.py::test_issue_6853",
"sympy/printing/tests/test_latex.py::test_Mul",
"sympy/printing/tests/test_latex.py::test_Pow",
"sympy/printing/tests/test_latex.py::test_issue_7180",
"sympy/printing/tests/test_latex.py::test_issue_8409",
"sympy/printing/tests/test_latex.py::test_issue_8470",
"sympy/printing/tests/test_latex.py::test_issue_7117",
"sympy/printing/tests/test_latex.py::test_issue_2934",
"sympy/solvers/tests/test_solveset.py::test_invert_real",
"sympy/solvers/tests/test_solveset.py::test_invert_complex",
"sympy/solvers/tests/test_solveset.py::test_domain_check",
"sympy/solvers/tests/test_solveset.py::test_is_function_class_equation",
"sympy/solvers/tests/test_solveset.py::test_garbage_input",
"sympy/solvers/tests/test_solveset.py::test_solve_mul",
"sympy/solvers/tests/test_solveset.py::test_solve_invert",
"sympy/solvers/tests/test_solveset.py::test_errorinverses",
"sympy/solvers/tests/test_solveset.py::test_solve_polynomial",
"sympy/solvers/tests/test_solveset.py::test_return_root_of",
"sympy/solvers/tests/test_solveset.py::test__has_rational_power",
"sympy/solvers/tests/test_solveset.py::test_solveset_sqrt_1",
"sympy/solvers/tests/test_solveset.py::test_solveset_sqrt_2",
"sympy/solvers/tests/test_solveset.py::test_solve_sqrt_3",
"sympy/solvers/tests/test_solveset.py::test_solve_polynomial_symbolic_param",
"sympy/solvers/tests/test_solveset.py::test_solve_rational",
"sympy/solvers/tests/test_solveset.py::test_solveset_real_gen_is_pow",
"sympy/solvers/tests/test_solveset.py::test_no_sol",
"sympy/solvers/tests/test_solveset.py::test_sol_zero_real",
"sympy/solvers/tests/test_solveset.py::test_no_sol_rational_extragenous",
"sympy/solvers/tests/test_solveset.py::test_solve_polynomial_cv_1a",
"sympy/solvers/tests/test_solveset.py::test_solveset_real_rational",
"sympy/solvers/tests/test_solveset.py::test_solveset_real_log",
"sympy/solvers/tests/test_solveset.py::test_poly_gens",
"sympy/solvers/tests/test_solveset.py::test_solve_abs",
"sympy/solvers/tests/test_solveset.py::test_real_imag_splitting",
"sympy/solvers/tests/test_solveset.py::test_units",
"sympy/solvers/tests/test_solveset.py::test_solve_only_exp_1",
"sympy/solvers/tests/test_solveset.py::test_atan2",
"sympy/solvers/tests/test_solveset.py::test_piecewise",
"sympy/solvers/tests/test_solveset.py::test_solveset_complex_polynomial",
"sympy/solvers/tests/test_solveset.py::test_sol_zero_complex",
"sympy/solvers/tests/test_solveset.py::test_solveset_complex_rational",
"sympy/solvers/tests/test_solveset.py::test_solveset_complex_exp",
"sympy/solvers/tests/test_solveset.py::test_solve_complex_log",
"sympy/solvers/tests/test_solveset.py::test_solve_complex_sqrt",
"sympy/solvers/tests/test_solveset.py::test_solveset_complex_tan",
"sympy/solvers/tests/test_solveset.py::test_solve_trig",
"sympy/solvers/tests/test_solveset.py::test_solve_invalid_sol",
"sympy/solvers/tests/test_solveset.py::test_solve_complex_unsolvable",
"sympy/solvers/tests/test_solveset.py::test_solveset",
"sympy/solvers/tests/test_solveset.py::test_conditonset",
"sympy/solvers/tests/test_solveset.py::test_solveset_domain",
"sympy/solvers/tests/test_solveset.py::test_improve_coverage",
"sympy/solvers/tests/test_solveset.py::test_issue_9522",
"sympy/solvers/tests/test_solveset.py::test_linear_eq_to_matrix",
"sympy/solvers/tests/test_solveset.py::test_linsolve",
"sympy/solvers/tests/test_solveset.py::test_issue_9556",
"sympy/solvers/tests/test_solveset.py::test_issue_9611",
"sympy/solvers/tests/test_solveset.py::test_issue_9557",
"sympy/solvers/tests/test_solveset.py::test_issue_9778"
] | [] | BSD | 216 |
|
enthought__okonomiyaki-91 | 231ef105738438f69c19c1805d9df1e410b9630a | 2015-08-24 15:34:23 | 5faaff42f15508429bcbd588ccadb4a6e5bbaf97 | diff --git a/CHANGELOG b/CHANGELOG
index 5e8f7ce..b21e68e 100644
--- a/CHANGELOG
+++ b/CHANGELOG
@@ -5,6 +5,8 @@ Improvements:
* EnpkgVersion.from_string now handles versions of the form `1.3.0`, with the
build number being implicitly 0.
+ * EggMetadata.from_egg now handles eggs built for RedHat Enterprise
+ Linux 3 (#88).
Internals:
diff --git a/okonomiyaki/platforms/epd_platform.py b/okonomiyaki/platforms/epd_platform.py
index ec327a9..433605a 100644
--- a/okonomiyaki/platforms/epd_platform.py
+++ b/okonomiyaki/platforms/epd_platform.py
@@ -136,7 +136,9 @@ class EPDPlatform(HasTraits):
elif platform == "win32":
epd_name = "win"
elif platform.startswith("linux"):
- if osdist in (None, "RedHat_5"):
+ if osdist == "RedHat_3":
+ epd_name = "rh3"
+ elif osdist in (None, "RedHat_5"):
epd_name = "rh5"
elif osdist == "RedHat_6":
epd_name = "rh6"
| Okonomiyaki fails to parse existing RedHat3-built eggs
```python
metadata = file_formats.EggMetadata.from_egg(path)
File "okonomiyaki/file_formats/_egg_info.py", line 627, in from_egg
spec_depend = LegacySpecDepend.from_egg(path_or_file)
File "okonomiyaki/file_formats/_egg_info.py", line 387, in from_egg
return cls.from_string(spec_depend_string)
File "okonomiyaki/file_formats/_egg_info.py", line 391, in from_string
data, epd_platform = _normalized_info_from_string(spec_depend_string)
File "okonomiyaki/file_formats/_egg_info.py", line 562, in _normalized_info_from_string
epd_platform = _epd_platform_from_raw_spec(data)
File "okonomiyaki/file_formats/_egg_info.py", line 307, in _epd_platform_from_raw_spec
platform_string, osdist_string, arch_string
File "okonomiyaki/platforms/epd_platform.py", line 135, in _from_spec_depend_data
raise ValueError(msg)
ValueError: Unrecognized platform/osdist combination: 'linux2'/'RedHat_3'
``` | enthought/okonomiyaki | diff --git a/okonomiyaki/platforms/tests/test_epd_platform.py b/okonomiyaki/platforms/tests/test_epd_platform.py
index e2d8729..b566340 100644
--- a/okonomiyaki/platforms/tests/test_epd_platform.py
+++ b/okonomiyaki/platforms/tests/test_epd_platform.py
@@ -327,6 +327,8 @@ class TestGuessEPDPlatform(unittest.TestCase):
examples = (
(("linux2", None, "x86"),
EPDPlatform.from_epd_string("rh5-32"),),
+ (("linux2", "RedHat_3", "x86"),
+ EPDPlatform.from_epd_string("rh3-32"),),
(("linux2", "RedHat_5", "x86"),
EPDPlatform.from_epd_string("rh5-32"),),
(("linux2", "RedHat_5", "amd64"),
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 3,
"issue_text_score": 1,
"test_score": 0
},
"num_modified_files": 2
} | 0.9 | {
"env_vars": null,
"env_yml_path": [],
"install": "pip install -e .[dev]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest"
],
"pre_install": [],
"python": "3.7",
"reqs_path": [
"dev_requirements.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | certifi @ file:///croot/certifi_1671487769961/work/certifi
coverage==7.2.7
docutils==0.20.1
enum34==1.1.10
exceptiongroup==1.2.2
flake8==5.0.4
haas==0.9.0
importlib-metadata==4.2.0
iniconfig==2.0.0
mccabe==0.7.0
mock==1.0.1
-e git+https://github.com/enthought/okonomiyaki.git@231ef105738438f69c19c1805d9df1e410b9630a#egg=okonomiyaki
packaging==24.0
pbr==6.1.1
pluggy==1.2.0
pycodestyle==2.9.1
pyflakes==2.5.0
pytest==7.4.4
statistics==1.0.3.5
stevedore==3.5.2
tomli==2.0.1
typing_extensions==4.7.1
zipfile2==0.0.12
zipp==3.15.0
| name: okonomiyaki
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2022.12.7=py37h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- pip=22.3.1=py37h06a4308_0
- python=3.7.16=h7a1cb2a_0
- readline=8.2=h5eee18b_0
- setuptools=65.6.3=py37h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- wheel=0.38.4=py37h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- coverage==7.2.7
- docutils==0.20.1
- enum34==1.1.10
- exceptiongroup==1.2.2
- flake8==5.0.4
- haas==0.9.0
- importlib-metadata==4.2.0
- iniconfig==2.0.0
- mccabe==0.7.0
- mock==1.0.1
- packaging==24.0
- pbr==6.1.1
- pluggy==1.2.0
- pycodestyle==2.9.1
- pyflakes==2.5.0
- pytest==7.4.4
- statistics==1.0.3.5
- stevedore==3.5.2
- tomli==2.0.1
- typing-extensions==4.7.1
- zipfile2==0.0.12
- zipp==3.15.0
prefix: /opt/conda/envs/okonomiyaki
| [
"okonomiyaki/platforms/tests/test_epd_platform.py::TestGuessEPDPlatform::test_from_spec_depend_data"
] | [] | [
"okonomiyaki/platforms/tests/test_epd_platform.py::TestEPDPlatform::test_epd_platform_from_string",
"okonomiyaki/platforms/tests/test_epd_platform.py::TestEPDPlatform::test_epd_platform_from_string_new_arch",
"okonomiyaki/platforms/tests/test_epd_platform.py::TestEPDPlatform::test_epd_platform_from_string_new_names",
"okonomiyaki/platforms/tests/test_epd_platform.py::TestEPDPlatform::test_epd_platform_from_string_new_names_underscore",
"okonomiyaki/platforms/tests/test_epd_platform.py::TestEPDPlatform::test_from_running_python",
"okonomiyaki/platforms/tests/test_epd_platform.py::TestEPDPlatform::test_from_running_system",
"okonomiyaki/platforms/tests/test_epd_platform.py::TestEPDPlatform::test_guessed_epd_platform",
"okonomiyaki/platforms/tests/test_epd_platform.py::TestEPDPlatform::test_short_names_consistency",
"okonomiyaki/platforms/tests/test_epd_platform.py::TestEPDPlatformApplies::test_all",
"okonomiyaki/platforms/tests/test_epd_platform.py::TestEPDPlatformApplies::test_applies_rh",
"okonomiyaki/platforms/tests/test_epd_platform.py::TestEPDPlatformApplies::test_current_linux",
"okonomiyaki/platforms/tests/test_epd_platform.py::TestEPDPlatformApplies::test_current_windows",
"okonomiyaki/platforms/tests/test_epd_platform.py::TestGuessEPDPlatform::test_from_epd_platform_string",
"okonomiyaki/platforms/tests/test_epd_platform.py::TestGuessEPDPlatform::test_from_epd_platform_string_invalid",
"okonomiyaki/platforms/tests/test_epd_platform.py::TestGuessEPDPlatform::test_guess_darwin_platform",
"okonomiyaki/platforms/tests/test_epd_platform.py::TestGuessEPDPlatform::test_guess_linux2_platform",
"okonomiyaki/platforms/tests/test_epd_platform.py::TestGuessEPDPlatform::test_guess_linux2_unsupported",
"okonomiyaki/platforms/tests/test_epd_platform.py::TestGuessEPDPlatform::test_guess_solaris_unsupported",
"okonomiyaki/platforms/tests/test_epd_platform.py::TestGuessEPDPlatform::test_guess_win32_platform"
] | [] | BSD License | 217 |
|
sympy__sympy-9857 | a76b3faf10c928e0fa6e543740861ac8eec6c20c | 2015-08-24 18:37:09 | 0241b35cae5f2adc04dc37b25f7dc9c5f00bd746 | diff --git a/sympy/sets/conditionset.py b/sympy/sets/conditionset.py
index c3627b9486..2e0c3daaf5 100644
--- a/sympy/sets/conditionset.py
+++ b/sympy/sets/conditionset.py
@@ -1,5 +1,6 @@
from __future__ import print_function, division
+from sympy import S
from sympy.core.basic import Basic
from sympy.logic.boolalg import And
from sympy.sets.sets import (Set, Interval, Intersection, EmptySet, Union,
@@ -28,6 +29,10 @@ class ConditionSet(Set):
True
"""
def __new__(cls, condition, base_set):
+ if condition.args[1] is S.false:
+ return S.EmptySet
+ if condition.args[1] is S.true:
+ return base_set
return Basic.__new__(cls, condition, base_set)
condition = property(lambda self: self.args[0])
| solveset(Abs(sin(x)) + 1, x, S.Reals) returns `Non-Empty`
```
>>> solveset(Abs(sin(x)) + 1, x, S.Reals)
{x | x ∈ ℝ ∧ False } # this should return S.EmptySet
```
While the `Eq` version works correctly
```
>>> solveset(Eq(Abs(sin(x)), -1), x, S.Reals)
∅
```
The reason for this i think is(i am guessing):
```
>>> imageset(Lambda(n, S.false), S.Naturals)
{False | n ∈ ℕ }
``` | sympy/sympy | diff --git a/sympy/sets/tests/test_conditionset.py b/sympy/sets/tests/test_conditionset.py
index c7ba55c399..368621310f 100644
--- a/sympy/sets/tests/test_conditionset.py
+++ b/sympy/sets/tests/test_conditionset.py
@@ -1,5 +1,5 @@
from sympy.sets import (ConditionSet, Intersection)
-from sympy import (Symbol, Eq, S, sin, pi, Lambda, Interval)
+from sympy import (Symbol, Eq, S, Abs, sin, pi, Lambda, Interval)
x = Symbol('x')
@@ -19,3 +19,8 @@ def test_CondSet_intersect():
other_domain = Interval(0, 3, False, False)
output_conditionset = ConditionSet(Lambda(x, x**2 > 4), Interval(1, 3, False, False))
assert Intersection(input_conditionset, other_domain) == output_conditionset
+
+
+def test_issue_9849():
+ assert ConditionSet(Lambda(x, Eq(x, x)), S.Naturals) == S.Naturals
+ assert ConditionSet(Lambda(x, Eq(Abs(sin(x)), -1)), S.Naturals) == S.EmptySet
diff --git a/sympy/solvers/tests/test_solveset.py b/sympy/solvers/tests/test_solveset.py
index 44f3548acc..fae00b37ed 100644
--- a/sympy/solvers/tests/test_solveset.py
+++ b/sympy/solvers/tests/test_solveset.py
@@ -1009,3 +1009,7 @@ def test_issue_9778():
@XFAIL
def test_issue_failing_pow():
assert solveset(x**(S(3)/2) + 4, x, S.Reals) == S.EmptySet
+
+
+def test_issue_9849():
+ assert solveset(Abs(sin(x)) + 1, x, S.Reals) == S.EmptySet
| {
"commit_name": "head_commit",
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true,
"llm_score": {
"difficulty_score": 1,
"issue_text_score": 0,
"test_score": 0
},
"num_modified_files": 1
} | 0.7 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "pytest",
"pip_packages": [
"mpmath>=0.19",
"pytest"
],
"pre_install": [
"apt-get update",
"apt-get install -y python3-dev python3-pip"
],
"python": "3.6",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | attrs @ file:///opt/conda/conda-bld/attrs_1642510447205/work
certifi==2021.5.30
importlib-metadata @ file:///tmp/build/80754af9/importlib-metadata_1631916693255/work
iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work
more-itertools @ file:///tmp/build/80754af9/more-itertools_1637733554872/work
mpmath==1.3.0
packaging @ file:///tmp/build/80754af9/packaging_1637314298585/work
pluggy @ file:///tmp/build/80754af9/pluggy_1615976315926/work
py @ file:///opt/conda/conda-bld/py_1644396412707/work
pyparsing @ file:///tmp/build/80754af9/pyparsing_1635766073266/work
pytest==6.2.4
-e git+https://github.com/sympy/sympy.git@a76b3faf10c928e0fa6e543740861ac8eec6c20c#egg=sympy
toml @ file:///tmp/build/80754af9/toml_1616166611790/work
typing_extensions @ file:///opt/conda/conda-bld/typing_extensions_1647553014482/work
zipp @ file:///tmp/build/80754af9/zipp_1633618647012/work
| name: sympy
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- attrs=21.4.0=pyhd3eb1b0_0
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2021.5.30=py36h06a4308_0
- importlib-metadata=4.8.1=py36h06a4308_0
- importlib_metadata=4.8.1=hd3eb1b0_0
- iniconfig=1.1.1=pyhd3eb1b0_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.3=he6710b0_2
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- more-itertools=8.12.0=pyhd3eb1b0_0
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- packaging=21.3=pyhd3eb1b0_0
- pip=21.2.2=py36h06a4308_0
- pluggy=0.13.1=py36h06a4308_0
- py=1.11.0=pyhd3eb1b0_0
- pyparsing=3.0.4=pyhd3eb1b0_0
- pytest=6.2.4=py36h06a4308_2
- python=3.6.13=h12debd9_1
- readline=8.2=h5eee18b_0
- setuptools=58.0.4=py36h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- toml=0.10.2=pyhd3eb1b0_0
- typing_extensions=4.1.1=pyh06a4308_0
- wheel=0.37.1=pyhd3eb1b0_0
- xz=5.6.4=h5eee18b_1
- zipp=3.6.0=pyhd3eb1b0_0
- zlib=1.2.13=h5eee18b_1
- pip:
- mpmath==1.3.0
prefix: /opt/conda/envs/sympy
| [
"sympy/sets/tests/test_conditionset.py::test_issue_9849",
"sympy/solvers/tests/test_solveset.py::test_issue_9849"
] | [] | [
"sympy/sets/tests/test_conditionset.py::test_CondSet",
"sympy/sets/tests/test_conditionset.py::test_CondSet_intersect",
"sympy/solvers/tests/test_solveset.py::test_invert_real",
"sympy/solvers/tests/test_solveset.py::test_invert_complex",
"sympy/solvers/tests/test_solveset.py::test_domain_check",
"sympy/solvers/tests/test_solveset.py::test_is_function_class_equation",
"sympy/solvers/tests/test_solveset.py::test_garbage_input",
"sympy/solvers/tests/test_solveset.py::test_solve_mul",
"sympy/solvers/tests/test_solveset.py::test_solve_invert",
"sympy/solvers/tests/test_solveset.py::test_errorinverses",
"sympy/solvers/tests/test_solveset.py::test_solve_polynomial",
"sympy/solvers/tests/test_solveset.py::test_return_root_of",
"sympy/solvers/tests/test_solveset.py::test__has_rational_power",
"sympy/solvers/tests/test_solveset.py::test_solveset_sqrt_1",
"sympy/solvers/tests/test_solveset.py::test_solveset_sqrt_2",
"sympy/solvers/tests/test_solveset.py::test_solve_sqrt_3",
"sympy/solvers/tests/test_solveset.py::test_solve_polynomial_symbolic_param",
"sympy/solvers/tests/test_solveset.py::test_solve_rational",
"sympy/solvers/tests/test_solveset.py::test_solveset_real_gen_is_pow",
"sympy/solvers/tests/test_solveset.py::test_no_sol",
"sympy/solvers/tests/test_solveset.py::test_sol_zero_real",
"sympy/solvers/tests/test_solveset.py::test_no_sol_rational_extragenous",
"sympy/solvers/tests/test_solveset.py::test_solve_polynomial_cv_1a",
"sympy/solvers/tests/test_solveset.py::test_solveset_real_rational",
"sympy/solvers/tests/test_solveset.py::test_solveset_real_log",
"sympy/solvers/tests/test_solveset.py::test_poly_gens",
"sympy/solvers/tests/test_solveset.py::test_solve_abs",
"sympy/solvers/tests/test_solveset.py::test_real_imag_splitting",
"sympy/solvers/tests/test_solveset.py::test_units",
"sympy/solvers/tests/test_solveset.py::test_solve_only_exp_1",
"sympy/solvers/tests/test_solveset.py::test_atan2",
"sympy/solvers/tests/test_solveset.py::test_piecewise",
"sympy/solvers/tests/test_solveset.py::test_solveset_complex_polynomial",
"sympy/solvers/tests/test_solveset.py::test_sol_zero_complex",
"sympy/solvers/tests/test_solveset.py::test_solveset_complex_rational",
"sympy/solvers/tests/test_solveset.py::test_solveset_complex_exp",
"sympy/solvers/tests/test_solveset.py::test_solve_complex_log",
"sympy/solvers/tests/test_solveset.py::test_solve_complex_sqrt",
"sympy/solvers/tests/test_solveset.py::test_solveset_complex_tan",
"sympy/solvers/tests/test_solveset.py::test_solve_trig",
"sympy/solvers/tests/test_solveset.py::test_solve_invalid_sol",
"sympy/solvers/tests/test_solveset.py::test_solve_complex_unsolvable",
"sympy/solvers/tests/test_solveset.py::test_solveset",
"sympy/solvers/tests/test_solveset.py::test_conditonset",
"sympy/solvers/tests/test_solveset.py::test_solveset_domain",
"sympy/solvers/tests/test_solveset.py::test_improve_coverage",
"sympy/solvers/tests/test_solveset.py::test_issue_9522",
"sympy/solvers/tests/test_solveset.py::test_linear_eq_to_matrix",
"sympy/solvers/tests/test_solveset.py::test_linsolve",
"sympy/solvers/tests/test_solveset.py::test_issue_9556",
"sympy/solvers/tests/test_solveset.py::test_issue_9611",
"sympy/solvers/tests/test_solveset.py::test_issue_9557",
"sympy/solvers/tests/test_solveset.py::test_issue_9778"
] | [] | BSD | 218 |
|
Yelp__swagger_spec_validator-36 | 0d6a8a94a5ce2ea1a5b19bd9a07cad85192b038c | 2015-08-24 21:30:09 | 0d6a8a94a5ce2ea1a5b19bd9a07cad85192b038c | diff --git a/CHANGELOG b/CHANGELOG
index 1624c2b..c55f47a 100644
--- a/CHANGELOG
+++ b/CHANGELOG
@@ -1,3 +1,7 @@
+Version 1.1.0 (2015-08-24)
+-------------
+ * Validate crossrefs - #33, #34
+
Version 1.0.12 (2015-07-02)
-------------
* Handle API level parameters - #29
diff --git a/swagger_spec_validator/__about__.py b/swagger_spec_validator/__about__.py
index 2ef8969..75e6007 100644
--- a/swagger_spec_validator/__about__.py
+++ b/swagger_spec_validator/__about__.py
@@ -7,7 +7,7 @@ __title__ = "swagger_spec_validator"
__summary__ = "Validation of Swagger specifications"
__uri__ = "http://github.com/Yelp/swagger_spec_validator"
-__version__ = "1.0.12"
+__version__ = "1.1.0"
__author__ = "John Billings"
__email__ = "[email protected]"
diff --git a/swagger_spec_validator/util.py b/swagger_spec_validator/util.py
index 1975850..ff60fc3 100644
--- a/swagger_spec_validator/util.py
+++ b/swagger_spec_validator/util.py
@@ -44,7 +44,9 @@ def validate_spec_url(spec_url):
:param spec_url:
For Swagger 1.2, this is the URL to the resource listing in api-docs.
- For Swagger 2.0, this is the URL to swagger.json in api-docs.
+ For Swagger 2.0, this is the URL to swagger.json in api-docs. If given
+ as `file://` this must be an absolute url for
+ cross-refs to work correctly.
"""
spec_json = load_json(spec_url)
validator = get_validator(spec_json, spec_url)
diff --git a/swagger_spec_validator/validator20.py b/swagger_spec_validator/validator20.py
index e1d1a94..4882f24 100644
--- a/swagger_spec_validator/validator20.py
+++ b/swagger_spec_validator/validator20.py
@@ -21,16 +21,17 @@ def validate_spec_url(spec_url):
:raises: :py:class:`swagger_spec_validator.SwaggerValidationError`
"""
log.info('Validating %s' % spec_url)
- validate_spec(load_json(spec_url))
+ validate_spec(load_json(spec_url), spec_url)
-def validate_spec(spec_json, _spec_url=None):
+def validate_spec(spec_json, spec_url=None):
"""Validates a Swagger 2.0 API Specification given a Swagger Spec.
:param spec_json: the json dict of the swagger spec.
:type spec_json: dict
- :param _spec_url: url serving the spec json (currently not used)
- :type _spec_url: string
+ :param spec_url: url serving the spec json. Used for dereferencing
+ relative refs. eg: file:///foo/swagger.json
+ :type spec_url: string
:returns: `None` in case of success, otherwise raises an exception.
:raises: :py:class:`swagger_spec_validator.SwaggerValidationError`
"""
@@ -38,7 +39,8 @@ def validate_spec(spec_json, _spec_url=None):
# Dereference all $refs so we don't have to deal with them
fix_malformed_model_refs(spec_json)
- spec_json = jsonref.JsonRef.replace_refs(spec_json)
+ spec_json = jsonref.JsonRef.replace_refs(spec_json,
+ base_uri=spec_url or '')
replace_jsonref_proxies(spec_json)
# TODO: Extract 'parameters', 'responses' from the spec as well.
@@ -159,7 +161,9 @@ def replace_jsonref_proxies(obj):
fragment[k] = v.__subject__
descend(fragment[k])
elif isinstance(fragment, list):
- for element in fragment:
+ for index, element in enumerate(fragment):
+ if isinstance(element, jsonref.JsonRef):
+ fragment[index] = element.__subject__
descend(element)
descend(obj)
| Make use of spec_url being passed to `validate_spec`
`spec_url` [here](https://github.com/Yelp/swagger_spec_validator/blob/master/swagger_spec_validator/validator20.py#L27) is not getting used as of now. Use it to resolve `$ref`s. | Yelp/swagger_spec_validator | diff --git a/tests/data/v2.0/pingpong.json b/tests/data/v2.0/pingpong.json
new file mode 100644
index 0000000..541d9ee
--- /dev/null
+++ b/tests/data/v2.0/pingpong.json
@@ -0,0 +1,21 @@
+{
+ "ping": {
+ "get": {
+ "operationId": "ping",
+ "parameters": [
+ {
+ "name": "pung",
+ "in": "query",
+ "description": "true or false",
+ "type": "boolean"
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "Successful response"
+ }
+ }
+ }
+ }
+}
+
diff --git a/tests/data/v2.0/relative_ref.json b/tests/data/v2.0/relative_ref.json
new file mode 100644
index 0000000..0c9f600
--- /dev/null
+++ b/tests/data/v2.0/relative_ref.json
@@ -0,0 +1,19 @@
+{
+ "swagger": "2.0",
+ "info": {
+ "version": "1.0.0",
+ "title": "Simple"
+ },
+ "tags": [
+ {
+ "name": "pingpong",
+ "description": "pingpong related specs"
+ }
+ ],
+ "paths": {
+ "/ping": {
+ "$ref": "pingpong.json#/ping"
+ }
+ }
+}
+
diff --git a/tests/validator20/validate_spec_url_test.py b/tests/validator20/validate_spec_url_test.py
index 890d7d2..4112eeb 100644
--- a/tests/validator20/validate_spec_url_test.py
+++ b/tests/validator20/validate_spec_url_test.py
@@ -1,5 +1,6 @@
import json
import mock
+import os
import pytest
from swagger_spec_validator.common import SwaggerValidationError
@@ -14,6 +15,13 @@ def test_success(petstore_contents):
mock_load_json.assert_called_once_with('http://localhost/api-docs')
+def test_success_crossref_url():
+ my_dir = os.path.abspath(os.path.dirname(__file__))
+ urlpath = "file://{0}".format(os.path.join(
+ my_dir, "../data/v2.0/relative_ref.json"))
+ validate_spec_url(urlpath)
+
+
def test_raise_SwaggerValidationError_on_urlopen_error():
with pytest.raises(SwaggerValidationError) as excinfo:
validate_spec_url('http://foo')
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 0,
"issue_text_score": 0,
"test_score": 0
},
"num_modified_files": 4
} | 1.0 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[dev]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "pytest",
"pip_packages": [
"pytest",
"flake8",
"mock",
"coverage"
],
"pre_install": null,
"python": "3.9",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | attrs==25.3.0
coverage==7.8.0
exceptiongroup @ file:///croot/exceptiongroup_1706031385326/work
flake8==7.2.0
iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work
jsonref==1.1.0
jsonschema==4.23.0
jsonschema-specifications==2024.10.1
mccabe==0.7.0
mock==5.2.0
packaging @ file:///croot/packaging_1734472117206/work
pluggy @ file:///croot/pluggy_1733169602837/work
pycodestyle==2.13.0
pyflakes==3.3.2
pytest @ file:///croot/pytest_1738938843180/work
referencing==0.36.2
rpds-py==0.24.0
six==1.17.0
-e git+https://github.com/Yelp/swagger_spec_validator.git@0d6a8a94a5ce2ea1a5b19bd9a07cad85192b038c#egg=swagger_spec_validator
tomli @ file:///opt/conda/conda-bld/tomli_1657175507142/work
typing_extensions==4.13.0
| name: swagger_spec_validator
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- exceptiongroup=1.2.0=py39h06a4308_0
- iniconfig=1.1.1=pyhd3eb1b0_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=3.0.16=h5eee18b_0
- packaging=24.2=py39h06a4308_0
- pip=25.0=py39h06a4308_0
- pluggy=1.5.0=py39h06a4308_0
- pytest=8.3.4=py39h06a4308_0
- python=3.9.21=he870216_1
- readline=8.2=h5eee18b_0
- setuptools=75.8.0=py39h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- tomli=2.0.1=py39h06a4308_0
- tzdata=2025a=h04d1e81_0
- wheel=0.45.1=py39h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- attrs==25.3.0
- coverage==7.8.0
- flake8==7.2.0
- jsonref==1.1.0
- jsonschema==4.23.0
- jsonschema-specifications==2024.10.1
- mccabe==0.7.0
- mock==5.2.0
- pycodestyle==2.13.0
- pyflakes==3.3.2
- referencing==0.36.2
- rpds-py==0.24.0
- six==1.17.0
- typing-extensions==4.13.0
prefix: /opt/conda/envs/swagger_spec_validator
| [
"tests/validator20/validate_spec_url_test.py::test_success_crossref_url"
] | [
"tests/validator20/validate_spec_url_test.py::test_raise_SwaggerValidationError_on_urlopen_error"
] | [
"tests/validator20/validate_spec_url_test.py::test_success"
] | [] | Apache License 2.0 | 219 |
|
chimpler__pyhocon-42 | cfe9a3c34f0fb5aabfa7f5257b573058be84e490 | 2015-08-24 23:27:53 | 4683937b1d195ce2f53ca78987571e41bfe273e7 | diff --git a/pyhocon/config_parser.py b/pyhocon/config_parser.py
index a3a2191..1c966d6 100644
--- a/pyhocon/config_parser.py
+++ b/pyhocon/config_parser.py
@@ -83,6 +83,16 @@ class ConfigFactory(object):
"""
return ConfigParser().parse(content, basedir, resolve)
+ @staticmethod
+ def from_dict(dictionary):
+ """Convert dictionary (and ordered dictionary) into a ConfigTree
+ :param dictionary: dictionary to convert
+ :type dictionary: dict
+ :return: Config object
+ :type return: Config
+ """
+ return ConfigTree(dictionary)
+
class ConfigParser(object):
"""
diff --git a/pyhocon/config_tree.py b/pyhocon/config_tree.py
index 92b98a0..a11433d 100644
--- a/pyhocon/config_tree.py
+++ b/pyhocon/config_tree.py
@@ -18,6 +18,7 @@ class ConfigTree(OrderedDict):
def __init__(self, *args, **kwds):
super(ConfigTree, self).__init__(*args, **kwds)
+
for key, value in self.items():
if isinstance(value, ConfigValues):
value.parent = self
diff --git a/pyhocon/tool.py b/pyhocon/tool.py
index 267a862..35010bd 100644
--- a/pyhocon/tool.py
+++ b/pyhocon/tool.py
@@ -9,6 +9,7 @@ LOG_FORMAT = '%(asctime)s %(levelname)s: %(message)s'
class HOCONConverter(object):
+
@staticmethod
def to_json(config, indent=2, level=0):
"""Convert HOCON input into a JSON output
| How to dump HOCON file?
Hi,
Just wonder how to do this with pyhocon?
https://marcinkubala.wordpress.com/2013/10/09/typesafe-config-hocon/
Thanks. | chimpler/pyhocon | diff --git a/tests/test_config_parser.py b/tests/test_config_parser.py
index 16bd518..4c02aed 100644
--- a/tests/test_config_parser.py
+++ b/tests/test_config_parser.py
@@ -3,6 +3,10 @@ from pyparsing import ParseSyntaxException, ParseException
import pytest
from pyhocon import ConfigFactory, ConfigSubstitutionException
from pyhocon.exceptions import ConfigMissingException, ConfigWrongTypeException
+try: # pragma: no cover
+ from collections import OrderedDict
+except ImportError: # pragma: no cover
+ from ordereddict import OrderedDict
class TestConfigParser(object):
@@ -1143,3 +1147,22 @@ with-escaped-newline-escape-sequence: \"\"\"
assert config['with-escaped-backslash'] == '\n\\\\\n'
assert config['with-newline-escape-sequence'] == '\n\\n\n'
assert config['with-escaped-newline-escape-sequence'] == '\n\\\\n\n'
+
+ def test_from_dict_with_dict(self):
+ d = {
+ 'banana': 3,
+ 'apple': 4,
+ 'pear': 1,
+ 'orange': 2,
+ }
+ config = ConfigFactory.from_dict(d)
+ assert config == d
+
+ def test_from_dict_with_ordered_dict(self):
+ d = OrderedDict()
+ d['banana'] = 3
+ d['apple'] = 4
+ d['pear'] = 1
+ d['orange'] = 2
+ config = ConfigFactory.from_dict(d)
+ assert config == d
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_short_problem_statement",
"has_hyperlinks",
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 2,
"issue_text_score": 3,
"test_score": 3
},
"num_modified_files": 3
} | 0.3 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[dev]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest"
],
"pre_install": null,
"python": "3.9",
"reqs_path": [
"requirements/base.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | exceptiongroup==1.2.2
iniconfig==2.1.0
packaging==24.2
pluggy==1.5.0
-e git+https://github.com/chimpler/pyhocon.git@cfe9a3c34f0fb5aabfa7f5257b573058be84e490#egg=pyhocon
pyparsing==2.0.3
pytest==8.3.5
tomli==2.2.1
| name: pyhocon
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=3.0.16=h5eee18b_0
- pip=25.0=py39h06a4308_0
- python=3.9.21=he870216_1
- readline=8.2=h5eee18b_0
- setuptools=75.8.0=py39h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- tzdata=2025a=h04d1e81_0
- wheel=0.45.1=py39h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- exceptiongroup==1.2.2
- iniconfig==2.1.0
- packaging==24.2
- pluggy==1.5.0
- pyparsing==2.0.3
- pytest==8.3.5
- tomli==2.2.1
prefix: /opt/conda/envs/pyhocon
| [
"tests/test_config_parser.py::TestConfigParser::test_from_dict_with_dict",
"tests/test_config_parser.py::TestConfigParser::test_from_dict_with_ordered_dict"
] | [] | [
"tests/test_config_parser.py::TestConfigParser::test_parse_simple_value",
"tests/test_config_parser.py::TestConfigParser::test_parse_with_enclosing_brace",
"tests/test_config_parser.py::TestConfigParser::test_parse_with_enclosing_square_bracket",
"tests/test_config_parser.py::TestConfigParser::test_quoted_key_with_dots",
"tests/test_config_parser.py::TestConfigParser::test_comma_to_separate_expr",
"tests/test_config_parser.py::TestConfigParser::test_dict_merge",
"tests/test_config_parser.py::TestConfigParser::test_parse_with_comments",
"tests/test_config_parser.py::TestConfigParser::test_missing_config",
"tests/test_config_parser.py::TestConfigParser::test_parse_null",
"tests/test_config_parser.py::TestConfigParser::test_parse_empty",
"tests/test_config_parser.py::TestConfigParser::test_parse_override",
"tests/test_config_parser.py::TestConfigParser::test_concat_dict",
"tests/test_config_parser.py::TestConfigParser::test_concat_string",
"tests/test_config_parser.py::TestConfigParser::test_concat_list",
"tests/test_config_parser.py::TestConfigParser::test_bad_concat",
"tests/test_config_parser.py::TestConfigParser::test_string_substitutions",
"tests/test_config_parser.py::TestConfigParser::test_int_substitutions",
"tests/test_config_parser.py::TestConfigParser::test_cascade_string_substitutions",
"tests/test_config_parser.py::TestConfigParser::test_dict_substitutions",
"tests/test_config_parser.py::TestConfigParser::test_list_substitutions",
"tests/test_config_parser.py::TestConfigParser::test_non_existent_substitution",
"tests/test_config_parser.py::TestConfigParser::test_non_compatible_substitution",
"tests/test_config_parser.py::TestConfigParser::test_concat_multi_line_string",
"tests/test_config_parser.py::TestConfigParser::test_concat_multi_line_list",
"tests/test_config_parser.py::TestConfigParser::test_concat_multi_line_dict",
"tests/test_config_parser.py::TestConfigParser::test_parse_URL_from_samples",
"tests/test_config_parser.py::TestConfigParser::test_include_dict_from_samples",
"tests/test_config_parser.py::TestConfigParser::test_list_of_dicts",
"tests/test_config_parser.py::TestConfigParser::test_list_of_lists",
"tests/test_config_parser.py::TestConfigParser::test_list_of_dicts_with_merge",
"tests/test_config_parser.py::TestConfigParser::test_list_of_lists_with_merge",
"tests/test_config_parser.py::TestConfigParser::test_invalid_assignment",
"tests/test_config_parser.py::TestConfigParser::test_invalid_dict",
"tests/test_config_parser.py::TestConfigParser::test_include_list",
"tests/test_config_parser.py::TestConfigParser::test_include_dict",
"tests/test_config_parser.py::TestConfigParser::test_include_substitution",
"tests/test_config_parser.py::TestConfigParser::test_substitution_override",
"tests/test_config_parser.py::TestConfigParser::test_substitution_flat_override",
"tests/test_config_parser.py::TestConfigParser::test_substitution_nested_override",
"tests/test_config_parser.py::TestConfigParser::test_optional_substitution",
"tests/test_config_parser.py::TestConfigParser::test_substitution_cycle",
"tests/test_config_parser.py::TestConfigParser::test_assign_number_with_eol",
"tests/test_config_parser.py::TestConfigParser::test_assign_strings_with_eol",
"tests/test_config_parser.py::TestConfigParser::test_assign_list_numbers_with_eol",
"tests/test_config_parser.py::TestConfigParser::test_assign_list_strings_with_eol",
"tests/test_config_parser.py::TestConfigParser::test_assign_dict_strings_with_equal_sign_with_eol",
"tests/test_config_parser.py::TestConfigParser::test_assign_dict_strings_no_equal_sign_with_eol",
"tests/test_config_parser.py::TestConfigParser::test_substitutions_overwrite",
"tests/test_config_parser.py::TestConfigParser::test_fallback_substitutions_overwrite",
"tests/test_config_parser.py::TestConfigParser::test_fallback_substitutions_overwrite_file",
"tests/test_config_parser.py::TestConfigParser::test_one_line_quote_escape",
"tests/test_config_parser.py::TestConfigParser::test_multi_line_escape"
] | [] | Apache License 2.0 | 220 |
|
mapbox__mapbox-sdk-py-21 | 7859e5abc3ad69a001a24bb9ae66dcdd38da064c | 2015-08-25 17:27:19 | 7859e5abc3ad69a001a24bb9ae66dcdd38da064c | diff --git a/mapbox/compat.py b/mapbox/compat.py
index baf551f..a46774e 100644
--- a/mapbox/compat.py
+++ b/mapbox/compat.py
@@ -4,7 +4,4 @@ import itertools
import sys
-if sys.version_info < (3,):
- map = itertools.imap
-else:
- map = map
+map = itertools.imap if sys.version_info < (3,) else map
diff --git a/mapbox/scripts/cli.py b/mapbox/scripts/cli.py
index 7a9f867..5159758 100644
--- a/mapbox/scripts/cli.py
+++ b/mapbox/scripts/cli.py
@@ -23,12 +23,27 @@ def configure_logging(verbosity):
@click.group()
@cligj.verbose_opt
@cligj.quiet_opt
[email protected]('--access-token', help="Your Mapbox access token.")
@click.version_option(version=mapbox.__version__, message='%(version)s')
@click.pass_context
-def main_group(ctx, verbose, quiet):
- """Command line interface to Mapbox web services.
+def main_group(ctx, verbose, quiet, access_token):
+ """This is the command line interface to Mapbox web services.
+
+ Mapbox web services require an access token. Your token is shown
+ on the https://www.mapbox.com/developers/api/ page when you are
+ logged in. The token can be provided on the command line
+
+ $ mbx --access-token MY_TOKEN ...
+
+ or as an environment variable.
+
+ \b
+ $ export MapboxAccessToken=MY_TOKEN
+ $ mbx ...
+
"""
verbosity = verbose - quiet
configure_logging(verbosity)
ctx.obj = {}
ctx.obj['verbosity'] = verbosity
+ ctx.obj['access_token'] = access_token
diff --git a/mapbox/scripts/geocoder.py b/mapbox/scripts/geocoder.py
index 3348b7f..4705242 100644
--- a/mapbox/scripts/geocoder.py
+++ b/mapbox/scripts/geocoder.py
@@ -34,15 +34,14 @@ def coords_from_query(query):
@click.command(short_help="Geocode an address or coordinates.")
@click.argument('query', default='-', required=False)
[email protected]('--access-token', help="Your access token")
@click.option(
'--forward/--reverse',
default=True,
help="Perform a forward or reverse geocode. [default: forward]")
@click.pass_context
-def geocode(ctx, query, access_token, forward):
- """Get coordinates for an address (forward geocoding) or addresses
- for coordinates (reverse geocoding)
+def geocode(ctx, query, forward):
+ """This command gets coordinates for an address (forward mode) or
+ addresses for coordinates (reverse mode).
In forward (the default) mode the query argument shall be an address
such as '1600 pennsylvania ave nw'.
@@ -57,6 +56,8 @@ def geocode(ctx, query, access_token, forward):
"""
verbosity = (ctx.obj and ctx.obj.get('verbosity')) or 2
logger = logging.getLogger('mapbox')
+
+ access_token = (ctx.obj and ctx.obj.get('access_token')) or None
geocoder = mapbox.Geocoder(access_token=access_token)
if forward:
| Move --access-token option from command to group
New commands won't have to implement the option if it's on the group.
This means `mbx --access-token MY_TOKEN geocode` instead of `mbx geocode --access-token MY_TOKEN`.
Support for the token environment variable will be unchanged. | mapbox/mapbox-sdk-py | diff --git a/tests/test_cli.py b/tests/test_cli.py
index ad1a75d..278edfe 100644
--- a/tests/test_cli.py
+++ b/tests/test_cli.py
@@ -41,7 +41,7 @@ def test_cli_geocode_fwd():
runner = CliRunner()
result = runner.invoke(
main_group,
- ['geocode', '--forward', '1600 pennsylvania ave nw', '--access-token', 'bogus'])
+ ['--access-token', 'bogus', 'geocode', '--forward', '1600 pennsylvania ave nw'])
assert result.exit_code == 0
assert result.output == '{"query": ["1600", "pennsylvania", "ave", "nw"]}\n'
@@ -81,7 +81,7 @@ def test_cli_geocode_reverse():
runner = CliRunner()
result = runner.invoke(
main_group,
- ['geocode', '--reverse', '--access-token', 'pk.test'],
+ ['--access-token', 'pk.test', 'geocode', '--reverse'],
input=','.join([str(x) for x in coords]))
assert result.exit_code == 0
assert result.output == '{"query": %s}\n' % json.dumps(coords)
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 0,
"issue_text_score": 0,
"test_score": 0
},
"num_modified_files": 3
} | unknown | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[test]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": null,
"pre_install": null,
"python": "3.9",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | certifi==2025.1.31
charset-normalizer==3.4.1
click==8.1.8
click-plugins==1.1.1
cligj==0.7.2
coverage==7.8.0
coveralls==4.0.1
docopt==0.6.2
exceptiongroup==1.2.2
idna==3.10
iniconfig==2.1.0
-e git+https://github.com/mapbox/mapbox-sdk-py.git@7859e5abc3ad69a001a24bb9ae66dcdd38da064c#egg=mapbox
packaging==24.2
pluggy==1.5.0
pytest==8.3.5
pytest-cov==6.0.0
PyYAML==6.0.2
requests==2.32.3
responses==0.25.7
tomli==2.2.1
uritemplate==4.1.1
uritemplate.py==3.0.2
urllib3==2.3.0
| name: mapbox-sdk-py
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=3.0.16=h5eee18b_0
- pip=25.0=py39h06a4308_0
- python=3.9.21=he870216_1
- readline=8.2=h5eee18b_0
- setuptools=75.8.0=py39h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- tzdata=2025a=h04d1e81_0
- wheel=0.45.1=py39h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- certifi==2025.1.31
- charset-normalizer==3.4.1
- click==8.1.8
- click-plugins==1.1.1
- cligj==0.7.2
- coverage==7.8.0
- coveralls==4.0.1
- docopt==0.6.2
- exceptiongroup==1.2.2
- idna==3.10
- iniconfig==2.1.0
- packaging==24.2
- pluggy==1.5.0
- pytest==8.3.5
- pytest-cov==6.0.0
- pyyaml==6.0.2
- requests==2.32.3
- responses==0.25.7
- tomli==2.2.1
- uritemplate==4.1.1
- uritemplate-py==3.0.2
- urllib3==2.3.0
prefix: /opt/conda/envs/mapbox-sdk-py
| [
"tests/test_cli.py::test_cli_geocode_fwd"
] | [
"tests/test_cli.py::test_coords_from_query_csv",
"tests/test_cli.py::test_coords_from_query_ws",
"tests/test_cli.py::test_cli_geocode_reverse",
"tests/test_cli.py::test_cli_geocode_reverse_env_token",
"tests/test_cli.py::test_cli_geocode_rev_unauthorized"
] | [
"tests/test_cli.py::test_iter_query_string",
"tests/test_cli.py::test_iter_query_file",
"tests/test_cli.py::test_coords_from_query_json",
"tests/test_cli.py::test_cli_geocode_fwd_env_token",
"tests/test_cli.py::test_cli_geocode_unauthorized"
] | [] | MIT License | 221 |
|
praw-dev__praw-509 | fea4a6df0508c93e200ef9fcacecf2b423f2aa27 | 2015-08-25 23:23:35 | c45e5f6ca0c5cd9968b51301989eb82740f8dc85 | diff --git a/CHANGES.rst b/CHANGES.rst
index 5e55a57e..4cd5cc03 100644
--- a/CHANGES.rst
+++ b/CHANGES.rst
@@ -22,13 +22,35 @@ formatted links that link to the relevant place in the code overview.
.. begin_changelog_body
-UNRELEASED
+Unreleased
----------
* **[BUGFIX]** Fixed login password prompt issue on windows (#485).
* **[BUGFIX]** Fixed unicode user-agent issue (#483).
* **[BUGFIX]** Fix duplicate request issue with comment and submission streams
(#501).
+ * **[BUGFIX]** Stopped :meth:`praw.objects.Redditor.friend` from raising
+ LoginRequired when using OAuth.
+ * **[BUGFIX]** Stopped a json-parsing error from occuring in cases where
+ reddit's response to a request was an empty string. :meth:`request_json`
+ will now simply return that empty string.
* **[CHANGE]** Added messages to all PRAW exceptions (#491).
+ * **[CHANGE]** Made it easier to send JSON dumps instead of form-encoded data
+ for http requests. Some api-v1 endpoints require the request body to be in
+ the json format.
+ * **[CHANGE]** Moved and deprecated
+ :meth:`praw.objects.LoggedInRedditor.get_friends` to
+ :class:`praw.AuthenticatedReddit`, leaving a pointer in its place.
+ Previously, `get_friends` was difficult to access because the only instance
+ of `LoggedInRedditor` was the reddit session's `user` attribute, which is
+ only instantiated if the user has the "identity" scope. By moving
+ `get_friends` to the reddit session, it can be used without having to
+ manipulate a :class:`praw.objects.Redditor` intsance's class.
+ * **[FEATURE]** Added support for adding "notes" to your friends. Users with
+ reddit Gold can set the ``note`` parameter of
+ :meth:`praw.objects.Redditor.friend`. 300 character max enforced by reddit.
+ * **[FEATURE]** New :meth:`praw.objects.Redditor.get_friend_info` to see info
+ about one of your friends. Includes their name, ID, when you added them, and
+ if you have reddit Gold, your note about them.
PRAW 3.2.1
----------
diff --git a/praw/__init__.py b/praw/__init__.py
index 398d64b5..6a31d2dc 100644
--- a/praw/__init__.py
+++ b/praw/__init__.py
@@ -102,6 +102,7 @@ class Config(object): # pylint: disable=R0903
'flairselector': 'api/flairselector/',
'flairtemplate': 'api/flairtemplate/',
'friend': 'api/friend/',
+ 'friend_v1': 'api/v1/me/friends/{user}',
'friends': 'prefs/friends/',
'gild_thing': 'api/v1/gold/gild/{fullname}/',
'gild_user': 'api/v1/gold/give/{username}/',
@@ -612,6 +613,12 @@ class BaseReddit(object):
hook = self._json_reddit_objecter if as_objects else None
# Request url just needs to be available for the objecter to use
self._request_url = url # pylint: disable=W0201
+
+ if response == '':
+ # Some of the v1 urls don't return anything, even when they're
+ # successful.
+ return response
+
data = json.loads(response, object_hook=hook)
delattr(self, '_request_url')
# Update the modhash
@@ -1321,6 +1328,12 @@ class AuthenticatedReddit(OAuth2Reddit, UnauthenticatedReddit):
data = {'r': six.text_type(subreddit), 'link': link}
return self.request_json(self.config['flairselector'], data=data)
+ @decorators.restrict_access(scope='read', login=True)
+ def get_friends(self, **params):
+ """Return a UserList of Redditors with whom the user is friends."""
+ url = self.config['friends']
+ return self.request_json(url, params=params)[0]
+
@decorators.restrict_access(scope='identity', oauth_only=True)
def get_me(self):
"""Return a LoggedInRedditor object.
diff --git a/praw/internal.py b/praw/internal.py
index 7967eb24..62eefe7c 100644
--- a/praw/internal.py
+++ b/praw/internal.py
@@ -158,10 +158,15 @@ def _prepare_request(reddit_session, url, params, data, auth, files,
# Most POST requests require adding `api_type` and `uh` to the data.
if data is True:
data = {}
- if not auth:
- data.setdefault('api_type', 'json')
- if reddit_session.modhash:
- data.setdefault('uh', reddit_session.modhash)
+
+ if isinstance(data, dict):
+ if not auth:
+ data.setdefault('api_type', 'json')
+ if reddit_session.modhash:
+ data.setdefault('uh', reddit_session.modhash)
+ else:
+ request.headers.setdefault('Content-Type', 'application/json')
+
request.data = data
request.files = files
return request
diff --git a/praw/objects.py b/praw/objects.py
index f6a0822a..9f9d557b 100755
--- a/praw/objects.py
+++ b/praw/objects.py
@@ -843,14 +843,38 @@ class Redditor(Gildable, Messageable, Refreshable):
self._case_name = self.name
self.name = tmp
- def friend(self):
+ @restrict_access(scope='subscribe')
+ def friend(self, note=None, _unfriend=False):
"""Friend the user.
+ :param note: A personal note about the user. Requires reddit Gold.
+ :param _unfriend: Unfriend the user. Please use :meth:`unfriend`
+ instead of setting this parameter manually.
+
:returns: The json response from the server.
"""
self.reddit_session.evict(self.reddit_session.config['friends'])
- return _modify_relationship('friend')(self.reddit_session.user, self)
+
+ # Requests through password auth use /api/friend
+ # Requests through oauth use /api/v1/me/friends/%username%
+ if not self.reddit_session.is_oauth_session():
+ modifier = _modify_relationship('friend', unlink=_unfriend)
+ data = {'note': note} if note else {}
+ return modifier(self.reddit_session.user, self, **data)
+
+ url = self.reddit_session.config['friend_v1'].format(user=self.name)
+ # This endpoint wants the data to be a string instead of an actual
+ # dictionary, although it is not required to have any content for adds.
+ # Unfriending does require the 'id' key.
+ if _unfriend:
+ data = {'id': self.name}
+ else:
+ # We cannot send a null or empty note string.
+ data = {'note': note} if note else {}
+ data = dumps(data)
+ method = 'DELETE' if _unfriend else 'PUT'
+ return self.reddit_session.request_json(url, data=data, method=method)
def get_disliked(self, *args, **kwargs):
"""Return a listing of the Submissions the user has downvoted.
@@ -881,6 +905,20 @@ class Redditor(Gildable, Messageable, Refreshable):
kwargs['_use_oauth'] = self.reddit_session.is_oauth_session()
return _get_redditor_listing('downvoted')(self, *args, **kwargs)
+ @restrict_access(scope='mysubreddits')
+ def get_friend_info(self):
+ """Return information about this friend, including personal notes.
+
+ The personal note can be added or overwritten with :meth:friend, but
+ only if the user has reddit Gold.
+
+ :returns: The json response from the server.
+
+ """
+ url = self.reddit_session.config['friend_v1'].format(user=self.name)
+ data = {'id': self.name}
+ return self.reddit_session.request_json(url, data=data, method='GET')
+
def get_liked(self, *args, **kwargs):
"""Return a listing of the Submissions the user has upvoted.
@@ -935,9 +973,7 @@ class Redditor(Gildable, Messageable, Refreshable):
:returns: The json response from the server.
"""
- self.reddit_session.evict(self.reddit_session.config['friends'])
- return _modify_relationship('friend', unlink=True)(
- self.reddit_session.user, self)
+ return self.friend(_unfriend=True)
class LoggedInRedditor(Redditor):
@@ -965,10 +1001,16 @@ class LoggedInRedditor(Redditor):
self._mod_subs[six.text_type(sub).lower()] = sub
return self._mod_subs
+ @deprecated(':meth:`get_friends` has been moved to '
+ ':class:`praw.AuthenticatedReddit` and will be removed from '
+ ':class:`objects.LoggedInRedditor` in PRAW v4.0.0')
def get_friends(self, **params):
- """Return a UserList of Redditors with whom the user has friended."""
- url = self.reddit_session.config['friends']
- return self.reddit_session.request_json(url, params=params)[0]
+ """Return a UserList of Redditors with whom the user is friends.
+
+ This method has been moved to :class:`praw.AuthenticatedReddit.
+
+ """
+ return self.reddit_session.get_friends(**params)
class ModAction(RedditContentObject):
| Redditor.friend() raises LoginRequired through OAuth; doesn't use suggested URL
I decided to try playing around with reddit's Friend system today, and found that Redditor.friend() raises a LoginRequired when used through OAuth.
First, I found that internal.py [chooses a restrict_access decorator with scope=None](https://github.com/praw-dev/praw/blob/c05bab70ff4b26967ca0b114436e0edad24aa6aa/praw/internal.py#L89) causing [all these checks](https://github.com/praw-dev/praw/blob/31d4984fd66930dbc886dfedb27c835dc6609262/praw/decorators.py#L329-L342) to fail until it finally gets to `elif login` and raises the exception. I tried changing that to scope='subscribers', but this causes an OAuthException with the message *"praw.errors.OAuthException: Bearer realm="reddit", error="invalid_request" on url https://oauth.reddit.com/api/friend/.json"*
At this point I looked at the [api docs](https://www.reddit.com/dev/api/oauth#POST_api_friend) and saw that they actually want you to use [PUT /api/v1/me/friends/username](https://www.reddit.com/dev/api/oauth#PUT_api_v1_me_friends_%7Busername%7D) instead (ostensibly so that /api/friend will one day control everything except adding friends). I tried this:
@restrict_access(scope='subscribe')
def friend(self):
# friend_v1 = 'api/v1/me/friends/%s'
url = self.reddit_session.config['friend_v1'] % self.name
data = {'name': self.name, 'note': 'u'}
method = 'PUT'
self.reddit_session.evict(self.reddit_session.config['friends'])
self.reddit_session.request_json(url, data=data, method=method)
But I'm still getting HTTPException 400 errors.
I'd love to make a pull request, but I'm not sure what to try next. Any insight? | praw-dev/praw | diff --git a/tests/cassettes/test_friends_oauth.json b/tests/cassettes/test_friends_oauth.json
new file mode 100644
index 00000000..b0a7cc0e
--- /dev/null
+++ b/tests/cassettes/test_friends_oauth.json
@@ -0,0 +1,1 @@
+{"recorded_with": "betamax/0.4.2", "http_interactions": [{"response": {"body": {"encoding": "UTF-8", "base64_string": "H4sIAAAAAAAAA6pWSkxOTi0uji/Jz07NU7JSUDI3NjCyMDPXdS4oDgxwKfByzfILMU8yi6wqiAo3yzYLtyzNV9JRUAKrjy+pLEgFaUpKTSxKLQKJp1YUZBalFsdnggwzNjMw0FFQKk7OhygrLk0qTi7KTEpVqgUAAAD//wMAZlrF43kAAAA="}, "url": "https://api.reddit.com/api/v1/access_token/", "headers": {"connection": ["keep-alive"], "server": ["cloudflare-nginx"], "set-cookie": ["__cfduid=dbfab20b40c347a3f6ae70df0dc539d481440570943; expires=Thu, 25-Aug-16 06:35:43 GMT; path=/; domain=.reddit.com; HttpOnly"], "transfer-encoding": ["chunked"], "content-type": ["application/json; charset=UTF-8"], "x-moose": ["majestic"], "content-encoding": ["gzip"], "date": ["Wed, 26 Aug 2015 06:35:43 GMT"], "cache-control": ["max-age=0, must-revalidate"], "x-xss-protection": ["1; mode=block"], "strict-transport-security": ["max-age=15552000; includeSubDomains; preload"], "x-content-type-options": ["nosniff"], "x-frame-options": ["SAMEORIGIN"], "cf-ray": ["21bd84aa3c7f1413-LAX"]}, "status": {"code": 200, "message": "OK"}}, "recorded_at": "2015-08-26T06:35:41", "request": {"body": {"string": "grant_type=refresh_token&redirect_uri=https%3A%2F%2F127.0.0.1%3A65010%2Fauthorize_callback&refresh_token=LlqwOLjyu_l6GMZIBqhcLWB0hAE", "encoding": "utf-8"}, "uri": "https://api.reddit.com/api/v1/access_token/", "method": "POST", "headers": {"Authorization": ["Basic c3RKbFVTVWJQUWU1bFE6aVUtTHNPenlKSDdCRFZvcS1xT1dORXEyenVJ"], "Accept": ["*/*"], "Connection": ["keep-alive"], "Accept-Encoding": ["gzip, deflate"], "User-Agent": ["PRAW_test_suite PRAW/3.2.1 Python/3.4.3 b'Windows-7-6.1.7601-SP1'"], "Content-Type": ["application/x-www-form-urlencoded"], "Content-Length": ["132"]}}}, {"response": {"body": {"string": "{\"fields\": [\"note\"], \"explanation\": \"you must have an active reddit gold subscription to do that\", \"reason\": \"GOLD_REQUIRED\"}", "encoding": "UTF-8"}, "url": "https://oauth.reddit.com/api/v1/me/friends/PyAPITestUser3.json", "headers": {"x-ratelimit-used": ["2"], "server": ["cloudflare-nginx"], "set-cookie": ["__cfduid=d51d9956cff66a4d8321b1e82c334037e1440570943; expires=Thu, 25-Aug-16 06:35:43 GMT; path=/; domain=.reddit.com; HttpOnly"], "x-frame-options": ["SAMEORIGIN"], "content-type": ["application/json; charset=UTF-8"], "x-moose": ["majestic"], "x-ratelimit-remaining": ["598.0"], "x-ua-compatible": ["IE=edge"], "x-xss-protection": ["1; mode=block"], "cache-control": ["private, s-maxage=0, max-age=0, must-revalidate", "max-age=0, must-revalidate"], "connection": ["keep-alive"], "date": ["Wed, 26 Aug 2015 06:35:43 GMT"], "x-ratelimit-reset": ["257"], "strict-transport-security": ["max-age=15552000; includeSubDomains; preload"], "x-content-type-options": ["nosniff"], "content-length": ["125"], "expires": ["-1"], "cf-ray": ["21bd84ad935022a0-LAX"]}, "status": {"code": 400, "message": "Bad Request"}}, "recorded_at": "2015-08-26T06:35:41", "request": {"body": {"string": "{\"note\": \"note\"}", "encoding": "utf-8"}, "uri": "https://oauth.reddit.com/api/v1/me/friends/PyAPITestUser3.json", "method": "PUT", "headers": {"Authorization": ["bearer 7302867-CpsQPDpJEjNT7b6YzpZW6k6W9uo"], "Accept": ["*/*"], "Connection": ["keep-alive"], "Accept-Encoding": ["gzip, deflate"], "User-Agent": ["PRAW_test_suite PRAW/3.2.1 Python/3.4.3 b'Windows-7-6.1.7601-SP1'"], "Content-Type": ["application/json"], "Content-Length": ["16"]}}}, {"response": {"body": {"string": "{\"date\": 1440570943.0, \"name\": \"PyAPITestUser3\", \"id\": \"t2_6c1xj\"}", "encoding": "UTF-8"}, "url": "https://oauth.reddit.com/api/v1/me/friends/PyAPITestUser3.json", "headers": {"x-ratelimit-used": ["3"], "server": ["cloudflare-nginx"], "set-cookie": ["__cfduid=d51d9956cff66a4d8321b1e82c334037e1440570943; expires=Thu, 25-Aug-16 06:35:43 GMT; path=/; domain=.reddit.com; HttpOnly"], "x-frame-options": ["SAMEORIGIN"], "content-type": ["application/json; charset=UTF-8"], "x-moose": ["majestic"], "x-ratelimit-reset": ["257"], "x-ratelimit-remaining": ["597.0"], "x-xss-protection": ["1; mode=block"], "cache-control": ["private, s-maxage=0, max-age=0, must-revalidate", "max-age=0, must-revalidate"], "connection": ["keep-alive"], "date": ["Wed, 26 Aug 2015 06:35:43 GMT"], "strict-transport-security": ["max-age=15552000; includeSubDomains; preload"], "x-content-type-options": ["nosniff"], "content-length": ["66"], "expires": ["-1"], "cf-ray": ["21bd84ae735822a0-LAX"]}, "status": {"code": 201, "message": "Created"}}, "recorded_at": "2015-08-26T06:35:42", "request": {"body": {"string": "{}", "encoding": "utf-8"}, "uri": "https://oauth.reddit.com/api/v1/me/friends/PyAPITestUser3.json", "method": "PUT", "headers": {"Authorization": ["bearer 7302867-CpsQPDpJEjNT7b6YzpZW6k6W9uo"], "Accept": ["*/*"], "Connection": ["keep-alive"], "Accept-Encoding": ["gzip, deflate"], "User-Agent": ["PRAW_test_suite PRAW/3.2.1 Python/3.4.3 b'Windows-7-6.1.7601-SP1'"], "Content-Type": ["application/json"], "Content-Length": ["2"]}}}, {"response": {"body": {"encoding": "UTF-8", "base64_string": "H4sIAAAAAAAAA2SPsQqDMBRFfyW8WUqNWKhbx24O7fxIzUt91SSQxNIi/nuJQxFcD+fAvTMM7DQ0ApKEQoBWSUEjZnDKUsbt99JebxTTPVKossIRTWBaK6PGSIWALpBKlElZSVnX8lxXh2MhoGdNaIK3GPzDp7hvcErdvhvZDTioYPOaMtveWnLpz7LEEZ9+3O7giNZvQa8ivimwYdJIVvEIjUhhWuX196krPy9Ylh8AAAD//wMAK4nJkwoBAAA="}, "url": "https://api.reddit.com/user/PyAPITestUser3/about/.json", "headers": {"connection": ["keep-alive"], "server": ["cloudflare-nginx"], "x-frame-options": ["SAMEORIGIN"], "transfer-encoding": ["chunked"], "content-type": ["application/json; charset=UTF-8"], "x-moose": ["majestic"], "x-ua-compatible": ["IE=edge"], "content-encoding": ["gzip"], "cache-control": ["max-age=0, must-revalidate"], "access-control-allow-origin": ["*"], "date": ["Wed, 26 Aug 2015 06:35:44 GMT"], "x-reddit-tracking": ["https://pixel.redditmedia.com/pixel/of_destiny.png?v=a1F8dTU0p4RfH24s95%2BiRD1fBaZBy1d2xVjexwqCj%2B%2FZ8Q6CupfRyQ9gjwW%2B%2BjAn%2BCuS9y7didg%3D"], "x-xss-protection": ["1; mode=block"], "x-content-type-options": ["nosniff"], "strict-transport-security": ["max-age=15552000; includeSubDomains; preload"], "access-control-expose-headers": ["X-Reddit-Tracking, X-Moose"], "cf-ray": ["21bd84af6cba1413-LAX"]}, "status": {"code": 200, "message": "OK"}}, "recorded_at": "2015-08-26T06:35:42", "request": {"body": {"string": "", "encoding": "utf-8"}, "uri": "https://api.reddit.com/user/PyAPITestUser3/about/.json", "method": "GET", "headers": {"User-Agent": ["PRAW_test_suite PRAW/3.2.1 Python/3.4.3 b'Windows-7-6.1.7601-SP1'"], "Accept": ["*/*"], "Connection": ["keep-alive"], "Cookie": ["__cfduid=d51d9956cff66a4d8321b1e82c334037e1440570943"], "Accept-Encoding": ["gzip, deflate"]}}}, {"response": {"body": {"encoding": "UTF-8", "base64_string": "H4sIAAAAAAAAA6pWSkxOTi0uji/Jz07NU7JSUDI3NjCyMDPX9XML180p0/Wryo4PqLRMDXQpScxx83ZyyXDJVtJRUAKrjy+pLEgFaUpKTSxKLQKJp1YUZBalFsdnggwzNjMw0FFQKk7OhyjLrSwuTSpKTUnJLClWqgUAAAD//wMA6XtVbnwAAAA="}, "url": "https://api.reddit.com/api/v1/access_token/", "headers": {"connection": ["keep-alive"], "server": ["cloudflare-nginx"], "x-frame-options": ["SAMEORIGIN"], "transfer-encoding": ["chunked"], "content-type": ["application/json; charset=UTF-8"], "x-moose": ["majestic"], "content-encoding": ["gzip"], "date": ["Wed, 26 Aug 2015 06:35:44 GMT"], "cache-control": ["max-age=0, must-revalidate"], "x-xss-protection": ["1; mode=block"], "strict-transport-security": ["max-age=15552000; includeSubDomains; preload"], "x-content-type-options": ["nosniff"], "cf-ray": ["21bd84b18cc71413-LAX"]}, "status": {"code": 200, "message": "OK"}}, "recorded_at": "2015-08-26T06:35:42", "request": {"body": {"string": "grant_type=refresh_token&redirect_uri=https%3A%2F%2F127.0.0.1%3A65010%2Fauthorize_callback&refresh_token=O7tfWhqem6fQZqxhoTiLca1s7VA", "encoding": "utf-8"}, "uri": "https://api.reddit.com/api/v1/access_token/", "method": "POST", "headers": {"Authorization": ["Basic c3RKbFVTVWJQUWU1bFE6aVUtTHNPenlKSDdCRFZvcS1xT1dORXEyenVJ"], "Accept": ["*/*"], "Connection": ["keep-alive"], "Cookie": ["__cfduid=d51d9956cff66a4d8321b1e82c334037e1440570943"], "User-Agent": ["PRAW_test_suite PRAW/3.2.1 Python/3.4.3 b'Windows-7-6.1.7601-SP1'"], "Content-Type": ["application/x-www-form-urlencoded"], "Content-Length": ["132"], "Accept-Encoding": ["gzip, deflate"]}}}, {"response": {"body": {"encoding": "UTF-8", "base64_string": "H4sIAAAAAAAAA6pWSkksSVWyUjA0MTEwNTewNDHWM9BRUMpLzAWJKgVUOgZ4hqQWl4QWpxYZK+koKGWmgMRLjOLNkg0rspRqAQAAAP//AwC0C6M5QgAAAA=="}, "url": "https://oauth.reddit.com/api/v1/me/friends/PyAPITestUser3.json", "headers": {"x-ratelimit-used": ["4"], "server": ["cloudflare-nginx"], "set-cookie": ["__cfduid=dcfacd553cdaabb519e3a258c4c7f962d1440570944; expires=Thu, 25-Aug-16 06:35:44 GMT; path=/; domain=.reddit.com; HttpOnly"], "transfer-encoding": ["chunked"], "content-type": ["application/json; charset=UTF-8"], "x-moose": ["majestic"], "x-ratelimit-reset": ["256"], "x-ratelimit-remaining": ["596.0"], "date": ["Wed, 26 Aug 2015 06:35:44 GMT"], "cache-control": ["private, s-maxage=0, max-age=0, must-revalidate", "max-age=0, must-revalidate"], "strict-transport-security": ["max-age=15552000; includeSubDomains; preload"], "content-encoding": ["gzip"], "connection": ["keep-alive"], "x-xss-protection": ["1; mode=block"], "x-content-type-options": ["nosniff"], "x-frame-options": ["SAMEORIGIN"], "expires": ["-1"], "cf-ray": ["21bd84b2636a22a0-LAX"]}, "status": {"code": 200, "message": "OK"}}, "recorded_at": "2015-08-26T06:35:42", "request": {"body": {"string": "", "encoding": "utf-8"}, "uri": "https://oauth.reddit.com/api/v1/me/friends/PyAPITestUser3.json", "method": "GET", "headers": {"Authorization": ["bearer 7302867-NFW-lv-Nzk_Py9eQDtalFKBDhDk"], "User-Agent": ["PRAW_test_suite PRAW/3.2.1 Python/3.4.3 b'Windows-7-6.1.7601-SP1'"], "Connection": ["keep-alive"], "Accept": ["*/*"], "Accept-Encoding": ["gzip, deflate"]}}}, {"response": {"body": {"encoding": "UTF-8", "base64_string": "H4sIAAAAAAAAA6pWSkxOTi0uji/Jz07NU7JSUDI3NjCyMDPXrTJzNs30rzQK9NR1KQiNN3dPD3XJN9J1DPLIV9JRUAKrjy+pLEgFaUpKTSxKLQKJp1YUZBalFsdnggwzNjMw0FFQKk7OhygrSk1MUaoFAAAA//8DAFnIJVd0AAAA"}, "url": "https://api.reddit.com/api/v1/access_token/", "headers": {"connection": ["keep-alive"], "server": ["cloudflare-nginx"], "x-frame-options": ["SAMEORIGIN"], "transfer-encoding": ["chunked"], "content-type": ["application/json; charset=UTF-8"], "x-moose": ["majestic"], "content-encoding": ["gzip"], "date": ["Wed, 26 Aug 2015 06:35:45 GMT"], "cache-control": ["max-age=0, must-revalidate"], "x-xss-protection": ["1; mode=block"], "strict-transport-security": ["max-age=15552000; includeSubDomains; preload"], "x-content-type-options": ["nosniff"], "cf-ray": ["21bd84b49ce71413-LAX"]}, "status": {"code": 200, "message": "OK"}}, "recorded_at": "2015-08-26T06:35:43", "request": {"body": {"string": "grant_type=refresh_token&redirect_uri=https%3A%2F%2F127.0.0.1%3A65010%2Fauthorize_callback&refresh_token=_mmtb8YjDym0eC26G-rTxXUMea0", "encoding": "utf-8"}, "uri": "https://api.reddit.com/api/v1/access_token/", "method": "POST", "headers": {"Authorization": ["Basic c3RKbFVTVWJQUWU1bFE6aVUtTHNPenlKSDdCRFZvcS1xT1dORXEyenVJ"], "Accept": ["*/*"], "Connection": ["keep-alive"], "Cookie": ["__cfduid=dcfacd553cdaabb519e3a258c4c7f962d1440570944"], "User-Agent": ["PRAW_test_suite PRAW/3.2.1 Python/3.4.3 b'Windows-7-6.1.7601-SP1'"], "Content-Type": ["application/x-www-form-urlencoded"], "Content-Length": ["132"], "Accept-Encoding": ["gzip, deflate"]}}}, {"response": {"body": {"encoding": "UTF-8", "base64_string": "H4sIAAAAAAAAA4yOPQvCMBgG/8rLMxdJbVI1m6Pg0EGnEqQfAVM1SpNBDfnvkm7ZXA/uuDbgZuwISTg7PR+N8ygIY+c7SAoYruY+ztpCUhsS1pBUcs74VnBRrVhBsN0jUfT9UyfZLDm/vlSvb60RC8pMsWE7npvNZ98cTtr59FBljXoo3xOiikvm71cVo/oBAAD//wMA8Hm2kdwAAAA="}, "url": "https://oauth.reddit.com/prefs/friends/.json", "headers": {"x-ratelimit-used": ["5"], "server": ["cloudflare-nginx"], "set-cookie": ["__cfduid=dffa64eb3980af2982a62afec11f2fbe11440570945; expires=Thu, 25-Aug-16 06:35:45 GMT; path=/; domain=.reddit.com; HttpOnly"], "transfer-encoding": ["chunked"], "content-type": ["application/json; charset=UTF-8"], "x-moose": ["majestic"], "x-ratelimit-remaining": ["595.0"], "x-ua-compatible": ["IE=edge"], "date": ["Wed, 26 Aug 2015 06:35:45 GMT"], "connection": ["keep-alive"], "cache-control": ["private, s-maxage=0, max-age=0, must-revalidate", "max-age=0, must-revalidate"], "strict-transport-security": ["max-age=15552000; includeSubDomains; preload"], "content-encoding": ["gzip"], "x-ratelimit-reset": ["255"], "x-reddit-tracking": ["https://pixel.redditmedia.com/pixel/of_destiny.png?v=z%2FUU9bl2%2FDxqL2Ui%2BXXj%2Fud5RIcTJqljWl9%2BQCEyV2voMh1ns0FvhGp%2BsSS7bZCNeva0U%2FpmKT6YW6fhEgLpKZe5fztZndwh"], "x-xss-protection": ["1; mode=block"], "x-content-type-options": ["nosniff"], "x-frame-options": ["SAMEORIGIN"], "expires": ["-1"], "cf-ray": ["21bd84b6e38722a0-LAX"]}, "status": {"code": 200, "message": "OK"}}, "recorded_at": "2015-08-26T06:35:43", "request": {"body": {"string": "", "encoding": "utf-8"}, "uri": "https://oauth.reddit.com/prefs/friends/.json", "method": "GET", "headers": {"Authorization": ["bearer 7302867-z6C5iOy2QI-DpU_7GgUDo2-ARHo"], "User-Agent": ["PRAW_test_suite PRAW/3.2.1 Python/3.4.3 b'Windows-7-6.1.7601-SP1'"], "Connection": ["keep-alive"], "Accept": ["*/*"], "Accept-Encoding": ["gzip, deflate"]}}}, {"response": {"body": {"string": "", "encoding": "UTF-8"}, "url": "https://oauth.reddit.com/api/v1/me/friends/PyAPITestUser3.json", "headers": {"x-ratelimit-used": ["6"], "server": ["cloudflare-nginx"], "set-cookie": ["__cfduid=dffa64eb3980af2982a62afec11f2fbe11440570945; expires=Thu, 25-Aug-16 06:35:45 GMT; path=/; domain=.reddit.com; HttpOnly"], "x-frame-options": ["SAMEORIGIN"], "content-type": ["application/json; charset=UTF-8"], "x-moose": ["majestic"], "x-ratelimit-reset": ["255"], "x-ratelimit-remaining": ["594.0"], "x-xss-protection": ["1; mode=block"], "cache-control": ["private, s-maxage=0, max-age=0, must-revalidate", "max-age=0, must-revalidate"], "connection": ["keep-alive"], "date": ["Wed, 26 Aug 2015 06:35:45 GMT"], "strict-transport-security": ["max-age=15552000; includeSubDomains; preload"], "x-content-type-options": ["nosniff"], "content-length": ["0"], "expires": ["-1"], "cf-ray": ["21bd84b9139322a0-LAX"]}, "status": {"code": 204, "message": "No Content"}}, "recorded_at": "2015-08-26T06:35:44", "request": {"body": {"string": "{\"id\": \"PyAPITestUser3\"}", "encoding": "utf-8"}, "uri": "https://oauth.reddit.com/api/v1/me/friends/PyAPITestUser3.json", "method": "DELETE", "headers": {"Authorization": ["bearer 7302867-CpsQPDpJEjNT7b6YzpZW6k6W9uo"], "Accept": ["*/*"], "Connection": ["keep-alive"], "Accept-Encoding": ["gzip, deflate"], "User-Agent": ["PRAW_test_suite PRAW/3.2.1 Python/3.4.3 b'Windows-7-6.1.7601-SP1'"], "Content-Type": ["application/json"], "Content-Length": ["24"]}}}, {"response": {"body": {"encoding": "UTF-8", "base64_string": "H4sIAAAAAAAAA2SPsQqDMBRFfyW8WUqNWKhbx24O7fxIzUt91SSQxNIi/nuJQxFcD+fAvTMM7DQ0ApKEQoBWSUEjZnDKUsbt99JebxTTPVKossIRTWBaK6PGSIWALpBKlElZSVnX8lxXh2MhoGdNaIK3GPzDp7hvcErdvhvZDTioYPOaMtveWnLpz7LEEZ9+3O7giNZvQa8ivimwYdJIVvEIjUhhWuX196krPy9Ylh8AAAD//wMAK4nJkwoBAAA="}, "url": "https://api.reddit.com/user/PyAPITestUser3/about/.json?uniq=1", "headers": {"connection": ["keep-alive"], "server": ["cloudflare-nginx"], "x-frame-options": ["SAMEORIGIN"], "transfer-encoding": ["chunked"], "content-type": ["application/json; charset=UTF-8"], "x-moose": ["majestic"], "x-ua-compatible": ["IE=edge"], "content-encoding": ["gzip"], "cache-control": ["max-age=0, must-revalidate"], "access-control-allow-origin": ["*"], "date": ["Wed, 26 Aug 2015 06:35:46 GMT"], "x-reddit-tracking": ["https://pixel.redditmedia.com/pixel/of_destiny.png?v=DjXAucekmGU%2FnCJKF2pS6zxzUmQhnQfTxCR7K3JVyyBuaTVh9x%2FgM4uRwRfzENLRP0lB30DU0aQ%3D"], "x-xss-protection": ["1; mode=block"], "x-content-type-options": ["nosniff"], "strict-transport-security": ["max-age=15552000; includeSubDomains; preload"], "access-control-expose-headers": ["X-Reddit-Tracking, X-Moose"], "cf-ray": ["21bd84bb5d1a1413-LAX"]}, "status": {"code": 200, "message": "OK"}}, "recorded_at": "2015-08-26T06:35:44", "request": {"body": {"string": "", "encoding": "utf-8"}, "uri": "https://api.reddit.com/user/PyAPITestUser3/about/.json?uniq=1", "method": "GET", "headers": {"User-Agent": ["PRAW_test_suite PRAW/3.2.1 Python/3.4.3 b'Windows-7-6.1.7601-SP1'"], "Accept": ["*/*"], "Connection": ["keep-alive"], "Cookie": ["__cfduid=dffa64eb3980af2982a62afec11f2fbe11440570945"], "Accept-Encoding": ["gzip, deflate"]}}}]}
\ No newline at end of file
diff --git a/tests/helper.py b/tests/helper.py
index 03700625..c6e5ad6f 100644
--- a/tests/helper.py
+++ b/tests/helper.py
@@ -7,6 +7,7 @@ import time
import unittest
from betamax import Betamax, BaseMatcher
from betamax_matchers.form_urlencoded import URLEncodedBodyMatcher
+from betamax_matchers.json_body import JSONBodyMatcher
from functools import wraps
from praw import Reddit
from requests.compat import urljoin
@@ -30,7 +31,8 @@ class BodyMatcher(BaseMatcher):
to_compare = request.copy()
to_compare.body = text_type(to_compare.body)
- return URLEncodedBodyMatcher().match(to_compare, recorded_request)
+ return URLEncodedBodyMatcher().match(to_compare, recorded_request) or \
+ JSONBodyMatcher().match(to_compare, recorded_request)
class PRAWTest(unittest.TestCase):
diff --git a/tests/test_redditor.py b/tests/test_redditor.py
index a7326063..a1452a9d 100644
--- a/tests/test_redditor.py
+++ b/tests/test_redditor.py
@@ -1,9 +1,10 @@
"""Tests for Redditor class."""
from __future__ import print_function, unicode_literals
+from praw import errors
from praw.objects import LoggedInRedditor
from six import text_type
-from .helper import PRAWTest, betamax
+from .helper import OAuthPRAWTest, PRAWTest, betamax
class RedditorTest(PRAWTest):
@@ -13,16 +14,16 @@ class RedditorTest(PRAWTest):
@betamax()
def test_add_remove_friends(self):
- friends = self.r.user.get_friends()
+ friends = self.r.get_friends()
redditor = friends[0] if friends else self.other_user
redditor.unfriend()
self.delay_for_listing_update()
- self.assertTrue(redditor not in self.r.user.get_friends(u=1))
+ self.assertTrue(redditor not in self.r.get_friends(u=1))
redditor.friend()
self.delay_for_listing_update()
- self.assertTrue(redditor in self.r.user.get_friends(u=2))
+ self.assertTrue(redditor in self.r.get_friends(u=2))
@betamax()
def test_duplicate_login(self):
@@ -94,3 +95,28 @@ class RedditorTest(PRAWTest):
@betamax()
def test_user_set_on_login(self):
self.assertTrue(isinstance(self.r.user, LoggedInRedditor))
+
+
+class OAuthRedditorTest(OAuthPRAWTest):
+ @betamax()
+ def test_friends_oauth(self):
+ self.r.refresh_access_information(self.refresh_token['subscribe'])
+ user = self.r.get_redditor(self.other_user_name)
+
+ # Only Gold users can include personal notes
+ self.assertRaises(errors.HTTPException, user.friend, 'note')
+
+ friendship = user.friend()
+ self.assertEqual(friendship['id'], user.fullname)
+
+ self.r.refresh_access_information(self.refresh_token['mysubreddits'])
+ friendship2 = user.get_friend_info()
+ self.assertEqual(friendship, friendship2)
+
+ self.r.refresh_access_information(self.refresh_token['read'])
+ friends = list(self.r.get_friends())
+ self.assertTrue(user in friends)
+
+ self.r.refresh_access_information(self.refresh_token['subscribe'])
+ user.unfriend()
+ self.assertFalse(user.refresh().is_friend)
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_hyperlinks",
"has_many_modified_files",
"has_many_hunks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 2,
"issue_text_score": 0,
"test_score": 3
},
"num_modified_files": 4
} | 3.2 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "pytest",
"pip_packages": [
"coveralls",
"flake8",
"pep257",
"betamax_matchers",
"pytest"
],
"pre_install": null,
"python": "3.9",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | betamax==0.9.0
betamax-matchers==0.4.0
certifi==2025.1.31
charset-normalizer==3.4.1
coverage==7.8.0
coveralls==4.0.1
decorator==5.2.1
docopt==0.6.2
exceptiongroup @ file:///croot/exceptiongroup_1706031385326/work
flake8==7.2.0
idna==3.10
iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work
mccabe==0.7.0
packaging @ file:///croot/packaging_1734472117206/work
pep257==0.7.0
pluggy @ file:///croot/pluggy_1733169602837/work
-e git+https://github.com/praw-dev/praw.git@fea4a6df0508c93e200ef9fcacecf2b423f2aa27#egg=praw
pycodestyle==2.13.0
pyflakes==3.3.1
pytest @ file:///croot/pytest_1738938843180/work
requests==2.32.3
requests-toolbelt==1.0.0
six==1.17.0
tomli @ file:///opt/conda/conda-bld/tomli_1657175507142/work
update-checker==0.18.0
urllib3==2.3.0
| name: praw
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- exceptiongroup=1.2.0=py39h06a4308_0
- iniconfig=1.1.1=pyhd3eb1b0_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=3.0.16=h5eee18b_0
- packaging=24.2=py39h06a4308_0
- pip=25.0=py39h06a4308_0
- pluggy=1.5.0=py39h06a4308_0
- pytest=8.3.4=py39h06a4308_0
- python=3.9.21=he870216_1
- readline=8.2=h5eee18b_0
- setuptools=75.8.0=py39h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- tomli=2.0.1=py39h06a4308_0
- tzdata=2025a=h04d1e81_0
- wheel=0.45.1=py39h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- betamax==0.9.0
- betamax-matchers==0.4.0
- certifi==2025.1.31
- charset-normalizer==3.4.1
- coverage==7.8.0
- coveralls==4.0.1
- decorator==5.2.1
- docopt==0.6.2
- flake8==7.2.0
- idna==3.10
- mccabe==0.7.0
- pep257==0.7.0
- pycodestyle==2.13.0
- pyflakes==3.3.1
- requests==2.32.3
- requests-toolbelt==1.0.0
- six==1.17.0
- update-checker==0.18.0
- urllib3==2.3.0
prefix: /opt/conda/envs/praw
| [
"tests/test_redditor.py::RedditorTest::test_add_remove_friends"
] | [
"tests/test_redditor.py::OAuthRedditorTest::test_friends_oauth"
] | [
"tests/test_redditor.py::RedditorTest::test_duplicate_login",
"tests/test_redditor.py::RedditorTest::test_get_hidden",
"tests/test_redditor.py::RedditorTest::test_get_redditor",
"tests/test_redditor.py::RedditorTest::test_get_submitted",
"tests/test_redditor.py::RedditorTest::test_get_upvoted_and_downvoted",
"tests/test_redditor.py::RedditorTest::test_name_lazy_update",
"tests/test_redditor.py::RedditorTest::test_redditor_comparison",
"tests/test_redditor.py::RedditorTest::test_user_set_on_login"
] | [] | BSD 2-Clause "Simplified" License | 222 |
|
sympy__sympy-9864 | b38fbf5d9bcc90d41b5099f7ddbd446b17ce5007 | 2015-08-26 16:17:12 | 0241b35cae5f2adc04dc37b25f7dc9c5f00bd746 | diff --git a/sympy/printing/latex.py b/sympy/printing/latex.py
index d177f2aedd..4391242388 100644
--- a/sympy/printing/latex.py
+++ b/sympy/printing/latex.py
@@ -9,6 +9,7 @@
from sympy.core.sympify import SympifyError
from sympy.core.alphabets import greeks
from sympy.core.operations import AssocOp
+from sympy.core.containers import Tuple
from sympy.logic.boolalg import true
## sympy.printing imports
@@ -1571,12 +1572,12 @@ def _print_ImageSet(self, s):
self._print(s.base_set))
def _print_ConditionSet(self, s):
- vars_print = ', '.join([self._print(var) for var in s.condition.variables])
+ vars_print = ', '.join([self._print(var) for var in Tuple(s.sym)])
return r"\left\{%s\; |\; %s \in %s \wedge %s \right\}" % (
vars_print,
vars_print,
self._print(s.base_set),
- self._print(s.condition.expr))
+ self._print(s.condition.as_expr()))
def _print_ComplexPlane(self, s):
vars_print = ', '.join([self._print(var) for var in s.args[0].variables])
diff --git a/sympy/printing/pretty/pretty.py b/sympy/printing/pretty/pretty.py
index b46013af50..0685dabfa5 100644
--- a/sympy/printing/pretty/pretty.py
+++ b/sympy/printing/pretty/pretty.py
@@ -1,6 +1,7 @@
from __future__ import print_function, division
from sympy.core import S
+from sympy.core.containers import Tuple
from sympy.core.function import _coeff_isneg
from sympy.core.mul import Mul
from sympy.core.numbers import Rational
@@ -1523,8 +1524,8 @@ def _print_ConditionSet(self, ts):
else:
inn = 'in'
_and = 'and'
- variables = self._print_seq(ts.condition.variables)
- cond = self._print(ts.condition.expr)
+ variables = self._print_seq(Tuple(ts.sym))
+ cond = self._print(ts.condition.as_expr())
bar = self._print("|")
base = self._print(ts.base_set)
diff --git a/sympy/sets/conditionset.py b/sympy/sets/conditionset.py
index 2e0c3daaf5..1fa874f219 100644
--- a/sympy/sets/conditionset.py
+++ b/sympy/sets/conditionset.py
@@ -2,6 +2,7 @@
from sympy import S
from sympy.core.basic import Basic
+from sympy.core.function import Lambda
from sympy.logic.boolalg import And
from sympy.sets.sets import (Set, Interval, Intersection, EmptySet, Union,
FiniteSet)
@@ -18,30 +19,31 @@ class ConditionSet(Set):
>>> from sympy import Symbol, S, ConditionSet, Lambda, pi, Eq, sin, Interval
>>> x = Symbol('x')
- >>> sin_sols = ConditionSet(Lambda(x, Eq(sin(x), 0)), Interval(0, 2*pi))
+ >>> sin_sols = ConditionSet(x, Eq(sin(x), 0), Interval(0, 2*pi))
>>> 2*pi in sin_sols
True
>>> pi/2 in sin_sols
False
>>> 3*pi in sin_sols
False
- >>> 5 in ConditionSet(Lambda(x, x**2 > 4), S.Reals)
+ >>> 5 in ConditionSet(x, x**2 > 4, S.Reals)
True
"""
- def __new__(cls, condition, base_set):
- if condition.args[1] is S.false:
+ def __new__(cls, sym, condition, base_set):
+ if condition == S.false:
return S.EmptySet
- if condition.args[1] is S.true:
+ if condition == S.true:
return base_set
- return Basic.__new__(cls, condition, base_set)
+ return Basic.__new__(cls, sym, condition, base_set)
- condition = property(lambda self: self.args[0])
- base_set = property(lambda self: self.args[1])
+ sym = property(lambda self: self.args[0])
+ condition = property(lambda self: self.args[1])
+ base_set = property(lambda self: self.args[2])
def _intersect(self, other):
if not isinstance(other, ConditionSet):
- return ConditionSet(self.condition,
+ return ConditionSet(self.sym, self.condition,
Intersection(self.base_set, other))
def contains(self, other):
- return And(self.condition(other), self.base_set.contains(other))
+ return And(Lambda(self.sym, self.condition)(other), self.base_set.contains(other))
diff --git a/sympy/solvers/solveset.py b/sympy/solvers/solveset.py
index 73116e8e49..62a082b058 100644
--- a/sympy/solvers/solveset.py
+++ b/sympy/solvers/solveset.py
@@ -502,7 +502,7 @@ def solveset_real(f, symbol):
else:
result += solveset_real(equation, symbol)
else:
- result = ConditionSet(Lambda(symbol, Eq(f, 0)), S.Reals)
+ result = ConditionSet(symbol, Eq(f, 0), S.Reals)
if isinstance(result, FiniteSet):
result = [s for s in result
@@ -535,7 +535,7 @@ def _solve_real_trig(f, symbol):
g, h = g.expand(), h.expand()
g, h = g.subs(exp(I*symbol), y), h.subs(exp(I*symbol), y)
if g.has(symbol) or h.has(symbol):
- return ConditionSet(Lambda(symbol, Eq(f, 0)), S.Reals)
+ return ConditionSet(symbol, Eq(f, 0), S.Reals)
solns = solveset_complex(g, y) - solveset_complex(h, y)
@@ -545,7 +545,7 @@ def _solve_real_trig(f, symbol):
elif solns is S.EmptySet:
return S.EmptySet
else:
- return ConditionSet(Lambda(symbol, Eq(f, 0)), S.Reals)
+ return ConditionSet(symbol, Eq(f, 0), S.Reals)
def _solve_as_poly(f, symbol, solveset_solver, invert_func):
@@ -567,11 +567,11 @@ def _solve_as_poly(f, symbol, solveset_solver, invert_func):
if poly.degree() <= len(solns):
result = FiniteSet(*solns)
else:
- result = ConditionSet(Lambda(symbol, Eq(f, 0)), S.Complexes)
+ result = ConditionSet(symbol, Eq(f, 0), S.Complexes)
else:
poly = Poly(f)
if poly is None:
- result = ConditionSet(Lambda(symbol, Eq(f, 0)), S.Complexes)
+ result = ConditionSet(symbol, Eq(f, 0), S.Complexes)
gens = [g for g in poly.gens if g.has(symbol)]
if len(gens) == 1:
@@ -583,7 +583,7 @@ def _solve_as_poly(f, symbol, solveset_solver, invert_func):
quintics=True).keys())
if len(poly_solns) < deg:
- result = ConditionSet(Lambda(symbol, Eq(f, 0)), S.Complexes)
+ result = ConditionSet(symbol, Eq(f, 0), S.Complexes)
if gen != symbol:
y = Dummy('y')
@@ -591,9 +591,9 @@ def _solve_as_poly(f, symbol, solveset_solver, invert_func):
if lhs is symbol:
result = Union(*[rhs_s.subs(y, s) for s in poly_solns])
else:
- result = ConditionSet(Lambda(symbol, Eq(f, 0)), S.Complexes)
+ result = ConditionSet(symbol, Eq(f, 0), S.Complexes)
else:
- result = ConditionSet(Lambda(symbol, Eq(f, 0)), S.Complexes)
+ result = ConditionSet(symbol, Eq(f, 0), S.Complexes)
if result is not None:
if isinstance(result, FiniteSet):
@@ -607,7 +607,7 @@ def _solve_as_poly(f, symbol, solveset_solver, invert_func):
result = imageset(Lambda(s, expand_complex(s)), result)
return result
else:
- return ConditionSet(Lambda(symbol, Eq(f, 0)), S.Complexes)
+ return ConditionSet(symbol, Eq(f, 0), S.Complexes)
def _solve_as_poly_real(f, symbol):
@@ -706,7 +706,7 @@ def _solve_abs(f, symbol):
symbol).intersect(q_neg_cond)
return Union(sols_q_pos, sols_q_neg)
else:
- return ConditionSet(Lambda(symbol, Eq(f, 0)), S.Complexes)
+ return ConditionSet(symbol, Eq(f, 0), S.Complexes)
def solveset_complex(f, symbol):
@@ -806,7 +806,7 @@ def solveset_complex(f, symbol):
else:
result += solveset_complex(equation, symbol)
else:
- result = ConditionSet(Lambda(symbol, Eq(f, 0)), S.Complexes)
+ result = ConditionSet(symbol, Eq(f, 0), S.Complexes)
if isinstance(result, FiniteSet):
result = [s for s in result
@@ -931,7 +931,7 @@ def solveset(f, symbol=None, domain=S.Complexes):
result = solve_univariate_inequality(
f, symbol, relational=False).intersection(domain)
except NotImplementedError:
- result = ConditionSet(Lambda(symbol, f), domain)
+ result = ConditionSet(symbol, f, domain)
return result
if isinstance(f, (Expr, Number)):
| Change interface for ConditionSet
In a recent [PR](https://github.com/sympy/sympy/pull/9696) we added a ConditionSet class to represent sets of form `{x | condition(x) is True for x in S}`. The current interface to create a condition set is `ConditionSet(imageset(var, condition), input_set)`. Since the first argument is always an `imageset` the interface can be simplified to `ConditionSet(var, condition, input_set)`. | sympy/sympy | diff --git a/sympy/core/tests/test_args.py b/sympy/core/tests/test_args.py
index a21a53ea15..a4a78520cc 100644
--- a/sympy/core/tests/test_args.py
+++ b/sympy/core/tests/test_args.py
@@ -569,7 +569,7 @@ def test_sympy__sets__conditionset__ConditionSet():
from sympy.sets.conditionset import ConditionSet
from sympy import S, Symbol
x = Symbol('x')
- assert _test_args(ConditionSet(Lambda(x, Eq(x**2, 1)), S.Reals))
+ assert _test_args(ConditionSet(x, Eq(x**2, 1), S.Reals))
def test_sympy__sets__contains__Contains():
diff --git a/sympy/printing/pretty/tests/test_pretty.py b/sympy/printing/pretty/tests/test_pretty.py
index 9cba38a101..ec8a01a8bf 100644
--- a/sympy/printing/pretty/tests/test_pretty.py
+++ b/sympy/printing/pretty/tests/test_pretty.py
@@ -3104,8 +3104,8 @@ def test_pretty_ConditionSet():
from sympy import ConditionSet
ascii_str = '{x | x in (-oo, oo) and sin(x) = 0}'
ucode_str = u('{x | x ∊ ℝ ∧ sin(x) = 0}')
- assert pretty(ConditionSet(Lambda(x, Eq(sin(x), 0)), S.Reals)) == ascii_str
- assert upretty(ConditionSet(Lambda(x, Eq(sin(x), 0)), S.Reals)) == ucode_str
+ assert pretty(ConditionSet(x, Eq(sin(x), 0), S.Reals)) == ascii_str
+ assert upretty(ConditionSet(x, Eq(sin(x), 0), S.Reals)) == ucode_str
def test_pretty_ComplexPlane():
diff --git a/sympy/printing/tests/test_latex.py b/sympy/printing/tests/test_latex.py
index a24fc533d2..7c3a966cc9 100644
--- a/sympy/printing/tests/test_latex.py
+++ b/sympy/printing/tests/test_latex.py
@@ -612,7 +612,7 @@ def test_latex_ImageSet():
def test_latex_ConditionSet():
x = Symbol('x')
- assert latex(ConditionSet(Lambda(x, Eq(x**2, 1)), S.Reals)) == \
+ assert latex(ConditionSet(x, Eq(x**2, 1), S.Reals)) == \
r"\left\{x\; |\; x \in \mathbb{R} \wedge x^{2} = 1 \right\}"
diff --git a/sympy/sets/tests/test_conditionset.py b/sympy/sets/tests/test_conditionset.py
index 368621310f..c7d02044b4 100644
--- a/sympy/sets/tests/test_conditionset.py
+++ b/sympy/sets/tests/test_conditionset.py
@@ -5,22 +5,22 @@
def test_CondSet():
- sin_sols_principal = ConditionSet(Lambda(x, Eq(sin(x), 0)),
+ sin_sols_principal = ConditionSet(x, Eq(sin(x), 0),
Interval(0, 2*pi, False, True))
assert pi in sin_sols_principal
assert pi/2 not in sin_sols_principal
assert 3*pi not in sin_sols_principal
- assert 5 in ConditionSet(Lambda(x, x**2 > 4), S.Reals)
- assert 1 not in ConditionSet(Lambda(x, x**2 > 4), S.Reals)
+ assert 5 in ConditionSet(x, x**2 > 4, S.Reals)
+ assert 1 not in ConditionSet(x, x**2 > 4, S.Reals)
def test_CondSet_intersect():
- input_conditionset = ConditionSet(Lambda(x, x**2 > 4), Interval(1, 4, False, False))
+ input_conditionset = ConditionSet(x, x**2 > 4, Interval(1, 4, False, False))
other_domain = Interval(0, 3, False, False)
- output_conditionset = ConditionSet(Lambda(x, x**2 > 4), Interval(1, 3, False, False))
+ output_conditionset = ConditionSet(x, x**2 > 4, Interval(1, 3, False, False))
assert Intersection(input_conditionset, other_domain) == output_conditionset
def test_issue_9849():
- assert ConditionSet(Lambda(x, Eq(x, x)), S.Naturals) == S.Naturals
- assert ConditionSet(Lambda(x, Eq(Abs(sin(x)), -1)), S.Naturals) == S.EmptySet
+ assert ConditionSet(x, Eq(x, x), S.Naturals) == S.Naturals
+ assert ConditionSet(x, Eq(Abs(sin(x)), -1), S.Naturals) == S.EmptySet
diff --git a/sympy/solvers/tests/test_solveset.py b/sympy/solvers/tests/test_solveset.py
index fae00b37ed..ea004acea7 100644
--- a/sympy/solvers/tests/test_solveset.py
+++ b/sympy/solvers/tests/test_solveset.py
@@ -439,7 +439,7 @@ def test_solve_sqrt_3():
eq = -sqrt((m - q)**2 + (-m/(2*q) + S(1)/2)**2) + sqrt((-m**2/2 - sqrt(
4*m**4 - 4*m**2 + 8*m + 1)/4 - S(1)/4)**2 + (m**2/2 - m - sqrt(
4*m**4 - 4*m**2 + 8*m + 1)/4 - S(1)/4)**2)
- unsolved_object = ConditionSet(Lambda(q, Eq((-2*sqrt(4*q**2*(m - q)**2 + (-m + q)**2) + sqrt((-2*m**2 - sqrt(4*m**4 - 4*m**2 + 8*m + 1) - 1)**2 + (2*m**2 - 4*m - sqrt(4*m**4 - 4*m**2 + 8*m + 1) - 1)**2)*Abs(q))/Abs(q), 0)), S.Reals)
+ unsolved_object = ConditionSet(q, Eq((-2*sqrt(4*q**2*(m - q)**2 + (-m + q)**2) + sqrt((-2*m**2 - sqrt(4*m**4 - 4*m**2 + 8*m + 1) - 1)**2 + (2*m**2 - 4*m - sqrt(4*m**4 - 4*m**2 + 8*m + 1) - 1)**2)*Abs(q))/Abs(q), 0), S.Reals)
assert solveset_real(eq, q) == unsolved_object
@@ -723,7 +723,7 @@ def test_solve_invalid_sol():
def test_solve_complex_unsolvable():
- unsolved_object = ConditionSet(Lambda(x, Eq(2*cos(x) - 1, 0)), S.Complexes)
+ unsolved_object = ConditionSet(x, Eq(2*cos(x) - 1, 0), S.Complexes)
solution = solveset_complex(cos(x) - S.Half, x)
assert solution == unsolved_object
@@ -851,25 +851,25 @@ def test_solveset():
def test_conditonset():
assert solveset(Eq(sin(x)**2 + cos(x)**2, 1), x, domain=S.Reals) == \
- ConditionSet(Lambda(x, True), S.Reals)
+ ConditionSet(x, True, S.Reals)
assert solveset(Eq(x**2 + x*sin(x), 1), x, domain=S.Reals) == \
- ConditionSet(Lambda(x, Eq(x*(x + sin(x)) - 1, 0)), S.Reals)
+ ConditionSet(x, Eq(x*(x + sin(x)) - 1, 0), S.Reals)
assert solveset(Eq(sin(Abs(x)), x), x, domain=S.Reals) == \
- ConditionSet(Lambda(x, Eq(-x + sin(Abs(x)), 0)), Interval(-oo, oo))
+ ConditionSet(x, Eq(-x + sin(Abs(x)), 0), Interval(-oo, oo))
assert solveset(Eq(-I*(exp(I*x) - exp(-I*x))/2, 1), x) == \
imageset(Lambda(n, 2*n*pi + pi/2), S.Integers)
assert solveset(x + sin(x) > 1, x, domain=S.Reals) == \
- ConditionSet(Lambda(x, x + sin(x) > 1), S.Reals)
+ ConditionSet(x, x + sin(x) > 1, S.Reals)
@XFAIL
def test_conditionset_equality():
''' Checking equality of different representations of ConditionSet'''
- assert solveset(Eq(tan(x), y), x) == ConditionSet(Lambda(x, Eq(tan(x), y)), S.Complexes)
+ assert solveset(Eq(tan(x), y), x) == ConditionSet(x, Eq(tan(x), y), S.Complexes)
def test_solveset_domain():
@@ -885,7 +885,7 @@ def test_improve_coverage():
x = Symbol('x')
y = exp(x+1/x**2)
solution = solveset(y**2+y, x, S.Reals)
- unsolved_object = ConditionSet(Lambda(x, Eq((exp((x**3 + 1)/x**2) + 1)*exp((x**3 + 1)/x**2), 0)), S.Reals)
+ unsolved_object = ConditionSet(x, Eq((exp((x**3 + 1)/x**2) + 1)*exp((x**3 + 1)/x**2), 0), S.Reals)
assert solution == unsolved_object
assert _has_rational_power(sin(x)*exp(x) + 1, x) == (False, S.One)
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 2,
"issue_text_score": 1,
"test_score": 0
},
"num_modified_files": 4
} | 0.7 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "pytest",
"pip_packages": [
"mpmath>=0.19",
"pytest"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.6",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | attrs @ file:///opt/conda/conda-bld/attrs_1642510447205/work
certifi==2021.5.30
importlib-metadata @ file:///tmp/build/80754af9/importlib-metadata_1631916693255/work
iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work
more-itertools @ file:///tmp/build/80754af9/more-itertools_1637733554872/work
mpmath==1.3.0
packaging @ file:///tmp/build/80754af9/packaging_1637314298585/work
pluggy @ file:///tmp/build/80754af9/pluggy_1615976315926/work
py @ file:///opt/conda/conda-bld/py_1644396412707/work
pyparsing @ file:///tmp/build/80754af9/pyparsing_1635766073266/work
pytest==6.2.4
-e git+https://github.com/sympy/sympy.git@b38fbf5d9bcc90d41b5099f7ddbd446b17ce5007#egg=sympy
toml @ file:///tmp/build/80754af9/toml_1616166611790/work
typing_extensions @ file:///opt/conda/conda-bld/typing_extensions_1647553014482/work
zipp @ file:///tmp/build/80754af9/zipp_1633618647012/work
| name: sympy
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- attrs=21.4.0=pyhd3eb1b0_0
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2021.5.30=py36h06a4308_0
- importlib-metadata=4.8.1=py36h06a4308_0
- importlib_metadata=4.8.1=hd3eb1b0_0
- iniconfig=1.1.1=pyhd3eb1b0_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.3=he6710b0_2
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- more-itertools=8.12.0=pyhd3eb1b0_0
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- packaging=21.3=pyhd3eb1b0_0
- pip=21.2.2=py36h06a4308_0
- pluggy=0.13.1=py36h06a4308_0
- py=1.11.0=pyhd3eb1b0_0
- pyparsing=3.0.4=pyhd3eb1b0_0
- pytest=6.2.4=py36h06a4308_2
- python=3.6.13=h12debd9_1
- readline=8.2=h5eee18b_0
- setuptools=58.0.4=py36h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- toml=0.10.2=pyhd3eb1b0_0
- typing_extensions=4.1.1=pyh06a4308_0
- wheel=0.37.1=pyhd3eb1b0_0
- xz=5.6.4=h5eee18b_1
- zipp=3.6.0=pyhd3eb1b0_0
- zlib=1.2.13=h5eee18b_1
- pip:
- mpmath==1.3.0
prefix: /opt/conda/envs/sympy
| [
"sympy/core/tests/test_args.py::test_sympy__sets__conditionset__ConditionSet",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_ConditionSet",
"sympy/printing/tests/test_latex.py::test_latex_ConditionSet",
"sympy/sets/tests/test_conditionset.py::test_CondSet",
"sympy/sets/tests/test_conditionset.py::test_CondSet_intersect",
"sympy/sets/tests/test_conditionset.py::test_issue_9849",
"sympy/solvers/tests/test_solveset.py::test_solve_sqrt_3",
"sympy/solvers/tests/test_solveset.py::test_solve_complex_unsolvable",
"sympy/solvers/tests/test_solveset.py::test_conditonset",
"sympy/solvers/tests/test_solveset.py::test_improve_coverage"
] | [] | [
"sympy/core/tests/test_args.py::test_all_classes_are_tested",
"sympy/core/tests/test_args.py::test_sympy__assumptions__assume__AppliedPredicate",
"sympy/core/tests/test_args.py::test_sympy__assumptions__assume__Predicate",
"sympy/core/tests/test_args.py::test_sympy__assumptions__sathandlers__UnevaluatedOnFree",
"sympy/core/tests/test_args.py::test_sympy__assumptions__sathandlers__AllArgs",
"sympy/core/tests/test_args.py::test_sympy__assumptions__sathandlers__AnyArgs",
"sympy/core/tests/test_args.py::test_sympy__assumptions__sathandlers__ExactlyOneArg",
"sympy/core/tests/test_args.py::test_sympy__assumptions__sathandlers__CheckOldAssump",
"sympy/core/tests/test_args.py::test_sympy__assumptions__sathandlers__CheckIsPrime",
"sympy/core/tests/test_args.py::test_sympy__combinatorics__subsets__Subset",
"sympy/core/tests/test_args.py::test_sympy__combinatorics__perm_groups__PermutationGroup",
"sympy/core/tests/test_args.py::test_sympy__combinatorics__polyhedron__Polyhedron",
"sympy/core/tests/test_args.py::test_sympy__combinatorics__partitions__Partition",
"sympy/core/tests/test_args.py::test_sympy__concrete__products__Product",
"sympy/core/tests/test_args.py::test_sympy__concrete__summations__Sum",
"sympy/core/tests/test_args.py::test_sympy__core__add__Add",
"sympy/core/tests/test_args.py::test_sympy__core__basic__Atom",
"sympy/core/tests/test_args.py::test_sympy__core__basic__Basic",
"sympy/core/tests/test_args.py::test_sympy__core__containers__Dict",
"sympy/core/tests/test_args.py::test_sympy__core__containers__Tuple",
"sympy/core/tests/test_args.py::test_sympy__core__expr__AtomicExpr",
"sympy/core/tests/test_args.py::test_sympy__core__expr__Expr",
"sympy/core/tests/test_args.py::test_sympy__core__function__Application",
"sympy/core/tests/test_args.py::test_sympy__core__function__AppliedUndef",
"sympy/core/tests/test_args.py::test_sympy__core__function__Derivative",
"sympy/core/tests/test_args.py::test_sympy__core__function__Lambda",
"sympy/core/tests/test_args.py::test_sympy__core__function__Subs",
"sympy/core/tests/test_args.py::test_sympy__core__function__WildFunction",
"sympy/core/tests/test_args.py::test_sympy__core__mod__Mod",
"sympy/core/tests/test_args.py::test_sympy__core__mul__Mul",
"sympy/core/tests/test_args.py::test_sympy__core__numbers__Catalan",
"sympy/core/tests/test_args.py::test_sympy__core__numbers__ComplexInfinity",
"sympy/core/tests/test_args.py::test_sympy__core__numbers__EulerGamma",
"sympy/core/tests/test_args.py::test_sympy__core__numbers__Exp1",
"sympy/core/tests/test_args.py::test_sympy__core__numbers__Float",
"sympy/core/tests/test_args.py::test_sympy__core__numbers__GoldenRatio",
"sympy/core/tests/test_args.py::test_sympy__core__numbers__Half",
"sympy/core/tests/test_args.py::test_sympy__core__numbers__ImaginaryUnit",
"sympy/core/tests/test_args.py::test_sympy__core__numbers__Infinity",
"sympy/core/tests/test_args.py::test_sympy__core__numbers__Integer",
"sympy/core/tests/test_args.py::test_sympy__core__numbers__NaN",
"sympy/core/tests/test_args.py::test_sympy__core__numbers__NegativeInfinity",
"sympy/core/tests/test_args.py::test_sympy__core__numbers__NegativeOne",
"sympy/core/tests/test_args.py::test_sympy__core__numbers__Number",
"sympy/core/tests/test_args.py::test_sympy__core__numbers__NumberSymbol",
"sympy/core/tests/test_args.py::test_sympy__core__numbers__One",
"sympy/core/tests/test_args.py::test_sympy__core__numbers__Pi",
"sympy/core/tests/test_args.py::test_sympy__core__numbers__Rational",
"sympy/core/tests/test_args.py::test_sympy__core__numbers__Zero",
"sympy/core/tests/test_args.py::test_sympy__core__power__Pow",
"sympy/core/tests/test_args.py::test_sympy__core__relational__Equality",
"sympy/core/tests/test_args.py::test_sympy__core__relational__GreaterThan",
"sympy/core/tests/test_args.py::test_sympy__core__relational__LessThan",
"sympy/core/tests/test_args.py::test_sympy__core__relational__StrictGreaterThan",
"sympy/core/tests/test_args.py::test_sympy__core__relational__StrictLessThan",
"sympy/core/tests/test_args.py::test_sympy__core__relational__Unequality",
"sympy/core/tests/test_args.py::test_sympy__sets__sets__EmptySet",
"sympy/core/tests/test_args.py::test_sympy__sets__sets__UniversalSet",
"sympy/core/tests/test_args.py::test_sympy__sets__sets__FiniteSet",
"sympy/core/tests/test_args.py::test_sympy__sets__sets__Interval",
"sympy/core/tests/test_args.py::test_sympy__sets__sets__ProductSet",
"sympy/core/tests/test_args.py::test_sympy__sets__sets__Intersection",
"sympy/core/tests/test_args.py::test_sympy__sets__sets__Union",
"sympy/core/tests/test_args.py::test_sympy__sets__sets__Complement",
"sympy/core/tests/test_args.py::test_sympy__sets__sets__SymmetricDifference",
"sympy/core/tests/test_args.py::test_sympy__core__trace__Tr",
"sympy/core/tests/test_args.py::test_sympy__sets__fancysets__Naturals",
"sympy/core/tests/test_args.py::test_sympy__sets__fancysets__Naturals0",
"sympy/core/tests/test_args.py::test_sympy__sets__fancysets__Integers",
"sympy/core/tests/test_args.py::test_sympy__sets__fancysets__Reals",
"sympy/core/tests/test_args.py::test_sympy__sets__fancysets__Complexes",
"sympy/core/tests/test_args.py::test_sympy__sets__fancysets__ComplexPlane",
"sympy/core/tests/test_args.py::test_sympy__sets__fancysets__ImageSet",
"sympy/core/tests/test_args.py::test_sympy__sets__fancysets__Range",
"sympy/core/tests/test_args.py::test_sympy__sets__contains__Contains",
"sympy/core/tests/test_args.py::test_sympy__stats__crv__ContinuousDomain",
"sympy/core/tests/test_args.py::test_sympy__stats__crv__SingleContinuousDomain",
"sympy/core/tests/test_args.py::test_sympy__stats__crv__ProductContinuousDomain",
"sympy/core/tests/test_args.py::test_sympy__stats__crv__ConditionalContinuousDomain",
"sympy/core/tests/test_args.py::test_sympy__stats__crv__ContinuousPSpace",
"sympy/core/tests/test_args.py::test_sympy__stats__crv__SingleContinuousPSpace",
"sympy/core/tests/test_args.py::test_sympy__stats__crv__ProductContinuousPSpace",
"sympy/core/tests/test_args.py::test_sympy__stats__drv__SingleDiscreteDomain",
"sympy/core/tests/test_args.py::test_sympy__stats__drv__SingleDiscretePSpace",
"sympy/core/tests/test_args.py::test_sympy__stats__rv__RandomDomain",
"sympy/core/tests/test_args.py::test_sympy__stats__rv__SingleDomain",
"sympy/core/tests/test_args.py::test_sympy__stats__rv__ConditionalDomain",
"sympy/core/tests/test_args.py::test_sympy__stats__rv__PSpace",
"sympy/core/tests/test_args.py::test_sympy__stats__rv__RandomSymbol",
"sympy/core/tests/test_args.py::test_sympy__stats__rv__ProductPSpace",
"sympy/core/tests/test_args.py::test_sympy__stats__rv__ProductDomain",
"sympy/core/tests/test_args.py::test_sympy__stats__frv_types__DiscreteUniformDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__frv_types__DieDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__frv_types__BernoulliDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__frv_types__BinomialDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__frv_types__HypergeometricDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__frv_types__RademacherDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__frv__FiniteDomain",
"sympy/core/tests/test_args.py::test_sympy__stats__frv__SingleFiniteDomain",
"sympy/core/tests/test_args.py::test_sympy__stats__frv__ProductFiniteDomain",
"sympy/core/tests/test_args.py::test_sympy__stats__frv__ConditionalFiniteDomain",
"sympy/core/tests/test_args.py::test_sympy__stats__frv__FinitePSpace",
"sympy/core/tests/test_args.py::test_sympy__stats__frv__SingleFinitePSpace",
"sympy/core/tests/test_args.py::test_sympy__stats__frv__ProductFinitePSpace",
"sympy/core/tests/test_args.py::test_sympy__stats__frv_types__FiniteDistributionHandmade",
"sympy/core/tests/test_args.py::test_sympy__stats__crv__ContinuousDistributionHandmade",
"sympy/core/tests/test_args.py::test_sympy__stats__rv__Density",
"sympy/core/tests/test_args.py::test_sympy__stats__crv_types__ArcsinDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__crv_types__BeniniDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__crv_types__BetaDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__crv_types__BetaPrimeDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__crv_types__CauchyDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__crv_types__ChiDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__crv_types__ChiNoncentralDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__crv_types__ChiSquaredDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__crv_types__DagumDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__crv_types__ExponentialDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__crv_types__FDistributionDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__crv_types__FisherZDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__crv_types__FrechetDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__crv_types__GammaInverseDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__crv_types__GammaDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__crv_types__KumaraswamyDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__crv_types__LaplaceDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__crv_types__LogisticDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__crv_types__LogNormalDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__crv_types__MaxwellDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__crv_types__NakagamiDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__crv_types__NormalDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__crv_types__ParetoDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__crv_types__QuadraticUDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__crv_types__RaisedCosineDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__crv_types__RayleighDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__crv_types__StudentTDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__crv_types__TriangularDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__crv_types__UniformDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__crv_types__UniformSumDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__crv_types__VonMisesDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__crv_types__WeibullDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__crv_types__WignerSemicircleDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__drv_types__PoissonDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__drv_types__GeometricDistribution",
"sympy/core/tests/test_args.py::test_sympy__core__symbol__Dummy",
"sympy/core/tests/test_args.py::test_sympy__core__symbol__Symbol",
"sympy/core/tests/test_args.py::test_sympy__core__symbol__Wild",
"sympy/core/tests/test_args.py::test_sympy__functions__combinatorial__factorials__FallingFactorial",
"sympy/core/tests/test_args.py::test_sympy__functions__combinatorial__factorials__MultiFactorial",
"sympy/core/tests/test_args.py::test_sympy__functions__combinatorial__factorials__RisingFactorial",
"sympy/core/tests/test_args.py::test_sympy__functions__combinatorial__factorials__binomial",
"sympy/core/tests/test_args.py::test_sympy__functions__combinatorial__factorials__subfactorial",
"sympy/core/tests/test_args.py::test_sympy__functions__combinatorial__factorials__factorial",
"sympy/core/tests/test_args.py::test_sympy__functions__combinatorial__factorials__factorial2",
"sympy/core/tests/test_args.py::test_sympy__functions__combinatorial__numbers__bell",
"sympy/core/tests/test_args.py::test_sympy__functions__combinatorial__numbers__bernoulli",
"sympy/core/tests/test_args.py::test_sympy__functions__combinatorial__numbers__catalan",
"sympy/core/tests/test_args.py::test_sympy__functions__combinatorial__numbers__genocchi",
"sympy/core/tests/test_args.py::test_sympy__functions__combinatorial__numbers__euler",
"sympy/core/tests/test_args.py::test_sympy__functions__combinatorial__numbers__fibonacci",
"sympy/core/tests/test_args.py::test_sympy__functions__combinatorial__numbers__harmonic",
"sympy/core/tests/test_args.py::test_sympy__functions__combinatorial__numbers__lucas",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__complexes__Abs",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__complexes__adjoint",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__complexes__arg",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__complexes__conjugate",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__complexes__im",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__complexes__re",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__complexes__sign",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__complexes__polar_lift",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__complexes__periodic_argument",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__complexes__principal_branch",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__complexes__transpose",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__exponential__LambertW",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__exponential__exp",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__exponential__exp_polar",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__exponential__log",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__hyperbolic__acosh",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__hyperbolic__acoth",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__hyperbolic__asinh",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__hyperbolic__atanh",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__hyperbolic__asech",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__hyperbolic__cosh",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__hyperbolic__coth",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__hyperbolic__csch",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__hyperbolic__sech",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__hyperbolic__sinh",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__hyperbolic__tanh",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__integers__ceiling",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__integers__floor",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__integers__frac",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__miscellaneous__IdentityFunction",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__miscellaneous__Max",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__miscellaneous__Min",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__piecewise__ExprCondPair",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__piecewise__Piecewise",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__trigonometric__acos",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__trigonometric__acot",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__trigonometric__asin",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__trigonometric__asec",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__trigonometric__acsc",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__trigonometric__atan",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__trigonometric__atan2",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__trigonometric__cos",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__trigonometric__csc",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__trigonometric__cot",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__trigonometric__sin",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__trigonometric__sinc",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__trigonometric__sec",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__trigonometric__tan",
"sympy/core/tests/test_args.py::test_sympy__functions__special__bessel__besseli",
"sympy/core/tests/test_args.py::test_sympy__functions__special__bessel__besselj",
"sympy/core/tests/test_args.py::test_sympy__functions__special__bessel__besselk",
"sympy/core/tests/test_args.py::test_sympy__functions__special__bessel__bessely",
"sympy/core/tests/test_args.py::test_sympy__functions__special__bessel__hankel1",
"sympy/core/tests/test_args.py::test_sympy__functions__special__bessel__hankel2",
"sympy/core/tests/test_args.py::test_sympy__functions__special__bessel__jn",
"sympy/core/tests/test_args.py::test_sympy__functions__special__bessel__yn",
"sympy/core/tests/test_args.py::test_sympy__functions__special__bessel__AiryBase",
"sympy/core/tests/test_args.py::test_sympy__functions__special__bessel__airyai",
"sympy/core/tests/test_args.py::test_sympy__functions__special__bessel__airybi",
"sympy/core/tests/test_args.py::test_sympy__functions__special__bessel__airyaiprime",
"sympy/core/tests/test_args.py::test_sympy__functions__special__bessel__airybiprime",
"sympy/core/tests/test_args.py::test_sympy__functions__special__elliptic_integrals__elliptic_k",
"sympy/core/tests/test_args.py::test_sympy__functions__special__elliptic_integrals__elliptic_f",
"sympy/core/tests/test_args.py::test_sympy__functions__special__elliptic_integrals__elliptic_e",
"sympy/core/tests/test_args.py::test_sympy__functions__special__elliptic_integrals__elliptic_pi",
"sympy/core/tests/test_args.py::test_sympy__functions__special__delta_functions__DiracDelta",
"sympy/core/tests/test_args.py::test_sympy__functions__special__delta_functions__Heaviside",
"sympy/core/tests/test_args.py::test_sympy__functions__special__error_functions__erf",
"sympy/core/tests/test_args.py::test_sympy__functions__special__error_functions__erfc",
"sympy/core/tests/test_args.py::test_sympy__functions__special__error_functions__erfi",
"sympy/core/tests/test_args.py::test_sympy__functions__special__error_functions__erf2",
"sympy/core/tests/test_args.py::test_sympy__functions__special__error_functions__erfinv",
"sympy/core/tests/test_args.py::test_sympy__functions__special__error_functions__erfcinv",
"sympy/core/tests/test_args.py::test_sympy__functions__special__error_functions__erf2inv",
"sympy/core/tests/test_args.py::test_sympy__functions__special__error_functions__fresnels",
"sympy/core/tests/test_args.py::test_sympy__functions__special__error_functions__fresnelc",
"sympy/core/tests/test_args.py::test_sympy__functions__special__error_functions__erfs",
"sympy/core/tests/test_args.py::test_sympy__functions__special__error_functions__Ei",
"sympy/core/tests/test_args.py::test_sympy__functions__special__error_functions__li",
"sympy/core/tests/test_args.py::test_sympy__functions__special__error_functions__Li",
"sympy/core/tests/test_args.py::test_sympy__functions__special__error_functions__Si",
"sympy/core/tests/test_args.py::test_sympy__functions__special__error_functions__Ci",
"sympy/core/tests/test_args.py::test_sympy__functions__special__error_functions__Shi",
"sympy/core/tests/test_args.py::test_sympy__functions__special__error_functions__Chi",
"sympy/core/tests/test_args.py::test_sympy__functions__special__error_functions__expint",
"sympy/core/tests/test_args.py::test_sympy__functions__special__gamma_functions__gamma",
"sympy/core/tests/test_args.py::test_sympy__functions__special__gamma_functions__loggamma",
"sympy/core/tests/test_args.py::test_sympy__functions__special__gamma_functions__lowergamma",
"sympy/core/tests/test_args.py::test_sympy__functions__special__gamma_functions__polygamma",
"sympy/core/tests/test_args.py::test_sympy__functions__special__gamma_functions__uppergamma",
"sympy/core/tests/test_args.py::test_sympy__functions__special__beta_functions__beta",
"sympy/core/tests/test_args.py::test_sympy__functions__special__mathieu_functions__MathieuBase",
"sympy/core/tests/test_args.py::test_sympy__functions__special__mathieu_functions__mathieus",
"sympy/core/tests/test_args.py::test_sympy__functions__special__mathieu_functions__mathieuc",
"sympy/core/tests/test_args.py::test_sympy__functions__special__mathieu_functions__mathieusprime",
"sympy/core/tests/test_args.py::test_sympy__functions__special__mathieu_functions__mathieucprime",
"sympy/core/tests/test_args.py::test_sympy__functions__special__hyper__hyper",
"sympy/core/tests/test_args.py::test_sympy__functions__special__hyper__meijerg",
"sympy/core/tests/test_args.py::test_sympy__functions__special__hyper__HyperRep_power1",
"sympy/core/tests/test_args.py::test_sympy__functions__special__hyper__HyperRep_power2",
"sympy/core/tests/test_args.py::test_sympy__functions__special__hyper__HyperRep_log1",
"sympy/core/tests/test_args.py::test_sympy__functions__special__hyper__HyperRep_atanh",
"sympy/core/tests/test_args.py::test_sympy__functions__special__hyper__HyperRep_asin1",
"sympy/core/tests/test_args.py::test_sympy__functions__special__hyper__HyperRep_asin2",
"sympy/core/tests/test_args.py::test_sympy__functions__special__hyper__HyperRep_sqrts1",
"sympy/core/tests/test_args.py::test_sympy__functions__special__hyper__HyperRep_sqrts2",
"sympy/core/tests/test_args.py::test_sympy__functions__special__hyper__HyperRep_log2",
"sympy/core/tests/test_args.py::test_sympy__functions__special__hyper__HyperRep_cosasin",
"sympy/core/tests/test_args.py::test_sympy__functions__special__hyper__HyperRep_sinasin",
"sympy/core/tests/test_args.py::test_sympy__functions__special__polynomials__jacobi",
"sympy/core/tests/test_args.py::test_sympy__functions__special__polynomials__gegenbauer",
"sympy/core/tests/test_args.py::test_sympy__functions__special__polynomials__chebyshevt",
"sympy/core/tests/test_args.py::test_sympy__functions__special__polynomials__chebyshevt_root",
"sympy/core/tests/test_args.py::test_sympy__functions__special__polynomials__chebyshevu",
"sympy/core/tests/test_args.py::test_sympy__functions__special__polynomials__chebyshevu_root",
"sympy/core/tests/test_args.py::test_sympy__functions__special__polynomials__hermite",
"sympy/core/tests/test_args.py::test_sympy__functions__special__polynomials__legendre",
"sympy/core/tests/test_args.py::test_sympy__functions__special__polynomials__assoc_legendre",
"sympy/core/tests/test_args.py::test_sympy__functions__special__polynomials__laguerre",
"sympy/core/tests/test_args.py::test_sympy__functions__special__polynomials__assoc_laguerre",
"sympy/core/tests/test_args.py::test_sympy__functions__special__spherical_harmonics__Ynm",
"sympy/core/tests/test_args.py::test_sympy__functions__special__spherical_harmonics__Znm",
"sympy/core/tests/test_args.py::test_sympy__functions__special__tensor_functions__LeviCivita",
"sympy/core/tests/test_args.py::test_sympy__functions__special__tensor_functions__KroneckerDelta",
"sympy/core/tests/test_args.py::test_sympy__functions__special__zeta_functions__dirichlet_eta",
"sympy/core/tests/test_args.py::test_sympy__functions__special__zeta_functions__zeta",
"sympy/core/tests/test_args.py::test_sympy__functions__special__zeta_functions__lerchphi",
"sympy/core/tests/test_args.py::test_sympy__functions__special__zeta_functions__polylog",
"sympy/core/tests/test_args.py::test_sympy__functions__special__zeta_functions__stieltjes",
"sympy/core/tests/test_args.py::test_sympy__integrals__integrals__Integral",
"sympy/core/tests/test_args.py::test_sympy__integrals__risch__NonElementaryIntegral",
"sympy/core/tests/test_args.py::test_sympy__integrals__transforms__MellinTransform",
"sympy/core/tests/test_args.py::test_sympy__integrals__transforms__InverseMellinTransform",
"sympy/core/tests/test_args.py::test_sympy__integrals__transforms__LaplaceTransform",
"sympy/core/tests/test_args.py::test_sympy__integrals__transforms__InverseLaplaceTransform",
"sympy/core/tests/test_args.py::test_sympy__integrals__transforms__InverseFourierTransform",
"sympy/core/tests/test_args.py::test_sympy__integrals__transforms__FourierTransform",
"sympy/core/tests/test_args.py::test_sympy__integrals__transforms__InverseSineTransform",
"sympy/core/tests/test_args.py::test_sympy__integrals__transforms__SineTransform",
"sympy/core/tests/test_args.py::test_sympy__integrals__transforms__InverseCosineTransform",
"sympy/core/tests/test_args.py::test_sympy__integrals__transforms__CosineTransform",
"sympy/core/tests/test_args.py::test_sympy__integrals__transforms__InverseHankelTransform",
"sympy/core/tests/test_args.py::test_sympy__integrals__transforms__HankelTransform",
"sympy/core/tests/test_args.py::test_sympy__logic__boolalg__And",
"sympy/core/tests/test_args.py::test_sympy__logic__boolalg__BooleanFunction",
"sympy/core/tests/test_args.py::test_sympy__logic__boolalg__BooleanTrue",
"sympy/core/tests/test_args.py::test_sympy__logic__boolalg__BooleanFalse",
"sympy/core/tests/test_args.py::test_sympy__logic__boolalg__Equivalent",
"sympy/core/tests/test_args.py::test_sympy__logic__boolalg__ITE",
"sympy/core/tests/test_args.py::test_sympy__logic__boolalg__Implies",
"sympy/core/tests/test_args.py::test_sympy__logic__boolalg__Nand",
"sympy/core/tests/test_args.py::test_sympy__logic__boolalg__Nor",
"sympy/core/tests/test_args.py::test_sympy__logic__boolalg__Not",
"sympy/core/tests/test_args.py::test_sympy__logic__boolalg__Or",
"sympy/core/tests/test_args.py::test_sympy__logic__boolalg__Xor",
"sympy/core/tests/test_args.py::test_sympy__matrices__matrices__DeferredVector",
"sympy/core/tests/test_args.py::test_sympy__matrices__immutable__ImmutableMatrix",
"sympy/core/tests/test_args.py::test_sympy__matrices__immutable__ImmutableSparseMatrix",
"sympy/core/tests/test_args.py::test_sympy__matrices__expressions__slice__MatrixSlice",
"sympy/core/tests/test_args.py::test_sympy__matrices__expressions__blockmatrix__BlockDiagMatrix",
"sympy/core/tests/test_args.py::test_sympy__matrices__expressions__blockmatrix__BlockMatrix",
"sympy/core/tests/test_args.py::test_sympy__matrices__expressions__inverse__Inverse",
"sympy/core/tests/test_args.py::test_sympy__matrices__expressions__matadd__MatAdd",
"sympy/core/tests/test_args.py::test_sympy__matrices__expressions__matexpr__Identity",
"sympy/core/tests/test_args.py::test_sympy__matrices__expressions__matexpr__MatrixElement",
"sympy/core/tests/test_args.py::test_sympy__matrices__expressions__matexpr__ZeroMatrix",
"sympy/core/tests/test_args.py::test_sympy__matrices__expressions__matmul__MatMul",
"sympy/core/tests/test_args.py::test_sympy__matrices__expressions__diagonal__DiagonalMatrix",
"sympy/core/tests/test_args.py::test_sympy__matrices__expressions__diagonal__DiagonalOf",
"sympy/core/tests/test_args.py::test_sympy__matrices__expressions__hadamard__HadamardProduct",
"sympy/core/tests/test_args.py::test_sympy__matrices__expressions__matpow__MatPow",
"sympy/core/tests/test_args.py::test_sympy__matrices__expressions__transpose__Transpose",
"sympy/core/tests/test_args.py::test_sympy__matrices__expressions__adjoint__Adjoint",
"sympy/core/tests/test_args.py::test_sympy__matrices__expressions__trace__Trace",
"sympy/core/tests/test_args.py::test_sympy__matrices__expressions__determinant__Determinant",
"sympy/core/tests/test_args.py::test_sympy__matrices__expressions__funcmatrix__FunctionMatrix",
"sympy/core/tests/test_args.py::test_sympy__matrices__expressions__fourier__DFT",
"sympy/core/tests/test_args.py::test_sympy__matrices__expressions__fourier__IDFT",
"sympy/core/tests/test_args.py::test_sympy__matrices__expressions__factorizations__LofLU",
"sympy/core/tests/test_args.py::test_sympy__matrices__expressions__factorizations__UofLU",
"sympy/core/tests/test_args.py::test_sympy__matrices__expressions__factorizations__QofQR",
"sympy/core/tests/test_args.py::test_sympy__matrices__expressions__factorizations__RofQR",
"sympy/core/tests/test_args.py::test_sympy__matrices__expressions__factorizations__LofCholesky",
"sympy/core/tests/test_args.py::test_sympy__matrices__expressions__factorizations__UofCholesky",
"sympy/core/tests/test_args.py::test_sympy__matrices__expressions__factorizations__EigenVectors",
"sympy/core/tests/test_args.py::test_sympy__matrices__expressions__factorizations__EigenValues",
"sympy/core/tests/test_args.py::test_sympy__matrices__expressions__factorizations__UofSVD",
"sympy/core/tests/test_args.py::test_sympy__matrices__expressions__factorizations__VofSVD",
"sympy/core/tests/test_args.py::test_sympy__matrices__expressions__factorizations__SofSVD",
"sympy/core/tests/test_args.py::test_sympy__physics__vector__frame__CoordinateSym",
"sympy/core/tests/test_args.py::test_sympy__physics__paulialgebra__Pauli",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__anticommutator__AntiCommutator",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__cartesian__PositionBra3D",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__cartesian__PositionKet3D",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__cartesian__PositionState3D",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__cartesian__PxBra",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__cartesian__PxKet",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__cartesian__PxOp",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__cartesian__XBra",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__cartesian__XKet",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__cartesian__XOp",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__cartesian__YOp",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__cartesian__ZOp",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__cg__CG",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__cg__Wigner3j",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__cg__Wigner6j",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__cg__Wigner9j",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__circuitplot__Mz",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__circuitplot__Mx",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__commutator__Commutator",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__constants__HBar",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__dagger__Dagger",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__gate__CGate",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__gate__CGateS",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__gate__CNotGate",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__gate__Gate",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__gate__HadamardGate",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__gate__IdentityGate",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__gate__OneQubitGate",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__gate__PhaseGate",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__gate__SwapGate",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__gate__TGate",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__gate__TwoQubitGate",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__gate__UGate",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__gate__XGate",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__gate__YGate",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__gate__ZGate",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__grover__WGate",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__hilbert__ComplexSpace",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__hilbert__DirectSumHilbertSpace",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__hilbert__FockSpace",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__hilbert__HilbertSpace",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__hilbert__L2",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__hilbert__TensorPowerHilbertSpace",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__hilbert__TensorProductHilbertSpace",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__innerproduct__InnerProduct",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__operator__DifferentialOperator",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__operator__HermitianOperator",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__operator__IdentityOperator",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__operator__Operator",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__operator__OuterProduct",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__operator__UnitaryOperator",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__piab__PIABBra",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__boson__BosonOp",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__boson__BosonFockKet",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__boson__BosonFockBra",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__boson__BosonCoherentKet",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__boson__BosonCoherentBra",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__fermion__FermionOp",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__fermion__FermionFockKet",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__fermion__FermionFockBra",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__pauli__SigmaOpBase",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__pauli__SigmaX",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__pauli__SigmaY",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__pauli__SigmaZ",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__pauli__SigmaMinus",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__pauli__SigmaPlus",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__pauli__SigmaZKet",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__pauli__SigmaZBra",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__piab__PIABHamiltonian",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__piab__PIABKet",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__qexpr__QExpr",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__qft__Fourier",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__qft__IQFT",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__qft__QFT",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__qft__RkGate",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__qubit__IntQubit",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__qubit__IntQubitBra",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__qubit__IntQubitState",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__qubit__Qubit",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__qubit__QubitBra",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__qubit__QubitState",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__density__Density",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__spin__CoupledSpinState",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__spin__J2Op",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__spin__JminusOp",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__spin__JplusOp",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__spin__JxBra",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__spin__JxBraCoupled",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__spin__JxKet",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__spin__JxKetCoupled",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__spin__JxOp",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__spin__JyBra",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__spin__JyBraCoupled",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__spin__JyKet",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__spin__JyKetCoupled",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__spin__JyOp",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__spin__JzBra",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__spin__JzBraCoupled",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__spin__JzKet",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__spin__JzKetCoupled",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__spin__JzOp",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__spin__Rotation",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__spin__SpinState",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__spin__WignerD",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__state__Bra",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__state__BraBase",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__state__Ket",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__state__KetBase",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__state__State",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__state__StateBase",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__state__TimeDepBra",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__state__TimeDepKet",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__state__TimeDepState",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__state__Wavefunction",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__tensorproduct__TensorProduct",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__identitysearch__GateIdentity",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__sho1d__SHOOp",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__sho1d__RaisingOp",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__sho1d__LoweringOp",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__sho1d__NumberOp",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__sho1d__Hamiltonian",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__sho1d__SHOState",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__sho1d__SHOKet",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__sho1d__SHOBra",
"sympy/core/tests/test_args.py::test_sympy__physics__secondquant__AnnihilateBoson",
"sympy/core/tests/test_args.py::test_sympy__physics__secondquant__AnnihilateFermion",
"sympy/core/tests/test_args.py::test_sympy__physics__secondquant__AntiSymmetricTensor",
"sympy/core/tests/test_args.py::test_sympy__physics__secondquant__BosonState",
"sympy/core/tests/test_args.py::test_sympy__physics__secondquant__Commutator",
"sympy/core/tests/test_args.py::test_sympy__physics__secondquant__CreateBoson",
"sympy/core/tests/test_args.py::test_sympy__physics__secondquant__CreateFermion",
"sympy/core/tests/test_args.py::test_sympy__physics__secondquant__Dagger",
"sympy/core/tests/test_args.py::test_sympy__physics__secondquant__FermionState",
"sympy/core/tests/test_args.py::test_sympy__physics__secondquant__FermionicOperator",
"sympy/core/tests/test_args.py::test_sympy__physics__secondquant__FockState",
"sympy/core/tests/test_args.py::test_sympy__physics__secondquant__FockStateBosonBra",
"sympy/core/tests/test_args.py::test_sympy__physics__secondquant__FockStateBosonKet",
"sympy/core/tests/test_args.py::test_sympy__physics__secondquant__FockStateBra",
"sympy/core/tests/test_args.py::test_sympy__physics__secondquant__FockStateFermionBra",
"sympy/core/tests/test_args.py::test_sympy__physics__secondquant__FockStateFermionKet",
"sympy/core/tests/test_args.py::test_sympy__physics__secondquant__FockStateKet",
"sympy/core/tests/test_args.py::test_sympy__physics__secondquant__InnerProduct",
"sympy/core/tests/test_args.py::test_sympy__physics__secondquant__NO",
"sympy/core/tests/test_args.py::test_sympy__physics__secondquant__PermutationOperator",
"sympy/core/tests/test_args.py::test_sympy__physics__secondquant__SqOperator",
"sympy/core/tests/test_args.py::test_sympy__physics__secondquant__TensorSymbol",
"sympy/core/tests/test_args.py::test_sympy__physics__units__Unit",
"sympy/core/tests/test_args.py::test_sympy__physics__unitsystems__dimensions__Dimension",
"sympy/core/tests/test_args.py::test_sympy__physics__unitsystems__quantities__Quantity",
"sympy/core/tests/test_args.py::test_sympy__physics__unitsystems__units__Constant",
"sympy/core/tests/test_args.py::test_sympy__physics__unitsystems__units__Unit",
"sympy/core/tests/test_args.py::test_sympy__core__numbers__AlgebraicNumber",
"sympy/core/tests/test_args.py::test_sympy__polys__polytools__GroebnerBasis",
"sympy/core/tests/test_args.py::test_sympy__polys__polytools__Poly",
"sympy/core/tests/test_args.py::test_sympy__polys__polytools__PurePoly",
"sympy/core/tests/test_args.py::test_sympy__polys__rootoftools__RootOf",
"sympy/core/tests/test_args.py::test_sympy__polys__rootoftools__RootSum",
"sympy/core/tests/test_args.py::test_sympy__series__limits__Limit",
"sympy/core/tests/test_args.py::test_sympy__series__order__Order",
"sympy/core/tests/test_args.py::test_sympy__series__sequences__EmptySequence",
"sympy/core/tests/test_args.py::test_sympy__series__sequences__SeqPer",
"sympy/core/tests/test_args.py::test_sympy__series__sequences__SeqFormula",
"sympy/core/tests/test_args.py::test_sympy__series__sequences__SeqExprOp",
"sympy/core/tests/test_args.py::test_sympy__series__sequences__SeqAdd",
"sympy/core/tests/test_args.py::test_sympy__series__sequences__SeqMul",
"sympy/core/tests/test_args.py::test_sympy__series__fourier__FourierSeries",
"sympy/core/tests/test_args.py::test_sympy__series__formal__FormalPowerSeries",
"sympy/core/tests/test_args.py::test_sympy__simplify__hyperexpand__Hyper_Function",
"sympy/core/tests/test_args.py::test_sympy__simplify__hyperexpand__G_Function",
"sympy/core/tests/test_args.py::test_sympy__tensor__indexed__Idx",
"sympy/core/tests/test_args.py::test_sympy__tensor__indexed__Indexed",
"sympy/core/tests/test_args.py::test_sympy__tensor__indexed__IndexedBase",
"sympy/core/tests/test_args.py::test_sympy__tensor__tensor__TensorIndexType",
"sympy/core/tests/test_args.py::test_sympy__tensor__tensor__TensorSymmetry",
"sympy/core/tests/test_args.py::test_sympy__tensor__tensor__TensorType",
"sympy/core/tests/test_args.py::test_sympy__tensor__tensor__TensorHead",
"sympy/core/tests/test_args.py::test_sympy__tensor__tensor__TensorIndex",
"sympy/core/tests/test_args.py::test_sympy__tensor__tensor__TensAdd",
"sympy/core/tests/test_args.py::test_sympy__tensor__tensor__Tensor",
"sympy/core/tests/test_args.py::test_sympy__tensor__tensor__TensMul",
"sympy/core/tests/test_args.py::test_as_coeff_add",
"sympy/core/tests/test_args.py::test_sympy__geometry__curve__Curve",
"sympy/core/tests/test_args.py::test_sympy__geometry__point__Point",
"sympy/core/tests/test_args.py::test_sympy__geometry__point__Point2D",
"sympy/core/tests/test_args.py::test_sympy__geometry__point__Point3D",
"sympy/core/tests/test_args.py::test_sympy__geometry__ellipse__Ellipse",
"sympy/core/tests/test_args.py::test_sympy__geometry__ellipse__Circle",
"sympy/core/tests/test_args.py::test_sympy__geometry__line__Line",
"sympy/core/tests/test_args.py::test_sympy__geometry__line__Ray",
"sympy/core/tests/test_args.py::test_sympy__geometry__line__Segment",
"sympy/core/tests/test_args.py::test_sympy__geometry__line3d__Line3D",
"sympy/core/tests/test_args.py::test_sympy__geometry__line3d__Segment3D",
"sympy/core/tests/test_args.py::test_sympy__geometry__line3d__Ray3D",
"sympy/core/tests/test_args.py::test_sympy__geometry__plane__Plane",
"sympy/core/tests/test_args.py::test_sympy__geometry__polygon__Polygon",
"sympy/core/tests/test_args.py::test_sympy__geometry__polygon__RegularPolygon",
"sympy/core/tests/test_args.py::test_sympy__geometry__polygon__Triangle",
"sympy/core/tests/test_args.py::test_sympy__geometry__entity__GeometryEntity",
"sympy/core/tests/test_args.py::test_sympy__diffgeom__diffgeom__Manifold",
"sympy/core/tests/test_args.py::test_sympy__diffgeom__diffgeom__Patch",
"sympy/core/tests/test_args.py::test_sympy__diffgeom__diffgeom__CoordSystem",
"sympy/core/tests/test_args.py::test_sympy__diffgeom__diffgeom__BaseScalarField",
"sympy/core/tests/test_args.py::test_sympy__diffgeom__diffgeom__BaseVectorField",
"sympy/core/tests/test_args.py::test_sympy__diffgeom__diffgeom__Differential",
"sympy/core/tests/test_args.py::test_sympy__diffgeom__diffgeom__Commutator",
"sympy/core/tests/test_args.py::test_sympy__diffgeom__diffgeom__TensorProduct",
"sympy/core/tests/test_args.py::test_sympy__diffgeom__diffgeom__WedgeProduct",
"sympy/core/tests/test_args.py::test_sympy__diffgeom__diffgeom__LieDerivative",
"sympy/core/tests/test_args.py::test_sympy__diffgeom__diffgeom__CovarDerivativeOp",
"sympy/core/tests/test_args.py::test_sympy__categories__baseclasses__Class",
"sympy/core/tests/test_args.py::test_sympy__categories__baseclasses__Object",
"sympy/core/tests/test_args.py::test_sympy__categories__baseclasses__IdentityMorphism",
"sympy/core/tests/test_args.py::test_sympy__categories__baseclasses__NamedMorphism",
"sympy/core/tests/test_args.py::test_sympy__categories__baseclasses__CompositeMorphism",
"sympy/core/tests/test_args.py::test_sympy__categories__baseclasses__Diagram",
"sympy/core/tests/test_args.py::test_sympy__categories__baseclasses__Category",
"sympy/core/tests/test_args.py::test_sympy__ntheory__factor___totient",
"sympy/core/tests/test_args.py::test_sympy__ntheory__factor___divisor_sigma",
"sympy/core/tests/test_args.py::test_sympy__ntheory__factor___udivisor_sigma",
"sympy/core/tests/test_args.py::test_sympy__ntheory__residue_ntheory__mobius",
"sympy/core/tests/test_args.py::test_sympy__physics__optics__waves__TWave",
"sympy/core/tests/test_args.py::test_sympy__physics__optics__gaussopt__BeamParameter",
"sympy/core/tests/test_args.py::test_sympy__physics__optics__medium__Medium",
"sympy/core/tests/test_args.py::test_sympy__printing__codeprinter__Assignment",
"sympy/core/tests/test_args.py::test_sympy__vector__coordsysrect__CoordSysCartesian",
"sympy/core/tests/test_args.py::test_sympy__vector__point__Point",
"sympy/core/tests/test_args.py::test_sympy__vector__basisdependent__BasisDependent",
"sympy/core/tests/test_args.py::test_sympy__vector__basisdependent__BasisDependentMul",
"sympy/core/tests/test_args.py::test_sympy__vector__basisdependent__BasisDependentAdd",
"sympy/core/tests/test_args.py::test_sympy__vector__basisdependent__BasisDependentZero",
"sympy/core/tests/test_args.py::test_sympy__vector__vector__BaseVector",
"sympy/core/tests/test_args.py::test_sympy__vector__vector__VectorAdd",
"sympy/core/tests/test_args.py::test_sympy__vector__vector__VectorMul",
"sympy/core/tests/test_args.py::test_sympy__vector__vector__VectorZero",
"sympy/core/tests/test_args.py::test_sympy__vector__vector__Vector",
"sympy/core/tests/test_args.py::test_sympy__vector__dyadic__Dyadic",
"sympy/core/tests/test_args.py::test_sympy__vector__dyadic__BaseDyadic",
"sympy/core/tests/test_args.py::test_sympy__vector__dyadic__DyadicMul",
"sympy/core/tests/test_args.py::test_sympy__vector__dyadic__DyadicAdd",
"sympy/core/tests/test_args.py::test_sympy__vector__dyadic__DyadicZero",
"sympy/core/tests/test_args.py::test_sympy__vector__deloperator__Del",
"sympy/core/tests/test_args.py::test_sympy__vector__orienters__Orienter",
"sympy/core/tests/test_args.py::test_sympy__vector__orienters__ThreeAngleOrienter",
"sympy/core/tests/test_args.py::test_sympy__vector__orienters__AxisOrienter",
"sympy/core/tests/test_args.py::test_sympy__vector__orienters__BodyOrienter",
"sympy/core/tests/test_args.py::test_sympy__vector__orienters__SpaceOrienter",
"sympy/core/tests/test_args.py::test_sympy__vector__orienters__QuaternionOrienter",
"sympy/core/tests/test_args.py::test_sympy__vector__scalar__BaseScalar",
"sympy/core/tests/test_args.py::test_sympy__physics__wigner__Wigner3j",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_ascii_str",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_unicode_str",
"sympy/printing/pretty/tests/test_pretty.py::test_upretty_greek",
"sympy/printing/pretty/tests/test_pretty.py::test_upretty_multiindex",
"sympy/printing/pretty/tests/test_pretty.py::test_upretty_sub_super",
"sympy/printing/pretty/tests/test_pretty.py::test_upretty_subs_missing_in_24",
"sympy/printing/pretty/tests/test_pretty.py::test_upretty_modifiers",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_basic",
"sympy/printing/pretty/tests/test_pretty.py::test_negative_fractions",
"sympy/printing/pretty/tests/test_pretty.py::test_issue_5524",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_ordering",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_relational",
"sympy/printing/pretty/tests/test_pretty.py::test_issue_7117",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_rational",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_functions",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_sqrt",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_sqrt_char_knob",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_sqrt_longsymbol_no_sqrt_char",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_KroneckerDelta",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_product",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_lambda",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_order",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_derivatives",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_integrals",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_matrix",
"sympy/printing/pretty/tests/test_pretty.py::test_Adjoint",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_piecewise",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_seq",
"sympy/printing/pretty/tests/test_pretty.py::test_any_object_in_sequence",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_sets",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_ComplexPlane",
"sympy/printing/pretty/tests/test_pretty.py::test_ProductSet_paranthesis",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_sequences",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_FourierSeries",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_FormalPowerSeries",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_limits",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_RootOf",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_RootSum",
"sympy/printing/pretty/tests/test_pretty.py::test_GroebnerBasis",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_Boolean",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_Domain",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_prec",
"sympy/printing/pretty/tests/test_pretty.py::test_pprint",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_class",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_no_wrap_line",
"sympy/printing/pretty/tests/test_pretty.py::test_settings",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_sum",
"sympy/printing/pretty/tests/test_pretty.py::test_units",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_Subs",
"sympy/printing/pretty/tests/test_pretty.py::test_gammas",
"sympy/printing/pretty/tests/test_pretty.py::test_hyper",
"sympy/printing/pretty/tests/test_pretty.py::test_meijerg",
"sympy/printing/pretty/tests/test_pretty.py::test_noncommutative",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_special_functions",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_geometry",
"sympy/printing/pretty/tests/test_pretty.py::test_expint",
"sympy/printing/pretty/tests/test_pretty.py::test_elliptic_functions",
"sympy/printing/pretty/tests/test_pretty.py::test_RandomDomain",
"sympy/printing/pretty/tests/test_pretty.py::test_PrettyPoly",
"sympy/printing/pretty/tests/test_pretty.py::test_issue_6285",
"sympy/printing/pretty/tests/test_pretty.py::test_issue_6359",
"sympy/printing/pretty/tests/test_pretty.py::test_issue_6739",
"sympy/printing/pretty/tests/test_pretty.py::test_complicated_symbol_unchanged",
"sympy/printing/pretty/tests/test_pretty.py::test_categories",
"sympy/printing/pretty/tests/test_pretty.py::test_PrettyModules",
"sympy/printing/pretty/tests/test_pretty.py::test_QuotientRing",
"sympy/printing/pretty/tests/test_pretty.py::test_Homomorphism",
"sympy/printing/pretty/tests/test_pretty.py::test_Tr",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_Add",
"sympy/printing/pretty/tests/test_pretty.py::test_issue_7179",
"sympy/printing/pretty/tests/test_pretty.py::test_issue_7180",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_Complement",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_SymmetricDifference",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_Contains",
"sympy/printing/pretty/tests/test_pretty.py::test_issue_8292",
"sympy/printing/pretty/tests/test_pretty.py::test_issue_4335",
"sympy/printing/pretty/tests/test_pretty.py::test_issue_8344",
"sympy/printing/pretty/tests/test_pretty.py::test_issue_6324",
"sympy/printing/pretty/tests/test_pretty.py::test_issue_7927",
"sympy/printing/pretty/tests/test_pretty.py::test_issue_6134",
"sympy/printing/tests/test_latex.py::test_printmethod",
"sympy/printing/tests/test_latex.py::test_latex_basic",
"sympy/printing/tests/test_latex.py::test_latex_builtins",
"sympy/printing/tests/test_latex.py::test_latex_Float",
"sympy/printing/tests/test_latex.py::test_latex_symbols",
"sympy/printing/tests/test_latex.py::test_latex_functions",
"sympy/printing/tests/test_latex.py::test_hyper_printing",
"sympy/printing/tests/test_latex.py::test_latex_bessel",
"sympy/printing/tests/test_latex.py::test_latex_fresnel",
"sympy/printing/tests/test_latex.py::test_latex_brackets",
"sympy/printing/tests/test_latex.py::test_latex_indexed",
"sympy/printing/tests/test_latex.py::test_latex_derivatives",
"sympy/printing/tests/test_latex.py::test_latex_subs",
"sympy/printing/tests/test_latex.py::test_latex_integrals",
"sympy/printing/tests/test_latex.py::test_latex_sets",
"sympy/printing/tests/test_latex.py::test_latex_Range",
"sympy/printing/tests/test_latex.py::test_latex_sequences",
"sympy/printing/tests/test_latex.py::test_latex_FourierSeries",
"sympy/printing/tests/test_latex.py::test_latex_FormalPowerSeries",
"sympy/printing/tests/test_latex.py::test_latex_intervals",
"sympy/printing/tests/test_latex.py::test_latex_emptyset",
"sympy/printing/tests/test_latex.py::test_latex_union",
"sympy/printing/tests/test_latex.py::test_latex_symmetric_difference",
"sympy/printing/tests/test_latex.py::test_latex_Complement",
"sympy/printing/tests/test_latex.py::test_latex_Complexes",
"sympy/printing/tests/test_latex.py::test_latex_productset",
"sympy/printing/tests/test_latex.py::test_latex_Naturals",
"sympy/printing/tests/test_latex.py::test_latex_Naturals0",
"sympy/printing/tests/test_latex.py::test_latex_Integers",
"sympy/printing/tests/test_latex.py::test_latex_ImageSet",
"sympy/printing/tests/test_latex.py::test_latex_ComplexPlane",
"sympy/printing/tests/test_latex.py::test_latex_Contains",
"sympy/printing/tests/test_latex.py::test_latex_sum",
"sympy/printing/tests/test_latex.py::test_latex_product",
"sympy/printing/tests/test_latex.py::test_latex_limits",
"sympy/printing/tests/test_latex.py::test_issue_3568",
"sympy/printing/tests/test_latex.py::test_latex",
"sympy/printing/tests/test_latex.py::test_latex_dict",
"sympy/printing/tests/test_latex.py::test_latex_list",
"sympy/printing/tests/test_latex.py::test_latex_rational",
"sympy/printing/tests/test_latex.py::test_latex_inverse",
"sympy/printing/tests/test_latex.py::test_latex_DiracDelta",
"sympy/printing/tests/test_latex.py::test_latex_Heaviside",
"sympy/printing/tests/test_latex.py::test_latex_KroneckerDelta",
"sympy/printing/tests/test_latex.py::test_latex_LeviCivita",
"sympy/printing/tests/test_latex.py::test_mode",
"sympy/printing/tests/test_latex.py::test_latex_Piecewise",
"sympy/printing/tests/test_latex.py::test_latex_Matrix",
"sympy/printing/tests/test_latex.py::test_latex_matrix_with_functions",
"sympy/printing/tests/test_latex.py::test_latex_mul_symbol",
"sympy/printing/tests/test_latex.py::test_latex_issue_4381",
"sympy/printing/tests/test_latex.py::test_latex_issue_4576",
"sympy/printing/tests/test_latex.py::test_latex_pow_fraction",
"sympy/printing/tests/test_latex.py::test_noncommutative",
"sympy/printing/tests/test_latex.py::test_latex_order",
"sympy/printing/tests/test_latex.py::test_latex_Lambda",
"sympy/printing/tests/test_latex.py::test_latex_PolyElement",
"sympy/printing/tests/test_latex.py::test_latex_FracElement",
"sympy/printing/tests/test_latex.py::test_latex_Poly",
"sympy/printing/tests/test_latex.py::test_latex_RootOf",
"sympy/printing/tests/test_latex.py::test_latex_RootSum",
"sympy/printing/tests/test_latex.py::test_settings",
"sympy/printing/tests/test_latex.py::test_latex_numbers",
"sympy/printing/tests/test_latex.py::test_lamda",
"sympy/printing/tests/test_latex.py::test_custom_symbol_names",
"sympy/printing/tests/test_latex.py::test_matAdd",
"sympy/printing/tests/test_latex.py::test_matMul",
"sympy/printing/tests/test_latex.py::test_latex_MatrixSlice",
"sympy/printing/tests/test_latex.py::test_latex_RandomDomain",
"sympy/printing/tests/test_latex.py::test_PrettyPoly",
"sympy/printing/tests/test_latex.py::test_integral_transforms",
"sympy/printing/tests/test_latex.py::test_PolynomialRingBase",
"sympy/printing/tests/test_latex.py::test_categories",
"sympy/printing/tests/test_latex.py::test_Modules",
"sympy/printing/tests/test_latex.py::test_QuotientRing",
"sympy/printing/tests/test_latex.py::test_Tr",
"sympy/printing/tests/test_latex.py::test_Adjoint",
"sympy/printing/tests/test_latex.py::test_Hadamard",
"sympy/printing/tests/test_latex.py::test_ZeroMatrix",
"sympy/printing/tests/test_latex.py::test_boolean_args_order",
"sympy/printing/tests/test_latex.py::test_imaginary",
"sympy/printing/tests/test_latex.py::test_builtins_without_args",
"sympy/printing/tests/test_latex.py::test_latex_greek_functions",
"sympy/printing/tests/test_latex.py::test_translate",
"sympy/printing/tests/test_latex.py::test_other_symbols",
"sympy/printing/tests/test_latex.py::test_modifiers",
"sympy/printing/tests/test_latex.py::test_greek_symbols",
"sympy/printing/tests/test_latex.py::test_builtin_no_args",
"sympy/printing/tests/test_latex.py::test_issue_6853",
"sympy/printing/tests/test_latex.py::test_Mul",
"sympy/printing/tests/test_latex.py::test_Pow",
"sympy/printing/tests/test_latex.py::test_issue_7180",
"sympy/printing/tests/test_latex.py::test_issue_8409",
"sympy/printing/tests/test_latex.py::test_issue_8470",
"sympy/printing/tests/test_latex.py::test_issue_7117",
"sympy/printing/tests/test_latex.py::test_issue_2934",
"sympy/solvers/tests/test_solveset.py::test_invert_real",
"sympy/solvers/tests/test_solveset.py::test_invert_complex",
"sympy/solvers/tests/test_solveset.py::test_domain_check",
"sympy/solvers/tests/test_solveset.py::test_is_function_class_equation",
"sympy/solvers/tests/test_solveset.py::test_garbage_input",
"sympy/solvers/tests/test_solveset.py::test_solve_mul",
"sympy/solvers/tests/test_solveset.py::test_solve_invert",
"sympy/solvers/tests/test_solveset.py::test_errorinverses",
"sympy/solvers/tests/test_solveset.py::test_solve_polynomial",
"sympy/solvers/tests/test_solveset.py::test_return_root_of",
"sympy/solvers/tests/test_solveset.py::test__has_rational_power",
"sympy/solvers/tests/test_solveset.py::test_solveset_sqrt_1",
"sympy/solvers/tests/test_solveset.py::test_solveset_sqrt_2",
"sympy/solvers/tests/test_solveset.py::test_solve_polynomial_symbolic_param",
"sympy/solvers/tests/test_solveset.py::test_solve_rational",
"sympy/solvers/tests/test_solveset.py::test_solveset_real_gen_is_pow",
"sympy/solvers/tests/test_solveset.py::test_no_sol",
"sympy/solvers/tests/test_solveset.py::test_sol_zero_real",
"sympy/solvers/tests/test_solveset.py::test_no_sol_rational_extragenous",
"sympy/solvers/tests/test_solveset.py::test_solve_polynomial_cv_1a",
"sympy/solvers/tests/test_solveset.py::test_solveset_real_rational",
"sympy/solvers/tests/test_solveset.py::test_solveset_real_log",
"sympy/solvers/tests/test_solveset.py::test_poly_gens",
"sympy/solvers/tests/test_solveset.py::test_solve_abs",
"sympy/solvers/tests/test_solveset.py::test_real_imag_splitting",
"sympy/solvers/tests/test_solveset.py::test_units",
"sympy/solvers/tests/test_solveset.py::test_solve_only_exp_1",
"sympy/solvers/tests/test_solveset.py::test_atan2",
"sympy/solvers/tests/test_solveset.py::test_piecewise",
"sympy/solvers/tests/test_solveset.py::test_solveset_complex_polynomial",
"sympy/solvers/tests/test_solveset.py::test_sol_zero_complex",
"sympy/solvers/tests/test_solveset.py::test_solveset_complex_rational",
"sympy/solvers/tests/test_solveset.py::test_solveset_complex_exp",
"sympy/solvers/tests/test_solveset.py::test_solve_complex_log",
"sympy/solvers/tests/test_solveset.py::test_solve_complex_sqrt",
"sympy/solvers/tests/test_solveset.py::test_solveset_complex_tan",
"sympy/solvers/tests/test_solveset.py::test_solve_trig",
"sympy/solvers/tests/test_solveset.py::test_solve_invalid_sol",
"sympy/solvers/tests/test_solveset.py::test_solveset",
"sympy/solvers/tests/test_solveset.py::test_solveset_domain",
"sympy/solvers/tests/test_solveset.py::test_issue_9522",
"sympy/solvers/tests/test_solveset.py::test_linear_eq_to_matrix",
"sympy/solvers/tests/test_solveset.py::test_linsolve",
"sympy/solvers/tests/test_solveset.py::test_issue_9556",
"sympy/solvers/tests/test_solveset.py::test_issue_9611",
"sympy/solvers/tests/test_solveset.py::test_issue_9557",
"sympy/solvers/tests/test_solveset.py::test_issue_9778",
"sympy/solvers/tests/test_solveset.py::test_issue_9849"
] | [] | BSD | 223 |
|
sympy__sympy-9867 | b38fbf5d9bcc90d41b5099f7ddbd446b17ce5007 | 2015-08-27 05:20:13 | 0241b35cae5f2adc04dc37b25f7dc9c5f00bd746 | diff --git a/sympy/sets/fancysets.py b/sympy/sets/fancysets.py
index c44d8d3b8a..0a597f4edf 100644
--- a/sympy/sets/fancysets.py
+++ b/sympy/sets/fancysets.py
@@ -573,7 +573,7 @@ class ComplexPlane(Set):
>>> c = Interval(1, 8)
>>> c1 = ComplexPlane(a*b) # Rectangular Form
>>> c1
- ComplexPlane(Lambda((x, y), x + I*y), [2, 3] x [4, 6])
+ ComplexPlane(Lambda((_x, _y), _x + _y*I), [2, 3] x [4, 6])
* c1 represents the rectangular region in complex plane
surrounded by the coordinates (2, 4), (3, 4), (3, 6) and
@@ -581,7 +581,7 @@ class ComplexPlane(Set):
>>> c2 = ComplexPlane(Union(a*b, b*c))
>>> c2
- ComplexPlane(Lambda((x, y), x + I*y),
+ ComplexPlane(Lambda((_x, _y), _x + _y*I),
[2, 3] x [4, 6] U [4, 6] x [1, 8])
* c2 represents the Union of two rectangular regions in complex
@@ -598,7 +598,7 @@ class ComplexPlane(Set):
>>> theta = Interval(0, 2*S.Pi)
>>> c2 = ComplexPlane(r*theta, polar=True) # Polar Form
>>> c2 # unit Disk
- ComplexPlane(Lambda((r, theta), r*(I*sin(theta) + cos(theta))),
+ ComplexPlane(Lambda((_r, _theta), _r*(I*sin(_theta) + cos(_theta))),
[0, 1] x [0, 2*pi))
* c2 represents the region in complex plane inside the
@@ -613,7 +613,7 @@ class ComplexPlane(Set):
>>> upper_half_unit_disk = ComplexPlane(Interval(0, 1)*Interval(0, S.Pi), polar=True)
>>> intersection = unit_disk.intersect(upper_half_unit_disk)
>>> intersection
- ComplexPlane(Lambda((r, theta), r*(I*sin(theta) + cos(theta))), [0, 1] x [0, pi])
+ ComplexPlane(Lambda((_r, _theta), _r*(I*sin(_theta) + cos(_theta))), [0, 1] x [0, pi])
>>> intersection == upper_half_unit_disk
True
@@ -626,9 +626,9 @@ class ComplexPlane(Set):
is_ComplexPlane = True
def __new__(cls, sets, polar=False):
- from sympy import symbols
+ from sympy import symbols, Dummy
- x, y, r, theta = symbols('x, y, r, theta')
+ x, y, r, theta = symbols('x, y, r, theta', cls=Dummy)
I = S.ImaginaryUnit
# Rectangular Form
| Use Dummy symbols in ComplexPlane
We implemented `ComplexPlane` here #9463, Currently we defined symbols internally as:
```
x, y, r, theta = symbols('x, y, r, theta')
```
The above symbols should be changed to Dummy symbols. | sympy/sympy | diff --git a/sympy/printing/pretty/tests/test_pretty.py b/sympy/printing/pretty/tests/test_pretty.py
index 9cba38a101..d32806b57f 100644
--- a/sympy/printing/pretty/tests/test_pretty.py
+++ b/sympy/printing/pretty/tests/test_pretty.py
@@ -3110,7 +3110,7 @@ def test_pretty_ConditionSet():
def test_pretty_ComplexPlane():
from sympy import ComplexPlane
- ucode_str = u('{x + ⅈ⋅y | x, y ∊ [3, 5] × [4, 6]}')
+ ucode_str = u('{x + y⋅ⅈ | x, y ∊ [3, 5] × [4, 6]}')
assert upretty(ComplexPlane(Interval(3, 5)*Interval(4, 6))) == ucode_str
ucode_str = u('{r⋅(ⅈ⋅sin(θ) + cos(θ)) | r, θ ∊ [0, 1] × [0, 2⋅π)}')
diff --git a/sympy/printing/tests/test_latex.py b/sympy/printing/tests/test_latex.py
index a24fc533d2..56db3af167 100644
--- a/sympy/printing/tests/test_latex.py
+++ b/sympy/printing/tests/test_latex.py
@@ -618,7 +618,7 @@ def test_latex_ConditionSet():
def test_latex_ComplexPlane():
assert latex(ComplexPlane(Interval(3, 5)*Interval(4, 6))) == \
- r"\left\{x + i y\; |\; x, y \in \left[3, 5\right] \times \left[4, 6\right] \right\}"
+ r"\left\{x + y i\; |\; x, y \in \left[3, 5\right] \times \left[4, 6\right] \right\}"
assert latex(ComplexPlane(Interval(0, 1)*Interval(0, 2*pi), polar=True)) == \
r"\left\{r \left(i \sin{\left (\theta \right )} + \cos{\left (\theta \right )}\right)\; |\; r, \theta \in \left[0, 1\right] \times \left[0, 2 \pi\right) \right\}"
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 0,
"issue_text_score": 1,
"test_score": 3
},
"num_modified_files": 1
} | 0.7 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "pytest",
"pip_packages": [
"mpmath>=0.19",
"pytest"
],
"pre_install": null,
"python": "3.7",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | attrs @ file:///croot/attrs_1668696182826/work
certifi @ file:///croot/certifi_1671487769961/work/certifi
flit_core @ file:///opt/conda/conda-bld/flit-core_1644941570762/work/source/flit_core
importlib-metadata @ file:///tmp/build/80754af9/importlib-metadata_1648562407465/work
iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work
mpmath==1.3.0
packaging @ file:///croot/packaging_1671697413597/work
pluggy @ file:///tmp/build/80754af9/pluggy_1648042572264/work
py @ file:///opt/conda/conda-bld/py_1644396412707/work
pytest==7.1.2
-e git+https://github.com/sympy/sympy.git@b38fbf5d9bcc90d41b5099f7ddbd446b17ce5007#egg=sympy
tomli @ file:///opt/conda/conda-bld/tomli_1657175507142/work
typing_extensions @ file:///croot/typing_extensions_1669924550328/work
zipp @ file:///croot/zipp_1672387121353/work
| name: sympy
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- attrs=22.1.0=py37h06a4308_0
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2022.12.7=py37h06a4308_0
- flit-core=3.6.0=pyhd3eb1b0_0
- importlib-metadata=4.11.3=py37h06a4308_0
- importlib_metadata=4.11.3=hd3eb1b0_0
- iniconfig=1.1.1=pyhd3eb1b0_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- packaging=22.0=py37h06a4308_0
- pip=22.3.1=py37h06a4308_0
- pluggy=1.0.0=py37h06a4308_1
- py=1.11.0=pyhd3eb1b0_0
- pytest=7.1.2=py37h06a4308_0
- python=3.7.16=h7a1cb2a_0
- readline=8.2=h5eee18b_0
- setuptools=65.6.3=py37h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- tomli=2.0.1=py37h06a4308_0
- typing_extensions=4.4.0=py37h06a4308_0
- wheel=0.38.4=py37h06a4308_0
- xz=5.6.4=h5eee18b_1
- zipp=3.11.0=py37h06a4308_0
- zlib=1.2.13=h5eee18b_1
- pip:
- mpmath==1.3.0
prefix: /opt/conda/envs/sympy
| [
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_ComplexPlane",
"sympy/printing/tests/test_latex.py::test_latex_ComplexPlane"
] | [] | [
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_ascii_str",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_unicode_str",
"sympy/printing/pretty/tests/test_pretty.py::test_upretty_greek",
"sympy/printing/pretty/tests/test_pretty.py::test_upretty_multiindex",
"sympy/printing/pretty/tests/test_pretty.py::test_upretty_sub_super",
"sympy/printing/pretty/tests/test_pretty.py::test_upretty_subs_missing_in_24",
"sympy/printing/pretty/tests/test_pretty.py::test_upretty_modifiers",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_basic",
"sympy/printing/pretty/tests/test_pretty.py::test_negative_fractions",
"sympy/printing/pretty/tests/test_pretty.py::test_issue_5524",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_ordering",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_relational",
"sympy/printing/pretty/tests/test_pretty.py::test_issue_7117",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_rational",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_functions",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_sqrt",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_sqrt_char_knob",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_sqrt_longsymbol_no_sqrt_char",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_KroneckerDelta",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_product",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_lambda",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_order",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_derivatives",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_integrals",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_matrix",
"sympy/printing/pretty/tests/test_pretty.py::test_Adjoint",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_piecewise",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_seq",
"sympy/printing/pretty/tests/test_pretty.py::test_any_object_in_sequence",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_sets",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_ConditionSet",
"sympy/printing/pretty/tests/test_pretty.py::test_ProductSet_paranthesis",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_sequences",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_FourierSeries",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_FormalPowerSeries",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_limits",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_RootOf",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_RootSum",
"sympy/printing/pretty/tests/test_pretty.py::test_GroebnerBasis",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_Boolean",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_Domain",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_prec",
"sympy/printing/pretty/tests/test_pretty.py::test_pprint",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_class",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_no_wrap_line",
"sympy/printing/pretty/tests/test_pretty.py::test_settings",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_sum",
"sympy/printing/pretty/tests/test_pretty.py::test_units",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_Subs",
"sympy/printing/pretty/tests/test_pretty.py::test_gammas",
"sympy/printing/pretty/tests/test_pretty.py::test_hyper",
"sympy/printing/pretty/tests/test_pretty.py::test_meijerg",
"sympy/printing/pretty/tests/test_pretty.py::test_noncommutative",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_special_functions",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_geometry",
"sympy/printing/pretty/tests/test_pretty.py::test_expint",
"sympy/printing/pretty/tests/test_pretty.py::test_elliptic_functions",
"sympy/printing/pretty/tests/test_pretty.py::test_RandomDomain",
"sympy/printing/pretty/tests/test_pretty.py::test_PrettyPoly",
"sympy/printing/pretty/tests/test_pretty.py::test_issue_6285",
"sympy/printing/pretty/tests/test_pretty.py::test_issue_6359",
"sympy/printing/pretty/tests/test_pretty.py::test_issue_6739",
"sympy/printing/pretty/tests/test_pretty.py::test_complicated_symbol_unchanged",
"sympy/printing/pretty/tests/test_pretty.py::test_categories",
"sympy/printing/pretty/tests/test_pretty.py::test_PrettyModules",
"sympy/printing/pretty/tests/test_pretty.py::test_QuotientRing",
"sympy/printing/pretty/tests/test_pretty.py::test_Homomorphism",
"sympy/printing/pretty/tests/test_pretty.py::test_Tr",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_Add",
"sympy/printing/pretty/tests/test_pretty.py::test_issue_7179",
"sympy/printing/pretty/tests/test_pretty.py::test_issue_7180",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_Complement",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_SymmetricDifference",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_Contains",
"sympy/printing/pretty/tests/test_pretty.py::test_issue_8292",
"sympy/printing/pretty/tests/test_pretty.py::test_issue_4335",
"sympy/printing/pretty/tests/test_pretty.py::test_issue_8344",
"sympy/printing/pretty/tests/test_pretty.py::test_issue_6324",
"sympy/printing/pretty/tests/test_pretty.py::test_issue_7927",
"sympy/printing/pretty/tests/test_pretty.py::test_issue_6134",
"sympy/printing/tests/test_latex.py::test_printmethod",
"sympy/printing/tests/test_latex.py::test_latex_basic",
"sympy/printing/tests/test_latex.py::test_latex_builtins",
"sympy/printing/tests/test_latex.py::test_latex_Float",
"sympy/printing/tests/test_latex.py::test_latex_symbols",
"sympy/printing/tests/test_latex.py::test_latex_functions",
"sympy/printing/tests/test_latex.py::test_hyper_printing",
"sympy/printing/tests/test_latex.py::test_latex_bessel",
"sympy/printing/tests/test_latex.py::test_latex_fresnel",
"sympy/printing/tests/test_latex.py::test_latex_brackets",
"sympy/printing/tests/test_latex.py::test_latex_indexed",
"sympy/printing/tests/test_latex.py::test_latex_derivatives",
"sympy/printing/tests/test_latex.py::test_latex_subs",
"sympy/printing/tests/test_latex.py::test_latex_integrals",
"sympy/printing/tests/test_latex.py::test_latex_sets",
"sympy/printing/tests/test_latex.py::test_latex_Range",
"sympy/printing/tests/test_latex.py::test_latex_sequences",
"sympy/printing/tests/test_latex.py::test_latex_FourierSeries",
"sympy/printing/tests/test_latex.py::test_latex_FormalPowerSeries",
"sympy/printing/tests/test_latex.py::test_latex_intervals",
"sympy/printing/tests/test_latex.py::test_latex_emptyset",
"sympy/printing/tests/test_latex.py::test_latex_union",
"sympy/printing/tests/test_latex.py::test_latex_symmetric_difference",
"sympy/printing/tests/test_latex.py::test_latex_Complement",
"sympy/printing/tests/test_latex.py::test_latex_Complexes",
"sympy/printing/tests/test_latex.py::test_latex_productset",
"sympy/printing/tests/test_latex.py::test_latex_Naturals",
"sympy/printing/tests/test_latex.py::test_latex_Naturals0",
"sympy/printing/tests/test_latex.py::test_latex_Integers",
"sympy/printing/tests/test_latex.py::test_latex_ImageSet",
"sympy/printing/tests/test_latex.py::test_latex_ConditionSet",
"sympy/printing/tests/test_latex.py::test_latex_Contains",
"sympy/printing/tests/test_latex.py::test_latex_sum",
"sympy/printing/tests/test_latex.py::test_latex_product",
"sympy/printing/tests/test_latex.py::test_latex_limits",
"sympy/printing/tests/test_latex.py::test_issue_3568",
"sympy/printing/tests/test_latex.py::test_latex",
"sympy/printing/tests/test_latex.py::test_latex_dict",
"sympy/printing/tests/test_latex.py::test_latex_list",
"sympy/printing/tests/test_latex.py::test_latex_rational",
"sympy/printing/tests/test_latex.py::test_latex_inverse",
"sympy/printing/tests/test_latex.py::test_latex_DiracDelta",
"sympy/printing/tests/test_latex.py::test_latex_Heaviside",
"sympy/printing/tests/test_latex.py::test_latex_KroneckerDelta",
"sympy/printing/tests/test_latex.py::test_latex_LeviCivita",
"sympy/printing/tests/test_latex.py::test_mode",
"sympy/printing/tests/test_latex.py::test_latex_Piecewise",
"sympy/printing/tests/test_latex.py::test_latex_Matrix",
"sympy/printing/tests/test_latex.py::test_latex_matrix_with_functions",
"sympy/printing/tests/test_latex.py::test_latex_mul_symbol",
"sympy/printing/tests/test_latex.py::test_latex_issue_4381",
"sympy/printing/tests/test_latex.py::test_latex_issue_4576",
"sympy/printing/tests/test_latex.py::test_latex_pow_fraction",
"sympy/printing/tests/test_latex.py::test_noncommutative",
"sympy/printing/tests/test_latex.py::test_latex_order",
"sympy/printing/tests/test_latex.py::test_latex_Lambda",
"sympy/printing/tests/test_latex.py::test_latex_PolyElement",
"sympy/printing/tests/test_latex.py::test_latex_FracElement",
"sympy/printing/tests/test_latex.py::test_latex_Poly",
"sympy/printing/tests/test_latex.py::test_latex_RootOf",
"sympy/printing/tests/test_latex.py::test_latex_RootSum",
"sympy/printing/tests/test_latex.py::test_settings",
"sympy/printing/tests/test_latex.py::test_latex_numbers",
"sympy/printing/tests/test_latex.py::test_lamda",
"sympy/printing/tests/test_latex.py::test_custom_symbol_names",
"sympy/printing/tests/test_latex.py::test_matAdd",
"sympy/printing/tests/test_latex.py::test_matMul",
"sympy/printing/tests/test_latex.py::test_latex_MatrixSlice",
"sympy/printing/tests/test_latex.py::test_latex_RandomDomain",
"sympy/printing/tests/test_latex.py::test_PrettyPoly",
"sympy/printing/tests/test_latex.py::test_integral_transforms",
"sympy/printing/tests/test_latex.py::test_PolynomialRingBase",
"sympy/printing/tests/test_latex.py::test_categories",
"sympy/printing/tests/test_latex.py::test_Modules",
"sympy/printing/tests/test_latex.py::test_QuotientRing",
"sympy/printing/tests/test_latex.py::test_Tr",
"sympy/printing/tests/test_latex.py::test_Adjoint",
"sympy/printing/tests/test_latex.py::test_Hadamard",
"sympy/printing/tests/test_latex.py::test_ZeroMatrix",
"sympy/printing/tests/test_latex.py::test_boolean_args_order",
"sympy/printing/tests/test_latex.py::test_imaginary",
"sympy/printing/tests/test_latex.py::test_builtins_without_args",
"sympy/printing/tests/test_latex.py::test_latex_greek_functions",
"sympy/printing/tests/test_latex.py::test_translate",
"sympy/printing/tests/test_latex.py::test_other_symbols",
"sympy/printing/tests/test_latex.py::test_modifiers",
"sympy/printing/tests/test_latex.py::test_greek_symbols",
"sympy/printing/tests/test_latex.py::test_builtin_no_args",
"sympy/printing/tests/test_latex.py::test_issue_6853",
"sympy/printing/tests/test_latex.py::test_Mul",
"sympy/printing/tests/test_latex.py::test_Pow",
"sympy/printing/tests/test_latex.py::test_issue_7180",
"sympy/printing/tests/test_latex.py::test_issue_8409",
"sympy/printing/tests/test_latex.py::test_issue_8470",
"sympy/printing/tests/test_latex.py::test_issue_7117",
"sympy/printing/tests/test_latex.py::test_issue_2934"
] | [] | BSD | 224 |
|
kevin1024__vcrpy-201 | d620095c3667cc7f9fd7ea1213948dd58db6aefb | 2015-08-28 11:29:16 | 31c358c0350fdb56603fe4b96df2be05aa2c6838 | diff --git a/README.rst b/README.rst
index 23910bb..768e850 100644
--- a/README.rst
+++ b/README.rst
@@ -1,16 +1,14 @@
-|Build Status| |Stories in Ready| |Gitter|
-
VCR.py
======
-.. figure:: https://raw.github.com/kevin1024/vcrpy/master/vcr.png
+.. image:: vcr.png
:alt: vcr.py
- vcr.py
-
This is a Python version of `Ruby's VCR
library <https://github.com/vcr/vcr>`__.
+|Build Status| |Stories in Ready| |Gitter Chat|
+
What it does
------------
@@ -758,6 +756,6 @@ more details
:target: http://travis-ci.org/kevin1024/vcrpy
.. |Stories in Ready| image:: https://badge.waffle.io/kevin1024/vcrpy.png?label=ready&title=Ready
:target: https://waffle.io/kevin1024/vcrpy
-.. |Gitter| image:: https://badges.gitter.im/Join%20Chat.svg
+.. |Gitter Chat| image:: https://badges.gitter.im/Join%20Chat.svg
:alt: Join the chat at https://gitter.im/kevin1024/vcrpy
:target: https://gitter.im/kevin1024/vcrpy?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge
diff --git a/vcr/cassette.py b/vcr/cassette.py
index bc7410f..6dc6c40 100644
--- a/vcr/cassette.py
+++ b/vcr/cassette.py
@@ -75,7 +75,7 @@ class CassetteContextDecorator(object):
lambda key, _: key in self._non_cassette_arguments,
self._args_getter()
)
- if 'path_transformer' in other_kwargs:
+ if other_kwargs.get('path_transformer'):
transformer = other_kwargs['path_transformer']
cassette_kwargs['path'] = transformer(cassette_kwargs['path'])
self.__finish = self._patch_generator(self.cls.load(**cassette_kwargs))
diff --git a/vcr/config.py b/vcr/config.py
index 455d074..99e4cf7 100644
--- a/vcr/config.py
+++ b/vcr/config.py
@@ -2,25 +2,19 @@ import copy
import functools
import inspect
import os
-import types
import six
from .compat import collections
from .cassette import Cassette
from .serializers import yamlserializer, jsonserializer
-from .util import compose, auto_decorate
+from .util import compose
from . import matchers
from . import filters
class VCR(object):
- @staticmethod
- def is_test_method(method_name, function):
- return method_name.startswith('test') and \
- isinstance(function, types.FunctionType)
-
@staticmethod
def ensure_suffix(suffix):
def ensure(path):
@@ -29,7 +23,7 @@ class VCR(object):
return path
return ensure
- def __init__(self, path_transformer=lambda x: x, before_record_request=None,
+ def __init__(self, path_transformer=None, before_record_request=None,
custom_patches=(), filter_query_parameters=(), ignore_hosts=(),
record_mode="once", ignore_localhost=False, filter_headers=(),
before_record_response=None, filter_post_data_parameters=(),
@@ -114,7 +108,7 @@ class VCR(object):
matcher_names = kwargs.get('match_on', self.match_on)
path_transformer = kwargs.get(
'path_transformer',
- self.path_transformer or self.ensure_suffix('.yaml')
+ self.path_transformer
)
func_path_generator = kwargs.get(
'func_path_generator',
@@ -208,7 +202,7 @@ class VCR(object):
if filter_query_parameters:
filter_functions.append(functools.partial(
filters.remove_query_parameters,
- query_parameters_to_remove=filter_query_parameters
+ query_parameters_to_remove=filter_query_parameters
))
if filter_post_data_parameters:
filter_functions.append(
@@ -256,7 +250,3 @@ class VCR(object):
def register_matcher(self, name, matcher):
self.matchers[name] = matcher
-
- def test_case(self, predicate=None):
- predicate = predicate or self.is_test_method
- return six.with_metaclass(auto_decorate(self.use_cassette, predicate))
diff --git a/vcr/util.py b/vcr/util.py
index dd66320..b36ff75 100644
--- a/vcr/util.py
+++ b/vcr/util.py
@@ -1,6 +1,4 @@
import collections
-import types
-
# Shamelessly stolen from https://github.com/kennethreitz/requests/blob/master/requests/structures.py
class CaseInsensitiveDict(collections.MutableMapping):
@@ -83,8 +81,9 @@ def partition_dict(predicate, dictionary):
def compose(*functions):
def composed(incoming):
res = incoming
- for function in functions[::-1]:
- res = function(res)
+ for function in reversed(functions):
+ if function:
+ res = function(res)
return res
return composed
@@ -92,30 +91,3 @@ def read_body(request):
if hasattr(request.body, 'read'):
return request.body.read()
return request.body
-
-
-def auto_decorate(
- decorator,
- predicate=lambda name, value: isinstance(value, types.FunctionType)
-):
- def maybe_decorate(attribute, value):
- if predicate(attribute, value):
- value = decorator(value)
- return value
-
- class DecorateAll(type):
-
- def __setattr__(cls, attribute, value):
- return super(DecorateAll, cls).__setattr__(
- attribute, maybe_decorate(attribute, value)
- )
-
- def __new__(cls, name, bases, attributes_dict):
- new_attributes_dict = dict(
- (attribute, maybe_decorate(attribute, value))
- for attribute, value in attributes_dict.items()
- )
- return super(DecorateAll, cls).__new__(
- cls, name, bases, new_attributes_dict
- )
- return DecorateAll
| path_transformer doesn't default properly
In the code, we have
```python
class VCR(object):
def __init__(self, path_transformer=lambda x: x, before_record_request=None,
```
and then later
```python
def get_merged_config(self, **kwargs):
path_transformer = kwargs.get(
'path_transformer',
self.path_transformer or self.ensure_suffix('.yaml')
)
```
and then later
```python
if 'path_transformer' in other_kwargs:
transformer = other_kwargs['path_transformer']
cassette_kwargs['path'] = transformer(cassette_kwargs['path'])
```
So there are two problems with this code:
1. The default `ensure_suffix` doesn't fire because the parameter default is already the identity function which is truthy. The only way this fires is if the user specifies `path_transformer=None` which is surely not the intent.
2. If the context manager is called with `path_transformer=None` then it will blow up. | kevin1024/vcrpy | diff --git a/tests/unit/test_cassettes.py b/tests/unit/test_cassettes.py
index e1e9fb9..413b154 100644
--- a/tests/unit/test_cassettes.py
+++ b/tests/unit/test_cassettes.py
@@ -245,6 +245,13 @@ def test_path_transformer_with_context_manager():
assert cassette._path == 'a'
+def test_path_transformer_None():
+ with Cassette.use(
+ path='a', path_transformer=None,
+ ) as cassette:
+ assert cassette._path == 'a'
+
+
def test_func_path_generator():
def generator(function):
return os.path.join(os.path.dirname(inspect.getfile(function)),
diff --git a/tests/unit/test_vcr.py b/tests/unit/test_vcr.py
index 7150f15..6cbf21b 100644
--- a/tests/unit/test_vcr.py
+++ b/tests/unit/test_vcr.py
@@ -1,13 +1,11 @@
import os
import pytest
-from six.moves import http_client as httplib
from vcr import VCR, use_cassette
from vcr.compat import mock
from vcr.request import Request
from vcr.stubs import VCRHTTPSConnection
-from vcr.patch import _HTTPConnection, force_reset
def test_vcr_use_cassette():
@@ -100,6 +98,28 @@ def test_vcr_before_record_response_iterable():
assert mock_filter.call_count == 1
+def test_vcr_path_transformer():
+ # Regression test for #199
+
+ # Prevent actually saving the cassette
+ with mock.patch('vcr.cassette.save_cassette'):
+
+ # Baseline: path should be unchanged
+ vcr = VCR()
+ with vcr.use_cassette('test') as cassette:
+ assert cassette._path == 'test'
+
+ # Regression test: path_transformer=None should do the same.
+ vcr = VCR(path_transformer=None)
+ with vcr.use_cassette('test') as cassette:
+ assert cassette._path == 'test'
+
+ # and it should still work with cassette_library_dir
+ vcr = VCR(cassette_library_dir='/foo')
+ with vcr.use_cassette('test') as cassette:
+ assert cassette._path == '/foo/test'
+
+
@pytest.fixture
def random_fixture():
return 1
@@ -245,7 +265,6 @@ def test_path_transformer():
def test_cassette_name_generator_defaults_to_using_module_function_defined_in():
vcr = VCR(inject_cassette=True)
-
@vcr.use_cassette
def function_name(cassette):
assert cassette._path == os.path.join(os.path.dirname(__file__),
@@ -277,29 +296,3 @@ def test_additional_matchers():
function_defaults()
function_additional()
-
-
-class TestVCRClass(VCR().test_case()):
-
- def no_decoration(self):
- assert httplib.HTTPConnection == _HTTPConnection
- self.test_dynamically_added()
- assert httplib.HTTPConnection == _HTTPConnection
-
- def test_one(self):
- with force_reset():
- self.no_decoration()
- with force_reset():
- self.test_two()
- assert httplib.HTTPConnection != _HTTPConnection
-
- def test_two(self):
- assert httplib.HTTPConnection != _HTTPConnection
-
-
-def test_dynamically_added(self):
- assert httplib.HTTPConnection != _HTTPConnection
-
-
-TestVCRClass.test_dynamically_added = test_dynamically_added
-del test_dynamically_added
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 0,
"issue_text_score": 1,
"test_score": 2
},
"num_modified_files": 4
} | 1.7 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[dev]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest",
"pytest-localserver",
"mock"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.7",
"reqs_path": [
"requirements/base.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | certifi @ file:///croot/certifi_1671487769961/work/certifi
exceptiongroup==1.2.2
importlib-metadata==6.7.0
iniconfig==2.0.0
MarkupSafe==2.1.5
mock==5.2.0
packaging==24.0
pluggy==1.2.0
pytest==7.4.4
pytest-localserver==0.9.0.post0
PyYAML==6.0.1
six==1.17.0
tomli==2.0.1
typing_extensions==4.7.1
-e git+https://github.com/kevin1024/vcrpy.git@d620095c3667cc7f9fd7ea1213948dd58db6aefb#egg=vcrpy
Werkzeug==2.2.3
wrapt==1.16.0
zipp==3.15.0
| name: vcrpy
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2022.12.7=py37h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- pip=22.3.1=py37h06a4308_0
- python=3.7.16=h7a1cb2a_0
- readline=8.2=h5eee18b_0
- setuptools=65.6.3=py37h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- wheel=0.38.4=py37h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- exceptiongroup==1.2.2
- importlib-metadata==6.7.0
- iniconfig==2.0.0
- markupsafe==2.1.5
- mock==5.2.0
- packaging==24.0
- pluggy==1.2.0
- pytest==7.4.4
- pytest-localserver==0.9.0.post0
- pyyaml==6.0.1
- six==1.17.0
- tomli==2.0.1
- typing-extensions==4.7.1
- werkzeug==2.2.3
- wrapt==1.16.0
- zipp==3.15.0
prefix: /opt/conda/envs/vcrpy
| [
"tests/unit/test_cassettes.py::test_path_transformer_None",
"tests/unit/test_vcr.py::test_vcr_path_transformer"
] | [
"tests/unit/test_cassettes.py::test_use_as_decorator_on_coroutine",
"tests/unit/test_cassettes.py::test_use_as_decorator_on_generator"
] | [
"tests/unit/test_cassettes.py::test_cassette_load",
"tests/unit/test_cassettes.py::test_cassette_not_played",
"tests/unit/test_cassettes.py::test_cassette_append",
"tests/unit/test_cassettes.py::test_cassette_len",
"tests/unit/test_cassettes.py::test_cassette_contains",
"tests/unit/test_cassettes.py::test_cassette_responses_of",
"tests/unit/test_cassettes.py::test_cassette_get_missing_response",
"tests/unit/test_cassettes.py::test_cassette_cant_read_same_request_twice",
"tests/unit/test_cassettes.py::test_function_decorated_with_use_cassette_can_be_invoked_multiple_times",
"tests/unit/test_cassettes.py::test_arg_getter_functionality",
"tests/unit/test_cassettes.py::test_cassette_not_all_played",
"tests/unit/test_cassettes.py::test_cassette_all_played",
"tests/unit/test_cassettes.py::test_before_record_response",
"tests/unit/test_cassettes.py::test_nesting_cassette_context_managers",
"tests/unit/test_cassettes.py::test_nesting_context_managers_by_checking_references_of_http_connection",
"tests/unit/test_cassettes.py::test_custom_patchers",
"tests/unit/test_cassettes.py::test_decorated_functions_are_reentrant",
"tests/unit/test_cassettes.py::test_cassette_use_called_without_path_uses_function_to_generate_path",
"tests/unit/test_cassettes.py::test_path_transformer_with_function_path",
"tests/unit/test_cassettes.py::test_path_transformer_with_context_manager",
"tests/unit/test_cassettes.py::test_func_path_generator",
"tests/unit/test_vcr.py::test_vcr_use_cassette",
"tests/unit/test_vcr.py::test_vcr_before_record_request_params",
"tests/unit/test_vcr.py::test_vcr_before_record_response_iterable",
"tests/unit/test_vcr.py::test_fixtures_with_use_cassette",
"tests/unit/test_vcr.py::test_custom_patchers",
"tests/unit/test_vcr.py::test_inject_cassette",
"tests/unit/test_vcr.py::test_with_current_defaults",
"tests/unit/test_vcr.py::test_cassette_library_dir_with_decoration_and_no_explicit_path",
"tests/unit/test_vcr.py::test_cassette_library_dir_with_decoration_and_explicit_path",
"tests/unit/test_vcr.py::test_cassette_library_dir_with_decoration_and_super_explicit_path",
"tests/unit/test_vcr.py::test_cassette_library_dir_with_path_transformer",
"tests/unit/test_vcr.py::test_use_cassette_with_no_extra_invocation",
"tests/unit/test_vcr.py::test_path_transformer",
"tests/unit/test_vcr.py::test_cassette_name_generator_defaults_to_using_module_function_defined_in",
"tests/unit/test_vcr.py::test_ensure_suffix",
"tests/unit/test_vcr.py::test_additional_matchers"
] | [] | MIT License | 225 |
|
paver__paver-152 | e5e75eefb3ccbef2b112419740661d59017d043d | 2015-08-28 15:37:52 | e5e75eefb3ccbef2b112419740661d59017d043d | diff --git a/paver/tasks.py b/paver/tasks.py
index 2eb1c4a..3498321 100644
--- a/paver/tasks.py
+++ b/paver/tasks.py
@@ -147,11 +147,11 @@ class Environment(object):
for option in options:
task._set_value_to_task(task_name, option, None, options[option])
- if args and task.consume_args > 0:
+ if args is not None and task.consume_args > 0:
args = _consume_nargs(task, args)
elif args and (task.consume_args == 0):
raise BuildFailure("Task %s is not decorated with @consume_(n)args,"
- "but has been called with them")
+ "but has been called with them" % task)
task()
def _run_task(self, task_name, needs, func):
| When a empty args list is given to call_task, the args of the previous task are used.
I have a task that calls another task. The first one give 0 to n arguments to the the second one. The first needs a third task that is calling a fourth one with some arguments. When the first one gives at least 1 argument, the behavior is correct. But when the first one uses an empty list of arguments, the arguments of the call of the third to the fourth are reused.
```
from paver.easy import *
@task
@needs('specific_dep')
@consume_args
def my_task(args):
call_task('the_other_task', args=args)
@task
@consume_args
def the_other_task(args):
info('Doing the thing with the args: %s', args)
@task
def specific_dep():
call_task('generic_dep', args=['specific'])
@task
@consume_args
def generic_dep(args):
name, = args
info('Loading the dependency %s', name)
```
```
% ./venv/bin/paver my_task args
---> pavement.my_task
---> pavement.specific_dep
---> pavement.generic_dep
Loading the dependency specific
---> pavement.the_other_task
Doing the thing with the args: ['args']
% ./venv/bin/paver my_task
---> pavement.my_task
---> pavement.specific_dep
---> pavement.generic_dep
Loading the dependency specific
---> pavement.the_other_task
Doing the thing with the args: ['specific'] ### Should be Doing the thing with the args: []
``` | paver/paver | diff --git a/paver/tests/test_tasks.py b/paver/tests/test_tasks.py
index b8a419c..62419d7 100644
--- a/paver/tests/test_tasks.py
+++ b/paver/tests/test_tasks.py
@@ -847,6 +847,25 @@ def test_calling_task_with_arguments():
tasks._process_commands(['t1'])
+def test_calling_task_with_empty_arguments():
+ @tasks.task
+ def t1():
+ env.call_task('t3', args=['argument1'])
+ env.call_task('t2', args=[])
+
+ @tasks.task
+ @tasks.consume_args
+ def t2(args):
+ assert args == []
+
+ @tasks.task
+ @tasks.consume_args
+ def t3(args):
+ assert args == ['argument1']
+
+ env = _set_environment(t1=t1, t2=t2, t3=t3)
+ tasks._process_commands(['t1'])
+
def test_calling_nonconsuming_task_with_arguments():
@tasks.task
def t2():
| {
"commit_name": "head_commit",
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true,
"llm_score": {
"difficulty_score": 0,
"issue_text_score": 1,
"test_score": 0
},
"num_modified_files": 1
} | 1.2 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "pytest",
"pip_packages": [
"numpy>=1.16.0",
"pytest"
],
"pre_install": null,
"python": "3.9",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | exceptiongroup @ file:///croot/exceptiongroup_1706031385326/work
iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work
numpy==2.0.2
packaging @ file:///croot/packaging_1734472117206/work
-e git+https://github.com/paver/paver.git@e5e75eefb3ccbef2b112419740661d59017d043d#egg=Paver
pluggy @ file:///croot/pluggy_1733169602837/work
pytest @ file:///croot/pytest_1738938843180/work
tomli @ file:///opt/conda/conda-bld/tomli_1657175507142/work
| name: paver
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- exceptiongroup=1.2.0=py39h06a4308_0
- iniconfig=1.1.1=pyhd3eb1b0_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=3.0.16=h5eee18b_0
- packaging=24.2=py39h06a4308_0
- pip=25.0=py39h06a4308_0
- pluggy=1.5.0=py39h06a4308_0
- pytest=8.3.4=py39h06a4308_0
- python=3.9.21=he870216_1
- readline=8.2=h5eee18b_0
- setuptools=75.8.0=py39h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- tomli=2.0.1=py39h06a4308_0
- tzdata=2025a=h04d1e81_0
- wheel=0.45.1=py39h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- numpy==2.0.2
prefix: /opt/conda/envs/paver
| [
"paver/tests/test_tasks.py::test_calling_task_with_empty_arguments"
] | [] | [
"paver/tests/test_tasks.py::test_basic_dependencies",
"paver/tests/test_tasks.py::test_longname_resolution_in_dependencies",
"paver/tests/test_tasks.py::test_chained_dependencies",
"paver/tests/test_tasks.py::test_backwards_compatible_needs",
"paver/tests/test_tasks.py::test_tasks_dont_repeat",
"paver/tests/test_tasks.py::test_basic_command_line",
"paver/tests/test_tasks.py::test_list_tasks",
"paver/tests/test_tasks.py::test_environment_insertion",
"paver/tests/test_tasks.py::test_add_options_to_environment",
"paver/tests/test_tasks.py::test_shortname_access",
"paver/tests/test_tasks.py::test_longname_access",
"paver/tests/test_tasks.py::test_task_command_line_options",
"paver/tests/test_tasks.py::test_setting_of_options_with_equals",
"paver/tests/test_tasks.py::test_options_inherited_via_needs",
"paver/tests/test_tasks.py::test_options_inherited_via_needs_even_from_grandparents",
"paver/tests/test_tasks.py::test_options_shouldnt_overlap",
"paver/tests/test_tasks.py::test_options_shouldnt_overlap_when_bad_task_specified",
"paver/tests/test_tasks.py::test_options_may_overlap_if_explicitly_allowed",
"paver/tests/test_tasks.py::test_exactly_same_parameters_must_be_specified_in_order_to_allow_sharing",
"paver/tests/test_tasks.py::test_dest_parameter_should_map_opt_to_property",
"paver/tests/test_tasks.py::test_dotted_options",
"paver/tests/test_tasks.py::test_dry_run",
"paver/tests/test_tasks.py::test_consume_args",
"paver/tests/test_tasks.py::test_consume_nargs",
"paver/tests/test_tasks.py::test_consume_nargs_and_options",
"paver/tests/test_tasks.py::test_optional_args_in_tasks",
"paver/tests/test_tasks.py::test_debug_logging",
"paver/tests/test_tasks.py::test_base_logging",
"paver/tests/test_tasks.py::test_error_show_up_no_matter_what",
"paver/tests/test_tasks.py::test_all_messages_for_a_task_are_captured",
"paver/tests/test_tasks.py::test_messages_with_formatting_and_no_args_still_work",
"paver/tests/test_tasks.py::test_alternate_pavement_option",
"paver/tests/test_tasks.py::test_captured_output_shows_up_on_exception",
"paver/tests/test_tasks.py::test_calling_subpavement",
"paver/tests/test_tasks.py::test_task_finders",
"paver/tests/test_tasks.py::test_calling_a_function_rather_than_task",
"paver/tests/test_tasks.py::test_depending_on_a_function_rather_than_task",
"paver/tests/test_tasks.py::test_description_retrieval_trial",
"paver/tests/test_tasks.py::test_description_empty_without_docstring",
"paver/tests/test_tasks.py::test_description_retrieval_first_sentence",
"paver/tests/test_tasks.py::test_description_retrieval_first_sentence_even_with_version_numbers",
"paver/tests/test_tasks.py::test_auto_task_is_not_run_with_noauto",
"paver/tests/test_tasks.py::test_auto_task_is_run_when_present",
"paver/tests/test_tasks.py::test_task_can_be_called_repeatedly",
"paver/tests/test_tasks.py::test_options_passed_to_task",
"paver/tests/test_tasks.py::test_calling_task_with_option_arguments",
"paver/tests/test_tasks.py::test_calling_task_with_arguments_do_not_overwrite_it_for_other_tasks",
"paver/tests/test_tasks.py::test_options_might_be_provided_if_task_might_be_called",
"paver/tests/test_tasks.py::test_calling_task_with_arguments",
"paver/tests/test_tasks.py::test_calling_nonconsuming_task_with_arguments",
"paver/tests/test_tasks.py::test_options_may_overlap_between_multiple_tasks_even_when_specified_in_reverse_order",
"paver/tests/test_tasks.py::test_options_might_be_shared_both_way"
] | [] | BSD License | 226 |
|
sympy__sympy-9873 | af069afd35905b35c269350249a6230f96fc16b1 | 2015-08-29 07:20:46 | 0241b35cae5f2adc04dc37b25f7dc9c5f00bd746 | diff --git a/doc/src/modules/sets.rst b/doc/src/modules/sets.rst
index dafafc9591..c4fc93d66e 100644
--- a/doc/src/modules/sets.rst
+++ b/doc/src/modules/sets.rst
@@ -87,9 +87,9 @@ Range
.. autoclass:: Range
:members:
-ComplexPlane
-^^^^^^^^^^^^
-.. autoclass:: ComplexPlane
+ComplexRegion
+^^^^^^^^^^^^^
+.. autoclass:: ComplexRegion
:members:
.. autofunction:: normalize_theta_set
diff --git a/sympy/printing/latex.py b/sympy/printing/latex.py
index d177f2aedd..bf0658c4bc 100644
--- a/sympy/printing/latex.py
+++ b/sympy/printing/latex.py
@@ -1578,7 +1578,7 @@ def _print_ConditionSet(self, s):
self._print(s.base_set),
self._print(s.condition.expr))
- def _print_ComplexPlane(self, s):
+ def _print_ComplexRegion(self, s):
vars_print = ', '.join([self._print(var) for var in s.args[0].variables])
return r"\left\{%s\; |\; %s \in %s \right\}" % (
self._print(s.args[0].expr),
diff --git a/sympy/printing/pretty/pretty.py b/sympy/printing/pretty/pretty.py
index b46013af50..440ebaae27 100644
--- a/sympy/printing/pretty/pretty.py
+++ b/sympy/printing/pretty/pretty.py
@@ -1531,7 +1531,7 @@ def _print_ConditionSet(self, ts):
return self._print_seq((variables, bar, variables, inn,
base, _and, cond), "{", "}", ' ')
- def _print_ComplexPlane(self, ts):
+ def _print_ComplexRegion(self, ts):
if self._use_unicode:
inn = u("\N{SMALL ELEMENT OF}")
else:
diff --git a/sympy/sets/__init__.py b/sympy/sets/__init__.py
index ad1ed12cd1..3592acef91 100644
--- a/sympy/sets/__init__.py
+++ b/sympy/sets/__init__.py
@@ -1,5 +1,5 @@
from .sets import (Set, Interval, Union, EmptySet, FiniteSet, ProductSet,
Intersection, imageset, Complement, SymmetricDifference)
-from .fancysets import TransformationSet, ImageSet, Range, ComplexPlane
+from .fancysets import TransformationSet, ImageSet, Range, ComplexRegion
from .contains import Contains
from .conditionset import ConditionSet
diff --git a/sympy/sets/fancysets.py b/sympy/sets/fancysets.py
index 0a597f4edf..64c45366a7 100644
--- a/sympy/sets/fancysets.py
+++ b/sympy/sets/fancysets.py
@@ -543,7 +543,7 @@ def normalize_theta_set(theta):
raise ValueError(" %s is not a real set" % (theta))
-class ComplexPlane(Set):
+class ComplexRegion(Set):
"""
Represents the Set of all Complex Numbers. It can represent a
region of Complex Plane in both the standard forms Polar and
@@ -565,23 +565,23 @@ class ComplexPlane(Set):
Examples
========
- >>> from sympy.sets.fancysets import ComplexPlane
+ >>> from sympy.sets.fancysets import ComplexRegion
>>> from sympy.sets import Interval
>>> from sympy import S, I, Union
>>> a = Interval(2, 3)
>>> b = Interval(4, 6)
>>> c = Interval(1, 8)
- >>> c1 = ComplexPlane(a*b) # Rectangular Form
+ >>> c1 = ComplexRegion(a*b) # Rectangular Form
>>> c1
- ComplexPlane(Lambda((_x, _y), _x + _y*I), [2, 3] x [4, 6])
+ ComplexRegion(Lambda((_x, _y), _x + _y*I), [2, 3] x [4, 6])
* c1 represents the rectangular region in complex plane
surrounded by the coordinates (2, 4), (3, 4), (3, 6) and
(2, 6), of the four vertices.
- >>> c2 = ComplexPlane(Union(a*b, b*c))
+ >>> c2 = ComplexRegion(Union(a*b, b*c))
>>> c2
- ComplexPlane(Lambda((_x, _y), _x + _y*I),
+ ComplexRegion(Lambda((_x, _y), _x + _y*I),
[2, 3] x [4, 6] U [4, 6] x [1, 8])
* c2 represents the Union of two rectangular regions in complex
@@ -596,9 +596,9 @@ class ComplexPlane(Set):
>>> r = Interval(0, 1)
>>> theta = Interval(0, 2*S.Pi)
- >>> c2 = ComplexPlane(r*theta, polar=True) # Polar Form
+ >>> c2 = ComplexRegion(r*theta, polar=True) # Polar Form
>>> c2 # unit Disk
- ComplexPlane(Lambda((_r, _theta), _r*(I*sin(_theta) + cos(_theta))),
+ ComplexRegion(Lambda((_r, _theta), _r*(I*sin(_theta) + cos(_theta))),
[0, 1] x [0, 2*pi))
* c2 represents the region in complex plane inside the
@@ -609,11 +609,11 @@ class ComplexPlane(Set):
>>> 1 + 2*I in c2
False
- >>> unit_disk = ComplexPlane(Interval(0, 1)*Interval(0, 2*S.Pi), polar=True)
- >>> upper_half_unit_disk = ComplexPlane(Interval(0, 1)*Interval(0, S.Pi), polar=True)
+ >>> unit_disk = ComplexRegion(Interval(0, 1)*Interval(0, 2*S.Pi), polar=True)
+ >>> upper_half_unit_disk = ComplexRegion(Interval(0, 1)*Interval(0, S.Pi), polar=True)
>>> intersection = unit_disk.intersect(upper_half_unit_disk)
>>> intersection
- ComplexPlane(Lambda((_r, _theta), _r*(I*sin(_theta) + cos(_theta))), [0, 1] x [0, pi])
+ ComplexRegion(Lambda((_r, _theta), _r*(I*sin(_theta) + cos(_theta))), [0, 1] x [0, pi])
>>> intersection == upper_half_unit_disk
True
@@ -623,7 +623,7 @@ class ComplexPlane(Set):
Reals
"""
- is_ComplexPlane = True
+ is_ComplexRegion = True
def __new__(cls, sets, polar=False):
from sympy import symbols, Dummy
@@ -637,7 +637,7 @@ def __new__(cls, sets, polar=False):
if all(_a.is_FiniteSet for _a in sets.args) and (len(sets.args) == 2):
# ** ProductSet of FiniteSets in the Complex Plane. **
- # For Cases like ComplexPlane({2, 4}*{3}), It
+ # For Cases like ComplexRegion({2, 4}*{3}), It
# would return {2 + 3*I, 4 + 3*I}
complex_num = []
for x in sets.args[0]:
@@ -682,14 +682,14 @@ def sets(self):
Examples
========
- >>> from sympy import Interval, ComplexPlane, Union
+ >>> from sympy import Interval, ComplexRegion, Union
>>> a = Interval(2, 3)
>>> b = Interval(4, 5)
>>> c = Interval(1, 7)
- >>> C1 = ComplexPlane(a*b)
+ >>> C1 = ComplexRegion(a*b)
>>> C1.sets
[2, 3] x [4, 5]
- >>> C2 = ComplexPlane(Union(a*b, b*c))
+ >>> C2 = ComplexRegion(Union(a*b, b*c))
>>> C2.sets
[2, 3] x [4, 5] U [4, 5] x [1, 7]
@@ -704,14 +704,14 @@ def psets(self):
Examples
========
- >>> from sympy import Interval, ComplexPlane, Union
+ >>> from sympy import Interval, ComplexRegion, Union
>>> a = Interval(2, 3)
>>> b = Interval(4, 5)
>>> c = Interval(1, 7)
- >>> C1 = ComplexPlane(a*b)
+ >>> C1 = ComplexRegion(a*b)
>>> C1.psets
([2, 3] x [4, 5],)
- >>> C2 = ComplexPlane(Union(a*b, b*c))
+ >>> C2 = ComplexRegion(Union(a*b, b*c))
>>> C2.psets
([2, 3] x [4, 5], [4, 5] x [1, 7])
@@ -733,14 +733,14 @@ def a_interval(self):
Examples
========
- >>> from sympy import Interval, ComplexPlane, Union
+ >>> from sympy import Interval, ComplexRegion, Union
>>> a = Interval(2, 3)
>>> b = Interval(4, 5)
>>> c = Interval(1, 7)
- >>> C1 = ComplexPlane(a*b)
+ >>> C1 = ComplexRegion(a*b)
>>> C1.a_interval
[2, 3]
- >>> C2 = ComplexPlane(Union(a*b, b*c))
+ >>> C2 = ComplexRegion(Union(a*b, b*c))
>>> C2.a_interval
[2, 3] U [4, 5]
@@ -762,14 +762,14 @@ def b_interval(self):
Examples
========
- >>> from sympy import Interval, ComplexPlane, Union
+ >>> from sympy import Interval, ComplexRegion, Union
>>> a = Interval(2, 3)
>>> b = Interval(4, 5)
>>> c = Interval(1, 7)
- >>> C1 = ComplexPlane(a*b)
+ >>> C1 = ComplexRegion(a*b)
>>> C1.b_interval
[4, 5]
- >>> C2 = ComplexPlane(Union(a*b, b*c))
+ >>> C2 = ComplexRegion(Union(a*b, b*c))
>>> C2.b_interval
[1, 7]
@@ -789,14 +789,14 @@ def polar(self):
Examples
========
- >>> from sympy import Interval, ComplexPlane, Union, S
+ >>> from sympy import Interval, ComplexRegion, Union, S
>>> a = Interval(2, 3)
>>> b = Interval(4, 5)
>>> theta = Interval(0, 2*S.Pi)
- >>> C1 = ComplexPlane(a*b)
+ >>> C1 = ComplexRegion(a*b)
>>> C1.polar
False
- >>> C2 = ComplexPlane(a*theta, polar=True)
+ >>> C2 = ComplexRegion(a*theta, polar=True)
>>> C2.polar
True
"""
@@ -810,13 +810,13 @@ def _measure(self):
Examples
========
- >>> from sympy import Interval, ComplexPlane, S
+ >>> from sympy import Interval, ComplexRegion, S
>>> a, b = Interval(2, 5), Interval(4, 8)
>>> c = Interval(0, 2*S.Pi)
- >>> c1 = ComplexPlane(a*b)
+ >>> c1 = ComplexRegion(a*b)
>>> c1.measure
12
- >>> c2 = ComplexPlane(a*c, polar=True)
+ >>> c2 = ComplexRegion(a*c, polar=True)
>>> c2.measure
6*pi
@@ -849,10 +849,10 @@ def _contains(self, other):
def _intersect(self, other):
- if other.is_ComplexPlane:
+ if other.is_ComplexRegion:
# self in rectangular form
if (not self.polar) and (not other.polar):
- return ComplexPlane(Intersection(self.sets, other.sets))
+ return ComplexRegion(Intersection(self.sets, other.sets))
# self in polar form
elif self.polar and other.polar:
@@ -866,7 +866,7 @@ def _intersect(self, other):
(2*S.Pi in theta2 and S(0) in theta1)):
new_theta_interval = Union(new_theta_interval,
FiniteSet(0))
- return ComplexPlane(new_r_interval*new_theta_interval,
+ return ComplexRegion(new_r_interval*new_theta_interval,
polar=True)
if other is S.Reals:
@@ -893,15 +893,15 @@ def _intersect(self, other):
def _union(self, other):
- if other.is_ComplexPlane:
+ if other.is_ComplexRegion:
# self in rectangular form
if (not self.polar) and (not other.polar):
- return ComplexPlane(Union(self.sets, other.sets))
+ return ComplexRegion(Union(self.sets, other.sets))
# self in polar form
elif self.polar and other.polar:
- return ComplexPlane(Union(self.sets, other.sets), polar=True)
+ return ComplexRegion(Union(self.sets, other.sets), polar=True)
if other is S.Reals:
return self
@@ -909,14 +909,14 @@ def _union(self, other):
return None
-class Complexes(with_metaclass(Singleton, ComplexPlane)):
+class Complexes(with_metaclass(Singleton, ComplexRegion)):
def __new__(cls):
- return ComplexPlane.__new__(cls, S.Reals*S.Reals)
+ return ComplexRegion.__new__(cls, S.Reals*S.Reals)
def __eq__(self, other):
- if other == ComplexPlane(S.Reals*S.Reals):
+ if other == ComplexRegion(S.Reals*S.Reals):
return True
def __hash__(self):
- return hash(ComplexPlane(S.Reals*S.Reals))
+ return hash(ComplexRegion(S.Reals*S.Reals))
diff --git a/sympy/sets/sets.py b/sympy/sets/sets.py
index a748db622c..a447d607cb 100644
--- a/sympy/sets/sets.py
+++ b/sympy/sets/sets.py
@@ -42,7 +42,7 @@ class Set(Basic):
is_EmptySet = None
is_UniversalSet = None
is_Complement = None
- is_ComplexPlane = False
+ is_ComplexRegion = False
@staticmethod
def _infimum_key(expr):
| Rename ComplexPlane to ComplexRegion
See https://github.com/sympy/sympy/pull/9500#discussion_r37886701
The complex plane is the whole complex plane, whereas an instance of `ComplexPlane` is generally not. | sympy/sympy | diff --git a/sympy/core/tests/test_args.py b/sympy/core/tests/test_args.py
index a21a53ea15..88c4c68264 100644
--- a/sympy/core/tests/test_args.py
+++ b/sympy/core/tests/test_args.py
@@ -542,15 +542,15 @@ def test_sympy__sets__fancysets__Complexes():
assert _test_args(Complexes())
-def test_sympy__sets__fancysets__ComplexPlane():
- from sympy.sets.fancysets import ComplexPlane
+def test_sympy__sets__fancysets__ComplexRegion():
+ from sympy.sets.fancysets import ComplexRegion
from sympy import S
from sympy.sets import Interval
a = Interval(0, 1)
b = Interval(2, 3)
theta = Interval(0, 2*S.Pi)
- assert _test_args(ComplexPlane(a*b))
- assert _test_args(ComplexPlane(a*theta, polar=True))
+ assert _test_args(ComplexRegion(a*b))
+ assert _test_args(ComplexRegion(a*theta, polar=True))
def test_sympy__sets__fancysets__ImageSet():
diff --git a/sympy/printing/pretty/tests/test_pretty.py b/sympy/printing/pretty/tests/test_pretty.py
index d32806b57f..c35bcf549d 100644
--- a/sympy/printing/pretty/tests/test_pretty.py
+++ b/sympy/printing/pretty/tests/test_pretty.py
@@ -3108,13 +3108,13 @@ def test_pretty_ConditionSet():
assert upretty(ConditionSet(Lambda(x, Eq(sin(x), 0)), S.Reals)) == ucode_str
-def test_pretty_ComplexPlane():
- from sympy import ComplexPlane
+def test_pretty_ComplexRegion():
+ from sympy import ComplexRegion
ucode_str = u('{x + y⋅ⅈ | x, y ∊ [3, 5] × [4, 6]}')
- assert upretty(ComplexPlane(Interval(3, 5)*Interval(4, 6))) == ucode_str
+ assert upretty(ComplexRegion(Interval(3, 5)*Interval(4, 6))) == ucode_str
ucode_str = u('{r⋅(ⅈ⋅sin(θ) + cos(θ)) | r, θ ∊ [0, 1] × [0, 2⋅π)}')
- assert upretty(ComplexPlane(Interval(0, 1)*Interval(0, 2*pi), polar=True)) == ucode_str
+ assert upretty(ComplexRegion(Interval(0, 1)*Interval(0, 2*pi), polar=True)) == ucode_str
def test_ProductSet_paranthesis():
diff --git a/sympy/printing/tests/test_latex.py b/sympy/printing/tests/test_latex.py
index 56db3af167..d9e61ac0ae 100644
--- a/sympy/printing/tests/test_latex.py
+++ b/sympy/printing/tests/test_latex.py
@@ -15,7 +15,7 @@
uppergamma, zeta, subfactorial, totient, elliptic_k, elliptic_f,
elliptic_e, elliptic_pi, cos, tan, Wild, true, false, Equivalent, Not,
Contains, divisor_sigma, SymmetricDifference, SeqPer, SeqFormula,
- SeqAdd, SeqMul, fourier_series, pi, ConditionSet, ComplexPlane, fps)
+ SeqAdd, SeqMul, fourier_series, pi, ConditionSet, ComplexRegion, fps)
from sympy.ntheory.factor_ import udivisor_sigma
@@ -616,10 +616,10 @@ def test_latex_ConditionSet():
r"\left\{x\; |\; x \in \mathbb{R} \wedge x^{2} = 1 \right\}"
-def test_latex_ComplexPlane():
- assert latex(ComplexPlane(Interval(3, 5)*Interval(4, 6))) == \
+def test_latex_ComplexRegion():
+ assert latex(ComplexRegion(Interval(3, 5)*Interval(4, 6))) == \
r"\left\{x + y i\; |\; x, y \in \left[3, 5\right] \times \left[4, 6\right] \right\}"
- assert latex(ComplexPlane(Interval(0, 1)*Interval(0, 2*pi), polar=True)) == \
+ assert latex(ComplexRegion(Interval(0, 1)*Interval(0, 2*pi), polar=True)) == \
r"\left\{r \left(i \sin{\left (\theta \right )} + \cos{\left (\theta \right )}\right)\; |\; r, \theta \in \left[0, 1\right] \times \left[0, 2 \pi\right) \right\}"
diff --git a/sympy/sets/tests/test_fancysets.py b/sympy/sets/tests/test_fancysets.py
index 589b8d09e6..a15a09e22b 100644
--- a/sympy/sets/tests/test_fancysets.py
+++ b/sympy/sets/tests/test_fancysets.py
@@ -1,6 +1,6 @@
from sympy.core.compatibility import range
from sympy.sets.fancysets import (ImageSet, Range, normalize_theta_set,
- ComplexPlane)
+ ComplexRegion)
from sympy.sets.sets import (FiniteSet, Interval, imageset, EmptySet, Union,
Intersection)
from sympy import (S, Symbol, Lambda, symbols, cos, sin, pi, oo, Basic,
@@ -198,7 +198,7 @@ def test_Complex():
assert sqrt(-1) in S.Complexes
assert S.Complexes.intersect(S.Reals) == S.Reals
assert S.Complexes.union(S.Reals) == S.Complexes
- assert S.Complexes == ComplexPlane(S.Reals*S.Reals)
+ assert S.Complexes == ComplexRegion(S.Reals*S.Reals)
def take(n, iterable):
@@ -276,14 +276,14 @@ def test_ImageSet_simplification():
imageset(Lambda(m, sin(tan(m))), S.Integers)
-def test_ComplexPlane_contains():
+def test_ComplexRegion_contains():
- # contains in ComplexPlane
+ # contains in ComplexRegion
a = Interval(2, 3)
b = Interval(4, 6)
c = Interval(7, 9)
- c1 = ComplexPlane(a*b)
- c2 = ComplexPlane(Union(a*b, c*a))
+ c1 = ComplexRegion(a*b)
+ c2 = ComplexRegion(Union(a*b, c*a))
assert 2.5 + 4.5*I in c1
assert 2 + 4*I in c1
assert 3 + 4*I in c1
@@ -293,7 +293,7 @@ def test_ComplexPlane_contains():
r1 = Interval(0, 1)
theta1 = Interval(0, 2*S.Pi)
- c3 = ComplexPlane(r1*theta1, polar=True)
+ c3 = ComplexRegion(r1*theta1, polar=True)
assert 0.5 + 0.6*I in c3
assert I in c3
assert 1 in c3
@@ -302,89 +302,89 @@ def test_ComplexPlane_contains():
assert 1 - I not in c3
-def test_ComplexPlane_intersect():
+def test_ComplexRegion_intersect():
# Polar form
- X_axis = ComplexPlane(Interval(0, oo)*FiniteSet(0, S.Pi), polar=True)
+ X_axis = ComplexRegion(Interval(0, oo)*FiniteSet(0, S.Pi), polar=True)
- unit_disk = ComplexPlane(Interval(0, 1)*Interval(0, 2*S.Pi), polar=True)
- upper_half_unit_disk = ComplexPlane(Interval(0, 1)*Interval(0, S.Pi), polar=True)
- upper_half_disk = ComplexPlane(Interval(0, oo)*Interval(0, S.Pi), polar=True)
- lower_half_disk = ComplexPlane(Interval(0, oo)*Interval(S.Pi, 2*S.Pi), polar=True)
- right_half_disk = ComplexPlane(Interval(0, oo)*Interval(-S.Pi/2, S.Pi/2), polar=True)
- first_quad_disk = ComplexPlane(Interval(0, oo)*Interval(0, S.Pi/2), polar=True)
+ unit_disk = ComplexRegion(Interval(0, 1)*Interval(0, 2*S.Pi), polar=True)
+ upper_half_unit_disk = ComplexRegion(Interval(0, 1)*Interval(0, S.Pi), polar=True)
+ upper_half_disk = ComplexRegion(Interval(0, oo)*Interval(0, S.Pi), polar=True)
+ lower_half_disk = ComplexRegion(Interval(0, oo)*Interval(S.Pi, 2*S.Pi), polar=True)
+ right_half_disk = ComplexRegion(Interval(0, oo)*Interval(-S.Pi/2, S.Pi/2), polar=True)
+ first_quad_disk = ComplexRegion(Interval(0, oo)*Interval(0, S.Pi/2), polar=True)
assert upper_half_disk.intersect(unit_disk) == upper_half_unit_disk
assert right_half_disk.intersect(first_quad_disk) == first_quad_disk
assert upper_half_disk.intersect(right_half_disk) == first_quad_disk
assert upper_half_disk.intersect(lower_half_disk) == X_axis
- c1 = ComplexPlane(Interval(0, 4)*Interval(0, 2*S.Pi), polar=True)
+ c1 = ComplexRegion(Interval(0, 4)*Interval(0, 2*S.Pi), polar=True)
assert c1.intersect(Interval(1, 5)) == Interval(1, 4)
assert c1.intersect(Interval(4, 9)) == FiniteSet(4)
assert c1.intersect(Interval(5, 12)) == EmptySet()
# Rectangular form
- X_axis = ComplexPlane(Interval(-oo, oo)*FiniteSet(0))
+ X_axis = ComplexRegion(Interval(-oo, oo)*FiniteSet(0))
- unit_square = ComplexPlane(Interval(-1, 1)*Interval(-1, 1))
- upper_half_unit_square = ComplexPlane(Interval(-1, 1)*Interval(0, 1))
- upper_half_plane = ComplexPlane(Interval(-oo, oo)*Interval(0, oo))
- lower_half_plane = ComplexPlane(Interval(-oo, oo)*Interval(-oo, 0))
- right_half_plane = ComplexPlane(Interval(0, oo)*Interval(-oo, oo))
- first_quad_plane = ComplexPlane(Interval(0, oo)*Interval(0, oo))
+ unit_square = ComplexRegion(Interval(-1, 1)*Interval(-1, 1))
+ upper_half_unit_square = ComplexRegion(Interval(-1, 1)*Interval(0, 1))
+ upper_half_plane = ComplexRegion(Interval(-oo, oo)*Interval(0, oo))
+ lower_half_plane = ComplexRegion(Interval(-oo, oo)*Interval(-oo, 0))
+ right_half_plane = ComplexRegion(Interval(0, oo)*Interval(-oo, oo))
+ first_quad_plane = ComplexRegion(Interval(0, oo)*Interval(0, oo))
assert upper_half_plane.intersect(unit_square) == upper_half_unit_square
assert right_half_plane.intersect(first_quad_plane) == first_quad_plane
assert upper_half_plane.intersect(right_half_plane) == first_quad_plane
assert upper_half_plane.intersect(lower_half_plane) == X_axis
- c1 = ComplexPlane(Interval(-5, 5)*Interval(-10, 10))
+ c1 = ComplexRegion(Interval(-5, 5)*Interval(-10, 10))
assert c1.intersect(Interval(2, 7)) == Interval(2, 5)
assert c1.intersect(Interval(5, 7)) == FiniteSet(5)
assert c1.intersect(Interval(6, 9)) == EmptySet()
# unevaluated object
- C1 = ComplexPlane(Interval(0, 1)*Interval(0, 2*S.Pi), polar=True)
- C2 = ComplexPlane(Interval(-1, 1)*Interval(-1, 1))
+ C1 = ComplexRegion(Interval(0, 1)*Interval(0, 2*S.Pi), polar=True)
+ C2 = ComplexRegion(Interval(-1, 1)*Interval(-1, 1))
assert C1.intersect(C2) == Intersection(C1, C2)
-def test_ComplexPlane_union():
+def test_ComplexRegion_union():
# Polar form
- c1 = ComplexPlane(Interval(0, 1)*Interval(0, 2*S.Pi), polar=True)
- c2 = ComplexPlane(Interval(0, 1)*Interval(0, S.Pi), polar=True)
- c3 = ComplexPlane(Interval(0, oo)*Interval(0, S.Pi), polar=True)
- c4 = ComplexPlane(Interval(0, oo)*Interval(S.Pi, 2*S.Pi), polar=True)
+ c1 = ComplexRegion(Interval(0, 1)*Interval(0, 2*S.Pi), polar=True)
+ c2 = ComplexRegion(Interval(0, 1)*Interval(0, S.Pi), polar=True)
+ c3 = ComplexRegion(Interval(0, oo)*Interval(0, S.Pi), polar=True)
+ c4 = ComplexRegion(Interval(0, oo)*Interval(S.Pi, 2*S.Pi), polar=True)
p1 = Union(Interval(0, 1)*Interval(0, 2*S.Pi), Interval(0, 1)*Interval(0, S.Pi))
p2 = Union(Interval(0, oo)*Interval(0, S.Pi), Interval(0, oo)*Interval(S.Pi, 2*S.Pi))
- assert c1.union(c2) == ComplexPlane(p1, polar=True)
- assert c3.union(c4) == ComplexPlane(p2, polar=True)
+ assert c1.union(c2) == ComplexRegion(p1, polar=True)
+ assert c3.union(c4) == ComplexRegion(p2, polar=True)
# Rectangular form
- c5 = ComplexPlane(Interval(2, 5)*Interval(6, 9))
- c6 = ComplexPlane(Interval(4, 6)*Interval(10, 12))
- c7 = ComplexPlane(Interval(0, 10)*Interval(-10, 0))
- c8 = ComplexPlane(Interval(12, 16)*Interval(14, 20))
+ c5 = ComplexRegion(Interval(2, 5)*Interval(6, 9))
+ c6 = ComplexRegion(Interval(4, 6)*Interval(10, 12))
+ c7 = ComplexRegion(Interval(0, 10)*Interval(-10, 0))
+ c8 = ComplexRegion(Interval(12, 16)*Interval(14, 20))
p3 = Union(Interval(2, 5)*Interval(6, 9), Interval(4, 6)*Interval(10, 12))
p4 = Union(Interval(0, 10)*Interval(-10, 0), Interval(12, 16)*Interval(14, 20))
- assert c5.union(c6) == ComplexPlane(p3)
- assert c7.union(c8) == ComplexPlane(p4)
+ assert c5.union(c6) == ComplexRegion(p3)
+ assert c7.union(c8) == ComplexRegion(p4)
assert c1.union(Interval(2, 4)) == Union(c1, Interval(2, 4))
assert c5.union(Interval(2, 4)) == Union(c5, Interval(2, 4))
-def test_ComplexPlane_measure():
+def test_ComplexRegion_measure():
a, b = Interval(2, 5), Interval(4, 8)
theta1, theta2 = Interval(0, 2*S.Pi), Interval(0, S.Pi)
- c1 = ComplexPlane(a*b)
- c2 = ComplexPlane(Union(a*theta1, b*theta2), polar=True)
+ c1 = ComplexRegion(a*b)
+ c2 = ComplexRegion(Union(a*theta1, b*theta2), polar=True)
assert c1.measure == 12
assert c2.measure == 9*pi
@@ -416,11 +416,11 @@ def test_normalize_theta_set():
raises(ValueError, lambda: normalize_theta_set(S.Complexes))
-def test_ComplexPlane_FiniteSet():
+def test_ComplexRegion_FiniteSet():
x, y, z, a, b, c = symbols('x y z a b c')
# Issue #9669
- assert ComplexPlane(FiniteSet(a, b, c)*FiniteSet(x, y, z)) == \
+ assert ComplexRegion(FiniteSet(a, b, c)*FiniteSet(x, y, z)) == \
FiniteSet(a + I*x, a + I*y, a + I*z, b + I*x, b + I*y,
b + I*z, c + I*x, c + I*y, c + I*z)
- assert ComplexPlane(FiniteSet(2)*FiniteSet(3)) == FiniteSet(2 + 3*I)
+ assert ComplexRegion(FiniteSet(2)*FiniteSet(3)) == FiniteSet(2 + 3*I)
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 2,
"issue_text_score": 0,
"test_score": 0
},
"num_modified_files": 6
} | 0.7 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "pytest",
"pip_packages": [
"mpmath>=0.19",
"pytest",
"pytest-cov",
"pytest-xdist",
"pytest-mock",
"pytest-asyncio"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.6",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | attrs @ file:///opt/conda/conda-bld/attrs_1642510447205/work
certifi==2021.5.30
coverage==6.2
execnet==1.9.0
importlib-metadata @ file:///tmp/build/80754af9/importlib-metadata_1631916693255/work
iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work
more-itertools @ file:///tmp/build/80754af9/more-itertools_1637733554872/work
mpmath==1.3.0
packaging @ file:///tmp/build/80754af9/packaging_1637314298585/work
pluggy @ file:///tmp/build/80754af9/pluggy_1615976315926/work
py @ file:///opt/conda/conda-bld/py_1644396412707/work
pyparsing @ file:///tmp/build/80754af9/pyparsing_1635766073266/work
pytest==6.2.4
pytest-asyncio==0.16.0
pytest-cov==4.0.0
pytest-mock==3.6.1
pytest-xdist==3.0.2
-e git+https://github.com/sympy/sympy.git@af069afd35905b35c269350249a6230f96fc16b1#egg=sympy
toml @ file:///tmp/build/80754af9/toml_1616166611790/work
tomli==1.2.3
typing_extensions @ file:///opt/conda/conda-bld/typing_extensions_1647553014482/work
zipp @ file:///tmp/build/80754af9/zipp_1633618647012/work
| name: sympy
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- attrs=21.4.0=pyhd3eb1b0_0
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2021.5.30=py36h06a4308_0
- importlib-metadata=4.8.1=py36h06a4308_0
- importlib_metadata=4.8.1=hd3eb1b0_0
- iniconfig=1.1.1=pyhd3eb1b0_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.3=he6710b0_2
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- more-itertools=8.12.0=pyhd3eb1b0_0
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- packaging=21.3=pyhd3eb1b0_0
- pip=21.2.2=py36h06a4308_0
- pluggy=0.13.1=py36h06a4308_0
- py=1.11.0=pyhd3eb1b0_0
- pyparsing=3.0.4=pyhd3eb1b0_0
- pytest=6.2.4=py36h06a4308_2
- python=3.6.13=h12debd9_1
- readline=8.2=h5eee18b_0
- setuptools=58.0.4=py36h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- toml=0.10.2=pyhd3eb1b0_0
- typing_extensions=4.1.1=pyh06a4308_0
- wheel=0.37.1=pyhd3eb1b0_0
- xz=5.6.4=h5eee18b_1
- zipp=3.6.0=pyhd3eb1b0_0
- zlib=1.2.13=h5eee18b_1
- pip:
- coverage==6.2
- execnet==1.9.0
- mpmath==1.3.0
- pytest-asyncio==0.16.0
- pytest-cov==4.0.0
- pytest-mock==3.6.1
- pytest-xdist==3.0.2
- tomli==1.2.3
prefix: /opt/conda/envs/sympy
| [
"sympy/core/tests/test_args.py::test_all_classes_are_tested",
"sympy/core/tests/test_args.py::test_sympy__assumptions__assume__AppliedPredicate",
"sympy/core/tests/test_args.py::test_sympy__assumptions__assume__Predicate",
"sympy/core/tests/test_args.py::test_sympy__assumptions__sathandlers__UnevaluatedOnFree",
"sympy/core/tests/test_args.py::test_sympy__assumptions__sathandlers__AllArgs",
"sympy/core/tests/test_args.py::test_sympy__assumptions__sathandlers__AnyArgs",
"sympy/core/tests/test_args.py::test_sympy__assumptions__sathandlers__ExactlyOneArg",
"sympy/core/tests/test_args.py::test_sympy__assumptions__sathandlers__CheckOldAssump",
"sympy/core/tests/test_args.py::test_sympy__assumptions__sathandlers__CheckIsPrime",
"sympy/core/tests/test_args.py::test_sympy__combinatorics__subsets__Subset",
"sympy/core/tests/test_args.py::test_sympy__combinatorics__perm_groups__PermutationGroup",
"sympy/core/tests/test_args.py::test_sympy__combinatorics__polyhedron__Polyhedron",
"sympy/core/tests/test_args.py::test_sympy__combinatorics__partitions__Partition",
"sympy/core/tests/test_args.py::test_sympy__concrete__products__Product",
"sympy/core/tests/test_args.py::test_sympy__concrete__summations__Sum",
"sympy/core/tests/test_args.py::test_sympy__core__add__Add",
"sympy/core/tests/test_args.py::test_sympy__core__basic__Atom",
"sympy/core/tests/test_args.py::test_sympy__core__basic__Basic",
"sympy/core/tests/test_args.py::test_sympy__core__containers__Dict",
"sympy/core/tests/test_args.py::test_sympy__core__containers__Tuple",
"sympy/core/tests/test_args.py::test_sympy__core__expr__AtomicExpr",
"sympy/core/tests/test_args.py::test_sympy__core__expr__Expr",
"sympy/core/tests/test_args.py::test_sympy__core__function__Application",
"sympy/core/tests/test_args.py::test_sympy__core__function__AppliedUndef",
"sympy/core/tests/test_args.py::test_sympy__core__function__Derivative",
"sympy/core/tests/test_args.py::test_sympy__core__function__Lambda",
"sympy/core/tests/test_args.py::test_sympy__core__function__Subs",
"sympy/core/tests/test_args.py::test_sympy__core__function__WildFunction",
"sympy/core/tests/test_args.py::test_sympy__core__mod__Mod",
"sympy/core/tests/test_args.py::test_sympy__core__mul__Mul",
"sympy/core/tests/test_args.py::test_sympy__core__numbers__Catalan",
"sympy/core/tests/test_args.py::test_sympy__core__numbers__ComplexInfinity",
"sympy/core/tests/test_args.py::test_sympy__core__numbers__EulerGamma",
"sympy/core/tests/test_args.py::test_sympy__core__numbers__Exp1",
"sympy/core/tests/test_args.py::test_sympy__core__numbers__Float",
"sympy/core/tests/test_args.py::test_sympy__core__numbers__GoldenRatio",
"sympy/core/tests/test_args.py::test_sympy__core__numbers__Half",
"sympy/core/tests/test_args.py::test_sympy__core__numbers__ImaginaryUnit",
"sympy/core/tests/test_args.py::test_sympy__core__numbers__Infinity",
"sympy/core/tests/test_args.py::test_sympy__core__numbers__Integer",
"sympy/core/tests/test_args.py::test_sympy__core__numbers__NaN",
"sympy/core/tests/test_args.py::test_sympy__core__numbers__NegativeInfinity",
"sympy/core/tests/test_args.py::test_sympy__core__numbers__NegativeOne",
"sympy/core/tests/test_args.py::test_sympy__core__numbers__Number",
"sympy/core/tests/test_args.py::test_sympy__core__numbers__NumberSymbol",
"sympy/core/tests/test_args.py::test_sympy__core__numbers__One",
"sympy/core/tests/test_args.py::test_sympy__core__numbers__Pi",
"sympy/core/tests/test_args.py::test_sympy__core__numbers__Rational",
"sympy/core/tests/test_args.py::test_sympy__core__numbers__Zero",
"sympy/core/tests/test_args.py::test_sympy__core__power__Pow",
"sympy/core/tests/test_args.py::test_sympy__core__relational__Equality",
"sympy/core/tests/test_args.py::test_sympy__core__relational__GreaterThan",
"sympy/core/tests/test_args.py::test_sympy__core__relational__LessThan",
"sympy/core/tests/test_args.py::test_sympy__core__relational__StrictGreaterThan",
"sympy/core/tests/test_args.py::test_sympy__core__relational__StrictLessThan",
"sympy/core/tests/test_args.py::test_sympy__core__relational__Unequality",
"sympy/core/tests/test_args.py::test_sympy__sets__sets__EmptySet",
"sympy/core/tests/test_args.py::test_sympy__sets__sets__UniversalSet",
"sympy/core/tests/test_args.py::test_sympy__sets__sets__FiniteSet",
"sympy/core/tests/test_args.py::test_sympy__sets__sets__Interval",
"sympy/core/tests/test_args.py::test_sympy__sets__sets__ProductSet",
"sympy/core/tests/test_args.py::test_sympy__sets__sets__Intersection",
"sympy/core/tests/test_args.py::test_sympy__sets__sets__Union",
"sympy/core/tests/test_args.py::test_sympy__sets__sets__Complement",
"sympy/core/tests/test_args.py::test_sympy__sets__sets__SymmetricDifference",
"sympy/core/tests/test_args.py::test_sympy__core__trace__Tr",
"sympy/core/tests/test_args.py::test_sympy__sets__fancysets__Naturals",
"sympy/core/tests/test_args.py::test_sympy__sets__fancysets__Naturals0",
"sympy/core/tests/test_args.py::test_sympy__sets__fancysets__Integers",
"sympy/core/tests/test_args.py::test_sympy__sets__fancysets__Reals",
"sympy/core/tests/test_args.py::test_sympy__sets__fancysets__Complexes",
"sympy/core/tests/test_args.py::test_sympy__sets__fancysets__ComplexRegion",
"sympy/core/tests/test_args.py::test_sympy__sets__fancysets__ImageSet",
"sympy/core/tests/test_args.py::test_sympy__sets__fancysets__Range",
"sympy/core/tests/test_args.py::test_sympy__sets__conditionset__ConditionSet",
"sympy/core/tests/test_args.py::test_sympy__sets__contains__Contains",
"sympy/core/tests/test_args.py::test_sympy__stats__crv__ContinuousDomain",
"sympy/core/tests/test_args.py::test_sympy__stats__crv__SingleContinuousDomain",
"sympy/core/tests/test_args.py::test_sympy__stats__crv__ProductContinuousDomain",
"sympy/core/tests/test_args.py::test_sympy__stats__crv__ConditionalContinuousDomain",
"sympy/core/tests/test_args.py::test_sympy__stats__crv__ContinuousPSpace",
"sympy/core/tests/test_args.py::test_sympy__stats__crv__SingleContinuousPSpace",
"sympy/core/tests/test_args.py::test_sympy__stats__crv__ProductContinuousPSpace",
"sympy/core/tests/test_args.py::test_sympy__stats__drv__SingleDiscreteDomain",
"sympy/core/tests/test_args.py::test_sympy__stats__drv__SingleDiscretePSpace",
"sympy/core/tests/test_args.py::test_sympy__stats__rv__RandomDomain",
"sympy/core/tests/test_args.py::test_sympy__stats__rv__SingleDomain",
"sympy/core/tests/test_args.py::test_sympy__stats__rv__ConditionalDomain",
"sympy/core/tests/test_args.py::test_sympy__stats__rv__PSpace",
"sympy/core/tests/test_args.py::test_sympy__stats__rv__RandomSymbol",
"sympy/core/tests/test_args.py::test_sympy__stats__rv__ProductPSpace",
"sympy/core/tests/test_args.py::test_sympy__stats__rv__ProductDomain",
"sympy/core/tests/test_args.py::test_sympy__stats__frv_types__DiscreteUniformDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__frv_types__DieDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__frv_types__BernoulliDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__frv_types__BinomialDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__frv_types__HypergeometricDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__frv_types__RademacherDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__frv__FiniteDomain",
"sympy/core/tests/test_args.py::test_sympy__stats__frv__SingleFiniteDomain",
"sympy/core/tests/test_args.py::test_sympy__stats__frv__ProductFiniteDomain",
"sympy/core/tests/test_args.py::test_sympy__stats__frv__ConditionalFiniteDomain",
"sympy/core/tests/test_args.py::test_sympy__stats__frv__FinitePSpace",
"sympy/core/tests/test_args.py::test_sympy__stats__frv__SingleFinitePSpace",
"sympy/core/tests/test_args.py::test_sympy__stats__frv__ProductFinitePSpace",
"sympy/core/tests/test_args.py::test_sympy__stats__frv_types__FiniteDistributionHandmade",
"sympy/core/tests/test_args.py::test_sympy__stats__crv__ContinuousDistributionHandmade",
"sympy/core/tests/test_args.py::test_sympy__stats__rv__Density",
"sympy/core/tests/test_args.py::test_sympy__stats__crv_types__ArcsinDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__crv_types__BeniniDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__crv_types__BetaDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__crv_types__BetaPrimeDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__crv_types__CauchyDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__crv_types__ChiDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__crv_types__ChiNoncentralDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__crv_types__ChiSquaredDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__crv_types__DagumDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__crv_types__ExponentialDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__crv_types__FDistributionDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__crv_types__FisherZDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__crv_types__FrechetDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__crv_types__GammaInverseDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__crv_types__GammaDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__crv_types__KumaraswamyDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__crv_types__LaplaceDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__crv_types__LogisticDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__crv_types__LogNormalDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__crv_types__MaxwellDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__crv_types__NakagamiDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__crv_types__NormalDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__crv_types__ParetoDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__crv_types__QuadraticUDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__crv_types__RaisedCosineDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__crv_types__RayleighDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__crv_types__StudentTDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__crv_types__TriangularDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__crv_types__UniformDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__crv_types__UniformSumDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__crv_types__VonMisesDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__crv_types__WeibullDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__crv_types__WignerSemicircleDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__drv_types__PoissonDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__drv_types__GeometricDistribution",
"sympy/core/tests/test_args.py::test_sympy__core__symbol__Dummy",
"sympy/core/tests/test_args.py::test_sympy__core__symbol__Symbol",
"sympy/core/tests/test_args.py::test_sympy__core__symbol__Wild",
"sympy/core/tests/test_args.py::test_sympy__functions__combinatorial__factorials__FallingFactorial",
"sympy/core/tests/test_args.py::test_sympy__functions__combinatorial__factorials__MultiFactorial",
"sympy/core/tests/test_args.py::test_sympy__functions__combinatorial__factorials__RisingFactorial",
"sympy/core/tests/test_args.py::test_sympy__functions__combinatorial__factorials__binomial",
"sympy/core/tests/test_args.py::test_sympy__functions__combinatorial__factorials__subfactorial",
"sympy/core/tests/test_args.py::test_sympy__functions__combinatorial__factorials__factorial",
"sympy/core/tests/test_args.py::test_sympy__functions__combinatorial__factorials__factorial2",
"sympy/core/tests/test_args.py::test_sympy__functions__combinatorial__numbers__bell",
"sympy/core/tests/test_args.py::test_sympy__functions__combinatorial__numbers__bernoulli",
"sympy/core/tests/test_args.py::test_sympy__functions__combinatorial__numbers__catalan",
"sympy/core/tests/test_args.py::test_sympy__functions__combinatorial__numbers__genocchi",
"sympy/core/tests/test_args.py::test_sympy__functions__combinatorial__numbers__euler",
"sympy/core/tests/test_args.py::test_sympy__functions__combinatorial__numbers__fibonacci",
"sympy/core/tests/test_args.py::test_sympy__functions__combinatorial__numbers__harmonic",
"sympy/core/tests/test_args.py::test_sympy__functions__combinatorial__numbers__lucas",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__complexes__Abs",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__complexes__adjoint",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__complexes__arg",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__complexes__conjugate",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__complexes__im",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__complexes__re",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__complexes__sign",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__complexes__polar_lift",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__complexes__periodic_argument",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__complexes__principal_branch",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__complexes__transpose",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__exponential__LambertW",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__exponential__exp",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__exponential__exp_polar",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__exponential__log",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__hyperbolic__acosh",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__hyperbolic__acoth",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__hyperbolic__asinh",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__hyperbolic__atanh",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__hyperbolic__asech",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__hyperbolic__cosh",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__hyperbolic__coth",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__hyperbolic__csch",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__hyperbolic__sech",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__hyperbolic__sinh",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__hyperbolic__tanh",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__integers__ceiling",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__integers__floor",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__integers__frac",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__miscellaneous__IdentityFunction",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__miscellaneous__Max",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__miscellaneous__Min",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__piecewise__ExprCondPair",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__piecewise__Piecewise",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__trigonometric__acos",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__trigonometric__acot",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__trigonometric__asin",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__trigonometric__asec",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__trigonometric__acsc",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__trigonometric__atan",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__trigonometric__atan2",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__trigonometric__cos",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__trigonometric__csc",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__trigonometric__cot",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__trigonometric__sin",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__trigonometric__sinc",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__trigonometric__sec",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__trigonometric__tan",
"sympy/core/tests/test_args.py::test_sympy__functions__special__bessel__besseli",
"sympy/core/tests/test_args.py::test_sympy__functions__special__bessel__besselj",
"sympy/core/tests/test_args.py::test_sympy__functions__special__bessel__besselk",
"sympy/core/tests/test_args.py::test_sympy__functions__special__bessel__bessely",
"sympy/core/tests/test_args.py::test_sympy__functions__special__bessel__hankel1",
"sympy/core/tests/test_args.py::test_sympy__functions__special__bessel__hankel2",
"sympy/core/tests/test_args.py::test_sympy__functions__special__bessel__jn",
"sympy/core/tests/test_args.py::test_sympy__functions__special__bessel__yn",
"sympy/core/tests/test_args.py::test_sympy__functions__special__bessel__AiryBase",
"sympy/core/tests/test_args.py::test_sympy__functions__special__bessel__airyai",
"sympy/core/tests/test_args.py::test_sympy__functions__special__bessel__airybi",
"sympy/core/tests/test_args.py::test_sympy__functions__special__bessel__airyaiprime",
"sympy/core/tests/test_args.py::test_sympy__functions__special__bessel__airybiprime",
"sympy/core/tests/test_args.py::test_sympy__functions__special__elliptic_integrals__elliptic_k",
"sympy/core/tests/test_args.py::test_sympy__functions__special__elliptic_integrals__elliptic_f",
"sympy/core/tests/test_args.py::test_sympy__functions__special__elliptic_integrals__elliptic_e",
"sympy/core/tests/test_args.py::test_sympy__functions__special__elliptic_integrals__elliptic_pi",
"sympy/core/tests/test_args.py::test_sympy__functions__special__delta_functions__DiracDelta",
"sympy/core/tests/test_args.py::test_sympy__functions__special__delta_functions__Heaviside",
"sympy/core/tests/test_args.py::test_sympy__functions__special__error_functions__erf",
"sympy/core/tests/test_args.py::test_sympy__functions__special__error_functions__erfc",
"sympy/core/tests/test_args.py::test_sympy__functions__special__error_functions__erfi",
"sympy/core/tests/test_args.py::test_sympy__functions__special__error_functions__erf2",
"sympy/core/tests/test_args.py::test_sympy__functions__special__error_functions__erfinv",
"sympy/core/tests/test_args.py::test_sympy__functions__special__error_functions__erfcinv",
"sympy/core/tests/test_args.py::test_sympy__functions__special__error_functions__erf2inv",
"sympy/core/tests/test_args.py::test_sympy__functions__special__error_functions__fresnels",
"sympy/core/tests/test_args.py::test_sympy__functions__special__error_functions__fresnelc",
"sympy/core/tests/test_args.py::test_sympy__functions__special__error_functions__erfs",
"sympy/core/tests/test_args.py::test_sympy__functions__special__error_functions__Ei",
"sympy/core/tests/test_args.py::test_sympy__functions__special__error_functions__li",
"sympy/core/tests/test_args.py::test_sympy__functions__special__error_functions__Li",
"sympy/core/tests/test_args.py::test_sympy__functions__special__error_functions__Si",
"sympy/core/tests/test_args.py::test_sympy__functions__special__error_functions__Ci",
"sympy/core/tests/test_args.py::test_sympy__functions__special__error_functions__Shi",
"sympy/core/tests/test_args.py::test_sympy__functions__special__error_functions__Chi",
"sympy/core/tests/test_args.py::test_sympy__functions__special__error_functions__expint",
"sympy/core/tests/test_args.py::test_sympy__functions__special__gamma_functions__gamma",
"sympy/core/tests/test_args.py::test_sympy__functions__special__gamma_functions__loggamma",
"sympy/core/tests/test_args.py::test_sympy__functions__special__gamma_functions__lowergamma",
"sympy/core/tests/test_args.py::test_sympy__functions__special__gamma_functions__polygamma",
"sympy/core/tests/test_args.py::test_sympy__functions__special__gamma_functions__uppergamma",
"sympy/core/tests/test_args.py::test_sympy__functions__special__beta_functions__beta",
"sympy/core/tests/test_args.py::test_sympy__functions__special__mathieu_functions__MathieuBase",
"sympy/core/tests/test_args.py::test_sympy__functions__special__mathieu_functions__mathieus",
"sympy/core/tests/test_args.py::test_sympy__functions__special__mathieu_functions__mathieuc",
"sympy/core/tests/test_args.py::test_sympy__functions__special__mathieu_functions__mathieusprime",
"sympy/core/tests/test_args.py::test_sympy__functions__special__mathieu_functions__mathieucprime",
"sympy/core/tests/test_args.py::test_sympy__functions__special__hyper__hyper",
"sympy/core/tests/test_args.py::test_sympy__functions__special__hyper__meijerg",
"sympy/core/tests/test_args.py::test_sympy__functions__special__hyper__HyperRep_power1",
"sympy/core/tests/test_args.py::test_sympy__functions__special__hyper__HyperRep_power2",
"sympy/core/tests/test_args.py::test_sympy__functions__special__hyper__HyperRep_log1",
"sympy/core/tests/test_args.py::test_sympy__functions__special__hyper__HyperRep_atanh",
"sympy/core/tests/test_args.py::test_sympy__functions__special__hyper__HyperRep_asin1",
"sympy/core/tests/test_args.py::test_sympy__functions__special__hyper__HyperRep_asin2",
"sympy/core/tests/test_args.py::test_sympy__functions__special__hyper__HyperRep_sqrts1",
"sympy/core/tests/test_args.py::test_sympy__functions__special__hyper__HyperRep_sqrts2",
"sympy/core/tests/test_args.py::test_sympy__functions__special__hyper__HyperRep_log2",
"sympy/core/tests/test_args.py::test_sympy__functions__special__hyper__HyperRep_cosasin",
"sympy/core/tests/test_args.py::test_sympy__functions__special__hyper__HyperRep_sinasin",
"sympy/core/tests/test_args.py::test_sympy__functions__special__polynomials__jacobi",
"sympy/core/tests/test_args.py::test_sympy__functions__special__polynomials__gegenbauer",
"sympy/core/tests/test_args.py::test_sympy__functions__special__polynomials__chebyshevt",
"sympy/core/tests/test_args.py::test_sympy__functions__special__polynomials__chebyshevt_root",
"sympy/core/tests/test_args.py::test_sympy__functions__special__polynomials__chebyshevu",
"sympy/core/tests/test_args.py::test_sympy__functions__special__polynomials__chebyshevu_root",
"sympy/core/tests/test_args.py::test_sympy__functions__special__polynomials__hermite",
"sympy/core/tests/test_args.py::test_sympy__functions__special__polynomials__legendre",
"sympy/core/tests/test_args.py::test_sympy__functions__special__polynomials__assoc_legendre",
"sympy/core/tests/test_args.py::test_sympy__functions__special__polynomials__laguerre",
"sympy/core/tests/test_args.py::test_sympy__functions__special__polynomials__assoc_laguerre",
"sympy/core/tests/test_args.py::test_sympy__functions__special__spherical_harmonics__Ynm",
"sympy/core/tests/test_args.py::test_sympy__functions__special__spherical_harmonics__Znm",
"sympy/core/tests/test_args.py::test_sympy__functions__special__tensor_functions__LeviCivita",
"sympy/core/tests/test_args.py::test_sympy__functions__special__tensor_functions__KroneckerDelta",
"sympy/core/tests/test_args.py::test_sympy__functions__special__zeta_functions__dirichlet_eta",
"sympy/core/tests/test_args.py::test_sympy__functions__special__zeta_functions__zeta",
"sympy/core/tests/test_args.py::test_sympy__functions__special__zeta_functions__lerchphi",
"sympy/core/tests/test_args.py::test_sympy__functions__special__zeta_functions__polylog",
"sympy/core/tests/test_args.py::test_sympy__functions__special__zeta_functions__stieltjes",
"sympy/core/tests/test_args.py::test_sympy__integrals__integrals__Integral",
"sympy/core/tests/test_args.py::test_sympy__integrals__risch__NonElementaryIntegral",
"sympy/core/tests/test_args.py::test_sympy__integrals__transforms__MellinTransform",
"sympy/core/tests/test_args.py::test_sympy__integrals__transforms__InverseMellinTransform",
"sympy/core/tests/test_args.py::test_sympy__integrals__transforms__LaplaceTransform",
"sympy/core/tests/test_args.py::test_sympy__integrals__transforms__InverseLaplaceTransform",
"sympy/core/tests/test_args.py::test_sympy__integrals__transforms__InverseFourierTransform",
"sympy/core/tests/test_args.py::test_sympy__integrals__transforms__FourierTransform",
"sympy/core/tests/test_args.py::test_sympy__integrals__transforms__InverseSineTransform",
"sympy/core/tests/test_args.py::test_sympy__integrals__transforms__SineTransform",
"sympy/core/tests/test_args.py::test_sympy__integrals__transforms__InverseCosineTransform",
"sympy/core/tests/test_args.py::test_sympy__integrals__transforms__CosineTransform",
"sympy/core/tests/test_args.py::test_sympy__integrals__transforms__InverseHankelTransform",
"sympy/core/tests/test_args.py::test_sympy__integrals__transforms__HankelTransform",
"sympy/core/tests/test_args.py::test_sympy__logic__boolalg__And",
"sympy/core/tests/test_args.py::test_sympy__logic__boolalg__BooleanFunction",
"sympy/core/tests/test_args.py::test_sympy__logic__boolalg__BooleanTrue",
"sympy/core/tests/test_args.py::test_sympy__logic__boolalg__BooleanFalse",
"sympy/core/tests/test_args.py::test_sympy__logic__boolalg__Equivalent",
"sympy/core/tests/test_args.py::test_sympy__logic__boolalg__ITE",
"sympy/core/tests/test_args.py::test_sympy__logic__boolalg__Implies",
"sympy/core/tests/test_args.py::test_sympy__logic__boolalg__Nand",
"sympy/core/tests/test_args.py::test_sympy__logic__boolalg__Nor",
"sympy/core/tests/test_args.py::test_sympy__logic__boolalg__Not",
"sympy/core/tests/test_args.py::test_sympy__logic__boolalg__Or",
"sympy/core/tests/test_args.py::test_sympy__logic__boolalg__Xor",
"sympy/core/tests/test_args.py::test_sympy__matrices__matrices__DeferredVector",
"sympy/core/tests/test_args.py::test_sympy__matrices__immutable__ImmutableMatrix",
"sympy/core/tests/test_args.py::test_sympy__matrices__immutable__ImmutableSparseMatrix",
"sympy/core/tests/test_args.py::test_sympy__matrices__expressions__slice__MatrixSlice",
"sympy/core/tests/test_args.py::test_sympy__matrices__expressions__blockmatrix__BlockDiagMatrix",
"sympy/core/tests/test_args.py::test_sympy__matrices__expressions__blockmatrix__BlockMatrix",
"sympy/core/tests/test_args.py::test_sympy__matrices__expressions__inverse__Inverse",
"sympy/core/tests/test_args.py::test_sympy__matrices__expressions__matadd__MatAdd",
"sympy/core/tests/test_args.py::test_sympy__matrices__expressions__matexpr__Identity",
"sympy/core/tests/test_args.py::test_sympy__matrices__expressions__matexpr__MatrixElement",
"sympy/core/tests/test_args.py::test_sympy__matrices__expressions__matexpr__ZeroMatrix",
"sympy/core/tests/test_args.py::test_sympy__matrices__expressions__matmul__MatMul",
"sympy/core/tests/test_args.py::test_sympy__matrices__expressions__diagonal__DiagonalMatrix",
"sympy/core/tests/test_args.py::test_sympy__matrices__expressions__diagonal__DiagonalOf",
"sympy/core/tests/test_args.py::test_sympy__matrices__expressions__hadamard__HadamardProduct",
"sympy/core/tests/test_args.py::test_sympy__matrices__expressions__matpow__MatPow",
"sympy/core/tests/test_args.py::test_sympy__matrices__expressions__transpose__Transpose",
"sympy/core/tests/test_args.py::test_sympy__matrices__expressions__adjoint__Adjoint",
"sympy/core/tests/test_args.py::test_sympy__matrices__expressions__trace__Trace",
"sympy/core/tests/test_args.py::test_sympy__matrices__expressions__determinant__Determinant",
"sympy/core/tests/test_args.py::test_sympy__matrices__expressions__funcmatrix__FunctionMatrix",
"sympy/core/tests/test_args.py::test_sympy__matrices__expressions__fourier__DFT",
"sympy/core/tests/test_args.py::test_sympy__matrices__expressions__fourier__IDFT",
"sympy/core/tests/test_args.py::test_sympy__matrices__expressions__factorizations__LofLU",
"sympy/core/tests/test_args.py::test_sympy__matrices__expressions__factorizations__UofLU",
"sympy/core/tests/test_args.py::test_sympy__matrices__expressions__factorizations__QofQR",
"sympy/core/tests/test_args.py::test_sympy__matrices__expressions__factorizations__RofQR",
"sympy/core/tests/test_args.py::test_sympy__matrices__expressions__factorizations__LofCholesky",
"sympy/core/tests/test_args.py::test_sympy__matrices__expressions__factorizations__UofCholesky",
"sympy/core/tests/test_args.py::test_sympy__matrices__expressions__factorizations__EigenVectors",
"sympy/core/tests/test_args.py::test_sympy__matrices__expressions__factorizations__EigenValues",
"sympy/core/tests/test_args.py::test_sympy__matrices__expressions__factorizations__UofSVD",
"sympy/core/tests/test_args.py::test_sympy__matrices__expressions__factorizations__VofSVD",
"sympy/core/tests/test_args.py::test_sympy__matrices__expressions__factorizations__SofSVD",
"sympy/core/tests/test_args.py::test_sympy__physics__vector__frame__CoordinateSym",
"sympy/core/tests/test_args.py::test_sympy__physics__paulialgebra__Pauli",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__anticommutator__AntiCommutator",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__cartesian__PositionBra3D",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__cartesian__PositionKet3D",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__cartesian__PositionState3D",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__cartesian__PxBra",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__cartesian__PxKet",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__cartesian__PxOp",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__cartesian__XBra",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__cartesian__XKet",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__cartesian__XOp",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__cartesian__YOp",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__cartesian__ZOp",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__cg__CG",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__cg__Wigner3j",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__cg__Wigner6j",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__cg__Wigner9j",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__circuitplot__Mz",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__circuitplot__Mx",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__commutator__Commutator",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__constants__HBar",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__dagger__Dagger",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__gate__CGate",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__gate__CGateS",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__gate__CNotGate",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__gate__Gate",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__gate__HadamardGate",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__gate__IdentityGate",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__gate__OneQubitGate",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__gate__PhaseGate",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__gate__SwapGate",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__gate__TGate",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__gate__TwoQubitGate",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__gate__UGate",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__gate__XGate",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__gate__YGate",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__gate__ZGate",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__grover__WGate",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__hilbert__ComplexSpace",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__hilbert__DirectSumHilbertSpace",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__hilbert__FockSpace",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__hilbert__HilbertSpace",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__hilbert__L2",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__hilbert__TensorPowerHilbertSpace",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__hilbert__TensorProductHilbertSpace",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__innerproduct__InnerProduct",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__operator__DifferentialOperator",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__operator__HermitianOperator",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__operator__IdentityOperator",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__operator__Operator",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__operator__OuterProduct",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__operator__UnitaryOperator",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__piab__PIABBra",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__boson__BosonOp",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__boson__BosonFockKet",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__boson__BosonFockBra",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__boson__BosonCoherentKet",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__boson__BosonCoherentBra",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__fermion__FermionOp",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__fermion__FermionFockKet",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__fermion__FermionFockBra",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__pauli__SigmaOpBase",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__pauli__SigmaX",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__pauli__SigmaY",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__pauli__SigmaZ",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__pauli__SigmaMinus",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__pauli__SigmaPlus",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__pauli__SigmaZKet",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__pauli__SigmaZBra",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__piab__PIABHamiltonian",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__piab__PIABKet",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__qexpr__QExpr",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__qft__Fourier",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__qft__IQFT",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__qft__QFT",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__qft__RkGate",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__qubit__IntQubit",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__qubit__IntQubitBra",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__qubit__IntQubitState",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__qubit__Qubit",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__qubit__QubitBra",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__qubit__QubitState",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__density__Density",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__spin__CoupledSpinState",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__spin__J2Op",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__spin__JminusOp",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__spin__JplusOp",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__spin__JxBra",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__spin__JxBraCoupled",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__spin__JxKet",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__spin__JxKetCoupled",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__spin__JxOp",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__spin__JyBra",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__spin__JyBraCoupled",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__spin__JyKet",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__spin__JyKetCoupled",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__spin__JyOp",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__spin__JzBra",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__spin__JzBraCoupled",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__spin__JzKet",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__spin__JzKetCoupled",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__spin__JzOp",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__spin__Rotation",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__spin__SpinState",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__spin__WignerD",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__state__Bra",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__state__BraBase",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__state__Ket",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__state__KetBase",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__state__State",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__state__StateBase",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__state__TimeDepBra",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__state__TimeDepKet",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__state__TimeDepState",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__state__Wavefunction",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__tensorproduct__TensorProduct",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__identitysearch__GateIdentity",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__sho1d__SHOOp",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__sho1d__RaisingOp",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__sho1d__LoweringOp",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__sho1d__NumberOp",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__sho1d__Hamiltonian",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__sho1d__SHOState",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__sho1d__SHOKet",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__sho1d__SHOBra",
"sympy/core/tests/test_args.py::test_sympy__physics__secondquant__AnnihilateBoson",
"sympy/core/tests/test_args.py::test_sympy__physics__secondquant__AnnihilateFermion",
"sympy/core/tests/test_args.py::test_sympy__physics__secondquant__AntiSymmetricTensor",
"sympy/core/tests/test_args.py::test_sympy__physics__secondquant__BosonState",
"sympy/core/tests/test_args.py::test_sympy__physics__secondquant__Commutator",
"sympy/core/tests/test_args.py::test_sympy__physics__secondquant__CreateBoson",
"sympy/core/tests/test_args.py::test_sympy__physics__secondquant__CreateFermion",
"sympy/core/tests/test_args.py::test_sympy__physics__secondquant__Dagger",
"sympy/core/tests/test_args.py::test_sympy__physics__secondquant__FermionState",
"sympy/core/tests/test_args.py::test_sympy__physics__secondquant__FermionicOperator",
"sympy/core/tests/test_args.py::test_sympy__physics__secondquant__FockState",
"sympy/core/tests/test_args.py::test_sympy__physics__secondquant__FockStateBosonBra",
"sympy/core/tests/test_args.py::test_sympy__physics__secondquant__FockStateBosonKet",
"sympy/core/tests/test_args.py::test_sympy__physics__secondquant__FockStateBra",
"sympy/core/tests/test_args.py::test_sympy__physics__secondquant__FockStateFermionBra",
"sympy/core/tests/test_args.py::test_sympy__physics__secondquant__FockStateFermionKet",
"sympy/core/tests/test_args.py::test_sympy__physics__secondquant__FockStateKet",
"sympy/core/tests/test_args.py::test_sympy__physics__secondquant__InnerProduct",
"sympy/core/tests/test_args.py::test_sympy__physics__secondquant__NO",
"sympy/core/tests/test_args.py::test_sympy__physics__secondquant__PermutationOperator",
"sympy/core/tests/test_args.py::test_sympy__physics__secondquant__SqOperator",
"sympy/core/tests/test_args.py::test_sympy__physics__secondquant__TensorSymbol",
"sympy/core/tests/test_args.py::test_sympy__physics__units__Unit",
"sympy/core/tests/test_args.py::test_sympy__physics__unitsystems__dimensions__Dimension",
"sympy/core/tests/test_args.py::test_sympy__physics__unitsystems__quantities__Quantity",
"sympy/core/tests/test_args.py::test_sympy__physics__unitsystems__units__Constant",
"sympy/core/tests/test_args.py::test_sympy__physics__unitsystems__units__Unit",
"sympy/core/tests/test_args.py::test_sympy__core__numbers__AlgebraicNumber",
"sympy/core/tests/test_args.py::test_sympy__polys__polytools__GroebnerBasis",
"sympy/core/tests/test_args.py::test_sympy__polys__polytools__Poly",
"sympy/core/tests/test_args.py::test_sympy__polys__polytools__PurePoly",
"sympy/core/tests/test_args.py::test_sympy__polys__rootoftools__RootOf",
"sympy/core/tests/test_args.py::test_sympy__polys__rootoftools__RootSum",
"sympy/core/tests/test_args.py::test_sympy__series__limits__Limit",
"sympy/core/tests/test_args.py::test_sympy__series__order__Order",
"sympy/core/tests/test_args.py::test_sympy__series__sequences__EmptySequence",
"sympy/core/tests/test_args.py::test_sympy__series__sequences__SeqPer",
"sympy/core/tests/test_args.py::test_sympy__series__sequences__SeqFormula",
"sympy/core/tests/test_args.py::test_sympy__series__sequences__SeqExprOp",
"sympy/core/tests/test_args.py::test_sympy__series__sequences__SeqAdd",
"sympy/core/tests/test_args.py::test_sympy__series__sequences__SeqMul",
"sympy/core/tests/test_args.py::test_sympy__series__fourier__FourierSeries",
"sympy/core/tests/test_args.py::test_sympy__series__formal__FormalPowerSeries",
"sympy/core/tests/test_args.py::test_sympy__simplify__hyperexpand__Hyper_Function",
"sympy/core/tests/test_args.py::test_sympy__simplify__hyperexpand__G_Function",
"sympy/core/tests/test_args.py::test_sympy__tensor__indexed__Idx",
"sympy/core/tests/test_args.py::test_sympy__tensor__indexed__Indexed",
"sympy/core/tests/test_args.py::test_sympy__tensor__indexed__IndexedBase",
"sympy/core/tests/test_args.py::test_sympy__tensor__tensor__TensorIndexType",
"sympy/core/tests/test_args.py::test_sympy__tensor__tensor__TensorSymmetry",
"sympy/core/tests/test_args.py::test_sympy__tensor__tensor__TensorType",
"sympy/core/tests/test_args.py::test_sympy__tensor__tensor__TensorHead",
"sympy/core/tests/test_args.py::test_sympy__tensor__tensor__TensorIndex",
"sympy/core/tests/test_args.py::test_sympy__tensor__tensor__TensAdd",
"sympy/core/tests/test_args.py::test_sympy__tensor__tensor__Tensor",
"sympy/core/tests/test_args.py::test_sympy__tensor__tensor__TensMul",
"sympy/core/tests/test_args.py::test_as_coeff_add",
"sympy/core/tests/test_args.py::test_sympy__geometry__curve__Curve",
"sympy/core/tests/test_args.py::test_sympy__geometry__point__Point",
"sympy/core/tests/test_args.py::test_sympy__geometry__point__Point2D",
"sympy/core/tests/test_args.py::test_sympy__geometry__point__Point3D",
"sympy/core/tests/test_args.py::test_sympy__geometry__ellipse__Ellipse",
"sympy/core/tests/test_args.py::test_sympy__geometry__ellipse__Circle",
"sympy/core/tests/test_args.py::test_sympy__geometry__line__Line",
"sympy/core/tests/test_args.py::test_sympy__geometry__line__Ray",
"sympy/core/tests/test_args.py::test_sympy__geometry__line__Segment",
"sympy/core/tests/test_args.py::test_sympy__geometry__line3d__Line3D",
"sympy/core/tests/test_args.py::test_sympy__geometry__line3d__Segment3D",
"sympy/core/tests/test_args.py::test_sympy__geometry__line3d__Ray3D",
"sympy/core/tests/test_args.py::test_sympy__geometry__plane__Plane",
"sympy/core/tests/test_args.py::test_sympy__geometry__polygon__Polygon",
"sympy/core/tests/test_args.py::test_sympy__geometry__polygon__RegularPolygon",
"sympy/core/tests/test_args.py::test_sympy__geometry__polygon__Triangle",
"sympy/core/tests/test_args.py::test_sympy__geometry__entity__GeometryEntity",
"sympy/core/tests/test_args.py::test_sympy__diffgeom__diffgeom__Manifold",
"sympy/core/tests/test_args.py::test_sympy__diffgeom__diffgeom__Patch",
"sympy/core/tests/test_args.py::test_sympy__diffgeom__diffgeom__CoordSystem",
"sympy/core/tests/test_args.py::test_sympy__diffgeom__diffgeom__BaseScalarField",
"sympy/core/tests/test_args.py::test_sympy__diffgeom__diffgeom__BaseVectorField",
"sympy/core/tests/test_args.py::test_sympy__diffgeom__diffgeom__Differential",
"sympy/core/tests/test_args.py::test_sympy__diffgeom__diffgeom__Commutator",
"sympy/core/tests/test_args.py::test_sympy__diffgeom__diffgeom__TensorProduct",
"sympy/core/tests/test_args.py::test_sympy__diffgeom__diffgeom__WedgeProduct",
"sympy/core/tests/test_args.py::test_sympy__diffgeom__diffgeom__LieDerivative",
"sympy/core/tests/test_args.py::test_sympy__diffgeom__diffgeom__CovarDerivativeOp",
"sympy/core/tests/test_args.py::test_sympy__categories__baseclasses__Class",
"sympy/core/tests/test_args.py::test_sympy__categories__baseclasses__Object",
"sympy/core/tests/test_args.py::test_sympy__categories__baseclasses__IdentityMorphism",
"sympy/core/tests/test_args.py::test_sympy__categories__baseclasses__NamedMorphism",
"sympy/core/tests/test_args.py::test_sympy__categories__baseclasses__CompositeMorphism",
"sympy/core/tests/test_args.py::test_sympy__categories__baseclasses__Diagram",
"sympy/core/tests/test_args.py::test_sympy__categories__baseclasses__Category",
"sympy/core/tests/test_args.py::test_sympy__ntheory__factor___totient",
"sympy/core/tests/test_args.py::test_sympy__ntheory__factor___divisor_sigma",
"sympy/core/tests/test_args.py::test_sympy__ntheory__factor___udivisor_sigma",
"sympy/core/tests/test_args.py::test_sympy__ntheory__residue_ntheory__mobius",
"sympy/core/tests/test_args.py::test_sympy__physics__optics__waves__TWave",
"sympy/core/tests/test_args.py::test_sympy__physics__optics__gaussopt__BeamParameter",
"sympy/core/tests/test_args.py::test_sympy__physics__optics__medium__Medium",
"sympy/core/tests/test_args.py::test_sympy__printing__codeprinter__Assignment",
"sympy/core/tests/test_args.py::test_sympy__vector__coordsysrect__CoordSysCartesian",
"sympy/core/tests/test_args.py::test_sympy__vector__point__Point",
"sympy/core/tests/test_args.py::test_sympy__vector__basisdependent__BasisDependent",
"sympy/core/tests/test_args.py::test_sympy__vector__basisdependent__BasisDependentMul",
"sympy/core/tests/test_args.py::test_sympy__vector__basisdependent__BasisDependentAdd",
"sympy/core/tests/test_args.py::test_sympy__vector__basisdependent__BasisDependentZero",
"sympy/core/tests/test_args.py::test_sympy__vector__vector__BaseVector",
"sympy/core/tests/test_args.py::test_sympy__vector__vector__VectorAdd",
"sympy/core/tests/test_args.py::test_sympy__vector__vector__VectorMul",
"sympy/core/tests/test_args.py::test_sympy__vector__vector__VectorZero",
"sympy/core/tests/test_args.py::test_sympy__vector__vector__Vector",
"sympy/core/tests/test_args.py::test_sympy__vector__dyadic__Dyadic",
"sympy/core/tests/test_args.py::test_sympy__vector__dyadic__BaseDyadic",
"sympy/core/tests/test_args.py::test_sympy__vector__dyadic__DyadicMul",
"sympy/core/tests/test_args.py::test_sympy__vector__dyadic__DyadicAdd",
"sympy/core/tests/test_args.py::test_sympy__vector__dyadic__DyadicZero",
"sympy/core/tests/test_args.py::test_sympy__vector__deloperator__Del",
"sympy/core/tests/test_args.py::test_sympy__vector__orienters__Orienter",
"sympy/core/tests/test_args.py::test_sympy__vector__orienters__ThreeAngleOrienter",
"sympy/core/tests/test_args.py::test_sympy__vector__orienters__AxisOrienter",
"sympy/core/tests/test_args.py::test_sympy__vector__orienters__BodyOrienter",
"sympy/core/tests/test_args.py::test_sympy__vector__orienters__SpaceOrienter",
"sympy/core/tests/test_args.py::test_sympy__vector__orienters__QuaternionOrienter",
"sympy/core/tests/test_args.py::test_sympy__vector__scalar__BaseScalar",
"sympy/core/tests/test_args.py::test_sympy__physics__wigner__Wigner3j",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_ascii_str",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_unicode_str",
"sympy/printing/pretty/tests/test_pretty.py::test_upretty_greek",
"sympy/printing/pretty/tests/test_pretty.py::test_upretty_multiindex",
"sympy/printing/pretty/tests/test_pretty.py::test_upretty_sub_super",
"sympy/printing/pretty/tests/test_pretty.py::test_upretty_subs_missing_in_24",
"sympy/printing/pretty/tests/test_pretty.py::test_upretty_modifiers",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_basic",
"sympy/printing/pretty/tests/test_pretty.py::test_negative_fractions",
"sympy/printing/pretty/tests/test_pretty.py::test_issue_5524",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_ordering",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_relational",
"sympy/printing/pretty/tests/test_pretty.py::test_issue_7117",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_rational",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_functions",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_sqrt",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_sqrt_char_knob",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_sqrt_longsymbol_no_sqrt_char",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_KroneckerDelta",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_product",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_lambda",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_order",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_derivatives",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_integrals",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_matrix",
"sympy/printing/pretty/tests/test_pretty.py::test_Adjoint",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_piecewise",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_seq",
"sympy/printing/pretty/tests/test_pretty.py::test_any_object_in_sequence",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_sets",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_ConditionSet",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_ComplexRegion",
"sympy/printing/pretty/tests/test_pretty.py::test_ProductSet_paranthesis",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_sequences",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_FourierSeries",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_FormalPowerSeries",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_limits",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_RootOf",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_RootSum",
"sympy/printing/pretty/tests/test_pretty.py::test_GroebnerBasis",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_Boolean",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_Domain",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_prec",
"sympy/printing/pretty/tests/test_pretty.py::test_pprint",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_class",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_no_wrap_line",
"sympy/printing/pretty/tests/test_pretty.py::test_settings",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_sum",
"sympy/printing/pretty/tests/test_pretty.py::test_units",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_Subs",
"sympy/printing/pretty/tests/test_pretty.py::test_gammas",
"sympy/printing/pretty/tests/test_pretty.py::test_hyper",
"sympy/printing/pretty/tests/test_pretty.py::test_meijerg",
"sympy/printing/pretty/tests/test_pretty.py::test_noncommutative",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_special_functions",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_geometry",
"sympy/printing/pretty/tests/test_pretty.py::test_expint",
"sympy/printing/pretty/tests/test_pretty.py::test_elliptic_functions",
"sympy/printing/pretty/tests/test_pretty.py::test_RandomDomain",
"sympy/printing/pretty/tests/test_pretty.py::test_PrettyPoly",
"sympy/printing/pretty/tests/test_pretty.py::test_issue_6285",
"sympy/printing/pretty/tests/test_pretty.py::test_issue_6359",
"sympy/printing/pretty/tests/test_pretty.py::test_issue_6739",
"sympy/printing/pretty/tests/test_pretty.py::test_complicated_symbol_unchanged",
"sympy/printing/pretty/tests/test_pretty.py::test_categories",
"sympy/printing/pretty/tests/test_pretty.py::test_PrettyModules",
"sympy/printing/pretty/tests/test_pretty.py::test_QuotientRing",
"sympy/printing/pretty/tests/test_pretty.py::test_Homomorphism",
"sympy/printing/pretty/tests/test_pretty.py::test_Tr",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_Add",
"sympy/printing/pretty/tests/test_pretty.py::test_issue_7179",
"sympy/printing/pretty/tests/test_pretty.py::test_issue_7180",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_Complement",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_SymmetricDifference",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_Contains",
"sympy/printing/pretty/tests/test_pretty.py::test_issue_8292",
"sympy/printing/pretty/tests/test_pretty.py::test_issue_4335",
"sympy/printing/pretty/tests/test_pretty.py::test_issue_8344",
"sympy/printing/pretty/tests/test_pretty.py::test_issue_6324",
"sympy/printing/pretty/tests/test_pretty.py::test_issue_7927",
"sympy/printing/pretty/tests/test_pretty.py::test_issue_6134",
"sympy/printing/tests/test_latex.py::test_printmethod",
"sympy/printing/tests/test_latex.py::test_latex_basic",
"sympy/printing/tests/test_latex.py::test_latex_builtins",
"sympy/printing/tests/test_latex.py::test_latex_Float",
"sympy/printing/tests/test_latex.py::test_latex_symbols",
"sympy/printing/tests/test_latex.py::test_latex_functions",
"sympy/printing/tests/test_latex.py::test_hyper_printing",
"sympy/printing/tests/test_latex.py::test_latex_bessel",
"sympy/printing/tests/test_latex.py::test_latex_fresnel",
"sympy/printing/tests/test_latex.py::test_latex_brackets",
"sympy/printing/tests/test_latex.py::test_latex_indexed",
"sympy/printing/tests/test_latex.py::test_latex_derivatives",
"sympy/printing/tests/test_latex.py::test_latex_subs",
"sympy/printing/tests/test_latex.py::test_latex_integrals",
"sympy/printing/tests/test_latex.py::test_latex_sets",
"sympy/printing/tests/test_latex.py::test_latex_Range",
"sympy/printing/tests/test_latex.py::test_latex_sequences",
"sympy/printing/tests/test_latex.py::test_latex_FourierSeries",
"sympy/printing/tests/test_latex.py::test_latex_FormalPowerSeries",
"sympy/printing/tests/test_latex.py::test_latex_intervals",
"sympy/printing/tests/test_latex.py::test_latex_emptyset",
"sympy/printing/tests/test_latex.py::test_latex_union",
"sympy/printing/tests/test_latex.py::test_latex_symmetric_difference",
"sympy/printing/tests/test_latex.py::test_latex_Complement",
"sympy/printing/tests/test_latex.py::test_latex_Complexes",
"sympy/printing/tests/test_latex.py::test_latex_productset",
"sympy/printing/tests/test_latex.py::test_latex_Naturals",
"sympy/printing/tests/test_latex.py::test_latex_Naturals0",
"sympy/printing/tests/test_latex.py::test_latex_Integers",
"sympy/printing/tests/test_latex.py::test_latex_ImageSet",
"sympy/printing/tests/test_latex.py::test_latex_ConditionSet",
"sympy/printing/tests/test_latex.py::test_latex_ComplexRegion",
"sympy/printing/tests/test_latex.py::test_latex_Contains",
"sympy/printing/tests/test_latex.py::test_latex_sum",
"sympy/printing/tests/test_latex.py::test_latex_product",
"sympy/printing/tests/test_latex.py::test_latex_limits",
"sympy/printing/tests/test_latex.py::test_issue_3568",
"sympy/printing/tests/test_latex.py::test_latex",
"sympy/printing/tests/test_latex.py::test_latex_dict",
"sympy/printing/tests/test_latex.py::test_latex_list",
"sympy/printing/tests/test_latex.py::test_latex_rational",
"sympy/printing/tests/test_latex.py::test_latex_inverse",
"sympy/printing/tests/test_latex.py::test_latex_DiracDelta",
"sympy/printing/tests/test_latex.py::test_latex_Heaviside",
"sympy/printing/tests/test_latex.py::test_latex_KroneckerDelta",
"sympy/printing/tests/test_latex.py::test_latex_LeviCivita",
"sympy/printing/tests/test_latex.py::test_mode",
"sympy/printing/tests/test_latex.py::test_latex_Piecewise",
"sympy/printing/tests/test_latex.py::test_latex_Matrix",
"sympy/printing/tests/test_latex.py::test_latex_matrix_with_functions",
"sympy/printing/tests/test_latex.py::test_latex_mul_symbol",
"sympy/printing/tests/test_latex.py::test_latex_issue_4381",
"sympy/printing/tests/test_latex.py::test_latex_issue_4576",
"sympy/printing/tests/test_latex.py::test_latex_pow_fraction",
"sympy/printing/tests/test_latex.py::test_noncommutative",
"sympy/printing/tests/test_latex.py::test_latex_order",
"sympy/printing/tests/test_latex.py::test_latex_Lambda",
"sympy/printing/tests/test_latex.py::test_latex_PolyElement",
"sympy/printing/tests/test_latex.py::test_latex_FracElement",
"sympy/printing/tests/test_latex.py::test_latex_Poly",
"sympy/printing/tests/test_latex.py::test_latex_RootOf",
"sympy/printing/tests/test_latex.py::test_latex_RootSum",
"sympy/printing/tests/test_latex.py::test_settings",
"sympy/printing/tests/test_latex.py::test_latex_numbers",
"sympy/printing/tests/test_latex.py::test_lamda",
"sympy/printing/tests/test_latex.py::test_custom_symbol_names",
"sympy/printing/tests/test_latex.py::test_matAdd",
"sympy/printing/tests/test_latex.py::test_matMul",
"sympy/printing/tests/test_latex.py::test_latex_MatrixSlice",
"sympy/printing/tests/test_latex.py::test_latex_RandomDomain",
"sympy/printing/tests/test_latex.py::test_PrettyPoly",
"sympy/printing/tests/test_latex.py::test_integral_transforms",
"sympy/printing/tests/test_latex.py::test_PolynomialRingBase",
"sympy/printing/tests/test_latex.py::test_categories",
"sympy/printing/tests/test_latex.py::test_Modules",
"sympy/printing/tests/test_latex.py::test_QuotientRing",
"sympy/printing/tests/test_latex.py::test_Tr",
"sympy/printing/tests/test_latex.py::test_Adjoint",
"sympy/printing/tests/test_latex.py::test_Hadamard",
"sympy/printing/tests/test_latex.py::test_ZeroMatrix",
"sympy/printing/tests/test_latex.py::test_boolean_args_order",
"sympy/printing/tests/test_latex.py::test_imaginary",
"sympy/printing/tests/test_latex.py::test_builtins_without_args",
"sympy/printing/tests/test_latex.py::test_latex_greek_functions",
"sympy/printing/tests/test_latex.py::test_translate",
"sympy/printing/tests/test_latex.py::test_other_symbols",
"sympy/printing/tests/test_latex.py::test_modifiers",
"sympy/printing/tests/test_latex.py::test_greek_symbols",
"sympy/printing/tests/test_latex.py::test_builtin_no_args",
"sympy/printing/tests/test_latex.py::test_issue_6853",
"sympy/printing/tests/test_latex.py::test_Mul",
"sympy/printing/tests/test_latex.py::test_Pow",
"sympy/printing/tests/test_latex.py::test_issue_7180",
"sympy/printing/tests/test_latex.py::test_issue_8409",
"sympy/printing/tests/test_latex.py::test_issue_8470",
"sympy/printing/tests/test_latex.py::test_issue_7117",
"sympy/printing/tests/test_latex.py::test_issue_2934",
"sympy/sets/tests/test_fancysets.py::test_naturals",
"sympy/sets/tests/test_fancysets.py::test_naturals0",
"sympy/sets/tests/test_fancysets.py::test_integers",
"sympy/sets/tests/test_fancysets.py::test_ImageSet",
"sympy/sets/tests/test_fancysets.py::test_image_is_ImageSet",
"sympy/sets/tests/test_fancysets.py::test_ImageSet_iterator_not_injetive",
"sympy/sets/tests/test_fancysets.py::test_Range",
"sympy/sets/tests/test_fancysets.py::test_range_interval_intersection",
"sympy/sets/tests/test_fancysets.py::test_fun",
"sympy/sets/tests/test_fancysets.py::test_Reals",
"sympy/sets/tests/test_fancysets.py::test_Complex",
"sympy/sets/tests/test_fancysets.py::test_intersections",
"sympy/sets/tests/test_fancysets.py::test_infinitely_indexed_set_1",
"sympy/sets/tests/test_fancysets.py::test_infinitely_indexed_set_2",
"sympy/sets/tests/test_fancysets.py::test_imageset_intersect_real",
"sympy/sets/tests/test_fancysets.py::test_ImageSet_simplification",
"sympy/sets/tests/test_fancysets.py::test_ComplexRegion_contains",
"sympy/sets/tests/test_fancysets.py::test_ComplexRegion_intersect",
"sympy/sets/tests/test_fancysets.py::test_ComplexRegion_union",
"sympy/sets/tests/test_fancysets.py::test_ComplexRegion_measure",
"sympy/sets/tests/test_fancysets.py::test_normalize_theta_set",
"sympy/sets/tests/test_fancysets.py::test_ComplexRegion_FiniteSet"
] | [] | [] | [] | BSD | 227 |
|
docker__docker-py-752 | 33acb9d2e05d0f3abb7897abbe50dd54600da85b | 2015-08-31 22:02:13 | 33acb9d2e05d0f3abb7897abbe50dd54600da85b | diff --git a/docker/client.py b/docker/client.py
index b1f72e97..88bc50de 100644
--- a/docker/client.py
+++ b/docker/client.py
@@ -41,7 +41,7 @@ class Client(clientbase.ClientBase):
'stderr': stderr and 1 or 0,
'stream': stream and 1 or 0,
}
- u = self._url("/containers/{0}/attach".format(container))
+ u = self._url("/containers/{0}/attach", container)
response = self._post(u, params=params, stream=stream)
return self._get_result(container, stream, response)
@@ -58,7 +58,7 @@ class Client(clientbase.ClientBase):
if ws:
return self._attach_websocket(container, params)
- u = self._url("/containers/{0}/attach".format(container))
+ u = self._url("/containers/{0}/attach", container)
return self._get_raw_response_socket(self.post(
u, None, params=self._attach_params(params), stream=True))
@@ -275,8 +275,9 @@ class Client(clientbase.ClientBase):
@check_resource
def diff(self, container):
- return self._result(self._get(self._url("/containers/{0}/changes".
- format(container))), True)
+ return self._result(
+ self._get(self._url("/containers/{0}/changes", container)), True
+ )
def events(self, since=None, until=None, filters=None, decode=None):
if isinstance(since, datetime):
@@ -326,7 +327,7 @@ class Client(clientbase.ClientBase):
'Cmd': cmd
}
- url = self._url('/containers/{0}/exec'.format(container))
+ url = self._url('/containers/{0}/exec', container)
res = self._post_json(url, data=data)
return self._result(res, True)
@@ -337,7 +338,7 @@ class Client(clientbase.ClientBase):
)
if isinstance(exec_id, dict):
exec_id = exec_id.get('Id')
- res = self._get(self._url("/exec/{0}/json".format(exec_id)))
+ res = self._get(self._url("/exec/{0}/json", exec_id))
return self._result(res, True)
def exec_resize(self, exec_id, height=None, width=None):
@@ -347,7 +348,7 @@ class Client(clientbase.ClientBase):
exec_id = exec_id.get('Id')
params = {'h': height, 'w': width}
- url = self._url("/exec/{0}/resize".format(exec_id))
+ url = self._url("/exec/{0}/resize", exec_id)
res = self._post(url, params=params)
self._raise_for_status(res)
@@ -362,27 +363,28 @@ class Client(clientbase.ClientBase):
'Detach': detach
}
- res = self._post_json(self._url('/exec/{0}/start'.format(exec_id)),
- data=data, stream=stream)
+ res = self._post_json(
+ self._url('/exec/{0}/start', exec_id), data=data, stream=stream
+ )
return self._get_result_tty(stream, res, tty)
@check_resource
def export(self, container):
- res = self._get(self._url("/containers/{0}/export".format(container)),
- stream=True)
+ res = self._get(
+ self._url("/containers/{0}/export", container), stream=True
+ )
self._raise_for_status(res)
return res.raw
@check_resource
def get_image(self, image):
- res = self._get(self._url("/images/{0}/get".format(image)),
- stream=True)
+ res = self._get(self._url("/images/{0}/get", image), stream=True)
self._raise_for_status(res)
return res.raw
@check_resource
def history(self, image):
- res = self._get(self._url("/images/{0}/history".format(image)))
+ res = self._get(self._url("/images/{0}/history", image))
return self._result(res, True)
def images(self, name=None, quiet=False, all=False, viz=False,
@@ -496,7 +498,7 @@ class Client(clientbase.ClientBase):
raise errors.DeprecatedMethod(
'insert is not available for API version >=1.12'
)
- api_url = self._url("/images/{0}/insert".format(image))
+ api_url = self._url("/images/{0}/insert", image)
params = {
'url': url,
'path': path
@@ -506,21 +508,18 @@ class Client(clientbase.ClientBase):
@check_resource
def inspect_container(self, container):
return self._result(
- self._get(self._url("/containers/{0}/json".format(container))),
- True)
+ self._get(self._url("/containers/{0}/json", container)), True
+ )
@check_resource
def inspect_image(self, image):
return self._result(
- self._get(
- self._url("/images/{0}/json".format(image.replace('/', '%2F')))
- ),
- True
+ self._get(self._url("/images/{0}/json", image)), True
)
@check_resource
def kill(self, container, signal=None):
- url = self._url("/containers/{0}/kill".format(container))
+ url = self._url("/containers/{0}/kill", container)
params = {}
if signal is not None:
params['signal'] = signal
@@ -583,7 +582,7 @@ class Client(clientbase.ClientBase):
if tail != 'all' and (not isinstance(tail, int) or tail <= 0):
tail = 'all'
params['tail'] = tail
- url = self._url("/containers/{0}/logs".format(container))
+ url = self._url("/containers/{0}/logs", container)
res = self._get(url, params=params, stream=stream)
return self._get_result(container, stream, res)
return self.attach(
@@ -596,7 +595,7 @@ class Client(clientbase.ClientBase):
@check_resource
def pause(self, container):
- url = self._url('/containers/{0}/pause'.format(container))
+ url = self._url('/containers/{0}/pause', container)
res = self._post(url)
self._raise_for_status(res)
@@ -605,7 +604,7 @@ class Client(clientbase.ClientBase):
@check_resource
def port(self, container, private_port):
- res = self._get(self._url("/containers/{0}/json".format(container)))
+ res = self._get(self._url("/containers/{0}/json", container))
self._raise_for_status(res)
json_ = res.json()
s_port = str(private_port)
@@ -692,7 +691,7 @@ class Client(clientbase.ClientBase):
if not tag:
repository, tag = utils.parse_repository_tag(repository)
registry, repo_name = auth.resolve_repository_name(repository)
- u = self._url("/images/{0}/push".format(repository))
+ u = self._url("/images/{0}/push", repository)
params = {
'tag': tag
}
@@ -725,14 +724,15 @@ class Client(clientbase.ClientBase):
@check_resource
def remove_container(self, container, v=False, link=False, force=False):
params = {'v': v, 'link': link, 'force': force}
- res = self._delete(self._url("/containers/" + container),
- params=params)
+ res = self._delete(
+ self._url("/containers/{0}", container), params=params
+ )
self._raise_for_status(res)
@check_resource
def remove_image(self, image, force=False, noprune=False):
params = {'force': force, 'noprune': noprune}
- res = self._delete(self._url("/images/" + image), params=params)
+ res = self._delete(self._url("/images/{0}", image), params=params)
self._raise_for_status(res)
@check_resource
@@ -741,7 +741,7 @@ class Client(clientbase.ClientBase):
raise errors.InvalidVersion(
'rename was only introduced in API version 1.17'
)
- url = self._url("/containers/{0}/rename".format(container))
+ url = self._url("/containers/{0}/rename", container)
params = {'name': name}
res = self._post(url, params=params)
self._raise_for_status(res)
@@ -749,21 +749,22 @@ class Client(clientbase.ClientBase):
@check_resource
def resize(self, container, height, width):
params = {'h': height, 'w': width}
- url = self._url("/containers/{0}/resize".format(container))
+ url = self._url("/containers/{0}/resize", container)
res = self._post(url, params=params)
self._raise_for_status(res)
@check_resource
def restart(self, container, timeout=10):
params = {'t': timeout}
- url = self._url("/containers/{0}/restart".format(container))
+ url = self._url("/containers/{0}/restart", container)
res = self._post(url, params=params)
self._raise_for_status(res)
def search(self, term):
- return self._result(self._get(self._url("/images/search"),
- params={'term': term}),
- True)
+ return self._result(
+ self._get(self._url("/images/search"), params={'term': term}),
+ True
+ )
@check_resource
def start(self, container, binds=None, port_bindings=None, lxc_conf=None,
@@ -829,7 +830,7 @@ class Client(clientbase.ClientBase):
)
start_config = self.create_host_config(**start_config_kwargs)
- url = self._url("/containers/{0}/start".format(container))
+ url = self._url("/containers/{0}/start", container)
res = self._post_json(url, data=start_config)
self._raise_for_status(res)
@@ -839,13 +840,13 @@ class Client(clientbase.ClientBase):
raise errors.InvalidVersion(
'Stats retrieval is not supported in API < 1.17!')
- url = self._url("/containers/{0}/stats".format(container))
+ url = self._url("/containers/{0}/stats", container)
return self._stream_helper(self._get(url, stream=True), decode=decode)
@check_resource
def stop(self, container, timeout=10):
params = {'t': timeout}
- url = self._url("/containers/{0}/stop".format(container))
+ url = self._url("/containers/{0}/stop", container)
res = self._post(url, params=params,
timeout=(timeout + (self.timeout or 0)))
@@ -858,14 +859,14 @@ class Client(clientbase.ClientBase):
'repo': repository,
'force': 1 if force else 0
}
- url = self._url("/images/{0}/tag".format(image))
+ url = self._url("/images/{0}/tag", image)
res = self._post(url, params=params)
self._raise_for_status(res)
return res.status_code == 201
@check_resource
def top(self, container):
- u = self._url("/containers/{0}/top".format(container))
+ u = self._url("/containers/{0}/top", container)
return self._result(self._get(u), True)
def version(self, api_version=True):
@@ -874,13 +875,13 @@ class Client(clientbase.ClientBase):
@check_resource
def unpause(self, container):
- url = self._url('/containers/{0}/unpause'.format(container))
+ url = self._url('/containers/{0}/unpause', container)
res = self._post(url)
self._raise_for_status(res)
@check_resource
def wait(self, container, timeout=None):
- url = self._url("/containers/{0}/wait".format(container))
+ url = self._url("/containers/{0}/wait", container)
res = self._post(url, timeout=timeout)
self._raise_for_status(res)
json_ = res.json()
diff --git a/docker/clientbase.py b/docker/clientbase.py
index ce52ffa7..90dba63d 100644
--- a/docker/clientbase.py
+++ b/docker/clientbase.py
@@ -88,11 +88,21 @@ class ClientBase(requests.Session):
def _delete(self, url, **kwargs):
return self.delete(url, **self._set_request_timeout(kwargs))
- def _url(self, path, versioned_api=True):
+ def _url(self, pathfmt, resource_id=None, versioned_api=True):
+ if resource_id and not isinstance(resource_id, six.string_types):
+ raise ValueError(
+ 'Expected a resource ID string but found {0} ({1}) '
+ 'instead'.format(resource_id, type(resource_id))
+ )
+ elif resource_id:
+ resource_id = six.moves.urllib.parse.quote_plus(resource_id)
+
if versioned_api:
- return '{0}/v{1}{2}'.format(self.base_url, self._version, path)
+ return '{0}/v{1}{2}'.format(
+ self.base_url, self._version, pathfmt.format(resource_id)
+ )
else:
- return '{0}{1}'.format(self.base_url, path)
+ return '{0}{1}'.format(self.base_url, pathfmt.format(resource_id))
def _raise_for_status(self, response, explanation=None):
"""Raises stored :class:`APIError`, if one occurred."""
@@ -136,7 +146,7 @@ class ClientBase(requests.Session):
@check_resource
def _attach_websocket(self, container, params=None):
- url = self._url("/containers/{0}/attach/ws".format(container))
+ url = self._url("/containers/{0}/attach/ws", container)
req = requests.Request("POST", url, params=self._attach_params(params))
full_url = req.prepare().url
full_url = full_url.replace("http://", "ws://", 1)
| Hardening for URL request construction
The `Client` class performs a lot URL construction like this:
res = self._get(self._url("/exec/{0}/json".format(exec_id)))
This can be used to manipulate the query string if `exec_id` contains characters like `'?'` and `'/'`, which can lead to vulnerabilities elsewhere. The client code should be fixed to reject such invalid parameters.
Downstream bug report: https://bugzilla.redhat.com/show_bug.cgi?id=1248031 | docker/docker-py | diff --git a/tests/test.py b/tests/test.py
index 1bf8c55d..9cf94a18 100644
--- a/tests/test.py
+++ b/tests/test.py
@@ -144,6 +144,28 @@ class DockerClientTest(Cleanup, base.BaseTestCase):
'Version parameter must be a string or None. Found float'
)
+ def test_url_valid_resource(self):
+ url = self.client._url('/hello/{0}/world', 'somename')
+ self.assertEqual(
+ url, '{0}{1}'.format(url_prefix, 'hello/somename/world')
+ )
+
+ url = self.client._url('/hello/{0}/world', '/some?name')
+ self.assertEqual(
+ url, '{0}{1}'.format(url_prefix, 'hello/%2Fsome%3Fname/world')
+ )
+
+ def test_url_invalid_resource(self):
+ with pytest.raises(ValueError):
+ self.client._url('/hello/{0}/world', ['sakuya', 'izayoi'])
+
+ def test_url_no_resource(self):
+ url = self.client._url('/simple')
+ self.assertEqual(url, '{0}{1}'.format(url_prefix, 'simple'))
+
+ url = self.client._url('/simple', None)
+ self.assertEqual(url, '{0}{1}'.format(url_prefix, 'simple'))
+
#########################
# INFORMATION TESTS #
#########################
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_hyperlinks",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 2,
"issue_text_score": 2,
"test_score": 2
},
"num_modified_files": 2
} | 1.3 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[dev]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest",
"pytest-cov"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.7",
"reqs_path": [
"requirements.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | certifi @ file:///croot/certifi_1671487769961/work/certifi
coverage==7.2.7
-e git+https://github.com/docker/docker-py.git@33acb9d2e05d0f3abb7897abbe50dd54600da85b#egg=docker_py
exceptiongroup==1.2.2
importlib-metadata==6.7.0
iniconfig==2.0.0
packaging==24.0
pluggy==1.2.0
pytest==7.4.4
pytest-cov==4.1.0
requests==2.5.3
six==1.17.0
tomli==2.0.1
typing_extensions==4.7.1
websocket-client==0.32.0
zipp==3.15.0
| name: docker-py
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2022.12.7=py37h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- pip=22.3.1=py37h06a4308_0
- python=3.7.16=h7a1cb2a_0
- readline=8.2=h5eee18b_0
- setuptools=65.6.3=py37h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- wheel=0.38.4=py37h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- coverage==7.2.7
- exceptiongroup==1.2.2
- importlib-metadata==6.7.0
- iniconfig==2.0.0
- packaging==24.0
- pluggy==1.2.0
- pytest==7.4.4
- pytest-cov==4.1.0
- requests==2.5.3
- six==1.17.0
- tomli==2.0.1
- typing-extensions==4.7.1
- websocket-client==0.32.0
- zipp==3.15.0
prefix: /opt/conda/envs/docker-py
| [
"tests/test.py::DockerClientTest::test_url_invalid_resource",
"tests/test.py::DockerClientTest::test_url_no_resource",
"tests/test.py::DockerClientTest::test_url_valid_resource"
] | [] | [
"tests/test.py::DockerClientTest::test_auto_retrieve_server_version",
"tests/test.py::DockerClientTest::test_build_container",
"tests/test.py::DockerClientTest::test_build_container_custom_context",
"tests/test.py::DockerClientTest::test_build_container_custom_context_gzip",
"tests/test.py::DockerClientTest::test_build_container_invalid_container_limits",
"tests/test.py::DockerClientTest::test_build_container_pull",
"tests/test.py::DockerClientTest::test_build_container_stream",
"tests/test.py::DockerClientTest::test_build_container_with_container_limits",
"tests/test.py::DockerClientTest::test_build_container_with_named_dockerfile",
"tests/test.py::DockerClientTest::test_build_remote_with_registry_auth",
"tests/test.py::DockerClientTest::test_commit",
"tests/test.py::DockerClientTest::test_container_stats",
"tests/test.py::DockerClientTest::test_create_container",
"tests/test.py::DockerClientTest::test_create_container_empty_volumes_from",
"tests/test.py::DockerClientTest::test_create_container_privileged",
"tests/test.py::DockerClientTest::test_create_container_with_added_capabilities",
"tests/test.py::DockerClientTest::test_create_container_with_binds",
"tests/test.py::DockerClientTest::test_create_container_with_binds_list",
"tests/test.py::DockerClientTest::test_create_container_with_binds_mode",
"tests/test.py::DockerClientTest::test_create_container_with_binds_mode_and_ro_error",
"tests/test.py::DockerClientTest::test_create_container_with_binds_ro",
"tests/test.py::DockerClientTest::test_create_container_with_binds_rw",
"tests/test.py::DockerClientTest::test_create_container_with_cgroup_parent",
"tests/test.py::DockerClientTest::test_create_container_with_cpu_shares",
"tests/test.py::DockerClientTest::test_create_container_with_cpuset",
"tests/test.py::DockerClientTest::test_create_container_with_devices",
"tests/test.py::DockerClientTest::test_create_container_with_dropped_capabilities",
"tests/test.py::DockerClientTest::test_create_container_with_entrypoint",
"tests/test.py::DockerClientTest::test_create_container_with_labels_dict",
"tests/test.py::DockerClientTest::test_create_container_with_labels_list",
"tests/test.py::DockerClientTest::test_create_container_with_links",
"tests/test.py::DockerClientTest::test_create_container_with_links_as_list_of_tuples",
"tests/test.py::DockerClientTest::test_create_container_with_lxc_conf",
"tests/test.py::DockerClientTest::test_create_container_with_lxc_conf_compat",
"tests/test.py::DockerClientTest::test_create_container_with_mac_address",
"tests/test.py::DockerClientTest::test_create_container_with_mem_limit_as_int",
"tests/test.py::DockerClientTest::test_create_container_with_mem_limit_as_string",
"tests/test.py::DockerClientTest::test_create_container_with_mem_limit_as_string_with_g_unit",
"tests/test.py::DockerClientTest::test_create_container_with_mem_limit_as_string_with_k_unit",
"tests/test.py::DockerClientTest::test_create_container_with_mem_limit_as_string_with_m_unit",
"tests/test.py::DockerClientTest::test_create_container_with_mem_limit_as_string_with_wrong_value",
"tests/test.py::DockerClientTest::test_create_container_with_multiple_links",
"tests/test.py::DockerClientTest::test_create_container_with_named_volume",
"tests/test.py::DockerClientTest::test_create_container_with_port_binds",
"tests/test.py::DockerClientTest::test_create_container_with_ports",
"tests/test.py::DockerClientTest::test_create_container_with_restart_policy",
"tests/test.py::DockerClientTest::test_create_container_with_stdin_open",
"tests/test.py::DockerClientTest::test_create_container_with_volume_string",
"tests/test.py::DockerClientTest::test_create_container_with_volumes_from",
"tests/test.py::DockerClientTest::test_create_container_with_working_dir",
"tests/test.py::DockerClientTest::test_create_host_config_secopt",
"tests/test.py::DockerClientTest::test_create_named_container",
"tests/test.py::DockerClientTest::test_ctor",
"tests/test.py::DockerClientTest::test_diff",
"tests/test.py::DockerClientTest::test_diff_with_dict_instead_of_id",
"tests/test.py::DockerClientTest::test_events",
"tests/test.py::DockerClientTest::test_events_with_filters",
"tests/test.py::DockerClientTest::test_events_with_since_until",
"tests/test.py::DockerClientTest::test_exec_create",
"tests/test.py::DockerClientTest::test_exec_inspect",
"tests/test.py::DockerClientTest::test_exec_resize",
"tests/test.py::DockerClientTest::test_exec_start",
"tests/test.py::DockerClientTest::test_export",
"tests/test.py::DockerClientTest::test_export_with_dict_instead_of_id",
"tests/test.py::DockerClientTest::test_get_image",
"tests/test.py::DockerClientTest::test_image_history",
"tests/test.py::DockerClientTest::test_image_ids",
"tests/test.py::DockerClientTest::test_image_viz",
"tests/test.py::DockerClientTest::test_images",
"tests/test.py::DockerClientTest::test_images_filters",
"tests/test.py::DockerClientTest::test_images_quiet",
"tests/test.py::DockerClientTest::test_import_image",
"tests/test.py::DockerClientTest::test_import_image_from_bytes",
"tests/test.py::DockerClientTest::test_import_image_from_image",
"tests/test.py::DockerClientTest::test_info",
"tests/test.py::DockerClientTest::test_insert_image",
"tests/test.py::DockerClientTest::test_inspect_container",
"tests/test.py::DockerClientTest::test_inspect_container_undefined_id",
"tests/test.py::DockerClientTest::test_inspect_image",
"tests/test.py::DockerClientTest::test_inspect_image_undefined_id",
"tests/test.py::DockerClientTest::test_kill_container",
"tests/test.py::DockerClientTest::test_kill_container_with_dict_instead_of_id",
"tests/test.py::DockerClientTest::test_kill_container_with_signal",
"tests/test.py::DockerClientTest::test_list_containers",
"tests/test.py::DockerClientTest::test_load_config",
"tests/test.py::DockerClientTest::test_load_config_no_file",
"tests/test.py::DockerClientTest::test_load_config_with_random_name",
"tests/test.py::DockerClientTest::test_load_image",
"tests/test.py::DockerClientTest::test_log_streaming",
"tests/test.py::DockerClientTest::test_log_tail",
"tests/test.py::DockerClientTest::test_log_tty",
"tests/test.py::DockerClientTest::test_logs",
"tests/test.py::DockerClientTest::test_logs_with_dict_instead_of_id",
"tests/test.py::DockerClientTest::test_pause_container",
"tests/test.py::DockerClientTest::test_port",
"tests/test.py::DockerClientTest::test_pull",
"tests/test.py::DockerClientTest::test_pull_stream",
"tests/test.py::DockerClientTest::test_push_image",
"tests/test.py::DockerClientTest::test_push_image_stream",
"tests/test.py::DockerClientTest::test_push_image_with_tag",
"tests/test.py::DockerClientTest::test_remove_container",
"tests/test.py::DockerClientTest::test_remove_container_with_dict_instead_of_id",
"tests/test.py::DockerClientTest::test_remove_image",
"tests/test.py::DockerClientTest::test_remove_link",
"tests/test.py::DockerClientTest::test_rename_container",
"tests/test.py::DockerClientTest::test_resize_container",
"tests/test.py::DockerClientTest::test_restart_container",
"tests/test.py::DockerClientTest::test_restart_container_with_dict_instead_of_id",
"tests/test.py::DockerClientTest::test_retrieve_server_version",
"tests/test.py::DockerClientTest::test_search",
"tests/test.py::DockerClientTest::test_start_container",
"tests/test.py::DockerClientTest::test_start_container_none",
"tests/test.py::DockerClientTest::test_start_container_privileged",
"tests/test.py::DockerClientTest::test_start_container_regression_573",
"tests/test.py::DockerClientTest::test_start_container_with_binds_ro",
"tests/test.py::DockerClientTest::test_start_container_with_binds_rw",
"tests/test.py::DockerClientTest::test_start_container_with_dict_instead_of_id",
"tests/test.py::DockerClientTest::test_start_container_with_links",
"tests/test.py::DockerClientTest::test_start_container_with_links_as_list_of_tuples",
"tests/test.py::DockerClientTest::test_start_container_with_lxc_conf",
"tests/test.py::DockerClientTest::test_start_container_with_lxc_conf_compat",
"tests/test.py::DockerClientTest::test_start_container_with_multiple_links",
"tests/test.py::DockerClientTest::test_start_container_with_port_binds",
"tests/test.py::DockerClientTest::test_stop_container",
"tests/test.py::DockerClientTest::test_stop_container_with_dict_instead_of_id",
"tests/test.py::DockerClientTest::test_tag_image",
"tests/test.py::DockerClientTest::test_tag_image_force",
"tests/test.py::DockerClientTest::test_tag_image_tag",
"tests/test.py::DockerClientTest::test_tar_with_directory_symlinks",
"tests/test.py::DockerClientTest::test_tar_with_empty_directory",
"tests/test.py::DockerClientTest::test_tar_with_excludes",
"tests/test.py::DockerClientTest::test_tar_with_file_symlinks",
"tests/test.py::DockerClientTest::test_unpause_container",
"tests/test.py::DockerClientTest::test_url_compatibility_http",
"tests/test.py::DockerClientTest::test_url_compatibility_http_unix_triple_slash",
"tests/test.py::DockerClientTest::test_url_compatibility_tcp",
"tests/test.py::DockerClientTest::test_url_compatibility_unix",
"tests/test.py::DockerClientTest::test_url_compatibility_unix_triple_slash",
"tests/test.py::DockerClientTest::test_version",
"tests/test.py::DockerClientTest::test_wait",
"tests/test.py::DockerClientTest::test_wait_with_dict_instead_of_id",
"tests/test.py::StreamTest::test_early_stream_response"
] | [] | Apache License 2.0 | 228 |
|
sympy__sympy-9884 | 19f589457dfc4822e375e8715377ad71b4d21f25 | 2015-09-02 13:36:24 | 0241b35cae5f2adc04dc37b25f7dc9c5f00bd746 | moorepants: +1
aktech: I am getting the following warning:
```python
Coverage.py warning: No data was collected.
```
```
The generated coverage report is in covhtml directory.
Open sympy/covhtml/index.html in your web browser to view the report
```
leosartaj: @aktech I have made small changes. Can you have a look again? It's working for me.
aktech: @leosartaj
It looks good to me. Can you add a line for the usage in the doc-string at the top of the file.
leosartaj: Sure.
On 4 Sep 2015 09:33, "AMiT Kumar" <[email protected]> wrote:
> @leosartaj <https://github.com/leosartaj>
> It looks good to me. Can you add a line for the usage in the doc-string at
> the top of the file.
>
> —
> Reply to this email directly or view it on GitHub
> <https://github.com/sympy/sympy/pull/9884#issuecomment-137645664>.
>
| diff --git a/bin/coverage_report.py b/bin/coverage_report.py
index 6d27376f6d..26e570c77b 100755
--- a/bin/coverage_report.py
+++ b/bin/coverage_report.py
@@ -14,9 +14,9 @@
$ bin/coverage_report.py sympy/logic
runs only the tests in sympy/logic/ and reports only on the modules in
-sympy/logic/. You can also get a report on the parts of the whole sympy
-code covered by the tests in sympy/logic/ by following up the previous
-command with
+sympy/logic/. To also run slow tests use --slow option. You can also get a
+report on the parts of the whole sympy code covered by the tests in
+sympy/logic/ by following up the previous command with
$ bin/coverage_report.py -c
@@ -60,15 +60,16 @@ def generate_covered_files(top_dir):
yield os.path.join(dirpath, filename)
-def make_report(source_dir, report_dir, use_cache=False):
- #code adapted from /bin/test
- bin_dir = os.path.abspath(os.path.dirname(__file__)) # bin/
- sympy_top = os.path.split(bin_dir)[0] # ../
+def make_report(source_dir, report_dir, use_cache=False, slow=False):
+ # code adapted from /bin/test
+ bin_dir = os.path.abspath(os.path.dirname(__file__)) # bin/
+ sympy_top = os.path.split(bin_dir)[0] # ../
sympy_dir = os.path.join(sympy_top, 'sympy') # ../sympy/
if os.path.isdir(sympy_dir):
sys.path.insert(0, sympy_top)
os.chdir(sympy_top)
+ import sympy
cov = coverage.coverage()
cov.exclude("raise NotImplementedError")
cov.exclude("def canonize") # this should be "@decorated"
@@ -78,8 +79,9 @@ def make_report(source_dir, report_dir, use_cache=False):
else:
cov.erase()
cov.start()
- import sympy
sympy.test(source_dir, subprocess=False)
+ if slow:
+ sympy.test(source_dir, subprocess=False, slow=slow)
#sympy.doctest() # coverage doesn't play well with doctests
cov.stop()
cov.save()
@@ -99,6 +101,8 @@ def make_report(source_dir, report_dir, use_cache=False):
help='Use cached data.')
parser.add_option('-d', '--report-dir', default='covhtml',
help='Directory to put the generated report in.')
+ parser.add_option("--slow", action="store_true", dest="slow",
+ default=False, help="Run slow functions also.")
options, args = parser.parse_args()
diff --git a/sympy/series/formal.py b/sympy/series/formal.py
index b7c2ded401..1a21b2aafd 100644
--- a/sympy/series/formal.py
+++ b/sympy/series/formal.py
@@ -14,7 +14,6 @@
from sympy.core.symbol import Wild, Dummy, symbols, Symbol
from sympy.core.relational import Eq
from sympy.core.numbers import Rational
-from sympy.core.compatibility import iterable
from sympy.sets.sets import Interval
from sympy.functions.combinatorial.factorials import binomial, factorial, rf
from sympy.functions.elementary.piecewise import Piecewise
@@ -749,7 +748,7 @@ def hyper_algorithm(f, x, k, order=4):
return sol
-def _compute_fps(f, x, x0, dir, hyper, order, rational, full):
+def _compute_fps(f, x, x0, dir, hyper, order, rational, full, extract=True):
"""Recursive wrapper to compute fps.
See :func:`compute_fps` for details.
@@ -760,7 +759,8 @@ def _compute_fps(f, x, x0, dir, hyper, order, rational, full):
result = _compute_fps(temp, x, 0, dir, hyper, order, rational, full)
if result is None:
return None
- return (result[0], result[1].subs(x, 1/x), result[2].subs(x, 1/x))
+ return (result[0], result[1].subs(x, 1/x), result[2].subs(x, 1/x),
+ result[3].subs(x, 1/x))
elif x0 or dir == -S.One:
if dir == -S.One:
rep = -x + x0
@@ -775,11 +775,28 @@ def _compute_fps(f, x, x0, dir, hyper, order, rational, full):
if result is None:
return None
return (result[0], result[1].subs(x, rep2 + rep2b),
- result[2].subs(x, rep2 + rep2b))
+ result[2].subs(x, rep2 + rep2b),
+ result[3].subs(x, rep2 + rep2b))
if f.is_polynomial(x):
return None
+ # extract x**n from f(x)
+ mul = S.One
+ if extract and f.free_symbols.difference(set([x])):
+ m = Wild('m')
+ n = Wild('n', exclude=[m])
+ f = f.factor().powsimp()
+ s = f.match(x**n*m)
+ if s[n]:
+ for t in Add.make_args(s[n]):
+ if t.has(Symbol):
+ mul *= (x)**t
+ if mul is not S.One:
+ f = (f / mul)
+
+ f = f.expand()
+
# Break instances of Add
# this allows application of different
# algorithms on different terms increasing the
@@ -789,7 +806,8 @@ def _compute_fps(f, x, x0, dir, hyper, order, rational, full):
ak = sequence(S.Zero, (0, oo))
ind, xk = S.Zero, None
for t in Add.make_args(f):
- res = _compute_fps(t, x, 0, S.One, hyper, order, rational, full)
+ res = _compute_fps(t, x, 0, S.One, hyper, order, rational, full,
+ False)
if res:
if not result:
result = True
@@ -806,7 +824,7 @@ def _compute_fps(f, x, x0, dir, hyper, order, rational, full):
else:
ind += t
if result:
- return ak, xk, ind
+ return ak, xk, ind, mul
return None
result = None
@@ -826,7 +844,7 @@ def _compute_fps(f, x, x0, dir, hyper, order, rational, full):
xk = sequence(x**k, (k, 0, oo))
ind = result[1]
- return ak, xk, ind
+ return ak, xk, ind, mul
def compute_fps(f, x, x0=0, dir=1, hyper=True, order=4, rational=True,
@@ -929,10 +947,6 @@ def x(self):
def x0(self):
return self.args[2]
- @property
- def dir(self):
- return self.args[3]
-
@property
def ak(self):
return self.args[4][0]
@@ -945,6 +959,10 @@ def xk(self):
def ind(self):
return self.args[4][2]
+ @property
+ def mul(self):
+ return self.args[4][3]
+
@property
def interval(self):
return Interval(0, oo)
@@ -967,9 +985,11 @@ def infinite(self):
from sympy.concrete import Sum
ak, xk = self.ak, self.xk
k = ak.variables[0]
- inf_sum = Sum(ak.formula * xk.formula, (k, ak.start, ak.stop))
+ ind = (self.ind * self.mul).expand()
+ inf_sum = Sum(ak.formula * xk.formula * self.mul,
+ (k, ak.start, ak.stop))
- return self.ind + inf_sum
+ return ind + inf_sum
def _get_pow_x(self, term):
"""Returns the power of x in a term."""
@@ -992,7 +1012,7 @@ def polynomial(self, n=6):
elif xp.is_integer is True and i == n + 1:
break
elif t is not S.Zero:
- terms.append(t)
+ terms.append(t * self.mul)
return Add(*terms)
@@ -1012,16 +1032,17 @@ def truncate(self, n=6):
if x0 is S.NegativeInfinity:
x0 = S.Infinity
- return self.polynomial(n) + Order(pt_xk, (x, x0))
+ return self.polynomial(n) + self.mul * Order(pt_xk, (x, x0))
def _eval_term(self, pt):
+ pt_xk = self.xk.coeff(pt)
+
try:
- pt_xk = self.xk.coeff(pt)
pt_ak = self.ak.coeff(pt).simplify() # Simplify the coefficients
except IndexError:
- term = S.Zero
- else:
- term = (pt_ak * pt_xk)
+ pt_ak = S.Zero
+
+ term = (pt_ak * pt_xk)
if self.ind:
ind = S.Zero
@@ -1045,139 +1066,6 @@ def _eval_as_leading_term(self, x):
if t is not S.Zero:
return t
- def _eval_derivative(self, x):
- f = self.function.diff(x)
- ind = self.ind.diff(x)
-
- pow_xk = self._get_pow_x(self.xk.formula)
- ak = self.ak
- k = ak.variables[0]
- if ak.formula.has(x):
- form = []
- for e, c in ak.formula.args:
- temp = S.Zero
- for t in Add.make_args(e):
- pow_x = self._get_pow_x(t)
- temp += t * (pow_xk + pow_x)
- form.append((temp, c))
- form = Piecewise(*form)
- ak = sequence(form.subs(k, k + 1), (k, ak.start - 1, ak.stop))
- else:
- ak = sequence((ak.formula * pow_xk).subs(k, k + 1),
- (k, ak.start - 1, ak.stop))
-
- return self.func(f, self.x, self.x0, self.dir, (ak, self.xk, ind))
-
- def integrate(self, x=None):
- """Integrate Formal Power Series.
-
- Examples
- ========
-
- >>> from sympy import fps, sin
- >>> from sympy.abc import x
- >>> f = fps(sin(x))
- >>> f.integrate(x).truncate()
- -1 + x**2/2 - x**4/24 + O(x**6)
- >>> f.integrate((x, 0, 1))
- -cos(1) + 1
- """
- from sympy.integrals import integrate
-
- if x is None:
- x = self.x
- elif iterable(x):
- return integrate(self.function, x)
-
- f = integrate(self.function, x)
- ind = integrate(self.ind, x)
- ind += (f - ind).limit(x, 0) # constant of integration
-
- pow_xk = self._get_pow_x(self.xk.formula)
- ak = self.ak
- k = ak.variables[0]
- if ak.formula.has(x):
- form = []
- for e, c in ak.formula.args:
- temp = S.Zero
- for t in Add.make_args(e):
- pow_x = self._get_pow_x(t)
- temp += t / (pow_xk + pow_x + 1)
- form.append((temp, c))
- form = Piecewise(*form)
- ak = sequence(form.subs(k, k - 1), (k, ak.start + 1, ak.stop))
- else:
- ak = sequence((ak.formula / (pow_xk + 1)).subs(k, k - 1),
- (k, ak.start + 1, ak.stop))
-
- return self.func(f, self.x, self.x0, self.dir, (ak, self.xk, ind))
-
- def __add__(self, other):
- other = sympify(other)
-
- if isinstance(other, FormalPowerSeries):
- if self.dir != other.dir:
- raise ValueError("Both series should be calculated from the"
- " same direction.")
- elif self.x0 != other.x0:
- raise ValueError("Both series should be calculated about the"
- " same point.")
-
- x, y = self.x, other.x
- f = self.function + other.function.subs(y, x)
-
- if self.x not in f.free_symbols:
- return f
-
- ak = self.ak + other.ak
- if self.ak.start > other.ak.start:
- seq = other.ak
- s, e = other.ak.start, self.ak.start
- else:
- seq = self.ak
- s, e = self.ak.start, other.ak.start
- save = Add(*[z[0]*z[1] for z in zip(seq[0:(e - s)], self.xk[s:e])])
- ind = self.ind + other.ind + save
-
- return self.func(f, x, self.x0, self.dir, (ak, self.xk, ind))
-
- elif not other.has(self.x):
- f = self.function + other
- ind = self.ind + other
-
- return self.func(f, self.x, self.x0, self.dir,
- (self.ak, self.xk, ind))
-
- return Add(self, other)
-
- def __radd__(self, other):
- return self.__add__(other)
-
- def __neg__(self):
- return self.func(-self.function, self.x, self.x0, self.dir,
- (-self.ak, self.xk, -self.ind))
-
- def __sub__(self, other):
- return self.__add__(-other)
-
- def __rsub__(self, other):
- return (-self).__add__(other)
-
- def __mul__(self, other):
- other = sympify(other)
-
- if other.has(self.x):
- return Mul(self, other)
-
- f = self.function * other
- ak = self.ak.coeff_mul(other)
- ind = self.ind * other
-
- return self.func(f, self.x, self.x0, self.dir, (ak, self.xk, ind))
-
- def __rmul__(self, other):
- return self.__mul__(other)
-
def fps(f, x=None, x0=0, dir=1, hyper=True, order=4, rational=True, full=False):
"""Generates Formal Power Series of f.
| coverage_report.py should be able to run slow tests also
Currently Coverage report doesn't runs slow tests, so the coverage report generated is not accurate.
It should run slow tests by a flag.
```
bin/coverage_report.py
```
**EDIT**
It should accept a --slow flag just like bin/test. | sympy/sympy | diff --git a/sympy/series/tests/test_formal.py b/sympy/series/tests/test_formal.py
index b11de2cb5a..b0d2c21b83 100644
--- a/sympy/series/tests/test_formal.py
+++ b/sympy/series/tests/test_formal.py
@@ -1,6 +1,6 @@
from sympy import (symbols, factorial, sqrt, Rational, atan, I, log, fps, O,
Sum, oo, S, pi, cos, sin, Function, exp, Derivative, asin,
- airyai, acos, acosh, gamma, erf, asech, Add, Integral, Mul)
+ airyai, acos, acosh, gamma, erf, asech)
from sympy.series.formal import (rational_algorithm, FormalPowerSeries,
rational_independent, simpleDE, exp_re,
hyper_re)
@@ -374,7 +374,6 @@ def test_fps__logarithmic_singularity_fail():
assert fps(f, x) == log(2) - log(x) - x**2/4 - 3*x**4/64 + O(x**6)
-@XFAIL
def test_fps__symbolic():
f = x**n*sin(x**2)
assert fps(f, x).truncate(8) == x**2*x**n - x**6*x**n/6 + O(x**(n + 8), x)
@@ -412,84 +411,3 @@ def test_fps__symbolic():
def test_fps__slow():
f = x*exp(x)*sin(2*x) # TODO: rsolve needs improvement
assert fps(f, x).truncate() == 2*x**2 + 2*x**3 - x**4/3 - x**5 + O(x**6)
-
-
-def test_fps__operations():
- f1, f2 = fps(sin(x)), fps(cos(x))
-
- fsum = f1 + f2
- assert fsum.function == sin(x) + cos(x)
- assert fsum.truncate() == \
- 1 + x - x**2/2 - x**3/6 + x**4/24 + x**5/120 + O(x**6)
-
- fsum = f1 + 1
- assert fsum.function == sin(x) + 1
- assert fsum.truncate() == 1 + x - x**3/6 + x**5/120 + O(x**6)
-
- fsum = 1 + f2
- assert fsum.function == cos(x) + 1
- assert fsum.truncate() == 2 - x**2/2 + x**4/24 + O(x**6)
-
- assert (f1 + x) == Add(f1, x)
-
- assert -f2.truncate() == -1 + x**2/2 - x**4/24 + O(x**6)
- assert (f1 - f1) == S.Zero
-
- fsub = f1 - f2
- assert fsub.function == sin(x) - cos(x)
- assert fsub.truncate() == \
- -1 + x + x**2/2 - x**3/6 - x**4/24 + x**5/120 + O(x**6)
-
- fsub = f1 - 1
- assert fsub.function == sin(x) - 1
- assert fsub.truncate() == -1 + x - x**3/6 + x**5/120 + O(x**6)
-
- fsub = 1 - f2
- assert fsub.function == -cos(x) + 1
- assert fsub.truncate() == x**2/2 - x**4/24 + O(x**6)
-
- raises(ValueError, lambda: f1 + fps(exp(x), dir=-1))
- raises(ValueError, lambda: f1 + fps(exp(x), x0=1))
-
- fm = f1 * 3
-
- assert fm.function == 3*sin(x)
- assert fm.truncate() == 3*x - x**3/2 + x**5/40 + O(x**6)
-
- fm = 3 * f2
-
- assert fm.function == 3*cos(x)
- assert fm.truncate() == 3 - 3*x**2/2 + x**4/8 + O(x**6)
-
- assert (f1 * f2) == Mul(f1, f2)
- assert (f1 * x) == Mul(f1, x)
-
- fd = f1.diff()
- assert fd.function == cos(x)
- assert fd.truncate() == 1 - x**2/2 + x**4/24 + O(x**6)
-
- fd = f2.diff()
- assert fd.function == -sin(x)
- assert fd.truncate() == -x + x**3/6 - x**5/120 + O(x**6)
-
- fd = f2.diff().diff()
- assert fd.function == -cos(x)
- assert fd.truncate() == -1 + x**2/2 - x**4/24 + O(x**6)
-
- f3 = fps(exp(sqrt(x)))
- fd = f3.diff()
- assert fd.truncate().expand() == \
- (1/(2*sqrt(x)) + S(1)/2 + x/12 + x**2/240 + x**3/10080 + x**4/725760 +
- x**5/79833600 + sqrt(x)/4 + x**(S(3)/2)/48 + x**(S(5)/2)/1440 +
- x**(S(7)/2)/80640 + x**(S(9)/2)/7257600 + x**(S(11)/2)/958003200 +
- O(x**6))
-
- assert f1.integrate((x, 0, 1)) == -cos(1) + 1
-
- fi = f1.integrate(x)
- assert fi.function == -cos(x)
- assert fi.truncate() == -1 + x**2/2 - x**4/24 + O(x**6)
-
- fi = f2.integrate()
- assert fi.function == sin(x)
- assert fi.truncate() == x - x**3/6 + x**5/120 + O(x**6)
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 0,
"issue_text_score": 1,
"test_score": 0
},
"num_modified_files": 2
} | 0.7 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"mpmath>=0.19",
"pytest",
"pytest-cov"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.4",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | attrs==22.2.0
certifi==2021.5.30
coverage==6.2
importlib-metadata==4.8.3
iniconfig==1.1.1
mpmath==1.3.0
packaging==21.3
pluggy==1.0.0
py==1.11.0
pyparsing==3.1.4
pytest==7.0.1
pytest-cov==4.0.0
-e git+https://github.com/sympy/sympy.git@19f589457dfc4822e375e8715377ad71b4d21f25#egg=sympy
tomli==1.2.3
typing_extensions==4.1.1
zipp==3.6.0
| name: sympy
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2021.5.30=py36h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.3=he6710b0_2
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- pip=21.2.2=py36h06a4308_0
- python=3.6.13=h12debd9_1
- readline=8.2=h5eee18b_0
- setuptools=58.0.4=py36h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- wheel=0.37.1=pyhd3eb1b0_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- attrs==22.2.0
- coverage==6.2
- importlib-metadata==4.8.3
- iniconfig==1.1.1
- mpmath==1.3.0
- packaging==21.3
- pluggy==1.0.0
- py==1.11.0
- pyparsing==3.1.4
- pytest==7.0.1
- pytest-cov==4.0.0
- tomli==1.2.3
- typing-extensions==4.1.1
- zipp==3.6.0
prefix: /opt/conda/envs/sympy
| [
"sympy/series/tests/test_formal.py::test_fps__symbolic"
] | [] | [
"sympy/series/tests/test_formal.py::test_rational_algorithm",
"sympy/series/tests/test_formal.py::test_rational_independent",
"sympy/series/tests/test_formal.py::test_simpleDE",
"sympy/series/tests/test_formal.py::test_exp_re",
"sympy/series/tests/test_formal.py::test_hyper_re",
"sympy/series/tests/test_formal.py::test_fps",
"sympy/series/tests/test_formal.py::test_fps__rational",
"sympy/series/tests/test_formal.py::test_fps__hyper",
"sympy/series/tests/test_formal.py::test_fps_shift",
"sympy/series/tests/test_formal.py::test_fps__Add_expr",
"sympy/series/tests/test_formal.py::test_fps__asymptotic",
"sympy/series/tests/test_formal.py::test_fps__fractional",
"sympy/series/tests/test_formal.py::test_fps__logarithmic_singularity",
"sympy/series/tests/test_formal.py::test_fps__slow"
] | [] | BSD | 229 |
mopidy__mopidy-local-sqlite-72 | df6a368f3649efe4c2d691fdaced0a590553a4a2 | 2015-09-04 09:55:29 | df6a368f3649efe4c2d691fdaced0a590553a4a2 | diff --git a/CHANGES.rst b/CHANGES.rst
index ae7111f..16f16e6 100644
--- a/CHANGES.rst
+++ b/CHANGES.rst
@@ -8,6 +8,10 @@
If we can find the old data dir, all files are automatically moved to the new
data dir.
+- By default, browsing artists will use the "sortname" field for
+ ordering results, if available. Set ``use_artist_sortname = false``
+ to sort according to sort according to the displayed name only.
+
- Remove file system ("Folders") browsing, since this is already
handled by the ``file`` backend in Mopidy v1.1.
diff --git a/README.rst b/README.rst
index a9d63ce..ba529d3 100644
--- a/README.rst
+++ b/README.rst
@@ -64,6 +64,10 @@ but be aware that these are still subject to change::
# multi-artist tracks [https://github.com/sampsyo/beets/issues/907]
use_artist_mbid_uri = false
+ # whether to use the sortname field for sorting artist browse results;
+ # set to false to sort according to displayed name only
+ use_artist_sortname = true
+
Project Resources
------------------------------------------------------------------------
diff --git a/mopidy_local_sqlite/__init__.py b/mopidy_local_sqlite/__init__.py
index 279d7d0..e6c1939 100644
--- a/mopidy_local_sqlite/__init__.py
+++ b/mopidy_local_sqlite/__init__.py
@@ -26,6 +26,7 @@ class Extension(ext.Extension):
schema['timeout'] = config.Integer(optional=True, minimum=1)
schema['use_album_mbid_uri'] = config.Boolean()
schema['use_artist_mbid_uri'] = config.Boolean()
+ schema['use_artist_sortname'] = config.Boolean()
# no longer used
schema['search_limit'] = config.Deprecated()
schema['extract_images'] = config.Deprecated()
diff --git a/mopidy_local_sqlite/ext.conf b/mopidy_local_sqlite/ext.conf
index 5919d64..cfbfa46 100644
--- a/mopidy_local_sqlite/ext.conf
+++ b/mopidy_local_sqlite/ext.conf
@@ -23,3 +23,7 @@ use_album_mbid_uri = true
# disabled by default, since some taggers do not handle this well for
# multi-artist tracks [https://github.com/sampsyo/beets/issues/907]
use_artist_mbid_uri = false
+
+# whether to use the sortname field for sorting artist browse results;
+# set to false to sort according to displayed name only
+use_artist_sortname = true
diff --git a/mopidy_local_sqlite/library.py b/mopidy_local_sqlite/library.py
index d3623c5..da67cda 100644
--- a/mopidy_local_sqlite/library.py
+++ b/mopidy_local_sqlite/library.py
@@ -170,7 +170,8 @@ class SQLiteLibrary(local.Library):
# to composers and performers
if type == Ref.TRACK and 'album' in query:
order = ('disc_no', 'track_no', 'name')
-
+ if type == Ref.ARTIST and self._config['use_artist_sortname']:
+ order = ('coalesce(sortname, name)',)
roles = role or ('artist', 'albumartist') # FIXME: re-think 'roles'...
refs = []
diff --git a/mopidy_local_sqlite/schema.py b/mopidy_local_sqlite/schema.py
index df02db2..a169077 100644
--- a/mopidy_local_sqlite/schema.py
+++ b/mopidy_local_sqlite/schema.py
@@ -146,7 +146,7 @@ _SEARCH_FIELDS = {
'comment'
}
-schema_version = 5
+schema_version = 6
logger = logging.getLogger(__name__)
@@ -167,16 +167,18 @@ class Connection(sqlite3.Connection):
def load(c):
sql_dir = os.path.join(os.path.dirname(__file__), b'sql')
user_version = c.execute('PRAGMA user_version').fetchone()[0]
- if not user_version:
- logger.info('Creating SQLite database schema v%s', schema_version)
- script = os.path.join(sql_dir, 'create-v%s.sql' % schema_version)
- c.executescript(open(script).read())
- user_version = c.execute('PRAGMA user_version').fetchone()[0]
while user_version != schema_version:
- logger.info('Upgrading SQLite database schema v%s', user_version)
- script = os.path.join(sql_dir, 'upgrade-v%s.sql' % user_version)
- c.executescript(open(script).read())
- user_version = c.execute('PRAGMA user_version').fetchone()[0]
+ if user_version:
+ logger.info('Upgrading SQLite database schema v%s', user_version)
+ filename = 'upgrade-v%s.sql' % user_version
+ else:
+ logger.info('Creating SQLite database schema v%s', schema_version)
+ filename = 'schema.sql'
+ with open(os.path.join(sql_dir, filename)) as fh:
+ c.executescript(fh.read())
+ new_version = c.execute('PRAGMA user_version').fetchone()[0]
+ assert new_version != user_version
+ user_version = new_version
return user_version
@@ -269,6 +271,7 @@ def insert_artists(c, artists):
_insert(c, 'artist', {
'uri': artist.uri,
'name': artist.name,
+ 'sortname': artist.sortname,
'musicbrainz_id': artist.musicbrainz_id
})
return artist.uri
@@ -422,6 +425,7 @@ def _track(row):
albumartists = [Artist(
uri=row.albumartist_uri,
name=row.albumartist_name,
+ sortname=row.albumartist_sortname,
musicbrainz_id=row.albumartist_musicbrainz_id
)]
else:
@@ -440,18 +444,21 @@ def _track(row):
kwargs['artists'] = [Artist(
uri=row.artist_uri,
name=row.artist_name,
+ sortname=row.artist_sortname,
musicbrainz_id=row.artist_musicbrainz_id
)]
if row.composer_uri is not None:
kwargs['composers'] = [Artist(
uri=row.composer_uri,
name=row.composer_name,
+ sortname=row.composer_sortname,
musicbrainz_id=row.composer_musicbrainz_id
)]
if row.performer_uri is not None:
kwargs['performers'] = [Artist(
uri=row.performer_uri,
name=row.performer_name,
+ sortname=row.performer_sortname,
musicbrainz_id=row.performer_musicbrainz_id
)]
return Track(**kwargs)
diff --git a/mopidy_local_sqlite/sql/create-v5.sql b/mopidy_local_sqlite/sql/schema.sql
similarity index 94%
rename from mopidy_local_sqlite/sql/create-v5.sql
rename to mopidy_local_sqlite/sql/schema.sql
index d6c119c..c633016 100644
--- a/mopidy_local_sqlite/sql/create-v5.sql
+++ b/mopidy_local_sqlite/sql/schema.sql
@@ -2,11 +2,12 @@
BEGIN EXCLUSIVE TRANSACTION;
-PRAGMA user_version = 5; -- schema version
+PRAGMA user_version = 6; -- schema version
CREATE TABLE artist (
uri TEXT PRIMARY KEY, -- artist URI
name TEXT NOT NULL, -- artist name
+ sortname TEXT, -- artist name for sorting
musicbrainz_id TEXT -- MusicBrainz ID
);
@@ -66,6 +67,7 @@ SELECT album.uri AS uri,
album.name AS name,
artist.uri AS artist_uri,
artist.name AS artist_name,
+ artist.sortname AS artist_sortname,
artist.musicbrainz_id AS artist_musicbrainz_id,
album.num_tracks AS num_tracks,
album.num_discs AS num_discs,
@@ -97,15 +99,19 @@ SELECT track.rowid AS docid,
album.images AS album_images,
artist.uri AS artist_uri,
artist.name AS artist_name,
+ artist.sortname AS artist_sortname,
artist.musicbrainz_id AS artist_musicbrainz_id,
composer.uri AS composer_uri,
composer.name AS composer_name,
+ composer.sortname AS composer_sortname,
composer.musicbrainz_id AS composer_musicbrainz_id,
performer.uri AS performer_uri,
performer.name AS performer_name,
+ performer.sortname AS performer_sortname,
performer.musicbrainz_id AS performer_musicbrainz_id,
albumartist.uri AS albumartist_uri,
albumartist.name AS albumartist_name,
+ albumartist.sortname AS albumartist_sortname,
albumartist.musicbrainz_id AS albumartist_musicbrainz_id
FROM track
LEFT OUTER JOIN album ON track.album = album.uri
diff --git a/mopidy_local_sqlite/sql/upgrade-v5.sql b/mopidy_local_sqlite/sql/upgrade-v5.sql
new file mode 100644
index 0000000..45da1c1
--- /dev/null
+++ b/mopidy_local_sqlite/sql/upgrade-v5.sql
@@ -0,0 +1,70 @@
+-- Mopidy-Local-SQLite schema upgrade v5 -> v6
+
+BEGIN EXCLUSIVE TRANSACTION;
+
+ALTER TABLE artist ADD COLUMN sortname TEXT;
+
+DROP VIEW albums;
+DROP VIEW tracks;
+
+CREATE VIEW albums AS
+SELECT album.uri AS uri,
+ album.name AS name,
+ artist.uri AS artist_uri,
+ artist.name AS artist_name,
+ artist.sortname AS artist_sortname,
+ artist.musicbrainz_id AS artist_musicbrainz_id,
+ album.num_tracks AS num_tracks,
+ album.num_discs AS num_discs,
+ album.date AS date,
+ album.musicbrainz_id AS musicbrainz_id,
+ album.images AS images
+ FROM album
+ LEFT OUTER JOIN artist ON album.artists = artist.uri;
+
+CREATE VIEW tracks AS
+SELECT track.rowid AS docid,
+ track.uri AS uri,
+ track.name AS name,
+ track.genre AS genre,
+ track.track_no AS track_no,
+ track.disc_no AS disc_no,
+ track.date AS date,
+ track.length AS length,
+ track.bitrate AS bitrate,
+ track.comment AS comment,
+ track.musicbrainz_id AS musicbrainz_id,
+ track.last_modified AS last_modified,
+ album.uri AS album_uri,
+ album.name AS album_name,
+ album.num_tracks AS album_num_tracks,
+ album.num_discs AS album_num_discs,
+ album.date AS album_date,
+ album.musicbrainz_id AS album_musicbrainz_id,
+ album.images AS album_images,
+ artist.uri AS artist_uri,
+ artist.name AS artist_name,
+ artist.sortname AS artist_sortname,
+ artist.musicbrainz_id AS artist_musicbrainz_id,
+ composer.uri AS composer_uri,
+ composer.name AS composer_name,
+ composer.sortname AS composer_sortname,
+ composer.musicbrainz_id AS composer_musicbrainz_id,
+ performer.uri AS performer_uri,
+ performer.name AS performer_name,
+ performer.sortname AS performer_sortname,
+ performer.musicbrainz_id AS performer_musicbrainz_id,
+ albumartist.uri AS albumartist_uri,
+ albumartist.name AS albumartist_name,
+ albumartist.sortname AS albumartist_sortname,
+ albumartist.musicbrainz_id AS albumartist_musicbrainz_id
+ FROM track
+ LEFT OUTER JOIN album ON track.album = album.uri
+ LEFT OUTER JOIN artist ON track.artists = artist.uri
+ LEFT OUTER JOIN artist AS composer ON track.composers = composer.uri
+ LEFT OUTER JOIN artist AS performer ON track.performers = performer.uri
+ LEFT OUTER JOIN artist AS albumartist ON album.artists = albumartist.uri;
+
+PRAGMA user_version = 6; -- update schema version
+
+END TRANSACTION;
| Add "sortname" fields
See mopidy/mopidy#940.
Even if this doesn't get added to models, the fields can still be extracted from gstreamer tags passed to `Library.add()` in Mopidy v0.20. `Library.browse()` can then return results using
```
ORDER BY coalesce(sortname, name)
```
| mopidy/mopidy-local-sqlite | diff --git a/tests/test_extension.py b/tests/test_extension.py
index a865514..099be12 100644
--- a/tests/test_extension.py
+++ b/tests/test_extension.py
@@ -17,3 +17,4 @@ def test_get_config_schema():
assert 'timeout' in schema
assert 'use_album_mbid_uri' in schema
assert 'use_artist_mbid_uri' in schema
+ assert 'use_artist_sortname' in schema
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_short_problem_statement",
"has_added_files",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 3,
"issue_text_score": 2,
"test_score": 2
},
"num_modified_files": 7
} | 0.10 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[dev]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"mock",
"pytest",
"pytest-cov",
"pytest-xdist"
],
"pre_install": [
"apt-get update",
"apt-get install -y mopidy"
],
"python": "3.9",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | certifi==2025.1.31
charset-normalizer==3.4.1
coverage==7.8.0
exceptiongroup==1.2.2
execnet==2.1.1
idna==3.10
iniconfig==2.1.0
mock==5.2.0
Mopidy==3.4.2
-e git+https://github.com/mopidy/mopidy-local-sqlite.git@df6a368f3649efe4c2d691fdaced0a590553a4a2#egg=Mopidy_Local_SQLite
packaging==24.2
pluggy==1.5.0
pykka==4.2.0
pytest==8.3.5
pytest-cov==6.0.0
pytest-xdist==3.6.1
requests==2.32.3
tomli==2.2.1
tornado==6.4.2
typing_extensions==4.13.0
uritools==4.0.3
urllib3==2.3.0
| name: mopidy-local-sqlite
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=3.0.16=h5eee18b_0
- pip=25.0=py39h06a4308_0
- python=3.9.21=he870216_1
- readline=8.2=h5eee18b_0
- setuptools=75.8.0=py39h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- tzdata=2025a=h04d1e81_0
- wheel=0.45.1=py39h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- certifi==2025.1.31
- charset-normalizer==3.4.1
- coverage==7.8.0
- exceptiongroup==1.2.2
- execnet==2.1.1
- idna==3.10
- iniconfig==2.1.0
- mock==5.2.0
- mopidy==3.4.2
- packaging==24.2
- pluggy==1.5.0
- pykka==4.2.0
- pytest==8.3.5
- pytest-cov==6.0.0
- pytest-xdist==3.6.1
- requests==2.32.3
- tomli==2.2.1
- tornado==6.4.2
- typing-extensions==4.13.0
- uritools==4.0.3
- urllib3==2.3.0
prefix: /opt/conda/envs/mopidy-local-sqlite
| [
"tests/test_extension.py::test_get_config_schema"
] | [] | [
"tests/test_extension.py::test_get_default_config"
] | [] | Apache License 2.0 | 230 |
|
falconry__falcon-597 | dcbde2512cac6f282bc209702c7477379c9546c1 | 2015-09-06 00:04:56 | b78ffaac7c412d3b3d6cd3c70dd05024d79d2cce | philiptzou: Rebased onto the latest version.
philiptzou: Rebased onto the latest version. Again.
kgriffs: @philiptzou Nice work! Just a couple of nits to address and this should be ready to merge.
philiptzou: @kgriffs Sorry for the delay. Just fixed the issues you addressed. | diff --git a/falcon/util/uri.py b/falcon/util/uri.py
index f014e5a..2359672 100644
--- a/falcon/util/uri.py
+++ b/falcon/util/uri.py
@@ -178,9 +178,12 @@ if six.PY2:
tokens = decoded_uri.split('%')
decoded_uri = tokens[0]
for token in tokens[1:]:
- char, byte = _HEX_TO_BYTE[token[:2]]
- decoded_uri += char + token[2:]
-
+ token_partial = token[:2]
+ if token_partial in _HEX_TO_BYTE:
+ char, byte = _HEX_TO_BYTE[token_partial]
+ else:
+ char, byte = '%', 0
+ decoded_uri += char + (token[2:] if byte else token)
only_ascii = only_ascii and (byte <= 127)
# PERF(kgriffs): Only spend the time to do this if there
@@ -235,7 +238,12 @@ else:
tokens = decoded_uri.split(b'%')
decoded_uri = tokens[0]
for token in tokens[1:]:
- decoded_uri += _HEX_TO_BYTE[token[:2]] + token[2:]
+ token_partial = token[:2]
+ if token_partial in _HEX_TO_BYTE:
+ decoded_uri += _HEX_TO_BYTE[token_partial] + token[2:]
+ else:
+ # malformed percentage like "x=%" or "y=%+"
+ decoded_uri += b'%' + token
# Convert back to str
return decoded_uri.decode('utf-8', 'replace')
| Falcon crashes on decoding query string
When Falcon receives a request with query string that cannot be percent decoded (e.g. `x=%`), it crashes resulting in a rather unexpected 502 response.
Traceback (most recent call last):
File "/opt/ads/venv/local/lib/python2.7/site-packages/falcon/api.py", line 154, in __call__
req = self._request_type(env, options=self.req_options)
File "/opt/ads/venv/local/lib/python2.7/site-packages/falcon/request.py", line 237, in __init__
keep_blank_qs_values=self.options.keep_blank_qs_values,
File "/opt/ads/venv/local/lib/python2.7/site-packages/falcon/util/uri.py", line 327, in parse_query_string
params[k] = decode(v)
File "/opt/ads/venv/local/lib/python2.7/site-packages/falcon/util/uri.py", line 181, in decode
char, byte = _HEX_TO_BYTE[token[:2]]
KeyError: ''
Would it make more sense to pass-through the original value in this case without trying to decode it? It's a rather small change so I could prepare a pull request for it, but I would like to confirm first that this was not intentional behavior. | falconry/falcon | diff --git a/tests/test_query_params.py b/tests/test_query_params.py
index 5604e9a..50ed010 100644
--- a/tests/test_query_params.py
+++ b/tests/test_query_params.py
@@ -64,6 +64,16 @@ class _TestQueryParams(testing.TestBase):
self.assertEqual(req.get_param_as_list('id', int), [23, 42])
self.assertEqual(req.get_param('q'), u'\u8c46 \u74e3')
+ def test_bad_percentage(self):
+ query_string = 'x=%%20%+%&y=peregrine&z=%a%z%zz%1%20e'
+ self.simulate_request('/', query_string=query_string)
+ self.assertEqual(self.srmock.status, falcon.HTTP_200)
+
+ req = self.resource.req
+ self.assertEqual(req.get_param('x'), '% % %')
+ self.assertEqual(req.get_param('y'), 'peregrine')
+ self.assertEqual(req.get_param('z'), '%a%z%zz%1 e')
+
def test_allowed_names(self):
query_string = ('p=0&p1=23&2p=foo&some-thing=that&blank=&'
'some_thing=x&-bogus=foo&more.things=blah&'
| {
"commit_name": "head_commit",
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true,
"llm_score": {
"difficulty_score": 0,
"issue_text_score": 0,
"test_score": 2
},
"num_modified_files": 1
} | 0.3 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "pytest",
"pip_packages": [
"nose",
"coverage",
"ddt",
"pyyaml",
"requests",
"testtools",
"pytest"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.7",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | attrs @ file:///croot/attrs_1668696182826/work
certifi @ file:///croot/certifi_1671487769961/work/certifi
charset-normalizer==3.4.1
coverage==7.2.7
ddt==1.7.2
-e git+https://github.com/falconry/falcon.git@dcbde2512cac6f282bc209702c7477379c9546c1#egg=falcon
flit_core @ file:///opt/conda/conda-bld/flit-core_1644941570762/work/source/flit_core
idna==3.10
importlib-metadata @ file:///tmp/build/80754af9/importlib-metadata_1648562407465/work
iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work
nose==1.3.7
packaging @ file:///croot/packaging_1671697413597/work
pluggy @ file:///tmp/build/80754af9/pluggy_1648042572264/work
py @ file:///opt/conda/conda-bld/py_1644396412707/work
pytest==7.1.2
python-mimeparse==1.6.0
PyYAML==6.0.1
requests==2.31.0
six==1.17.0
testtools==2.7.1
tomli @ file:///opt/conda/conda-bld/tomli_1657175507142/work
typing_extensions @ file:///croot/typing_extensions_1669924550328/work
urllib3==2.0.7
zipp @ file:///croot/zipp_1672387121353/work
| name: falcon
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- attrs=22.1.0=py37h06a4308_0
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2022.12.7=py37h06a4308_0
- flit-core=3.6.0=pyhd3eb1b0_0
- importlib-metadata=4.11.3=py37h06a4308_0
- importlib_metadata=4.11.3=hd3eb1b0_0
- iniconfig=1.1.1=pyhd3eb1b0_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- packaging=22.0=py37h06a4308_0
- pip=22.3.1=py37h06a4308_0
- pluggy=1.0.0=py37h06a4308_1
- py=1.11.0=pyhd3eb1b0_0
- pytest=7.1.2=py37h06a4308_0
- python=3.7.16=h7a1cb2a_0
- readline=8.2=h5eee18b_0
- setuptools=65.6.3=py37h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- tomli=2.0.1=py37h06a4308_0
- typing_extensions=4.4.0=py37h06a4308_0
- wheel=0.38.4=py37h06a4308_0
- xz=5.6.4=h5eee18b_1
- zipp=3.11.0=py37h06a4308_0
- zlib=1.2.13=h5eee18b_1
- pip:
- charset-normalizer==3.4.1
- coverage==7.2.7
- ddt==1.7.2
- idna==3.10
- nose==1.3.7
- python-mimeparse==1.6.0
- pyyaml==6.0.1
- requests==2.31.0
- six==1.17.0
- testtools==2.7.1
- urllib3==2.0.7
prefix: /opt/conda/envs/falcon
| [
"tests/test_query_params.py::_TestQueryParams::test_bad_percentage",
"tests/test_query_params.py::PostQueryParams::test_bad_percentage",
"tests/test_query_params.py::GetQueryParams::test_bad_percentage"
] | [] | [
"tests/test_query_params.py::_TestQueryParams::test_allowed_names",
"tests/test_query_params.py::_TestQueryParams::test_blank",
"tests/test_query_params.py::_TestQueryParams::test_boolean",
"tests/test_query_params.py::_TestQueryParams::test_boolean_blank",
"tests/test_query_params.py::_TestQueryParams::test_get_date_invalid",
"tests/test_query_params.py::_TestQueryParams::test_get_date_missing_param",
"tests/test_query_params.py::_TestQueryParams::test_get_date_store",
"tests/test_query_params.py::_TestQueryParams::test_get_date_valid",
"tests/test_query_params.py::_TestQueryParams::test_get_date_valid_with_format",
"tests/test_query_params.py::_TestQueryParams::test_int",
"tests/test_query_params.py::_TestQueryParams::test_int_neg",
"tests/test_query_params.py::_TestQueryParams::test_list_transformer",
"tests/test_query_params.py::_TestQueryParams::test_list_type",
"tests/test_query_params.py::_TestQueryParams::test_list_type_blank",
"tests/test_query_params.py::_TestQueryParams::test_multiple_form_keys",
"tests/test_query_params.py::_TestQueryParams::test_multiple_form_keys_as_list",
"tests/test_query_params.py::_TestQueryParams::test_multiple_keys_as_bool",
"tests/test_query_params.py::_TestQueryParams::test_multiple_keys_as_int",
"tests/test_query_params.py::_TestQueryParams::test_none",
"tests/test_query_params.py::_TestQueryParams::test_param_property",
"tests/test_query_params.py::_TestQueryParams::test_percent_encoded",
"tests/test_query_params.py::_TestQueryParams::test_required_1_get_param",
"tests/test_query_params.py::_TestQueryParams::test_required_2_get_param_as_int",
"tests/test_query_params.py::_TestQueryParams::test_required_3_get_param_as_bool",
"tests/test_query_params.py::_TestQueryParams::test_required_4_get_param_as_list",
"tests/test_query_params.py::_TestQueryParams::test_simple",
"tests/test_query_params.py::PostQueryParams::test_allowed_names",
"tests/test_query_params.py::PostQueryParams::test_blank",
"tests/test_query_params.py::PostQueryParams::test_boolean",
"tests/test_query_params.py::PostQueryParams::test_boolean_blank",
"tests/test_query_params.py::PostQueryParams::test_get_date_invalid",
"tests/test_query_params.py::PostQueryParams::test_get_date_missing_param",
"tests/test_query_params.py::PostQueryParams::test_get_date_store",
"tests/test_query_params.py::PostQueryParams::test_get_date_valid",
"tests/test_query_params.py::PostQueryParams::test_get_date_valid_with_format",
"tests/test_query_params.py::PostQueryParams::test_int",
"tests/test_query_params.py::PostQueryParams::test_int_neg",
"tests/test_query_params.py::PostQueryParams::test_list_transformer",
"tests/test_query_params.py::PostQueryParams::test_list_type",
"tests/test_query_params.py::PostQueryParams::test_list_type_blank",
"tests/test_query_params.py::PostQueryParams::test_multiple_form_keys",
"tests/test_query_params.py::PostQueryParams::test_multiple_form_keys_as_list",
"tests/test_query_params.py::PostQueryParams::test_multiple_keys_as_bool",
"tests/test_query_params.py::PostQueryParams::test_multiple_keys_as_int",
"tests/test_query_params.py::PostQueryParams::test_non_ascii",
"tests/test_query_params.py::PostQueryParams::test_none",
"tests/test_query_params.py::PostQueryParams::test_param_property",
"tests/test_query_params.py::PostQueryParams::test_percent_encoded",
"tests/test_query_params.py::PostQueryParams::test_required_1_get_param",
"tests/test_query_params.py::PostQueryParams::test_required_2_get_param_as_int",
"tests/test_query_params.py::PostQueryParams::test_required_3_get_param_as_bool",
"tests/test_query_params.py::PostQueryParams::test_required_4_get_param_as_list",
"tests/test_query_params.py::PostQueryParams::test_simple",
"tests/test_query_params.py::GetQueryParams::test_allowed_names",
"tests/test_query_params.py::GetQueryParams::test_blank",
"tests/test_query_params.py::GetQueryParams::test_boolean",
"tests/test_query_params.py::GetQueryParams::test_boolean_blank",
"tests/test_query_params.py::GetQueryParams::test_get_date_invalid",
"tests/test_query_params.py::GetQueryParams::test_get_date_missing_param",
"tests/test_query_params.py::GetQueryParams::test_get_date_store",
"tests/test_query_params.py::GetQueryParams::test_get_date_valid",
"tests/test_query_params.py::GetQueryParams::test_get_date_valid_with_format",
"tests/test_query_params.py::GetQueryParams::test_int",
"tests/test_query_params.py::GetQueryParams::test_int_neg",
"tests/test_query_params.py::GetQueryParams::test_list_transformer",
"tests/test_query_params.py::GetQueryParams::test_list_type",
"tests/test_query_params.py::GetQueryParams::test_list_type_blank",
"tests/test_query_params.py::GetQueryParams::test_multiple_form_keys",
"tests/test_query_params.py::GetQueryParams::test_multiple_form_keys_as_list",
"tests/test_query_params.py::GetQueryParams::test_multiple_keys_as_bool",
"tests/test_query_params.py::GetQueryParams::test_multiple_keys_as_int",
"tests/test_query_params.py::GetQueryParams::test_none",
"tests/test_query_params.py::GetQueryParams::test_param_property",
"tests/test_query_params.py::GetQueryParams::test_percent_encoded",
"tests/test_query_params.py::GetQueryParams::test_required_1_get_param",
"tests/test_query_params.py::GetQueryParams::test_required_2_get_param_as_int",
"tests/test_query_params.py::GetQueryParams::test_required_3_get_param_as_bool",
"tests/test_query_params.py::GetQueryParams::test_required_4_get_param_as_list",
"tests/test_query_params.py::GetQueryParams::test_simple"
] | [] | Apache License 2.0 | 231 |
spendright__msd-20 | 02d85249b9e1f5b2824b9a268220a30301084e42 | 2015-09-07 05:17:33 | 02d85249b9e1f5b2824b9a268220a30301084e42 | diff --git a/msd/db.py b/msd/db.py
index 87ee840..9014087 100644
--- a/msd/db.py
+++ b/msd/db.py
@@ -15,6 +15,27 @@ import sqlite3
from itertools import groupby
+def create_table(db, table_name, columns, primary_key=None):
+ """Create a table with the given columns and, optionally, primary key.
+
+ *columns* is a map from column name to type
+ *primary_key* is a list of column names
+ """
+
+ col_def_sql = ', '.join('`{}` {}'.format(col_name, col_type)
+ for col_name, col_type in sorted(columns.items()))
+
+ # optional PRIMARY KEY
+ primary_key_sql = ''
+ if primary_key:
+ primary_key_sql = ', PRIMARY KEY({})'.format(col_sql(primary_key))
+
+ create_sql = 'CREATE TABLE `{}` ({}{})'.format(
+ table_name, col_def_sql, primary_key_sql)
+
+ db.execute(create_sql)
+
+
def create_index(db, table_name, index_cols):
if isinstance(index_cols, str):
raise TypeError
diff --git a/msd/merge.py b/msd/merge.py
index ba95d56..bff8f3f 100644
--- a/msd/merge.py
+++ b/msd/merge.py
@@ -14,6 +14,7 @@
"""Supporting code to merge data from the scratch table and write it
to the output table."""
from .db import create_index
+from .db import create_table
from .db import insert_row
from .table import TABLES
@@ -24,12 +25,7 @@ def create_output_table(output_db, table_name):
primary_key = table_def['primary_key']
indexes = table_def.get('indexes', ())
- create_sql = 'CREATE TABLE `{}` ({}, PRIMARY KEY ({}))'.format(
- table_name,
- ', '.join('`{}` {}'.format(col_name, col_type)
- for col_name, col_type in sorted(columns.items())),
- ', '.join('`{}`'.format(pk_col) for pk_col in primary_key))
- output_db.execute(create_sql)
+ create_table(output_db, table_name, columns, primary_key)
for index_cols in indexes:
create_index(output_db, table_name, index_cols)
diff --git a/msd/norm.py b/msd/norm.py
index fa70768..c6d6543 100644
--- a/msd/norm.py
+++ b/msd/norm.py
@@ -72,4 +72,4 @@ def norm(s):
def smunch(s):
"""Like norm(), except we remove whitespace too."""
- return WHITESPACE_RE.sub('', s)
+ return WHITESPACE_RE.sub('', norm(s))
diff --git a/msd/scratch.py b/msd/scratch.py
index dd64aec..60ef616 100644
--- a/msd/scratch.py
+++ b/msd/scratch.py
@@ -19,6 +19,7 @@ from os.path import exists
from os.path import getmtime
from .db import create_index
+from .db import create_table
from .db import insert_row
from .db import open_db
from .db import show_tables
@@ -63,7 +64,7 @@ def build_scratch_db(
with open_db(scratch_db_tmp_path) as scratch_db:
- init_scratch_tables(scratch_db)
+ create_scratch_tables(scratch_db)
for input_db_path in input_db_paths:
log.info('dumping data from {} -> {}'.format(
@@ -78,27 +79,29 @@ def build_scratch_db(
rename(scratch_db_tmp_path, scratch_db_path)
-def init_scratch_tables(scratch_db):
+def create_scratch_tables(scratch_db):
"""Add tables to the given (open) SQLite DB."""
- for table_name, table_def in sorted(TABLES.items()):
- columns = table_def['columns'].copy()
- columns['scraper_id'] = 'text'
-
- create_sql = 'CREATE TABLE `{}` ({})'.format(
- table_name, ', '.join(
- '`{}` {}'.format(col_name, col_type)
- for col_name, col_type in sorted(columns.items())))
- scratch_db.execute(create_sql)
-
- # add "primary key" index
- index_cols = list(table_def.get('primary_key', ()))
- if 'scraper_id' not in index_cols:
- index_cols = ['scraper_id'] + index_cols
- create_index(scratch_db, table_name, index_cols)
+ for table_name in sorted(TABLES):
+ create_scratch_table(scratch_db, table_name)
+
+
+def create_scratch_table(scratch_db, table_name):
+ table_def = TABLES[table_name]
- # add other indexes
- for index_cols in table_def.get('indexes', ()):
- create_index(scratch_db, table_name, index_cols)
+ columns = table_def['columns'].copy()
+ columns['scraper_id'] = 'text'
+
+ create_table(scratch_db, table_name, columns)
+
+ # add "primary key" (non-unique) index
+ index_cols = list(table_def.get('primary_key', ()))
+ if 'scraper_id' not in index_cols:
+ index_cols = ['scraper_id'] + index_cols
+ create_index(scratch_db, table_name, index_cols)
+
+ # add other indexes
+ for index_cols in table_def.get('indexes', ()):
+ create_index(scratch_db, table_name, index_cols)
def db_path_to_scraper_prefix(path):
diff --git a/srs b/srs
new file mode 120000
index 0000000..6ed0827
--- /dev/null
+++ b/srs
@@ -0,0 +1,1 @@
+submodules/srs/srs
\ No newline at end of file
diff --git a/titlecase b/titlecase
new file mode 120000
index 0000000..f64a324
--- /dev/null
+++ b/titlecase
@@ -0,0 +1,1 @@
+submodules/titlecase/titlecase
\ No newline at end of file
| fails to merge 'CardScan' and 'Cardscan'
Somehow, `msd` is producing two entries for `Newell Rubbermaid` brands, `CardScan` and `Cardscan`. | spendright/msd | diff --git a/test/db.py b/test/db.py
new file mode 100644
index 0000000..a4686ed
--- /dev/null
+++ b/test/db.py
@@ -0,0 +1,69 @@
+# Copyright 2014-2015 SpendRight, Inc.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""Utilities for testing databases."""
+import sqlite3
+from unittest import TestCase
+
+from msd.db import create_table
+from msd.db import create_index
+from msd.db import insert_row
+from msd.db import open_db
+from msd.merge import create_output_table
+from msd.scratch import create_scratch_table
+from msd.table import TABLES
+
+
+# stuff that could be in msd.db, but that we only use for testing
+
+def select_all(db, table_name):
+ """Get all rows from a table, and sort (for easy testing of equality)."""
+ return sorted(
+ (dict(row) for row in
+ db.execute('SELECT * FROM `{}`'.format(table_name))),
+ key=lambda row: [(k, repr(v)) for (k, v) in row.items()])
+
+
+def insert_rows(db, table_name, rows):
+ """Call insert_row() multiple times."""
+ for row in rows:
+ insert_row(db, table_name, row)
+
+
+
+class DBTestCase(TestCase):
+
+ # output_tables to create at setup time
+ OUTPUT_TABLES = []
+
+ # scratch tables to create at setup time
+ SCRATCH_TABLES = []
+
+ def setUp(self):
+ self.output_db = open_db(':memory:')
+ self.scratch_db = open_db(':memory:')
+ self._tmp_dir = None
+
+ for table_name in self.SCRATCH_TABLES:
+ create_scratch_table(self.scratch_db, table_name)
+
+ for table_name in self.OUTPUT_TABLES:
+ create_output_table(self.output_db, table_name)
+
+ @property
+ def tmp_dir(self):
+ if self._tmp_dir is None:
+ self._tmp_dir = mkdtemp()
+ self.addCleanup(rmtree, self._tmp_dir)
+
+ return self._tmp_dir
diff --git a/test/unit/msd/test_brand.py b/test/unit/msd/test_brand.py
index 68834fc..478f4e1 100644
--- a/test/unit/msd/test_brand.py
+++ b/test/unit/msd/test_brand.py
@@ -14,7 +14,13 @@
# limitations under the License.
from unittest import TestCase
+from msd.brand import build_scraper_brand_map_table
from msd.brand import split_brand_and_tm
+from msd.db import insert_row
+
+from ...db import DBTestCase
+from ...db import insert_rows
+from ...db import select_all
class TestSplitBrandAndTM(TestCase):
@@ -39,3 +45,44 @@ class TestSplitBrandAndTM(TestCase):
def test_on_tm(self):
self.assertEqual(split_brand_and_tm('™'), ('', '™'))
+
+
+class TestBuildScraperBrandMapTable(DBTestCase):
+
+ SCRATCH_TABLES = [
+ 'brand', 'category', 'claim', 'rating', 'scraper_brand_map']
+
+ OUTPUT_TABLES = ['company_name', 'scraper_company_map']
+
+ def test_merge_differing_capitalization(self):
+ # this tests #19
+ insert_rows(self.scratch_db, 'brand', [
+ dict(brand='CardScan',
+ company='Newell Rubbermaid',
+ scraper_id='sr.campaign.hrc'),
+ dict(brand='Cardscan',
+ company='Newell Rubbermaid',
+ scraper_id='sr.campaign.hrc'),
+ ])
+
+ insert_row(self.output_db, 'scraper_company_map', dict(
+ company='Newell Rubbermaid',
+ scraper_company='Newell Rubbermaid',
+ scraper_id='sr.campaign.hrc')
+ )
+
+ build_scraper_brand_map_table(self.output_db, self.scratch_db)
+
+ self.assertEqual(
+ select_all(self.output_db, 'scraper_brand_map'),
+ [dict(brand='CardScan',
+ company='Newell Rubbermaid',
+ scraper_brand='CardScan',
+ scraper_company='Newell Rubbermaid',
+ scraper_id='sr.campaign.hrc'),
+ dict(brand='CardScan',
+ company='Newell Rubbermaid',
+ scraper_brand='Cardscan',
+ scraper_company='Newell Rubbermaid',
+ scraper_id='sr.campaign.hrc'),
+ ])
diff --git a/test/unit/suite.py b/test/unit/suite.py
index fe78ab0..3448e2c 100644
--- a/test/unit/suite.py
+++ b/test/unit/suite.py
@@ -1,4 +1,4 @@
-# Copyright 2014 SpendRight, Inc.
+# Copyright 2014-2015 SpendRight, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_short_problem_statement",
"has_added_files",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 2,
"issue_text_score": 2,
"test_score": 2
},
"num_modified_files": 4
} | unknown | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest"
],
"pre_install": null,
"python": "3.9",
"reqs_path": [
"requirements.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | exceptiongroup==1.2.2
iniconfig==2.1.0
-e git+https://github.com/spendright/msd.git@02d85249b9e1f5b2824b9a268220a30301084e42#egg=msd
packaging==24.2
pluggy==1.5.0
pytest==8.3.5
titlecase==2.4.1
tomli==2.2.1
Unidecode==1.3.8
| name: msd
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=3.0.16=h5eee18b_0
- pip=25.0=py39h06a4308_0
- python=3.9.21=he870216_1
- readline=8.2=h5eee18b_0
- setuptools=75.8.0=py39h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- tzdata=2025a=h04d1e81_0
- wheel=0.45.1=py39h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- exceptiongroup==1.2.2
- iniconfig==2.1.0
- packaging==24.2
- pluggy==1.5.0
- pytest==8.3.5
- titlecase==2.4.1
- tomli==2.2.1
- unidecode==1.3.8
prefix: /opt/conda/envs/msd
| [
"test/unit/msd/test_brand.py::TestSplitBrandAndTM::test_brand_with_symbol",
"test/unit/msd/test_brand.py::TestSplitBrandAndTM::test_discard_part_after_symbol",
"test/unit/msd/test_brand.py::TestSplitBrandAndTM::test_empty",
"test/unit/msd/test_brand.py::TestSplitBrandAndTM::test_on_tm",
"test/unit/msd/test_brand.py::TestSplitBrandAndTM::test_plain_brand",
"test/unit/msd/test_brand.py::TestSplitBrandAndTM::test_strip",
"test/unit/msd/test_brand.py::TestBuildScraperBrandMapTable::test_merge_differing_capitalization"
] | [] | [] | [] | Apache License 2.0 | 232 |
|
johnpaulett__python-hl7-15 | 253b2071aa376e7f37854b30e38fc6a0ab5c203d | 2015-09-07 17:01:12 | 253b2071aa376e7f37854b30e38fc6a0ab5c203d | diff --git a/hl7/containers.py b/hl7/containers.py
index 231e3b1..a57f570 100644
--- a/hl7/containers.py
+++ b/hl7/containers.py
@@ -319,7 +319,7 @@ class Message(Container):
elif c in DEFAULT_MAP:
rv.append(esc + DEFAULT_MAP[c] + esc)
elif ord(c) >= 0x20 and ord(c) <= 0x7E:
- rv.append(c.encode('ascii'))
+ rv.append(c)
else:
rv.append('%sX%2x%s' % (esc, ord(c), esc))
| Buggy ASCII escaping
If you escape a string containing any ASCII characters, this will lead to a `TypeError`:
``` python
import hl7
msg = hl7.Message(separator='\r', separators='\r|^~\&')
msg.escape('asdf')
```
``` plain
Traceback (most recent call last):
File "hl7/__init__.py", line 630, in escape
return ''.join(rv)
TypeError: sequence item 0: expected str instance, bytes found
```
| johnpaulett/python-hl7 | diff --git a/tests/test_parse.py b/tests/test_parse.py
index e7ad1d4..dfed995 100644
--- a/tests/test_parse.py
+++ b/tests/test_parse.py
@@ -172,13 +172,19 @@ class ParseTest(unittest.TestCase):
def test_escape(self):
msg = hl7.parse(rep_sample_hl7)
+ # Escape Separators
self.assertEqual(msg.escape('\\'), '\\E\\')
self.assertEqual(msg.escape('|'), '\\F\\')
self.assertEqual(msg.escape('^'), '\\S\\')
self.assertEqual(msg.escape('&'), '\\T\\')
self.assertEqual(msg.escape('~'), '\\R\\')
+ # Escape ASCII characters
+ self.assertEqual(msg.escape('asdf'), 'asdf')
+
+ # Escape non-ASCII characters
self.assertEqual(msg.escape('áéíóú'), '\\Xe1\\\\Xe9\\\\Xed\\\\Xf3\\\\Xfa\\')
+ self.assertEqual(msg.escape('äsdf'), '\\Xe4\\sdf')
def test_file(self):
# Extract message from file
| {
"commit_name": "head_commit",
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true,
"llm_score": {
"difficulty_score": 0,
"issue_text_score": 1,
"test_score": 0
},
"num_modified_files": 1
} | 0.3 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[dev]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest"
],
"pre_install": null,
"python": "3.9",
"reqs_path": [
"requirements.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | distlib==0.3.9
docutils==0.21.2
exceptiongroup==1.2.2
filelock==3.18.0
flake8==2.1.0
-e git+https://github.com/johnpaulett/python-hl7.git@253b2071aa376e7f37854b30e38fc6a0ab5c203d#egg=hl7
iniconfig==2.1.0
Jinja2==3.1.6
MarkupSafe==3.0.2
mccabe==0.7.0
packaging==24.2
pep8==1.7.1
platformdirs==4.3.7
pluggy==1.5.0
py==1.11.0
pyflakes==3.3.2
Pygments==2.19.1
pytest==8.3.5
six==1.17.0
Sphinx==1.2.1
tomli==2.2.1
tox==1.7.0
virtualenv==20.30.0
| name: python-hl7
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=3.0.16=h5eee18b_0
- pip=25.0=py39h06a4308_0
- python=3.9.21=he870216_1
- readline=8.2=h5eee18b_0
- setuptools=75.8.0=py39h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- tzdata=2025a=h04d1e81_0
- wheel=0.45.1=py39h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- distlib==0.3.9
- docutils==0.21.2
- exceptiongroup==1.2.2
- filelock==3.18.0
- flake8==2.1.0
- iniconfig==2.1.0
- jinja2==3.1.6
- markupsafe==3.0.2
- mccabe==0.7.0
- packaging==24.2
- pep8==1.7.1
- platformdirs==4.3.7
- pluggy==1.5.0
- py==1.11.0
- pyflakes==3.3.2
- pygments==2.19.1
- pytest==8.3.5
- six==1.17.0
- sphinx==1.2.1
- tomli==2.2.1
- tox==1.7.0
- virtualenv==20.30.0
prefix: /opt/conda/envs/python-hl7
| [
"tests/test_parse.py::ParseTest::test_escape"
] | [] | [
"tests/test_parse.py::ParseTest::test_assign",
"tests/test_parse.py::ParseTest::test_bytestring_converted_to_unicode",
"tests/test_parse.py::ParseTest::test_elementnumbering",
"tests/test_parse.py::ParseTest::test_empty_initial_repetition",
"tests/test_parse.py::ParseTest::test_extract",
"tests/test_parse.py::ParseTest::test_file",
"tests/test_parse.py::ParseTest::test_non_ascii_bytestring",
"tests/test_parse.py::ParseTest::test_non_ascii_bytestring_no_encoding",
"tests/test_parse.py::ParseTest::test_nonstandard_separators",
"tests/test_parse.py::ParseTest::test_parse",
"tests/test_parse.py::ParseTest::test_parsing_classes",
"tests/test_parse.py::ParseTest::test_repetition",
"tests/test_parse.py::ParseTest::test_subcomponent",
"tests/test_parse.py::ParseTest::test_unescape",
"tests/test_parse.py::ParsePlanTest::test_create_parse_plan",
"tests/test_parse.py::ParsePlanTest::test_parse_plan",
"tests/test_parse.py::ParsePlanTest::test_parse_plan_next"
] | [] | BSD License | 233 |
|
enthought__okonomiyaki-119 | 9830662935a3432c0619f60bf72dd1f312f0f2a8 | 2015-09-09 14:07:38 | 9830662935a3432c0619f60bf72dd1f312f0f2a8 | diff --git a/CHANGELOG b/CHANGELOG
index da8cdd4..74c7922 100644
--- a/CHANGELOG
+++ b/CHANGELOG
@@ -6,6 +6,8 @@ Improvements:
* SemanticVersion class added
* MetadataVersion class added to easily manipulate metadata versions.
* runtime_metadata_factory function to parse and validate runtime packages.
+ * __str__ is now implemented for EPDPlatform. The implementation support
+ EPDPlatform.from_epd_string(str(epd_platform)) == epd_platform (#117)
2015-00-01 0.10.0:
--------------------
diff --git a/okonomiyaki/platforms/epd_platform.py b/okonomiyaki/platforms/epd_platform.py
index 433605a..33ab4bd 100644
--- a/okonomiyaki/platforms/epd_platform.py
+++ b/okonomiyaki/platforms/epd_platform.py
@@ -252,6 +252,9 @@ class EPDPlatform(HasTraits):
def short(self):
return "{0}-{1}".format(self.platform_name, self.arch_bits)
+ def __str__(self):
+ return "{0.platform_name}_{0.arch}".format(self)
+
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
| Implement str(epd_platform)
Should look as follows:
```python
>>> platform = EPDPlatform.from_epd_string("rh5-64")
>>> str(platform)
rh5_x86_64
``` | enthought/okonomiyaki | diff --git a/okonomiyaki/platforms/tests/test_epd_platform.py b/okonomiyaki/platforms/tests/test_epd_platform.py
index 9dfa96e..e159950 100644
--- a/okonomiyaki/platforms/tests/test_epd_platform.py
+++ b/okonomiyaki/platforms/tests/test_epd_platform.py
@@ -161,6 +161,28 @@ class TestEPDPlatform(unittest.TestCase):
epd_platform = EPDPlatform.from_running_system("amd64")
self.assertEqual(epd_platform.short, "rh5-64")
+ def test_str(self):
+ # Given
+ epd_platform = EPDPlatform.from_epd_string("rh5-64")
+
+ # When/Then
+ self.assertEqual(str(epd_platform), "rh5_x86_64")
+
+ # Given
+ epd_platform = EPDPlatform.from_epd_string("osx-32")
+
+ # When/Then
+ self.assertEqual(str(epd_platform), "osx_x86")
+
+ # Given
+ s = "osx_x86"
+
+ # When
+ epd_platform = EPDPlatform.from_epd_string(s)
+
+ # Then
+ self.assertEqual(str(epd_platform), s)
+
class TestEPDPlatformApplies(unittest.TestCase):
@mock_centos_5_8
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 0,
"issue_text_score": 2,
"test_score": 0
},
"num_modified_files": 2
} | 0.10 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[dev]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest",
"pytest-cov"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.9",
"reqs_path": [
"dev_requirements.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | attrs==25.3.0
coverage==7.8.0
docutils==0.21.2
enum34==1.1.10
exceptiongroup==1.2.2
flake8==7.2.0
haas==0.9.0
iniconfig==2.1.0
jsonschema==4.23.0
jsonschema-specifications==2024.10.1
mccabe==0.7.0
mock==1.0.1
-e git+https://github.com/enthought/okonomiyaki.git@9830662935a3432c0619f60bf72dd1f312f0f2a8#egg=okonomiyaki
packaging==24.2
pbr==6.1.1
pluggy==1.5.0
pycodestyle==2.13.0
pyflakes==3.3.2
pytest==8.3.5
pytest-cov==6.0.0
referencing==0.36.2
rpds-py==0.24.0
six==1.17.0
statistics==1.0.3.5
stevedore==4.1.1
tomli==2.2.1
typing_extensions==4.13.0
zipfile2==0.0.12
| name: okonomiyaki
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=3.0.16=h5eee18b_0
- pip=25.0=py39h06a4308_0
- python=3.9.21=he870216_1
- readline=8.2=h5eee18b_0
- setuptools=75.8.0=py39h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- tzdata=2025a=h04d1e81_0
- wheel=0.45.1=py39h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- attrs==25.3.0
- coverage==7.8.0
- docutils==0.21.2
- enum34==1.1.10
- exceptiongroup==1.2.2
- flake8==7.2.0
- haas==0.9.0
- iniconfig==2.1.0
- jsonschema==4.23.0
- jsonschema-specifications==2024.10.1
- mccabe==0.7.0
- mock==1.0.1
- packaging==24.2
- pbr==6.1.1
- pluggy==1.5.0
- pycodestyle==2.13.0
- pyflakes==3.3.2
- pytest==8.3.5
- pytest-cov==6.0.0
- referencing==0.36.2
- rpds-py==0.24.0
- six==1.17.0
- statistics==1.0.3.5
- stevedore==4.1.1
- tomli==2.2.1
- typing-extensions==4.13.0
- zipfile2==0.0.12
prefix: /opt/conda/envs/okonomiyaki
| [
"okonomiyaki/platforms/tests/test_epd_platform.py::TestEPDPlatform::test_str"
] | [
"okonomiyaki/platforms/tests/test_epd_platform.py::TestEPDPlatform::test_guessed_epd_platform",
"okonomiyaki/platforms/tests/test_epd_platform.py::TestEPDPlatformApplies::test_all",
"okonomiyaki/platforms/tests/test_epd_platform.py::TestEPDPlatformApplies::test_applies_rh",
"okonomiyaki/platforms/tests/test_epd_platform.py::TestEPDPlatformApplies::test_current_linux",
"okonomiyaki/platforms/tests/test_epd_platform.py::TestGuessEPDPlatform::test_guess_linux2_platform",
"okonomiyaki/platforms/tests/test_epd_platform.py::TestGuessEPDPlatform::test_guess_linux2_unsupported"
] | [
"okonomiyaki/platforms/tests/test_epd_platform.py::TestEPDPlatform::test_epd_platform_from_string",
"okonomiyaki/platforms/tests/test_epd_platform.py::TestEPDPlatform::test_epd_platform_from_string_new_arch",
"okonomiyaki/platforms/tests/test_epd_platform.py::TestEPDPlatform::test_epd_platform_from_string_new_names",
"okonomiyaki/platforms/tests/test_epd_platform.py::TestEPDPlatform::test_epd_platform_from_string_new_names_underscore",
"okonomiyaki/platforms/tests/test_epd_platform.py::TestEPDPlatform::test_from_running_python",
"okonomiyaki/platforms/tests/test_epd_platform.py::TestEPDPlatform::test_from_running_system",
"okonomiyaki/platforms/tests/test_epd_platform.py::TestEPDPlatform::test_short_names_consistency",
"okonomiyaki/platforms/tests/test_epd_platform.py::TestEPDPlatformApplies::test_current_windows",
"okonomiyaki/platforms/tests/test_epd_platform.py::TestGuessEPDPlatform::test_from_epd_platform_string",
"okonomiyaki/platforms/tests/test_epd_platform.py::TestGuessEPDPlatform::test_from_epd_platform_string_invalid",
"okonomiyaki/platforms/tests/test_epd_platform.py::TestGuessEPDPlatform::test_from_spec_depend_data",
"okonomiyaki/platforms/tests/test_epd_platform.py::TestGuessEPDPlatform::test_guess_darwin_platform",
"okonomiyaki/platforms/tests/test_epd_platform.py::TestGuessEPDPlatform::test_guess_solaris_unsupported",
"okonomiyaki/platforms/tests/test_epd_platform.py::TestGuessEPDPlatform::test_guess_win32_platform"
] | [] | BSD License | 234 |
|
mapbox__mapbox-sdk-py-26 | f56c2ffa9477819ce29fb42e87534244f14e43fe | 2015-09-09 14:44:31 | f56c2ffa9477819ce29fb42e87534244f14e43fe | diff --git a/mapbox/__init__.py b/mapbox/__init__.py
index c1889b3..362ae7c 100644
--- a/mapbox/__init__.py
+++ b/mapbox/__init__.py
@@ -9,11 +9,18 @@ from uritemplate import URITemplate
__version__ = "0.1.0"
+class InvalidPlaceTypeError(KeyError):
+ pass
+
+
class Service:
"""Base service class"""
def get_session(self, token=None, env=None):
- access_token = token or (env or os.environ).get('MapboxAccessToken')
+ access_token = (
+ token or
+ (env or os.environ).get('MapboxAccessToken') or
+ (env or os.environ).get('MAPBOX_ACCESS_TOKEN'))
session = requests.Session()
session.params.update(access_token=access_token)
return session
@@ -27,18 +34,47 @@ class Geocoder(Service):
self.baseuri = 'https://api.mapbox.com/v4/geocode'
self.session = self.get_session(access_token)
- def forward(self, address, params=None):
+ def _validate_place_types(self, types):
+ """Validate place types and return a mapping for use in requests"""
+ for pt in types:
+ if pt not in self.place_types:
+ raise InvalidPlaceTypeError(pt)
+ return {'types': ",".join(types)}
+
+ def forward(self, address, types=None, lng=None, lat=None):
"""A forward geocoding request
- See: https://www.mapbox.com/developers/api/geocoding/#forward"""
+ Results may be constrained to those in a sequence of place_types or
+ biased toward a given longitude and latitude.
+
+ See: https://www.mapbox.com/developers/api/geocoding/#forward."""
uri = URITemplate('%s/{dataset}/{query}.json' % self.baseuri).expand(
dataset=self.name, query=address)
+ params = {}
+ if types:
+ params.update(self._validate_place_types(types))
+ if lng is not None and lat is not None:
+ params.update(proximity='{0},{1}'.format(lng, lat))
return self.session.get(uri, params=params)
- def reverse(self, lon, lat, params=None):
+ def reverse(self, lon, lat, types=None):
"""A reverse geocoding request
- See: https://www.mapbox.com/developers/api/geocoding/#reverse"""
+ See: https://www.mapbox.com/developers/api/geocoding/#reverse."""
uri = URITemplate(self.baseuri + '/{dataset}/{lon},{lat}.json').expand(
dataset=self.name, lon=str(lon), lat=str(lat))
+ params = {}
+ if types:
+ params.update(self._validate_place_types(types))
return self.session.get(uri, params=params)
+
+ @property
+ def place_types(self):
+ """A mapping of place type names to descriptions"""
+ return {
+ 'address': "A street address with house number. Examples: 1600 Pennsylvania Ave NW, 1051 Market St, Oberbaumstrasse 7.",
+ 'country': "Sovereign states and other political entities. Examples: United States, France, China, Russia.",
+ 'place': "City, town, village or other municipality relevant to a country's address or postal system. Examples: Cleveland, Saratoga Springs, Berlin, Paris.",
+ 'poi': "Places of interest including commercial venues, major landmarks, parks, and other features. Examples: Yosemite National Park, Lake Superior.",
+ 'postcode': "Postal code, varies by a country's postal system. Examples: 20009, CR0 3RL.",
+ 'region': "First order administrative divisions within a country, usually provinces or states. Examples: California, Ontario, Essonne."}
diff --git a/mapbox/scripts/cli.py b/mapbox/scripts/cli.py
index f1bf3a3..b18509a 100644
--- a/mapbox/scripts/cli.py
+++ b/mapbox/scripts/cli.py
@@ -35,10 +35,11 @@ def main_group(ctx, verbose, quiet, access_token):
$ mbx --access-token MY_TOKEN ...
- or as an environment variable.
+ or as an environment variable named MAPBOX_ACCESS_TOKEN or
+ MapboxAccessToken.
\b
- $ export MapboxAccessToken=MY_TOKEN
+ $ export MAPBOX_ACCESS_TOKEN=MY_TOKEN
$ mbx ...
"""
diff --git a/mapbox/scripts/geocoder.py b/mapbox/scripts/geocoder.py
index f8f0b3a..e97f11e 100644
--- a/mapbox/scripts/geocoder.py
+++ b/mapbox/scripts/geocoder.py
@@ -8,7 +8,7 @@ import mapbox
from mapbox.compat import map
-class MapboxException(click.ClickException):
+class MapboxCLIException(click.ClickException):
pass
@@ -41,18 +41,30 @@ def echo_headers(headers, file=None):
@click.command(short_help="Geocode an address or coordinates.")
@click.argument('query', default='-', required=False)
[email protected]('--include', '-i', 'include_headers',
- is_flag=True, default=False,
- help="Include HTTP headers in the output.")
@click.option(
'--forward/--reverse',
default=True,
help="Perform a forward or reverse geocode. [default: forward]")
[email protected]('--include', '-i', 'include_headers',
+ is_flag=True, default=False,
+ help="Include HTTP headers in the output.")
[email protected](
+ '--lat', type=float, default=None,
+ help="Bias results toward this latitude (decimal degrees). --lng "
+ "is also required.")
[email protected](
+ '--lng', type=float, default=None,
+ help="Bias results toward this longitude (decimal degrees). --lat "
+ "is also required.")
[email protected](
+ '--place-type', '-t', multiple=True, metavar='NAME', default=None,
+ help="Restrict results to one or more of these place types: {0}.".format(
+ sorted(mapbox.Geocoder().place_types.keys())))
@click.option('--output', '-o', default='-', help="Save output to a file.")
@click.pass_context
-def geocode(ctx, query, include_headers, forward, output):
- """This command gets coordinates for an address (forward mode) or
- addresses for coordinates (reverse mode).
+def geocode(ctx, query, include_headers, forward, lat, lng, place_type, output):
+ """This command returns places matching an address (forward mode) or
+ places matching coordinates (reverse mode).
In forward (the default) mode the query argument shall be an address
such as '1600 pennsylvania ave nw'.
@@ -64,6 +76,7 @@ def geocode(ctx, query, include_headers, forward, output):
$ mbx geocode --reverse '[-77.4371, 37.5227]'
+ An access token is required, see `mbx --help`.
"""
verbosity = (ctx.obj and ctx.obj.get('verbosity')) or 2
logger = logging.getLogger('mapbox')
@@ -75,19 +88,20 @@ def geocode(ctx, query, include_headers, forward, output):
if forward:
for q in iter_query(query):
- resp = geocoder.forward(q)
+ resp = geocoder.forward(
+ q, types=place_type, lat=lat, lng=lng)
if include_headers:
echo_headers(resp.headers, file=stdout)
if resp.status_code == 200:
click.echo(resp.text, file=stdout)
else:
- raise MapboxException(resp.text.strip())
+ raise MapboxCLIException(resp.text.strip())
else:
for coords in map(coords_from_query, iter_query(query)):
- resp = geocoder.reverse(*coords)
+ resp = geocoder.reverse(*coords, types=place_type)
if include_headers:
echo_headers(resp.headers, file=stdout)
if resp.status_code == 200:
click.echo(resp.text, file=stdout)
else:
- raise MapboxException(resp.text.strip())
+ raise MapboxCLIException(resp.text.strip())
| Add proximity feature to forward geocoding
https://www.mapbox.com/developers/api/geocoding/#proximity | mapbox/mapbox-sdk-py | diff --git a/tests/test_geocoder.py b/tests/test_geocoder.py
index 84dd846..86ae506 100644
--- a/tests/test_geocoder.py
+++ b/tests/test_geocoder.py
@@ -1,5 +1,6 @@
import json
import responses
+
import mapbox
@@ -24,6 +25,14 @@ def test_service_session_os_environ(monkeypatch):
monkeypatch.undo()
+def test_service_session_os_environ_caps(monkeypatch):
+ """Get a session using os.environ's token"""
+ monkeypatch.setenv('MAPBOX_ACCESS_TOKEN', 'pk.test_os_environ')
+ session = mapbox.Service().get_session()
+ assert session.params.get('access_token') == 'pk.test_os_environ'
+ monkeypatch.undo()
+
+
def test_geocoder_default_name():
"""Default name is set"""
geocoder = mapbox.Geocoder()
@@ -69,3 +78,85 @@ def test_geocoder_reverse():
response = mapbox.Geocoder(access_token='pk.test').reverse(*[str(x) for x in coords])
assert response.status_code == 200
assert response.json()['query'] == coords
+
+
+def test_geocoder_place_types():
+ """Place types are enumerated"""
+ assert sorted(mapbox.Geocoder().place_types.items()) == [
+ ('address', "A street address with house number. Examples: 1600 Pennsylvania Ave NW, 1051 Market St, Oberbaumstrasse 7."),
+ ('country', "Sovereign states and other political entities. Examples: United States, France, China, Russia."),
+ ('place', "City, town, village or other municipality relevant to a country's address or postal system. Examples: Cleveland, Saratoga Springs, Berlin, Paris."),
+ ('poi', "Places of interest including commercial venues, major landmarks, parks, and other features. Examples: Yosemite National Park, Lake Superior."),
+ ('postcode', "Postal code, varies by a country's postal system. Examples: 20009, CR0 3RL."),
+ ('region', "First order administrative divisions within a country, usually provinces or states. Examples: California, Ontario, Essonne.")]
+
+
+def test_validate_place_types_err():
+ try:
+ mapbox.Geocoder()._validate_place_types(('address', 'bogus'))
+ except mapbox.InvalidPlaceTypeError as err:
+ assert str(err) == "'bogus'"
+
+
+def test_validate_place_types():
+ assert mapbox.Geocoder()._validate_place_types(
+ ('address', 'poi')) == {'types': 'address,poi'}
+
+
[email protected]
+def test_geocoder_forward_types():
+ """Type filtering of forward geocoding works"""
+
+ responses.add(
+ responses.GET,
+ 'https://api.mapbox.com/v4/geocode/mapbox.places/1600%20pennsylvania%20ave%20nw.json?types=address,country,place,poi,postcode,region&access_token=pk.test',
+ match_querystring=True,
+ body='{"query": ["1600", "pennsylvania", "ave", "nw"]}', status=200,
+ content_type='application/json')
+
+ response = mapbox.Geocoder(
+ access_token='pk.test').forward(
+ '1600 pennsylvania ave nw',
+ types=('address', 'country', 'place', 'poi', 'postcode', 'region'))
+ assert response.status_code == 200
+ assert response.json()['query'] == ["1600", "pennsylvania", "ave", "nw"]
+
+
[email protected]
+def test_geocoder_reverse_types():
+ """Type filtering of reverse geocoding works"""
+
+ coords = [-77.4371, 37.5227]
+
+ responses.add(
+ responses.GET,
+ 'https://api.mapbox.com/v4/geocode/mapbox.places/%s.json?types=address,country,place,poi,postcode,region&access_token=pk.test' % ','.join([str(x) for x in coords]),
+ match_querystring=True,
+ body='{"query": %s}' % json.dumps(coords),
+ status=200,
+ content_type='application/json')
+
+ response = mapbox.Geocoder(
+ access_token='pk.test').reverse(
+ *[str(x) for x in coords],
+ types=('address', 'country', 'place', 'poi', 'postcode', 'region'))
+ assert response.status_code == 200
+ assert response.json()['query'] == coords
+
+
[email protected]
+def test_geocoder_forward_proximity():
+ """Proximity parameter works"""
+
+ responses.add(
+ responses.GET,
+ 'https://api.mapbox.com/v4/geocode/mapbox.places/1600%20pennsylvania%20ave%20nw.json?proximity=0,0&access_token=pk.test',
+ match_querystring=True,
+ body='{"query": ["1600", "pennsylvania", "ave", "nw"]}', status=200,
+ content_type='application/json')
+
+ response = mapbox.Geocoder(
+ access_token='pk.test').forward(
+ '1600 pennsylvania ave nw', lng=0, lat=0)
+ assert response.status_code == 200
+ assert response.json()['query'] == ["1600", "pennsylvania", "ave", "nw"]
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_short_problem_statement",
"has_hyperlinks",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 2,
"issue_text_score": 2,
"test_score": 2
},
"num_modified_files": 3
} | unknown | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[test]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": null,
"pre_install": null,
"python": "3.9",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | certifi==2025.1.31
charset-normalizer==3.4.1
click==8.1.8
click-plugins==1.1.1
cligj==0.7.2
coverage==7.8.0
coveralls==4.0.1
docopt==0.6.2
exceptiongroup==1.2.2
idna==3.10
iniconfig==2.1.0
-e git+https://github.com/mapbox/mapbox-sdk-py.git@f56c2ffa9477819ce29fb42e87534244f14e43fe#egg=mapbox
packaging==24.2
pluggy==1.5.0
pytest==8.3.5
pytest-cov==6.0.0
PyYAML==6.0.2
requests==2.32.3
responses==0.25.7
tomli==2.2.1
uritemplate==4.1.1
uritemplate.py==3.0.2
urllib3==2.3.0
| name: mapbox-sdk-py
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=3.0.16=h5eee18b_0
- pip=25.0=py39h06a4308_0
- python=3.9.21=he870216_1
- readline=8.2=h5eee18b_0
- setuptools=75.8.0=py39h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- tzdata=2025a=h04d1e81_0
- wheel=0.45.1=py39h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- certifi==2025.1.31
- charset-normalizer==3.4.1
- click==8.1.8
- click-plugins==1.1.1
- cligj==0.7.2
- coverage==7.8.0
- coveralls==4.0.1
- docopt==0.6.2
- exceptiongroup==1.2.2
- idna==3.10
- iniconfig==2.1.0
- packaging==24.2
- pluggy==1.5.0
- pytest==8.3.5
- pytest-cov==6.0.0
- pyyaml==6.0.2
- requests==2.32.3
- responses==0.25.7
- tomli==2.2.1
- uritemplate==4.1.1
- uritemplate-py==3.0.2
- urllib3==2.3.0
prefix: /opt/conda/envs/mapbox-sdk-py
| [
"tests/test_geocoder.py::test_service_session_os_environ_caps",
"tests/test_geocoder.py::test_geocoder_place_types",
"tests/test_geocoder.py::test_validate_place_types_err",
"tests/test_geocoder.py::test_validate_place_types",
"tests/test_geocoder.py::test_geocoder_forward_types",
"tests/test_geocoder.py::test_geocoder_reverse_types",
"tests/test_geocoder.py::test_geocoder_forward_proximity"
] | [] | [
"tests/test_geocoder.py::test_service_session",
"tests/test_geocoder.py::test_service_session_env",
"tests/test_geocoder.py::test_service_session_os_environ",
"tests/test_geocoder.py::test_geocoder_default_name",
"tests/test_geocoder.py::test_geocoder_name",
"tests/test_geocoder.py::test_geocoder_forward",
"tests/test_geocoder.py::test_geocoder_reverse"
] | [] | MIT License | 235 |
|
bottlepy__bottle-787 | 534a2e08ac0ef55dd542a3a83b1118188c6a399b | 2015-09-11 12:49:06 | 90d749bef49120396ecc347ea67df98881157030 | diff --git a/bottle.py b/bottle.py
index e4b17d8..5287147 100644
--- a/bottle.py
+++ b/bottle.py
@@ -2176,6 +2176,22 @@ class ConfigDict(dict):
self._meta = {}
self._on_change = lambda name, value: None
+ def load_module(self, path, squash):
+ """ Load values from a Python module.
+ :param squash: Squash nested dicts into namespaces by using
+ load_dict(), otherwise use update()
+ Example: load_config('my.app.settings', True)
+ Example: load_config('my.app.settings', False)
+ """
+ config_obj = __import__(path)
+ obj = dict([(key, getattr(config_obj, key))
+ for key in dir(config_obj) if key.isupper()])
+ if squash:
+ self.load_dict(obj)
+ else:
+ self.update(obj)
+ return self
+
def load_config(self, filename):
""" Load values from an ``*.ini`` style config file.
| Ability to load config from module
Currently it is not possible to load config from a Python module (similar to the way Django does it).
I'd like to propose the following;
```py
class ConfigDict(dict):
def load_module(self, module_path):
"""
Load configuration from module path
>>> load_module('settings.prod')
"""
assert isinstance(module_path, str)
config = importlib.import_module(module_path)
obj = {key: getattr(config, key) for key in dir(config) if key.isupper()}
self.update(obj)
```
Happy to put together a tested PR if this proposal is accepted | bottlepy/bottle | diff --git a/test/example_settings.py b/test/example_settings.py
new file mode 100644
index 0000000..58dd992
--- /dev/null
+++ b/test/example_settings.py
@@ -0,0 +1,5 @@
+A = {
+ "B": {
+ "C": 3
+ }
+}
\ No newline at end of file
diff --git a/test/test_config.py b/test/test_config.py
index a4cfd9f..a9ea4ab 100644
--- a/test/test_config.py
+++ b/test/test_config.py
@@ -1,3 +1,4 @@
+import sys
import unittest
from bottle import ConfigDict
@@ -69,6 +70,17 @@ class TestConfDict(unittest.TestCase):
c = ConfigDict()
c.load_dict({key: {'subkey': 'value'}})
self.assertEqual('value', c[key + '.subkey'])
+
+ def test_load_module(self):
+ c = ConfigDict()
+ c.load_module('example_settings', True)
+ self.assertEqual(c['A.B.C'], 3)
+
+ c = ConfigDict()
+ c.load_module('example_settings', False)
+ self.assertEqual(c['A']['B']['C'], 3)
+
+
if __name__ == '__main__': #pragma: no cover
unittest.main()
| {
"commit_name": "head_commit",
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true,
"llm_score": {
"difficulty_score": 0,
"issue_text_score": 1,
"test_score": 1
},
"num_modified_files": 1
} | 0.12 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[dev]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "pytest",
"pip_packages": [
"Mako",
"jinja2",
"eventlet",
"cherrypy",
"paste",
"twisted",
"tornado",
"pytest"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.9",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | attrs==25.3.0
autocommand==2.2.2
Automat==24.8.1
backports.tarfile==1.2.0
-e git+https://github.com/bottlepy/bottle.git@534a2e08ac0ef55dd542a3a83b1118188c6a399b#egg=bottle
cheroot==10.0.1
CherryPy==18.10.0
constantly==23.10.4
dnspython==2.7.0
eventlet==0.39.1
exceptiongroup @ file:///croot/exceptiongroup_1706031385326/work
greenlet==3.1.1
hyperlink==21.0.0
idna==3.10
incremental==24.7.2
iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work
jaraco.collections==5.1.0
jaraco.context==6.0.1
jaraco.functools==4.1.0
jaraco.text==4.0.0
Jinja2==3.1.6
Mako==1.3.9
MarkupSafe==3.0.2
more-itertools==10.6.0
packaging @ file:///croot/packaging_1734472117206/work
Paste==3.10.1
pluggy @ file:///croot/pluggy_1733169602837/work
portend==3.2.0
pytest @ file:///croot/pytest_1738938843180/work
python-dateutil==2.9.0.post0
six==1.17.0
tempora==5.8.0
tomli @ file:///opt/conda/conda-bld/tomli_1657175507142/work
tornado==6.4.2
Twisted==24.11.0
typing_extensions==4.13.0
zc.lockfile==3.0.post1
zope.interface==7.2
| name: bottle
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- exceptiongroup=1.2.0=py39h06a4308_0
- iniconfig=1.1.1=pyhd3eb1b0_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=3.0.16=h5eee18b_0
- packaging=24.2=py39h06a4308_0
- pip=25.0=py39h06a4308_0
- pluggy=1.5.0=py39h06a4308_0
- pytest=8.3.4=py39h06a4308_0
- python=3.9.21=he870216_1
- readline=8.2=h5eee18b_0
- setuptools=75.8.0=py39h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- tomli=2.0.1=py39h06a4308_0
- tzdata=2025a=h04d1e81_0
- wheel=0.45.1=py39h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- attrs==25.3.0
- autocommand==2.2.2
- automat==24.8.1
- backports-tarfile==1.2.0
- cheroot==10.0.1
- cherrypy==18.10.0
- constantly==23.10.4
- dnspython==2.7.0
- eventlet==0.39.1
- greenlet==3.1.1
- hyperlink==21.0.0
- idna==3.10
- incremental==24.7.2
- jaraco-collections==5.1.0
- jaraco-context==6.0.1
- jaraco-functools==4.1.0
- jaraco-text==4.0.0
- jinja2==3.1.6
- mako==1.3.9
- markupsafe==3.0.2
- more-itertools==10.6.0
- paste==3.10.1
- portend==3.2.0
- python-dateutil==2.9.0.post0
- six==1.17.0
- tempora==5.8.0
- tornado==6.4.2
- twisted==24.11.0
- typing-extensions==4.13.0
- zc-lockfile==3.0.post1
- zope-interface==7.2
prefix: /opt/conda/envs/bottle
| [
"test/test_config.py::TestConfDict::test_load_module"
] | [] | [
"test/test_config.py::TestConfDict::test_isadict",
"test/test_config.py::TestConfDict::test_load_dict",
"test/test_config.py::TestConfDict::test_meta",
"test/test_config.py::TestConfDict::test_namespaces",
"test/test_config.py::TestConfDict::test_update",
"test/test_config.py::TestConfDict::test_write"
] | [] | MIT License | 236 |
|
sympy__sympy-9909 | 074db2010b7c56cafe2a57a1134a55ef61c2e025 | 2015-09-12 05:11:07 | 0241b35cae5f2adc04dc37b25f7dc9c5f00bd746 | diff --git a/sympy/functions/special/delta_functions.py b/sympy/functions/special/delta_functions.py
index c4777c5827..27dabc40e5 100644
--- a/sympy/functions/special/delta_functions.py
+++ b/sympy/functions/special/delta_functions.py
@@ -180,33 +180,12 @@ class Heaviside(Function):
1) ``diff(Heaviside(x),x) = DiracDelta(x)``
``( 0, if x < 0``
- 2) ``Heaviside(x) = < ( 1/2 if x==0 [*]``
+ 2) ``Heaviside(x) = < ( undefined if x==0 [*]``
``( 1, if x > 0``
.. [*] Regarding to the value at 0, Mathematica defines ``H(0) = 1``,
but Maple uses ``H(0) = undefined``
- I think is better to have H(0) = 1/2, due to the following::
-
- integrate(DiracDelta(x), x) = Heaviside(x)
- integrate(DiracDelta(x), (x, -oo, oo)) = 1
-
- and since DiracDelta is a symmetric function,
- ``integrate(DiracDelta(x), (x, 0, oo))`` should be 1/2 (which is what
- Maple returns).
-
- If we take ``Heaviside(0) = 1/2``, we would have
- ``integrate(DiracDelta(x), (x, 0, oo)) = ``
- ``Heaviside(oo) - Heaviside(0) = 1 - 1/2 = 1/2``
- and
- ``integrate(DiracDelta(x), (x, -oo, 0)) = ``
- ``Heaviside(0) - Heaviside(-oo) = 1/2 - 0 = 1/2``
-
- If we consider, instead ``Heaviside(0) = 1``, we would have
- ``integrate(DiracDelta(x), (x, 0, oo)) = Heaviside(oo) - Heaviside(0) = 0``
- and
- ``integrate(DiracDelta(x), (x, -oo, 0)) = Heaviside(0) - Heaviside(-oo) = 1``
-
See Also
========
@@ -237,8 +216,6 @@ def eval(cls, arg):
raise ValueError("Function defined only for Real Values. Complex part: %s found in %s ." % (repr(im(arg)), repr(arg)) )
elif arg.is_negative:
return S.Zero
- elif arg.is_zero:
- return S.Half
elif arg.is_positive:
return S.One
| Heaviside(0) should be undefined
I am working on an optimal-control problem that involves the derivative of a Max(0,x) function, which gives Heaviside(x) as it's derivative. In the subsequent analysis, any line `y=mx` is tangent to Max(0,x) at x=0, so long as m is in [0,1]. Thus, in the subsequent analysis, it's very useful to treat Heaviside(x) as a generalized function where Heaviside(0) returns the whole interval [0,1].
Currently, Heaviside(0) returns 1/2, and some justification of this case is given. However, reasonable
arguements have been made for Heaviside(0) = 1 or 0 as well, and my example above provides a 4th possibility. The situation reminds me of the argument we had some-time back over how to evaluate 1**oo, which we decided to leave as nan because there was no universally satisfactory convention.
I propose leaving Heaviside(0) as un-defined. This is the conservative choice, and avoids possibly incorrect assumptions. A `.subs(Heaviside(0),k)` can then be used if a specific value is desired. | sympy/sympy | diff --git a/sympy/functions/special/tests/test_delta_functions.py b/sympy/functions/special/tests/test_delta_functions.py
index 7a12636e01..dd14bbdf7e 100644
--- a/sympy/functions/special/tests/test_delta_functions.py
+++ b/sympy/functions/special/tests/test_delta_functions.py
@@ -47,7 +47,7 @@ def test_DiracDelta():
def test_heaviside():
- assert Heaviside(0) == 0.5
+ assert Heaviside(0).func == Heaviside
assert Heaviside(-5) == 0
assert Heaviside(1) == 1
assert Heaviside(nan) == nan
diff --git a/sympy/integrals/tests/test_integrals.py b/sympy/integrals/tests/test_integrals.py
index 507ef9adcd..8481f161ea 100644
--- a/sympy/integrals/tests/test_integrals.py
+++ b/sympy/integrals/tests/test_integrals.py
@@ -438,7 +438,6 @@ def test_integrate_DiracDelta():
# This is here to check that deltaintegrate is being called, but also
# to test definite integrals. More tests are in test_deltafunctions.py
assert integrate(DiracDelta(x) * f(x), (x, -oo, oo)) == f(0)
- assert integrate(DiracDelta(x) * f(x), (x, 0, oo)) == f(0)/2
assert integrate(DiracDelta(x)**2, (x, -oo, oo)) == DiracDelta(0)
# issue 4522
assert integrate(integrate((4 - 4*x + x*y - 4*y) * \
| {
"commit_name": "head_commit",
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true,
"llm_score": {
"difficulty_score": 0,
"issue_text_score": 1,
"test_score": 2
},
"num_modified_files": 1
} | 0.7 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "pytest",
"pip_packages": [
"pytest"
],
"pre_install": [
"apt-get update",
"apt-get install -y build-essential"
],
"python": "3.6",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | attrs @ file:///opt/conda/conda-bld/attrs_1642510447205/work
certifi==2021.5.30
importlib-metadata @ file:///tmp/build/80754af9/importlib-metadata_1631916693255/work
iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work
more-itertools @ file:///tmp/build/80754af9/more-itertools_1637733554872/work
mpmath==1.3.0
packaging @ file:///tmp/build/80754af9/packaging_1637314298585/work
pluggy @ file:///tmp/build/80754af9/pluggy_1615976315926/work
py @ file:///opt/conda/conda-bld/py_1644396412707/work
pyparsing @ file:///tmp/build/80754af9/pyparsing_1635766073266/work
pytest==6.2.4
-e git+https://github.com/sympy/sympy.git@074db2010b7c56cafe2a57a1134a55ef61c2e025#egg=sympy
toml @ file:///tmp/build/80754af9/toml_1616166611790/work
typing_extensions @ file:///opt/conda/conda-bld/typing_extensions_1647553014482/work
zipp @ file:///tmp/build/80754af9/zipp_1633618647012/work
| name: sympy
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- attrs=21.4.0=pyhd3eb1b0_0
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2021.5.30=py36h06a4308_0
- importlib-metadata=4.8.1=py36h06a4308_0
- importlib_metadata=4.8.1=hd3eb1b0_0
- iniconfig=1.1.1=pyhd3eb1b0_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.3=he6710b0_2
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- more-itertools=8.12.0=pyhd3eb1b0_0
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- packaging=21.3=pyhd3eb1b0_0
- pip=21.2.2=py36h06a4308_0
- pluggy=0.13.1=py36h06a4308_0
- py=1.11.0=pyhd3eb1b0_0
- pyparsing=3.0.4=pyhd3eb1b0_0
- pytest=6.2.4=py36h06a4308_2
- python=3.6.13=h12debd9_1
- readline=8.2=h5eee18b_0
- setuptools=58.0.4=py36h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- toml=0.10.2=pyhd3eb1b0_0
- typing_extensions=4.1.1=pyh06a4308_0
- wheel=0.37.1=pyhd3eb1b0_0
- xz=5.6.4=h5eee18b_1
- zipp=3.6.0=pyhd3eb1b0_0
- zlib=1.2.13=h5eee18b_1
- pip:
- mpmath==1.3.0
prefix: /opt/conda/envs/sympy
| [
"sympy/functions/special/tests/test_delta_functions.py::test_heaviside"
] | [] | [
"sympy/functions/special/tests/test_delta_functions.py::test_DiracDelta",
"sympy/functions/special/tests/test_delta_functions.py::test_rewrite",
"sympy/integrals/tests/test_integrals.py::test_improper_integral",
"sympy/integrals/tests/test_integrals.py::test_constructor",
"sympy/integrals/tests/test_integrals.py::test_basics",
"sympy/integrals/tests/test_integrals.py::test_basics_multiple",
"sympy/integrals/tests/test_integrals.py::test_conjugate_transpose",
"sympy/integrals/tests/test_integrals.py::test_integration",
"sympy/integrals/tests/test_integrals.py::test_multiple_integration",
"sympy/integrals/tests/test_integrals.py::test_issue_3532",
"sympy/integrals/tests/test_integrals.py::test_issue_3560",
"sympy/integrals/tests/test_integrals.py::test_integrate_poly",
"sympy/integrals/tests/test_integrals.py::test_integrate_poly_defined",
"sympy/integrals/tests/test_integrals.py::test_integrate_omit_var",
"sympy/integrals/tests/test_integrals.py::test_integrate_poly_accurately",
"sympy/integrals/tests/test_integrals.py::test_issue_3635",
"sympy/integrals/tests/test_integrals.py::test_integrate_linearterm_pow",
"sympy/integrals/tests/test_integrals.py::test_issue_3618",
"sympy/integrals/tests/test_integrals.py::test_issue_3623",
"sympy/integrals/tests/test_integrals.py::test_issue_3664",
"sympy/integrals/tests/test_integrals.py::test_issue_3679",
"sympy/integrals/tests/test_integrals.py::test_issue_3686",
"sympy/integrals/tests/test_integrals.py::test_integrate_units",
"sympy/integrals/tests/test_integrals.py::test_transcendental_functions",
"sympy/integrals/tests/test_integrals.py::test_issue_3740",
"sympy/integrals/tests/test_integrals.py::test_issue_3788",
"sympy/integrals/tests/test_integrals.py::test_issue_3952",
"sympy/integrals/tests/test_integrals.py::test_issue_4516",
"sympy/integrals/tests/test_integrals.py::test_issue_7450",
"sympy/integrals/tests/test_integrals.py::test_matrices",
"sympy/integrals/tests/test_integrals.py::test_integrate_functions",
"sympy/integrals/tests/test_integrals.py::test_integrate_derivatives",
"sympy/integrals/tests/test_integrals.py::test_transform",
"sympy/integrals/tests/test_integrals.py::test_issue_4052",
"sympy/integrals/tests/test_integrals.py::test_evalf_integrals",
"sympy/integrals/tests/test_integrals.py::test_evalf_issue_939",
"sympy/integrals/tests/test_integrals.py::test_integrate_DiracDelta",
"sympy/integrals/tests/test_integrals.py::test_integrate_returns_piecewise",
"sympy/integrals/tests/test_integrals.py::test_subs1",
"sympy/integrals/tests/test_integrals.py::test_subs2",
"sympy/integrals/tests/test_integrals.py::test_subs3",
"sympy/integrals/tests/test_integrals.py::test_subs4",
"sympy/integrals/tests/test_integrals.py::test_subs5",
"sympy/integrals/tests/test_integrals.py::test_subs6",
"sympy/integrals/tests/test_integrals.py::test_subs7",
"sympy/integrals/tests/test_integrals.py::test_expand",
"sympy/integrals/tests/test_integrals.py::test_integration_variable",
"sympy/integrals/tests/test_integrals.py::test_expand_integral",
"sympy/integrals/tests/test_integrals.py::test_as_sum_midpoint1",
"sympy/integrals/tests/test_integrals.py::test_as_sum_midpoint2",
"sympy/integrals/tests/test_integrals.py::test_as_sum_left",
"sympy/integrals/tests/test_integrals.py::test_as_sum_right",
"sympy/integrals/tests/test_integrals.py::test_as_sum_raises",
"sympy/integrals/tests/test_integrals.py::test_nested_doit",
"sympy/integrals/tests/test_integrals.py::test_issue_4665",
"sympy/integrals/tests/test_integrals.py::test_integral_reconstruct",
"sympy/integrals/tests/test_integrals.py::test_doit_integrals",
"sympy/integrals/tests/test_integrals.py::test_issue_4884",
"sympy/integrals/tests/test_integrals.py::test_is_number",
"sympy/integrals/tests/test_integrals.py::test_symbols",
"sympy/integrals/tests/test_integrals.py::test_is_zero",
"sympy/integrals/tests/test_integrals.py::test_series",
"sympy/integrals/tests/test_integrals.py::test_issue_4403",
"sympy/integrals/tests/test_integrals.py::test_issue_4403_2",
"sympy/integrals/tests/test_integrals.py::test_issue_4100",
"sympy/integrals/tests/test_integrals.py::test_issue_5167",
"sympy/integrals/tests/test_integrals.py::test_issue_4890",
"sympy/integrals/tests/test_integrals.py::test_issue_4376",
"sympy/integrals/tests/test_integrals.py::test_issue_4517",
"sympy/integrals/tests/test_integrals.py::test_issue_4527",
"sympy/integrals/tests/test_integrals.py::test_issue_4199",
"sympy/integrals/tests/test_integrals.py::test_issue_3940",
"sympy/integrals/tests/test_integrals.py::test_issue_5413",
"sympy/integrals/tests/test_integrals.py::test_issue_4892a",
"sympy/integrals/tests/test_integrals.py::test_issue_4892b",
"sympy/integrals/tests/test_integrals.py::test_issue_5178",
"sympy/integrals/tests/test_integrals.py::test_integrate_series",
"sympy/integrals/tests/test_integrals.py::test_atom_bug",
"sympy/integrals/tests/test_integrals.py::test_limit_bug",
"sympy/integrals/tests/test_integrals.py::test_issue_4703",
"sympy/integrals/tests/test_integrals.py::test_issue_1888",
"sympy/integrals/tests/test_integrals.py::test_issue_3558",
"sympy/integrals/tests/test_integrals.py::test_issue_4422",
"sympy/integrals/tests/test_integrals.py::test_issue_4493",
"sympy/integrals/tests/test_integrals.py::test_issue_4737",
"sympy/integrals/tests/test_integrals.py::test_issue_4992",
"sympy/integrals/tests/test_integrals.py::test_issue_4487",
"sympy/integrals/tests/test_integrals.py::test_issue_4400",
"sympy/integrals/tests/test_integrals.py::test_issue_6253",
"sympy/integrals/tests/test_integrals.py::test_issue_4153",
"sympy/integrals/tests/test_integrals.py::test_issue_4326",
"sympy/integrals/tests/test_integrals.py::test_powers",
"sympy/integrals/tests/test_integrals.py::test_risch_option",
"sympy/integrals/tests/test_integrals.py::test_issue_6828",
"sympy/integrals/tests/test_integrals.py::test_issue_4803",
"sympy/integrals/tests/test_integrals.py::test_issue_4234",
"sympy/integrals/tests/test_integrals.py::test_issue_4492",
"sympy/integrals/tests/test_integrals.py::test_issue_2708",
"sympy/integrals/tests/test_integrals.py::test_issue_8368",
"sympy/integrals/tests/test_integrals.py::test_issue_8901",
"sympy/integrals/tests/test_integrals.py::test_issue_7130",
"sympy/integrals/tests/test_integrals.py::test_issue_4950",
"sympy/integrals/tests/test_integrals.py::test_issue_4968"
] | [] | BSD | 237 |
|
tobgu__pyrsistent-57 | d35ea98728473bd070ff1e6ac5304e4e12ea816c | 2015-09-14 21:17:17 | 87706acb8297805b56bcc2c0f89ffa73eb1de0d1 | diff --git a/pyrsistent/_field_common.py b/pyrsistent/_field_common.py
index 6934978..04231c0 100644
--- a/pyrsistent/_field_common.py
+++ b/pyrsistent/_field_common.py
@@ -2,7 +2,8 @@ from collections import Iterable
import six
from pyrsistent._checked_types import (
CheckedType, CheckedPSet, CheckedPMap, CheckedPVector,
- optional as optional_type, InvariantException, get_type, wrap_invariant)
+ optional as optional_type, InvariantException, get_type, wrap_invariant,
+ _restore_pickle)
def set_fields(dct, bases, name):
@@ -121,12 +122,42 @@ class PTypeError(TypeError):
self.actual_type = actual_type
-def _sequence_field(checked_class, suffix, item_type, optional, initial):
+SEQ_FIELD_TYPE_SUFFIXES = {
+ CheckedPVector: "PVector",
+ CheckedPSet: "PSet",
+}
+
+# Global dictionary to hold auto-generated field types: used for unpickling
+_seq_field_types = {}
+
+def _restore_seq_field_pickle(checked_class, item_type, data):
+ """Unpickling function for auto-generated PVec/PSet field types."""
+ type_ = _seq_field_types[checked_class, item_type]
+ return _restore_pickle(type_, data)
+
+def _make_seq_field_type(checked_class, item_type):
+ """Create a subclass of the given checked class with the given item type."""
+ type_ = _seq_field_types.get((checked_class, item_type))
+ if type_ is not None:
+ return type_
+
+ class TheType(checked_class):
+ __type__ = item_type
+
+ def __reduce__(self):
+ return (_restore_seq_field_pickle,
+ (checked_class, item_type, list(self)))
+
+ suffix = SEQ_FIELD_TYPE_SUFFIXES[checked_class]
+ TheType.__name__ = item_type.__name__.capitalize() + suffix
+ _seq_field_types[checked_class, item_type] = TheType
+ return TheType
+
+def _sequence_field(checked_class, item_type, optional, initial):
"""
Create checked field for either ``PSet`` or ``PVector``.
:param checked_class: ``CheckedPSet`` or ``CheckedPVector``.
- :param suffix: Suffix for new type name.
:param item_type: The required type for the items in the set.
:param optional: If true, ``None`` can be used as a value for
this field.
@@ -134,9 +165,7 @@ def _sequence_field(checked_class, suffix, item_type, optional, initial):
:return: A ``field`` containing a checked class.
"""
- class TheType(checked_class):
- __type__ = item_type
- TheType.__name__ = item_type.__name__.capitalize() + suffix
+ TheType = _make_seq_field_type(checked_class, item_type)
if optional:
def factory(argument):
@@ -164,7 +193,7 @@ def pset_field(item_type, optional=False, initial=()):
:return: A ``field`` containing a ``CheckedPSet`` of the given type.
"""
- return _sequence_field(CheckedPSet, "PSet", item_type, optional,
+ return _sequence_field(CheckedPSet, item_type, optional,
initial)
@@ -180,13 +209,41 @@ def pvector_field(item_type, optional=False, initial=()):
:return: A ``field`` containing a ``CheckedPVector`` of the given type.
"""
- return _sequence_field(CheckedPVector, "PVector", item_type, optional,
+ return _sequence_field(CheckedPVector, item_type, optional,
initial)
_valid = lambda item: (True, "")
+# Global dictionary to hold auto-generated field types: used for unpickling
+_pmap_field_types = {}
+
+def _restore_pmap_field_pickle(key_type, value_type, data):
+ """Unpickling function for auto-generated PMap field types."""
+ type_ = _pmap_field_types[key_type, value_type]
+ return _restore_pickle(type_, data)
+
+def _make_pmap_field_type(key_type, value_type):
+ """Create a subclass of CheckedPMap with the given key and value types."""
+ type_ = _pmap_field_types.get((key_type, value_type))
+ if type_ is not None:
+ return type_
+
+ class TheMap(CheckedPMap):
+ __key_type__ = key_type
+ __value_type__ = value_type
+
+ def __reduce__(self):
+ return (_restore_pmap_field_pickle,
+ (self.__key_type__, self.__value_type__, dict(self)))
+
+ TheMap.__name__ = (key_type.__name__.capitalize() +
+ value_type.__name__.capitalize() + "PMap")
+ _pmap_field_types[key_type, value_type] = TheMap
+ return TheMap
+
+
def pmap_field(key_type, value_type, optional=False, invariant=PFIELD_NO_INVARIANT):
"""
Create a checked ``PMap`` field.
@@ -199,11 +256,7 @@ def pmap_field(key_type, value_type, optional=False, invariant=PFIELD_NO_INVARIA
:return: A ``field`` containing a ``CheckedPMap``.
"""
- class TheMap(CheckedPMap):
- __key_type__ = key_type
- __value_type__ = value_type
- TheMap.__name__ = (key_type.__name__.capitalize() +
- value_type.__name__.capitalize() + "PMap")
+ TheMap = _make_pmap_field_type(key_type, value_type)
if optional:
def factory(argument):
| p*_field prevents pickle from working on a PClass
I would never use pickle in production, but as I was trying to write some strawman example storage code for an example app, I discovered that while I could pickle basic PClasses, I can't pickle any that use pmap_field or pvector_field (and probably others that have similar implementations)
e.g.:
```
>>> class Foo(PClass):
... v = pvector_field(int)
...
>>> Foo()
Foo(v=IntPVector([]))
>>> dumps(Foo())
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
cPickle.PicklingError: Can't pickle <class 'pyrsistent._field_common.IntPVector'>: attribute lookup pyrsistent._field_common.IntPVector failed
```
The same happens for `pmap_field`.
I guess this is because of the way that those functions generate classes at runtime?
@tobgu if you can let me know what needs done to fix this I can try to submit a PR. | tobgu/pyrsistent | diff --git a/tests/class_test.py b/tests/class_test.py
index f7254b4..0caddba 100644
--- a/tests/class_test.py
+++ b/tests/class_test.py
@@ -2,7 +2,9 @@ from collections import Hashable
import math
import pickle
import pytest
-from pyrsistent import field, InvariantException, PClass, optional, CheckedPVector
+from pyrsistent import (
+ field, InvariantException, PClass, optional, CheckedPVector,
+ pmap_field, pset_field, pvector_field)
class Point(PClass):
@@ -11,6 +13,12 @@ class Point(PClass):
z = field(type=int, initial=0)
+class TypedContainerObj(PClass):
+ map = pmap_field(str, str)
+ set = pset_field(str)
+ vec = pvector_field(str)
+
+
def test_evolve_pclass_instance():
p = Point(x=1, y=2)
p2 = p.set(x=p.x+2)
@@ -165,6 +173,12 @@ def test_supports_pickling():
assert isinstance(p2, Point)
+def test_supports_pickling_with_typed_container_fields():
+ obj = TypedContainerObj(map={'foo': 'bar'}, set=['hello', 'there'], vec=['a', 'b'])
+ obj2 = pickle.loads(pickle.dumps(obj))
+ assert obj == obj2
+
+
def test_can_remove_optional_member():
p1 = Point(x=1, y=2)
p2 = p1.remove('y')
@@ -250,4 +264,4 @@ def test_multiple_global_invariants():
MultiInvariantGlobal(one=1)
assert False
except InvariantException as e:
- assert e.invariant_errors == (('x', 'y'),)
\ No newline at end of file
+ assert e.invariant_errors == (('x', 'y'),)
diff --git a/tests/record_test.py b/tests/record_test.py
index 9146bd0..b2439e5 100644
--- a/tests/record_test.py
+++ b/tests/record_test.py
@@ -13,6 +13,12 @@ class ARecord(PRecord):
y = field()
+class RecordContainingContainers(PRecord):
+ map = pmap_field(str, str)
+ vec = pvector_field(str)
+ set = pset_field(str)
+
+
def test_create():
r = ARecord(x=1, y='foo')
assert r.x == 1
@@ -223,6 +229,11 @@ def test_pickling():
assert x == y
assert isinstance(y, ARecord)
+def test_supports_pickling_with_typed_container_fields():
+ obj = RecordContainingContainers(
+ map={'foo': 'bar'}, set=['hello', 'there'], vec=['a', 'b'])
+ obj2 = pickle.loads(pickle.dumps(obj))
+ assert obj == obj2
def test_all_invariant_errors_reported():
class BRecord(PRecord):
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 1,
"issue_text_score": 2,
"test_score": 1
},
"num_modified_files": 1
} | 0.11 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest",
"pytest-cov"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.9",
"reqs_path": [
"requirements.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | alabaster==0.7.16
attrs==25.3.0
babel==2.17.0
cachetools==5.5.2
certifi==2025.1.31
chardet==5.2.0
charset-normalizer==3.4.1
colorama==0.4.6
coverage==7.8.0
distlib==0.3.9
docutils==0.21.2
exceptiongroup==1.2.2
filelock==3.18.0
hypothesis==6.130.5
idna==3.10
imagesize==1.4.1
importlib_metadata==8.6.1
iniconfig==2.1.0
Jinja2==3.1.6
MarkupSafe==3.0.2
memory_profiler==0.31
packaging==24.2
platformdirs==4.3.7
pluggy==1.5.0
psutil==2.1.1
py==1.11.0
Pygments==2.19.1
pyperform==1.86
pyproject-api==1.9.0
-e git+https://github.com/tobgu/pyrsistent.git@d35ea98728473bd070ff1e6ac5304e4e12ea816c#egg=pyrsistent
pytest==8.3.5
pytest-cov==6.0.0
requests==2.32.3
six==1.17.0
snowballstemmer==2.2.0
sortedcontainers==2.4.0
Sphinx==7.4.7
sphinx_rtd_theme==0.1.5
sphinxcontrib-applehelp==2.0.0
sphinxcontrib-devhelp==2.0.0
sphinxcontrib-htmlhelp==2.1.0
sphinxcontrib-jsmath==1.0.1
sphinxcontrib-qthelp==2.0.0
sphinxcontrib-serializinghtml==2.0.0
tomli==2.2.1
tox==4.25.0
typing_extensions==4.13.0
urllib3==2.3.0
virtualenv==20.29.3
zipp==3.21.0
| name: pyrsistent
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=3.0.16=h5eee18b_0
- pip=25.0=py39h06a4308_0
- python=3.9.21=he870216_1
- readline=8.2=h5eee18b_0
- setuptools=75.8.0=py39h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- tzdata=2025a=h04d1e81_0
- wheel=0.45.1=py39h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- alabaster==0.7.16
- attrs==25.3.0
- babel==2.17.0
- cachetools==5.5.2
- certifi==2025.1.31
- chardet==5.2.0
- charset-normalizer==3.4.1
- colorama==0.4.6
- coverage==7.8.0
- distlib==0.3.9
- docutils==0.21.2
- exceptiongroup==1.2.2
- filelock==3.18.0
- hypothesis==6.130.5
- idna==3.10
- imagesize==1.4.1
- importlib-metadata==8.6.1
- iniconfig==2.1.0
- jinja2==3.1.6
- markupsafe==3.0.2
- memory-profiler==0.31
- packaging==24.2
- platformdirs==4.3.7
- pluggy==1.5.0
- psutil==2.1.1
- py==1.11.0
- pygments==2.19.1
- pyperform==1.86
- pyproject-api==1.9.0
- pytest==8.3.5
- pytest-cov==6.0.0
- requests==2.32.3
- six==1.17.0
- snowballstemmer==2.2.0
- sortedcontainers==2.4.0
- sphinx==7.4.7
- sphinx-rtd-theme==0.1.5
- sphinxcontrib-applehelp==2.0.0
- sphinxcontrib-devhelp==2.0.0
- sphinxcontrib-htmlhelp==2.1.0
- sphinxcontrib-jsmath==1.0.1
- sphinxcontrib-qthelp==2.0.0
- sphinxcontrib-serializinghtml==2.0.0
- tomli==2.2.1
- tox==4.25.0
- typing-extensions==4.13.0
- urllib3==2.3.0
- virtualenv==20.29.3
- zipp==3.21.0
prefix: /opt/conda/envs/pyrsistent
| [
"tests/class_test.py::test_supports_pickling_with_typed_container_fields",
"tests/record_test.py::test_supports_pickling_with_typed_container_fields"
] | [] | [
"tests/class_test.py::test_evolve_pclass_instance",
"tests/class_test.py::test_direct_assignment_not_possible",
"tests/class_test.py::test_direct_delete_not_possible",
"tests/class_test.py::test_cannot_construct_with_undeclared_fields",
"tests/class_test.py::test_cannot_construct_with_wrong_type",
"tests/class_test.py::test_cannot_construct_without_mandatory_fields",
"tests/class_test.py::test_field_invariant_must_hold",
"tests/class_test.py::test_initial_value_set_when_not_present_in_arguments",
"tests/class_test.py::test_can_create_nested_structures_from_dict_and_serialize_back_to_dict",
"tests/class_test.py::test_can_serialize_with_custom_serializer",
"tests/class_test.py::test_implements_proper_equality_based_on_equality_of_fields",
"tests/class_test.py::test_is_hashable",
"tests/class_test.py::test_supports_nested_transformation",
"tests/class_test.py::test_repr",
"tests/class_test.py::test_global_invariant_check",
"tests/class_test.py::test_supports_pickling",
"tests/class_test.py::test_can_remove_optional_member",
"tests/class_test.py::test_cannot_remove_mandatory_member",
"tests/class_test.py::test_cannot_remove_non_existing_member",
"tests/class_test.py::test_evolver_without_evolution_returns_original_instance",
"tests/class_test.py::test_evolver_with_evolution_to_same_element_returns_original_instance",
"tests/class_test.py::test_evolver_supports_chained_set_and_remove",
"tests/class_test.py::test_string_as_type_specifier",
"tests/class_test.py::test_multiple_invariants_on_field",
"tests/class_test.py::test_multiple_global_invariants",
"tests/record_test.py::test_create",
"tests/record_test.py::test_correct_assignment",
"tests/record_test.py::test_direct_assignment_not_possible",
"tests/record_test.py::test_cannot_assign_undeclared_fields",
"tests/record_test.py::test_cannot_assign_wrong_type_to_fields",
"tests/record_test.py::test_cannot_construct_with_undeclared_fields",
"tests/record_test.py::test_cannot_construct_with_fields_of_wrong_type",
"tests/record_test.py::test_support_record_inheritance",
"tests/record_test.py::test_single_type_spec",
"tests/record_test.py::test_remove",
"tests/record_test.py::test_remove_non_existing_member",
"tests/record_test.py::test_field_invariant_must_hold",
"tests/record_test.py::test_global_invariant_must_hold",
"tests/record_test.py::test_set_multiple_fields",
"tests/record_test.py::test_initial_value",
"tests/record_test.py::test_type_specification_must_be_a_type",
"tests/record_test.py::test_initial_must_be_of_correct_type",
"tests/record_test.py::test_invariant_must_be_callable",
"tests/record_test.py::test_global_invariants_are_inherited",
"tests/record_test.py::test_global_invariants_must_be_callable",
"tests/record_test.py::test_repr",
"tests/record_test.py::test_factory",
"tests/record_test.py::test_factory_must_be_callable",
"tests/record_test.py::test_nested_record_construction",
"tests/record_test.py::test_pickling",
"tests/record_test.py::test_all_invariant_errors_reported",
"tests/record_test.py::test_precord_factory_method_is_idempotent",
"tests/record_test.py::test_serialize",
"tests/record_test.py::test_nested_serialize",
"tests/record_test.py::test_serializer_must_be_callable",
"tests/record_test.py::test_transform_without_update_returns_same_precord",
"tests/record_test.py::test_nested_create_serialize",
"tests/record_test.py::test_pset_field_initial_value",
"tests/record_test.py::test_pset_field_custom_initial",
"tests/record_test.py::test_pset_field_factory",
"tests/record_test.py::test_pset_field_checked_set",
"tests/record_test.py::test_pset_field_type",
"tests/record_test.py::test_pset_field_mandatory",
"tests/record_test.py::test_pset_field_default_non_optional",
"tests/record_test.py::test_pset_field_explicit_non_optional",
"tests/record_test.py::test_pset_field_optional",
"tests/record_test.py::test_pset_field_name",
"tests/record_test.py::test_pvector_field_initial_value",
"tests/record_test.py::test_pvector_field_custom_initial",
"tests/record_test.py::test_pvector_field_factory",
"tests/record_test.py::test_pvector_field_checked_vector",
"tests/record_test.py::test_pvector_field_type",
"tests/record_test.py::test_pvector_field_mandatory",
"tests/record_test.py::test_pvector_field_default_non_optional",
"tests/record_test.py::test_pvector_field_explicit_non_optional",
"tests/record_test.py::test_pvector_field_optional",
"tests/record_test.py::test_pvector_field_name",
"tests/record_test.py::test_pvector_field_create_from_nested_serialized_data",
"tests/record_test.py::test_pmap_field_initial_value",
"tests/record_test.py::test_pmap_field_factory",
"tests/record_test.py::test_pmap_field_checked_map_key",
"tests/record_test.py::test_pmap_field_checked_map_value",
"tests/record_test.py::test_pmap_field_mandatory",
"tests/record_test.py::test_pmap_field_default_non_optional",
"tests/record_test.py::test_pmap_field_explicit_non_optional",
"tests/record_test.py::test_pmap_field_optional",
"tests/record_test.py::test_pmap_field_name",
"tests/record_test.py::test_pmap_field_invariant",
"tests/record_test.py::test_pmap_field_create_from_nested_serialized_data"
] | [] | MIT License | 238 |
|
docker__docker-py-770 | 02f330d8dc3da47215bed47b44fac73941ea6920 | 2015-09-15 21:47:09 | f479720d517a7db7f886916190b3032d29d18f10 | shin-: #764 needs to be merged for the tests to pass. | diff --git a/docker/utils/utils.py b/docker/utils/utils.py
index 46b35160..36edf8de 100644
--- a/docker/utils/utils.py
+++ b/docker/utils/utils.py
@@ -457,7 +457,8 @@ def create_host_config(
restart_policy=None, cap_add=None, cap_drop=None, devices=None,
extra_hosts=None, read_only=None, pid_mode=None, ipc_mode=None,
security_opt=None, ulimits=None, log_config=None, mem_limit=None,
- memswap_limit=None, cgroup_parent=None, group_add=None, version=None
+ memswap_limit=None, cgroup_parent=None, group_add=None, cpu_quota=None,
+ cpu_period=None, version=None
):
host_config = {}
@@ -518,7 +519,7 @@ def create_host_config(
host_config['Devices'] = parse_devices(devices)
if group_add:
- if compare_version(version, '1.20') < 0:
+ if version_lt(version, '1.20'):
raise errors.InvalidVersion(
'group_add param not supported for API version < 1.20'
)
@@ -601,6 +602,30 @@ def create_host_config(
log_config = LogConfig(**log_config)
host_config['LogConfig'] = log_config
+ if cpu_quota:
+ if not isinstance(cpu_quota, int):
+ raise TypeError(
+ 'Invalid type for cpu_quota param: expected int but'
+ ' found {0}'.format(type(cpu_quota))
+ )
+ if version_lt(version, '1.19'):
+ raise errors.InvalidVersion(
+ 'cpu_quota param not supported for API version < 1.19'
+ )
+ host_config['CpuQuota'] = cpu_quota
+
+ if cpu_period:
+ if not isinstance(cpu_period, int):
+ raise TypeError(
+ 'Invalid type for cpu_period param: expected int but'
+ ' found {0}'.format(type(cpu_period))
+ )
+ if version_lt(version, '1.19'):
+ raise errors.InvalidVersion(
+ 'cpu_period param not supported for API version < 1.19'
+ )
+ host_config['CpuPeriod'] = cpu_period
+
return host_config
| Add support for --cpu-quota & --cpu-period run flags
Any chance we could add support for the above run flags?
https://docs.docker.com/reference/commandline/run/ | docker/docker-py | diff --git a/tests/utils_test.py b/tests/utils_test.py
index b67ac4ec..45929f73 100644
--- a/tests/utils_test.py
+++ b/tests/utils_test.py
@@ -25,6 +25,159 @@ TEST_CERT_DIR = os.path.join(
)
+class HostConfigTest(base.BaseTestCase):
+ def test_create_host_config_no_options(self):
+ config = create_host_config(version='1.19')
+ self.assertFalse('NetworkMode' in config)
+
+ def test_create_host_config_no_options_newer_api_version(self):
+ config = create_host_config(version='1.20')
+ self.assertEqual(config['NetworkMode'], 'default')
+
+ def test_create_host_config_invalid_cpu_cfs_types(self):
+ with pytest.raises(TypeError):
+ create_host_config(version='1.20', cpu_quota='0')
+
+ with pytest.raises(TypeError):
+ create_host_config(version='1.20', cpu_period='0')
+
+ with pytest.raises(TypeError):
+ create_host_config(version='1.20', cpu_quota=23.11)
+
+ with pytest.raises(TypeError):
+ create_host_config(version='1.20', cpu_period=1999.0)
+
+ def test_create_host_config_with_cpu_quota(self):
+ config = create_host_config(version='1.20', cpu_quota=1999)
+ self.assertEqual(config.get('CpuQuota'), 1999)
+
+ def test_create_host_config_with_cpu_period(self):
+ config = create_host_config(version='1.20', cpu_period=1999)
+ self.assertEqual(config.get('CpuPeriod'), 1999)
+
+
+class UlimitTest(base.BaseTestCase):
+ def test_create_host_config_dict_ulimit(self):
+ ulimit_dct = {'name': 'nofile', 'soft': 8096}
+ config = create_host_config(
+ ulimits=[ulimit_dct], version=DEFAULT_DOCKER_API_VERSION
+ )
+ self.assertIn('Ulimits', config)
+ self.assertEqual(len(config['Ulimits']), 1)
+ ulimit_obj = config['Ulimits'][0]
+ self.assertTrue(isinstance(ulimit_obj, Ulimit))
+ self.assertEqual(ulimit_obj.name, ulimit_dct['name'])
+ self.assertEqual(ulimit_obj.soft, ulimit_dct['soft'])
+ self.assertEqual(ulimit_obj['Soft'], ulimit_obj.soft)
+
+ def test_create_host_config_dict_ulimit_capitals(self):
+ ulimit_dct = {'Name': 'nofile', 'Soft': 8096, 'Hard': 8096 * 4}
+ config = create_host_config(
+ ulimits=[ulimit_dct], version=DEFAULT_DOCKER_API_VERSION
+ )
+ self.assertIn('Ulimits', config)
+ self.assertEqual(len(config['Ulimits']), 1)
+ ulimit_obj = config['Ulimits'][0]
+ self.assertTrue(isinstance(ulimit_obj, Ulimit))
+ self.assertEqual(ulimit_obj.name, ulimit_dct['Name'])
+ self.assertEqual(ulimit_obj.soft, ulimit_dct['Soft'])
+ self.assertEqual(ulimit_obj.hard, ulimit_dct['Hard'])
+ self.assertEqual(ulimit_obj['Soft'], ulimit_obj.soft)
+
+ def test_create_host_config_obj_ulimit(self):
+ ulimit_dct = Ulimit(name='nofile', soft=8096)
+ config = create_host_config(
+ ulimits=[ulimit_dct], version=DEFAULT_DOCKER_API_VERSION
+ )
+ self.assertIn('Ulimits', config)
+ self.assertEqual(len(config['Ulimits']), 1)
+ ulimit_obj = config['Ulimits'][0]
+ self.assertTrue(isinstance(ulimit_obj, Ulimit))
+ self.assertEqual(ulimit_obj, ulimit_dct)
+
+ def test_ulimit_invalid_type(self):
+ self.assertRaises(ValueError, lambda: Ulimit(name=None))
+ self.assertRaises(ValueError, lambda: Ulimit(name='hello', soft='123'))
+ self.assertRaises(ValueError, lambda: Ulimit(name='hello', hard='456'))
+
+
+class LogConfigTest(base.BaseTestCase):
+ def test_create_host_config_dict_logconfig(self):
+ dct = {'type': LogConfig.types.SYSLOG, 'config': {'key1': 'val1'}}
+ config = create_host_config(
+ version=DEFAULT_DOCKER_API_VERSION, log_config=dct
+ )
+ self.assertIn('LogConfig', config)
+ self.assertTrue(isinstance(config['LogConfig'], LogConfig))
+ self.assertEqual(dct['type'], config['LogConfig'].type)
+
+ def test_create_host_config_obj_logconfig(self):
+ obj = LogConfig(type=LogConfig.types.SYSLOG, config={'key1': 'val1'})
+ config = create_host_config(
+ version=DEFAULT_DOCKER_API_VERSION, log_config=obj
+ )
+ self.assertIn('LogConfig', config)
+ self.assertTrue(isinstance(config['LogConfig'], LogConfig))
+ self.assertEqual(obj, config['LogConfig'])
+
+ def test_logconfig_invalid_config_type(self):
+ with pytest.raises(ValueError):
+ LogConfig(type=LogConfig.types.JSON, config='helloworld')
+
+
+class KwargsFromEnvTest(base.BaseTestCase):
+ def setUp(self):
+ self.os_environ = os.environ.copy()
+
+ def tearDown(self):
+ os.environ = self.os_environ
+
+ def test_kwargs_from_env_empty(self):
+ os.environ.update(DOCKER_HOST='',
+ DOCKER_CERT_PATH='',
+ DOCKER_TLS_VERIFY='')
+
+ kwargs = kwargs_from_env()
+ self.assertEqual(None, kwargs.get('base_url'))
+ self.assertEqual(None, kwargs.get('tls'))
+
+ def test_kwargs_from_env_tls(self):
+ os.environ.update(DOCKER_HOST='tcp://192.168.59.103:2376',
+ DOCKER_CERT_PATH=TEST_CERT_DIR,
+ DOCKER_TLS_VERIFY='1')
+ kwargs = kwargs_from_env(assert_hostname=False)
+ self.assertEqual('https://192.168.59.103:2376', kwargs['base_url'])
+ self.assertTrue('ca.pem' in kwargs['tls'].verify)
+ self.assertTrue('cert.pem' in kwargs['tls'].cert[0])
+ self.assertTrue('key.pem' in kwargs['tls'].cert[1])
+ self.assertEqual(False, kwargs['tls'].assert_hostname)
+ try:
+ client = Client(**kwargs)
+ self.assertEqual(kwargs['base_url'], client.base_url)
+ self.assertEqual(kwargs['tls'].verify, client.verify)
+ self.assertEqual(kwargs['tls'].cert, client.cert)
+ except TypeError as e:
+ self.fail(e)
+
+ def test_kwargs_from_env_no_cert_path(self):
+ try:
+ temp_dir = tempfile.mkdtemp()
+ cert_dir = os.path.join(temp_dir, '.docker')
+ shutil.copytree(TEST_CERT_DIR, cert_dir)
+
+ os.environ.update(HOME=temp_dir,
+ DOCKER_CERT_PATH='',
+ DOCKER_TLS_VERIFY='1')
+
+ kwargs = kwargs_from_env()
+ self.assertIn(cert_dir, kwargs['tls'].verify)
+ self.assertIn(cert_dir, kwargs['tls'].cert[0])
+ self.assertIn(cert_dir, kwargs['tls'].cert[1])
+ finally:
+ if temp_dir:
+ shutil.rmtree(temp_dir)
+
+
class UtilsTest(base.BaseTestCase):
longMessage = True
@@ -39,12 +192,6 @@ class UtilsTest(base.BaseTestCase):
local_tempfile.close()
return local_tempfile.name
- def setUp(self):
- self.os_environ = os.environ.copy()
-
- def tearDown(self):
- os.environ = self.os_environ
-
def test_parse_repository_tag(self):
self.assertEqual(parse_repository_tag("root"),
("root", None))
@@ -103,51 +250,6 @@ class UtilsTest(base.BaseTestCase):
assert parse_host(val, 'win32') == tcp_port
- def test_kwargs_from_env_empty(self):
- os.environ.update(DOCKER_HOST='',
- DOCKER_CERT_PATH='',
- DOCKER_TLS_VERIFY='')
-
- kwargs = kwargs_from_env()
- self.assertEqual(None, kwargs.get('base_url'))
- self.assertEqual(None, kwargs.get('tls'))
-
- def test_kwargs_from_env_tls(self):
- os.environ.update(DOCKER_HOST='tcp://192.168.59.103:2376',
- DOCKER_CERT_PATH=TEST_CERT_DIR,
- DOCKER_TLS_VERIFY='1')
- kwargs = kwargs_from_env(assert_hostname=False)
- self.assertEqual('https://192.168.59.103:2376', kwargs['base_url'])
- self.assertTrue('ca.pem' in kwargs['tls'].verify)
- self.assertTrue('cert.pem' in kwargs['tls'].cert[0])
- self.assertTrue('key.pem' in kwargs['tls'].cert[1])
- self.assertEqual(False, kwargs['tls'].assert_hostname)
- try:
- client = Client(**kwargs)
- self.assertEqual(kwargs['base_url'], client.base_url)
- self.assertEqual(kwargs['tls'].verify, client.verify)
- self.assertEqual(kwargs['tls'].cert, client.cert)
- except TypeError as e:
- self.fail(e)
-
- def test_kwargs_from_env_no_cert_path(self):
- try:
- temp_dir = tempfile.mkdtemp()
- cert_dir = os.path.join(temp_dir, '.docker')
- shutil.copytree(TEST_CERT_DIR, cert_dir)
-
- os.environ.update(HOME=temp_dir,
- DOCKER_CERT_PATH='',
- DOCKER_TLS_VERIFY='1')
-
- kwargs = kwargs_from_env()
- self.assertIn(cert_dir, kwargs['tls'].verify)
- self.assertIn(cert_dir, kwargs['tls'].cert[0])
- self.assertIn(cert_dir, kwargs['tls'].cert[1])
- finally:
- if temp_dir:
- shutil.rmtree(temp_dir)
-
def test_parse_env_file_proper(self):
env_file = self.generate_tempfile(
file_content='USER=jdoe\nPASS=secret')
@@ -181,79 +283,6 @@ class UtilsTest(base.BaseTestCase):
for filters, expected in tests:
self.assertEqual(convert_filters(filters), expected)
- def test_create_host_config_no_options(self):
- config = create_host_config(version='1.19')
- self.assertFalse('NetworkMode' in config)
-
- def test_create_host_config_no_options_newer_api_version(self):
- config = create_host_config(version='1.20')
- self.assertEqual(config['NetworkMode'], 'default')
-
- def test_create_host_config_dict_ulimit(self):
- ulimit_dct = {'name': 'nofile', 'soft': 8096}
- config = create_host_config(
- ulimits=[ulimit_dct], version=DEFAULT_DOCKER_API_VERSION
- )
- self.assertIn('Ulimits', config)
- self.assertEqual(len(config['Ulimits']), 1)
- ulimit_obj = config['Ulimits'][0]
- self.assertTrue(isinstance(ulimit_obj, Ulimit))
- self.assertEqual(ulimit_obj.name, ulimit_dct['name'])
- self.assertEqual(ulimit_obj.soft, ulimit_dct['soft'])
- self.assertEqual(ulimit_obj['Soft'], ulimit_obj.soft)
-
- def test_create_host_config_dict_ulimit_capitals(self):
- ulimit_dct = {'Name': 'nofile', 'Soft': 8096, 'Hard': 8096 * 4}
- config = create_host_config(
- ulimits=[ulimit_dct], version=DEFAULT_DOCKER_API_VERSION
- )
- self.assertIn('Ulimits', config)
- self.assertEqual(len(config['Ulimits']), 1)
- ulimit_obj = config['Ulimits'][0]
- self.assertTrue(isinstance(ulimit_obj, Ulimit))
- self.assertEqual(ulimit_obj.name, ulimit_dct['Name'])
- self.assertEqual(ulimit_obj.soft, ulimit_dct['Soft'])
- self.assertEqual(ulimit_obj.hard, ulimit_dct['Hard'])
- self.assertEqual(ulimit_obj['Soft'], ulimit_obj.soft)
-
- def test_create_host_config_obj_ulimit(self):
- ulimit_dct = Ulimit(name='nofile', soft=8096)
- config = create_host_config(
- ulimits=[ulimit_dct], version=DEFAULT_DOCKER_API_VERSION
- )
- self.assertIn('Ulimits', config)
- self.assertEqual(len(config['Ulimits']), 1)
- ulimit_obj = config['Ulimits'][0]
- self.assertTrue(isinstance(ulimit_obj, Ulimit))
- self.assertEqual(ulimit_obj, ulimit_dct)
-
- def test_ulimit_invalid_type(self):
- self.assertRaises(ValueError, lambda: Ulimit(name=None))
- self.assertRaises(ValueError, lambda: Ulimit(name='hello', soft='123'))
- self.assertRaises(ValueError, lambda: Ulimit(name='hello', hard='456'))
-
- def test_create_host_config_dict_logconfig(self):
- dct = {'type': LogConfig.types.SYSLOG, 'config': {'key1': 'val1'}}
- config = create_host_config(
- version=DEFAULT_DOCKER_API_VERSION, log_config=dct
- )
- self.assertIn('LogConfig', config)
- self.assertTrue(isinstance(config['LogConfig'], LogConfig))
- self.assertEqual(dct['type'], config['LogConfig'].type)
-
- def test_create_host_config_obj_logconfig(self):
- obj = LogConfig(type=LogConfig.types.SYSLOG, config={'key1': 'val1'})
- config = create_host_config(
- version=DEFAULT_DOCKER_API_VERSION, log_config=obj
- )
- self.assertIn('LogConfig', config)
- self.assertTrue(isinstance(config['LogConfig'], LogConfig))
- self.assertEqual(obj, config['LogConfig'])
-
- def test_logconfig_invalid_config_type(self):
- with pytest.raises(ValueError):
- LogConfig(type=LogConfig.types.JSON, config='helloworld')
-
def test_resolve_repository_name(self):
# docker hub library image
self.assertEqual(
@@ -407,6 +436,8 @@ class UtilsTest(base.BaseTestCase):
None,
)
+
+class PortsTest(base.BaseTestCase):
def test_split_port_with_host_ip(self):
internal_port, external_port = split_port("127.0.0.1:1000:2000")
self.assertEqual(internal_port, ["2000"])
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_short_problem_statement",
"has_hyperlinks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 1,
"issue_text_score": 1,
"test_score": 2
},
"num_modified_files": 1
} | 1.4 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest",
"flake8"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.9",
"reqs_path": [
"requirements.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | -e git+https://github.com/docker/docker-py.git@02f330d8dc3da47215bed47b44fac73941ea6920#egg=docker_py
exceptiongroup==1.2.2
flake8==7.2.0
iniconfig==2.1.0
mccabe==0.7.0
packaging==24.2
pluggy==1.5.0
pycodestyle==2.13.0
pyflakes==3.3.2
pytest==8.3.5
requests==2.5.3
six==1.17.0
tomli==2.2.1
websocket_client==0.32.0
| name: docker-py
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=3.0.16=h5eee18b_0
- pip=25.0=py39h06a4308_0
- python=3.9.21=he870216_1
- readline=8.2=h5eee18b_0
- setuptools=75.8.0=py39h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- tzdata=2025a=h04d1e81_0
- wheel=0.45.1=py39h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- exceptiongroup==1.2.2
- flake8==7.2.0
- iniconfig==2.1.0
- mccabe==0.7.0
- packaging==24.2
- pluggy==1.5.0
- pycodestyle==2.13.0
- pyflakes==3.3.2
- pytest==8.3.5
- requests==2.5.3
- six==1.17.0
- tomli==2.2.1
- websocket-client==0.32.0
prefix: /opt/conda/envs/docker-py
| [
"tests/utils_test.py::HostConfigTest::test_create_host_config_with_cpu_period",
"tests/utils_test.py::HostConfigTest::test_create_host_config_with_cpu_quota"
] | [] | [
"tests/utils_test.py::HostConfigTest::test_create_host_config_invalid_cpu_cfs_types",
"tests/utils_test.py::HostConfigTest::test_create_host_config_no_options",
"tests/utils_test.py::HostConfigTest::test_create_host_config_no_options_newer_api_version",
"tests/utils_test.py::UlimitTest::test_create_host_config_dict_ulimit",
"tests/utils_test.py::UlimitTest::test_create_host_config_dict_ulimit_capitals",
"tests/utils_test.py::UlimitTest::test_create_host_config_obj_ulimit",
"tests/utils_test.py::UlimitTest::test_ulimit_invalid_type",
"tests/utils_test.py::LogConfigTest::test_create_host_config_dict_logconfig",
"tests/utils_test.py::LogConfigTest::test_create_host_config_obj_logconfig",
"tests/utils_test.py::LogConfigTest::test_logconfig_invalid_config_type",
"tests/utils_test.py::KwargsFromEnvTest::test_kwargs_from_env_empty",
"tests/utils_test.py::KwargsFromEnvTest::test_kwargs_from_env_no_cert_path",
"tests/utils_test.py::KwargsFromEnvTest::test_kwargs_from_env_tls",
"tests/utils_test.py::UtilsTest::test_convert_filters",
"tests/utils_test.py::UtilsTest::test_parse_bytes",
"tests/utils_test.py::UtilsTest::test_parse_env_file_commented_line",
"tests/utils_test.py::UtilsTest::test_parse_env_file_invalid_line",
"tests/utils_test.py::UtilsTest::test_parse_env_file_proper",
"tests/utils_test.py::UtilsTest::test_parse_host",
"tests/utils_test.py::UtilsTest::test_parse_host_empty_value",
"tests/utils_test.py::UtilsTest::test_parse_repository_tag",
"tests/utils_test.py::UtilsTest::test_resolve_authconfig",
"tests/utils_test.py::UtilsTest::test_resolve_registry_and_auth",
"tests/utils_test.py::UtilsTest::test_resolve_repository_name",
"tests/utils_test.py::PortsTest::test_build_port_bindings_with_matching_internal_port_ranges",
"tests/utils_test.py::PortsTest::test_build_port_bindings_with_matching_internal_ports",
"tests/utils_test.py::PortsTest::test_build_port_bindings_with_nonmatching_internal_port_ranges",
"tests/utils_test.py::PortsTest::test_build_port_bindings_with_nonmatching_internal_ports",
"tests/utils_test.py::PortsTest::test_build_port_bindings_with_one_port",
"tests/utils_test.py::PortsTest::test_build_port_bindings_with_port_range",
"tests/utils_test.py::PortsTest::test_host_only_with_colon",
"tests/utils_test.py::PortsTest::test_non_matching_length_port_ranges",
"tests/utils_test.py::PortsTest::test_port_and_range_invalid",
"tests/utils_test.py::PortsTest::test_port_only_with_colon",
"tests/utils_test.py::PortsTest::test_split_port_invalid",
"tests/utils_test.py::PortsTest::test_split_port_no_host_port",
"tests/utils_test.py::PortsTest::test_split_port_range_no_host_port",
"tests/utils_test.py::PortsTest::test_split_port_range_with_host_ip_no_port",
"tests/utils_test.py::PortsTest::test_split_port_range_with_host_port",
"tests/utils_test.py::PortsTest::test_split_port_range_with_protocol",
"tests/utils_test.py::PortsTest::test_split_port_with_host_ip",
"tests/utils_test.py::PortsTest::test_split_port_with_host_ip_no_port",
"tests/utils_test.py::PortsTest::test_split_port_with_host_port",
"tests/utils_test.py::PortsTest::test_split_port_with_protocol",
"tests/utils_test.py::ExcludePathsTest::test_directory",
"tests/utils_test.py::ExcludePathsTest::test_directory_with_single_exception",
"tests/utils_test.py::ExcludePathsTest::test_directory_with_subdir_exception",
"tests/utils_test.py::ExcludePathsTest::test_directory_with_trailing_slash",
"tests/utils_test.py::ExcludePathsTest::test_directory_with_wildcard_exception",
"tests/utils_test.py::ExcludePathsTest::test_exclude_custom_dockerfile",
"tests/utils_test.py::ExcludePathsTest::test_exclude_dockerfile_dockerignore",
"tests/utils_test.py::ExcludePathsTest::test_no_dupes",
"tests/utils_test.py::ExcludePathsTest::test_no_excludes",
"tests/utils_test.py::ExcludePathsTest::test_question_mark",
"tests/utils_test.py::ExcludePathsTest::test_single_filename",
"tests/utils_test.py::ExcludePathsTest::test_single_filename_trailing_slash",
"tests/utils_test.py::ExcludePathsTest::test_single_subdir_single_filename",
"tests/utils_test.py::ExcludePathsTest::test_single_subdir_wildcard_filename",
"tests/utils_test.py::ExcludePathsTest::test_subdirectory",
"tests/utils_test.py::ExcludePathsTest::test_wildcard_exclude",
"tests/utils_test.py::ExcludePathsTest::test_wildcard_filename_end",
"tests/utils_test.py::ExcludePathsTest::test_wildcard_filename_start",
"tests/utils_test.py::ExcludePathsTest::test_wildcard_subdir_single_filename",
"tests/utils_test.py::ExcludePathsTest::test_wildcard_subdir_wildcard_filename",
"tests/utils_test.py::ExcludePathsTest::test_wildcard_with_exception",
"tests/utils_test.py::ExcludePathsTest::test_wildcard_with_wildcard_exception"
] | [] | Apache License 2.0 | 239 |
rbarrois__python-semanticversion-27 | 2ed3d39c291080c61edd9139370939e1fdc3209a | 2015-09-15 22:15:55 | 2ed3d39c291080c61edd9139370939e1fdc3209a | diff --git a/CREDITS b/CREDITS
index c700c77..1506f2a 100644
--- a/CREDITS
+++ b/CREDITS
@@ -18,8 +18,9 @@ Contributors
The project has received contributions from (in alphabetical order):
* Raphaël Barrois <[email protected]> (https://github.com/rbarrois)
-* Michael Hrivnak <[email protected]> (https://github.com/mhrivnak)
* Rick Eyre <[email protected]> (https://github.com/rickeyre)
+* Michael Hrivnak <[email protected]> (https://github.com/mhrivnak)
+* William Minchin <[email protected]> (https://github.com/minchinweb)
Contributor license agreement
diff --git a/ChangeLog b/ChangeLog
index cd7c3db..7b233fe 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -1,35 +1,12 @@
ChangeLog
=========
-2.5.0 (master)
---------------
+2.4.3 (unreleased)
+------------------
*Bugfix:*
- `#18 <https://github.com/rbarrois/python-semanticversion/issues/18>`_: According to SemVer 2.0.0, build numbers aren't ordered.
-
- * Remove specs of the ``Spec('<1.1.3+')`` form
- * Comparing ``Version('0.1.0')`` to ``Version('0.1.0+bcd')`` has new
- rules::
-
- >>> Version('0.1.0+1') == Version('0.1.0+bcd')
- False
- >>> Version('0.1.0+1') != Version('0.1.0+bcd')
- True
- >>> Version('0.1.0+1') < Version('0.1.0+bcd')
- False
- >>> Version('0.1.0+1') > Version('0.1.0+bcd')
- False
- >>> Version('0.1.0+1') <= Version('0.1.0+bcd')
- False
- >>> Version('0.1.0+1') >= Version('0.1.0+bcd')
- False
- >>> compare(Version('0.1.0+1'), Version('0.1.0+bcd'))
- NotImplemented
-
- * :func:`semantic_version.compare` returns ``NotImplemented`` when its
- parameters differ only by build metadata
- * ``Spec('<=1.3.0')`` now matches ``Version('1.3.0+abde24fe883')``
+ * Fix handling of bumping pre-release versions, thanks to @minchinweb.
2.4.2 (2015-07-02)
------------------
diff --git a/README.rst b/README.rst
index 484692e..5923a30 100644
--- a/README.rst
+++ b/README.rst
@@ -247,18 +247,19 @@ definition or (for the empty pre-release number) if a single dash is appended
False
-Including build metadata in specifications
-""""""""""""""""""""""""""""""""""""""""""
+Including build identifiers in specifications
+"""""""""""""""""""""""""""""""""""""""""""""
-Build metadata has no ordering; thus, the only meaningful comparison including
-build metadata is equality.
+The same rule applies for the build identifier: comparisons will include it only
+if it was included in the :class:`Spec` definition, or - for the unnumbered build
+version - if a single + is appended to the definition(``1.0.0+``, ``1.0.0-alpha+``):
.. code-block:: pycon
- >>> Version('1.0.0+build2') in Spec('<=1.0.0') # Build metadata ignored
+ >>> Version('1.0.0+build2') in Spec('<=1.0.0') # Build identifier ignored
True
- >>> Version('1.0.0+build2') in Spec('==1.0.0+build2') # Include build in checks
+ >>> Version('1.0.0+build2') in Spec('<=1.0.0+') # Include build in checks
False
diff --git a/docs/reference.rst b/docs/reference.rst
index 261e738..3550c25 100644
--- a/docs/reference.rst
+++ b/docs/reference.rst
@@ -22,13 +22,9 @@ Module-level functions
:param str v1: The first version to compare
:param str v2: The second version to compare
:raises: :exc:`ValueError`, if any version string is invalid
- :rtype: ``int``, -1 / 0 / 1 as for a :func:`cmp` comparison;
- ``NotImplemented`` if versions only differ by build metadata
+ :rtype: ``int``, -1 / 0 / 1 as for a :func:`cmp` comparison
-.. warning:: Since build metadata has no ordering,
- ``compare(Version('0.1.1'), Version('0.1.1+3'))`` returns ``NotImplemented``
-
.. function:: match(spec, version)
@@ -111,9 +107,9 @@ Representing a version (the Version class)
.. attribute:: build
- ``tuple`` of ``strings``, the build metadata.
+ ``tuple`` of ``strings``, the build component.
- It contains the various dot-separated identifiers in the build metadata.
+ It contains the various dot-separated identifiers in the build component.
May be ``None`` for a :attr:`partial` version number in a ``<major>``, ``<major>.<minor>``,
``<major>.<minor>.<patch>`` or ``<major>.<minor>.<patch>-<prerelease>`` format.
@@ -155,7 +151,7 @@ Representing a version (the Version class)
For instance, ``Version('1.0', partial=True)`` means "any version beginning in ``1.0``".
``Version('1.0.1-alpha', partial=True)`` means "The ``1.0.1-alpha`` version or any
- any release differing only in build metadata": ``1.0.1-alpha+build3`` matches, ``1.0.1-alpha.2`` doesn't.
+ ulterior build of that same version": ``1.0.1-alpha+build3`` matches, ``1.0.1-alpha.2`` doesn't.
Examples::
@@ -250,6 +246,7 @@ The main issue with representing version specifications is that the usual syntax
does not map well onto `SemVer`_ precedence rules:
* A specification of ``<1.3.4`` is not expected to allow ``1.3.4-rc2``, but strict `SemVer`_ comparisons allow it ;
+* Converting the previous specification to ``<=1.3.3`` in order to avoid ``1.3.4``
prereleases has the issue of excluding ``1.3.3+build3`` ;
* It may be necessary to exclude either all variations on a patch-level release
(``!=1.3.3``) or specifically one build-level release (``1.3.3-build.434``).
@@ -259,7 +256,7 @@ In order to have version specification behave naturally, the rules are the follo
* If no pre-release number was included in the specification, pre-release numbers
are ignored when deciding whether a version satisfies a specification.
-* If no build metadata was included in the specification, build metadata is ignored
+* If no build number was included in the specification, build numbers are ignored
when deciding whether a version satisfies a specification.
This means that::
@@ -270,7 +267,7 @@ This means that::
True
>>> Version('1.1.1-rc1+build4') in Spec('<=1.1.1-rc1')
True
- >>> Version('1.1.1-rc1+build4') in Spec('==1.1.1-rc1+build2')
+ >>> Version('1.1.1-rc1+build4') in Spec('<=1.1.1-rc1+build2')
False
@@ -288,31 +285,20 @@ rules apply:
>>> Version('1.1.1-rc1') in Spec('<1.1.1-')
True
-* Setting a build metadata separator without build metadata (``<=1.1.1+``)
- forces matches "up to the build metadata"; use this to include/exclude a
- release lacking build metadata while excluding/including all other builds
- of that release
+* Setting a build separator without a build identifier (``>1.1.1+``) forces
+ satisfaction tests to include both prerelease and build identifiers::
- >>> Version('1.1.1') in Spec('==1.1.1+')
- True
- >>> Version('1.1.1+2') in Spec('==1.1.1+')
+ >>> Version('1.1.1+build2') in Spec('>1.1.1')
False
-
-
-.. warning:: As stated in the `SemVer`_ specification, the ordering of build metadata is *undefined*.
- Thus, a :class:`Spec` string can only mention build metadata to include or exclude a specific version:
-
- * ``==1.1.1+b1234`` includes this specific build
- * ``!=1.1.1+b1234`` excludes it (but would match ``1.1.1+b1235``
- * ``<1.1.1+b1`` is invalid
-
+ >>> Version('1.1.1+build2') in Spec('>1.1.1+')
+ True
.. class:: Spec(spec_string[, spec_string[, ...]])
Stores a list of :class:`SpecItem` and matches any :class:`Version` against all
contained :class:`specs <SpecItem>`.
- It is built from a comma-separated list of version specifications::
+ It is build from a comma-separated list of version specifications::
>>> Spec('>=1.0.0,<1.2.0,!=1.1.4')
<Spec: (
@@ -441,16 +427,16 @@ rules apply:
>>> SpecItem('>=0.1.1').match(Version('0.1.1-rc1')) # pre-release satisfy conditions
True
- >>> Version('0.1.1+build2') in SpecItem('>=0.1.1') # build metadata is ignored when checking for precedence
+ >>> Version('0.1.1+build2') in SpecItem('>=0.1.1') # build version satisfy specifications
True
>>>
>>> # Use the '-' marker to include the pre-release component in checks
>>> SpecItem('>=0.1.1-').match(Version('0.1.1-rc1')
False
- >>> # Use the '+' marker to include the build metadata in checks
- >>> SpecItem('==0.1.1+').match(Version('0.1.1+b1234')
- False
>>>
+ >>> # Use the '+' marker to include the build identifier in checks
+ >>> SpecItem('<=0.1.1-alpha+').match(Version('0.1.1-alpha+build1'))
+ False
.. rubric:: Attributes
diff --git a/semantic_version/base.py b/semantic_version/base.py
index 982fcc8..4d9b87e 100644
--- a/semantic_version/base.py
+++ b/semantic_version/base.py
@@ -89,15 +89,24 @@ class Version(object):
return int(value)
def next_major(self):
- return Version('.'.join(str(x) for x in [self.major + 1, 0, 0]))
+ if self.prerelease and self.minor is 0 and self.patch is 0:
+ return Version('.'.join(str(x) for x in [self.major, self.minor, self.patch]))
+ else:
+ return Version('.'.join(str(x) for x in [self.major + 1, 0, 0]))
def next_minor(self):
- return Version(
- '.'.join(str(x) for x in [self.major, self.minor + 1, 0]))
+ if self.prerelease and self.patch is 0:
+ return Version('.'.join(str(x) for x in [self.major, self.minor, self.patch]))
+ else:
+ return Version(
+ '.'.join(str(x) for x in [self.major, self.minor + 1, 0]))
def next_patch(self):
- return Version(
- '.'.join(str(x) for x in [self.major, self.minor, self.patch + 1]))
+ if self.prerelease:
+ return Version('.'.join(str(x) for x in [self.major, self.minor, self.patch]))
+ else:
+ return Version(
+ '.'.join(str(x) for x in [self.major, self.minor, self.patch + 1]))
@classmethod
def coerce(cls, version_string, partial=False):
@@ -290,14 +299,20 @@ class Version(object):
return 0
def build_cmp(a, b):
- """Compare build metadata.
+ """Compare build components.
- Special rule: there is no ordering on build metadata.
+ Special rule: a version without build component has lower
+ precedence than one with a build component.
"""
- if a == b:
- return 0
+ if a and b:
+ return identifier_list_cmp(a, b)
+ elif a:
+ # Versions with build field have higher precedence
+ return 1
+ elif b:
+ return -1
else:
- return NotImplemented
+ return 0
def make_optional(orig_cmp_fun):
"""Convert a cmp-like function to consider 'None == *'."""
@@ -326,7 +341,10 @@ class Version(object):
build_cmp,
]
- def __compare(self, other):
+ def __cmp__(self, other):
+ if not isinstance(other, self.__class__):
+ return NotImplemented
+
field_pairs = zip(self, other)
comparison_functions = self._comparison_functions(partial=self.partial or other.partial)
comparisons = zip(comparison_functions, self, other)
@@ -338,48 +356,44 @@ class Version(object):
return 0
+ def __eq__(self, other):
+ if not isinstance(other, self.__class__):
+ return NotImplemented
+
+ return self.__cmp__(other) == 0
+
def __hash__(self):
return hash((self.major, self.minor, self.patch, self.prerelease, self.build))
- def __cmp__(self, other):
+ def __ne__(self, other):
if not isinstance(other, self.__class__):
return NotImplemented
- return self.__compare(other)
- def __compare_helper(self, other, condition, notimpl_target):
- """Helper for comparison.
+ return self.__cmp__(other) != 0
- Allows the caller to provide:
- - The condition
- - The return value if the comparison is meaningless (ie versions with
- build metadata).
- """
+ def __lt__(self, other):
if not isinstance(other, self.__class__):
return NotImplemented
- cmp_res = self.__cmp__(other)
- if cmp_res is NotImplemented:
- return notimpl_target
-
- return condition(cmp_res)
-
- def __eq__(self, other):
- return self.__compare_helper(other, lambda x: x == 0, notimpl_target=False)
-
- def __ne__(self, other):
- return self.__compare_helper(other, lambda x: x != 0, notimpl_target=True)
-
- def __lt__(self, other):
- return self.__compare_helper(other, lambda x: x < 0, notimpl_target=False)
+ return self.__cmp__(other) < 0
def __le__(self, other):
- return self.__compare_helper(other, lambda x: x <= 0, notimpl_target=False)
+ if not isinstance(other, self.__class__):
+ return NotImplemented
+
+ return self.__cmp__(other) <= 0
def __gt__(self, other):
- return self.__compare_helper(other, lambda x: x > 0, notimpl_target=False)
+ if not isinstance(other, self.__class__):
+ return NotImplemented
+
+ return self.__cmp__(other) > 0
def __ge__(self, other):
- return self.__compare_helper(other, lambda x: x >= 0, notimpl_target=False)
+ if not isinstance(other, self.__class__):
+ return NotImplemented
+
+ return self.__cmp__(other) >= 0
class SpecItem(object):
@@ -415,10 +429,6 @@ class SpecItem(object):
kind, version = match.groups()
spec = Version(version, partial=True)
- if spec.build is not None and kind not in (cls.KIND_EQUAL, cls.KIND_NEQ):
- raise ValueError(
- "Invalid requirement specification %r: build numbers have no ordering."
- % requirement_string)
return (kind, spec)
def match(self, version):
diff --git a/semantic_version/compat.py b/semantic_version/compat.py
index 4dd60fe..bea6f67 100644
--- a/semantic_version/compat.py
+++ b/semantic_version/compat.py
@@ -2,14 +2,17 @@
# Copyright (c) 2012-2014 The python-semanticversion project
# This code is distributed under the two-clause BSD License.
+import sys
-def base_cmp(x, y):
- if x == y:
- return 0
- elif x > y:
- return 1
- elif x < y:
- return -1
- else:
- # Fix Py2's behavior: cmp(x, y) returns -1 for unorderable types
- return NotImplemented
+is_python2 = (sys.version_info[0] == 2)
+
+if is_python2: # pragma: no cover
+ base_cmp = cmp
+else: # pragma: no cover
+ def base_cmp(x, y):
+ if x < y:
+ return -1
+ elif x > y:
+ return 1
+ else:
+ return 0
| Version bump from prereleases not working as expected
I was expecting that a prerelease version, when bumped, would go up to the 'full' or release version without bumping the main version number if not needed.
Probably makes more sense if I give examples.
What I expected:
```
1.0.0-dev --[major]--> 1.0.0
1.0.1-dev --[major]--> 2.0.0
1.1.0-dev --[major]--> 2.0.0
1.0.0-dev --[minor]--> 1.0.0
1.0.1-dev --[minor]--> 1.1.0
1.1.0-dev --[minor]--> 1.1.0
1.0.0-dev --[patch]--> 1.0.0
1.0.1-dev --[patch]--> 1.0.1
1.1.0-dev --[patch]--> 1.1.0
```
What currently happens:
```
1.0.0-dev --[major]--> 2.0.0
1.0.1-dev --[major]--> 2.0.0
1.1.0-dev --[major]--> 2.0.0
1.0.0-dev --[minor]--> 1.1.0
1.0.1-dev --[minor]--> 1.1.0
1.1.0-dev --[minor]--> 1.2.0
1.0.0-dev --[patch]--> 1.0.1
1.0.1-dev --[patch]--> 1.0.2
1.1.0-dev --[patch]--> 1.1.1
```
If this a bug in the implementation, or have I missed something in the spec? Thanks!
| rbarrois/python-semanticversion | diff --git a/tests/test_base.py b/tests/test_base.py
index ae23d86..00c1216 100755
--- a/tests/test_base.py
+++ b/tests/test_base.py
@@ -64,7 +64,7 @@ class TopLevelTestCase(unittest.TestCase):
('0.1.1', '0.1.1', 0),
('0.1.1', '0.1.0', 1),
('0.1.0-alpha', '0.1.0', -1),
- ('0.1.0-alpha+2', '0.1.0-alpha', NotImplemented),
+ ('0.1.0-alpha+2', '0.1.0-alpha', 1),
)
def test_compare(self):
@@ -179,6 +179,7 @@ class VersionTestCase(unittest.TestCase):
'1.1.2': (1, 1, 2, None, None),
'1.1.3-rc4.5': (1, 1, 3, ('rc4', '5'), None),
'1.0.0-': (1, 0, 0, (), None),
+ '1.0.0+': (1, 0, 0, (), ()),
'1.0.0-rc.1+build.1': (1, 0, 0, ('rc', '1'), ('build', '1')),
'1.0.0+0.3.7': (1, 0, 0, (), ('0', '3', '7')),
'1.3.7+build': (1, 3, 7, (), ('build',)),
@@ -241,11 +242,111 @@ class VersionTestCase(unittest.TestCase):
self.assertTrue(v != '0.1.0')
self.assertFalse(v == '0.1.0')
- def test_bump_versions(self):
+ def test_bump_clean_versions(self):
# We Test each property explicitly as the == comparator for versions
# does not distinguish between prerelease or builds for equality.
+ v = base.Version('1.0.0+build')
+ v = v.next_major()
+ self.assertEqual(v.major, 2)
+ self.assertEqual(v.minor, 0)
+ self.assertEqual(v.patch, 0)
+ self.assertEqual(v.prerelease, ())
+ self.assertEqual(v.build, ())
+
+ v = base.Version('1.0.0+build')
+ v = v.next_minor()
+ self.assertEqual(v.major, 1)
+ self.assertEqual(v.minor, 1)
+ self.assertEqual(v.patch, 0)
+ self.assertEqual(v.prerelease, ())
+ self.assertEqual(v.build, ())
+
+ v = base.Version('1.0.0+build')
+ v = v.next_patch()
+ self.assertEqual(v.major, 1)
+ self.assertEqual(v.minor, 0)
+ self.assertEqual(v.patch, 1)
+ self.assertEqual(v.prerelease, ())
+ self.assertEqual(v.build, ())
+
+ v = base.Version('1.1.0+build')
+ v = v.next_major()
+ self.assertEqual(v.major, 2)
+ self.assertEqual(v.minor, 0)
+ self.assertEqual(v.patch, 0)
+ self.assertEqual(v.prerelease, ())
+ self.assertEqual(v.build, ())
+
+ v = base.Version('1.1.0+build')
+ v = v.next_minor()
+ self.assertEqual(v.major, 1)
+ self.assertEqual(v.minor, 2)
+ self.assertEqual(v.patch, 0)
+ self.assertEqual(v.prerelease, ())
+ self.assertEqual(v.build, ())
+
+ v = base.Version('1.1.0+build')
+ v = v.next_patch()
+ self.assertEqual(v.major, 1)
+ self.assertEqual(v.minor, 1)
+ self.assertEqual(v.patch, 1)
+ self.assertEqual(v.prerelease, ())
+ self.assertEqual(v.build, ())
+
+ v = base.Version('1.0.1+build')
+ v = v.next_major()
+ self.assertEqual(v.major, 2)
+ self.assertEqual(v.minor, 0)
+ self.assertEqual(v.patch, 0)
+ self.assertEqual(v.prerelease, ())
+ self.assertEqual(v.build, ())
+
+ v = base.Version('1.0.1+build')
+ v = v.next_minor()
+ self.assertEqual(v.major, 1)
+ self.assertEqual(v.minor, 1)
+ self.assertEqual(v.patch, 0)
+ self.assertEqual(v.prerelease, ())
+ self.assertEqual(v.build, ())
+
+ v = base.Version('1.0.1+build')
+ v = v.next_patch()
+ self.assertEqual(v.major, 1)
+ self.assertEqual(v.minor, 0)
+ self.assertEqual(v.patch, 2)
+ self.assertEqual(v.prerelease, ())
+ self.assertEqual(v.build, ())
+
+ def test_bump_prerelease_versions(self):
+ # We Test each property explicitly as the == comparator for versions
+ # does not distinguish between prerelease or builds for equality.
+
+ v = base.Version('1.0.0-pre+build')
+ v = v.next_major()
+ self.assertEqual(v.major, 1)
+ self.assertEqual(v.minor, 0)
+ self.assertEqual(v.patch, 0)
+ self.assertEqual(v.prerelease, ())
+ self.assertEqual(v.build, ())
+
+ v = base.Version('1.0.0-pre+build')
+ v = v.next_minor()
+ self.assertEqual(v.major, 1)
+ self.assertEqual(v.minor, 0)
+ self.assertEqual(v.patch, 0)
+ self.assertEqual(v.prerelease, ())
+ self.assertEqual(v.build, ())
+
v = base.Version('1.0.0-pre+build')
+ v = v.next_patch()
+ self.assertEqual(v.major, 1)
+ self.assertEqual(v.minor, 0)
+ self.assertEqual(v.patch, 0)
+ self.assertEqual(v.prerelease, ())
+ self.assertEqual(v.build, ())
+
+ v = base.Version('1.1.0-pre+build')
v = v.next_major()
self.assertEqual(v.major, 2)
self.assertEqual(v.minor, 0)
@@ -253,7 +354,7 @@ class VersionTestCase(unittest.TestCase):
self.assertEqual(v.prerelease, ())
self.assertEqual(v.build, ())
- v = base.Version('1.0.1-pre+build')
+ v = base.Version('1.1.0-pre+build')
v = v.next_minor()
self.assertEqual(v.major, 1)
self.assertEqual(v.minor, 1)
@@ -265,35 +366,48 @@ class VersionTestCase(unittest.TestCase):
v = v.next_patch()
self.assertEqual(v.major, 1)
self.assertEqual(v.minor, 1)
- self.assertEqual(v.patch, 1)
+ self.assertEqual(v.patch, 0)
self.assertEqual(v.prerelease, ())
self.assertEqual(v.build, ())
+ v = base.Version('1.0.1-pre+build')
+ v = v.next_major()
+ self.assertEqual(v.major, 2)
+ self.assertEqual(v.minor, 0)
+ self.assertEqual(v.patch, 0)
+ self.assertEqual(v.prerelease, ())
+ self.assertEqual(v.build, ())
-class SpecItemTestCase(unittest.TestCase):
- invalids = [
- '<=0.1.1+build3',
- '<=0.1.1+',
- '>0.2.3-rc2+',
- ]
+ v = base.Version('1.0.1-pre+build')
+ v = v.next_minor()
+ self.assertEqual(v.major, 1)
+ self.assertEqual(v.minor, 1)
+ self.assertEqual(v.patch, 0)
+ self.assertEqual(v.prerelease, ())
+ self.assertEqual(v.build, ())
+
+ v = base.Version('1.0.1-pre+build')
+ v = v.next_patch()
+ self.assertEqual(v.major, 1)
+ self.assertEqual(v.minor, 0)
+ self.assertEqual(v.patch, 1)
+ self.assertEqual(v.prerelease, ())
+ self.assertEqual(v.build, ())
- def test_invalids(self):
- for invalid in self.invalids:
- with self.assertRaises(ValueError, msg="SpecItem(%r) should be invalid" % invalid):
- _v = base.SpecItem(invalid)
+class SpecItemTestCase(unittest.TestCase):
components = {
'==0.1.0': (base.SpecItem.KIND_EQUAL, 0, 1, 0, None, None),
'==0.1.2-rc3': (base.SpecItem.KIND_EQUAL, 0, 1, 2, ('rc3',), None),
'==0.1.2+build3.14': (base.SpecItem.KIND_EQUAL, 0, 1, 2, (), ('build3', '14')),
- '<=0.1.1': (base.SpecItem.KIND_LTE, 0, 1, 1, None, None),
+ '<=0.1.1+': (base.SpecItem.KIND_LTE, 0, 1, 1, (), ()),
'<0.1.1': (base.SpecItem.KIND_LT, 0, 1, 1, None, None),
'<=0.1.1': (base.SpecItem.KIND_LTE, 0, 1, 1, None, None),
- '!=0.1.1+': (base.SpecItem.KIND_NEQ, 0, 1, 1, (), ()),
'<=0.1.1-': (base.SpecItem.KIND_LTE, 0, 1, 1, (), None),
'>=0.2.3-rc2': (base.SpecItem.KIND_GTE, 0, 2, 3, ('rc2',), None),
+ '>0.2.3-rc2+': (base.SpecItem.KIND_GT, 0, 2, 3, ('rc2',), ()),
'>=2.0.0': (base.SpecItem.KIND_GTE, 2, 0, 0, None, None),
- '!=0.1.1+rc3': (base.SpecItem.KIND_NEQ, 0, 1, 1, (), ('rc3',)),
+ '!=0.1.1+': (base.SpecItem.KIND_NEQ, 0, 1, 1, (), ()),
'!=0.3.0': (base.SpecItem.KIND_NEQ, 0, 3, 0, None, None),
}
@@ -345,17 +459,13 @@ class SpecItemTestCase(unittest.TestCase):
['0.2.3-rc3', '0.2.3', '0.2.3+1', '0.2.3-rc2', '0.2.3-rc2+1'],
['0.2.3-rc1', '0.2.2'],
),
- '==0.2.3+': (
- ['0.2.3'],
- ['0.2.3+rc1', '0.2.4', '0.2.3-rc2'],
- ),
- '!=0.2.3-rc2+12': (
- ['0.2.3-rc3', '0.2.3', '0.2.3-rc2+1', '0.2.4', '0.2.3-rc3+12'],
- ['0.2.3-rc2+12'],
+ '>0.2.3-rc2+': (
+ ['0.2.3-rc3', '0.2.3', '0.2.3-rc2+1'],
+ ['0.2.3-rc1', '0.2.2', '0.2.3-rc2'],
),
- '==2.0.0+b1': (
- ['2.0.0+b1'],
- ['2.1.1', '1.9.9', '1.9.9999', '2.0.0', '2.0.0-rc4'],
+ '>2.0.0+': (
+ ['2.1.1', '2.0.0+b1', '3.1.4'],
+ ['1.9.9', '1.9.9999', '2.0.0', '2.0.0-rc4'],
),
'!=0.1.1': (
['0.1.2', '0.1.0', '1.4.2'],
@@ -454,17 +564,13 @@ class SpecTestCase(unittest.TestCase):
self.assertTrue(repr(base.SpecItem(spec_text)) in repr(spec_list))
matches = {
- # At least 0.1.1 including pre-releases, less than 0.1.2 excluding pre-releases
'>=0.1.1,<0.1.2': (
['0.1.1', '0.1.1+4', '0.1.1-alpha'],
['0.1.2-alpha', '0.1.2', '1.3.4'],
),
- # At least 0.1.0 without pre-releases, less than 0.1.4 excluding pre-releases,
- # neither 0.1.3-rc1 nor any build of that version,
- # not 0.1.0+b3 precisely
- '>=0.1.0-,!=0.1.3-rc1,!=0.1.0+b3,<0.1.4': (
+ '>=0.1.0+,!=0.1.3-rc1,<0.1.4': (
['0.1.1', '0.1.0+b4', '0.1.2', '0.1.3-rc2'],
- ['0.0.1', '0.1.0+b3', '0.1.4', '0.1.4-alpha', '0.1.3-rc1+4',
+ ['0.0.1', '0.1.4', '0.1.4-alpha', '0.1.3-rc1+4',
'0.1.0-alpha', '0.2.2', '0.1.4-rc1'],
),
}
diff --git a/tests/test_match.py b/tests/test_match.py
index 6926e0a..155a612 100755
--- a/tests/test_match.py
+++ b/tests/test_match.py
@@ -15,7 +15,6 @@ class MatchTestCase(unittest.TestCase):
'<=0.1.4a',
'>0.1.1.1',
'~0.1.2-rc23,1',
- '<0.1.2-rc1.3-14.15+build.2012-01-01.11h34',
]
valid_specs = [
@@ -26,7 +25,7 @@ class MatchTestCase(unittest.TestCase):
'>0.1.2-rc1',
'>=0.1.2-rc1.3.4',
'==0.1.2+build42-12.2012-01-01.12h23',
- '!=0.1.2-rc1.3-14.15+build.2012-01-01.11h34',
+ '<0.1.2-rc1.3-14.15+build.2012-01-01.11h34',
]
matches = {
@@ -54,19 +53,11 @@ class MatchTestCase(unittest.TestCase):
'0.1.2',
'0.1.2+build4',
],
- '!=0.1.2+': [
- '0.1.2+1',
- '0.1.2-rc1',
- ],
- '!=0.1.2-': [
+ '<0.1.2+': [
'0.1.1',
'0.1.2-rc1',
- ],
- '!=0.1.2+345': [
- '0.1.1',
- '0.1.2-rc1+345',
- '0.1.2+346',
- '0.2.3+345',
+ '0.1.2-rc1.3.4',
+ '0.1.2-rc1+build4.5',
],
'>=0.1.1': [
'0.1.1',
@@ -81,6 +72,12 @@ class MatchTestCase(unittest.TestCase):
'0.2.0',
'1.0.0',
],
+ '>0.1.1+': [
+ '0.1.1+b2',
+ '0.1.2-rc1',
+ '1.1.1',
+ '2.0.4',
+ ],
'<0.1.1-': [
'0.1.1-alpha',
'0.1.1-rc4',
@@ -90,8 +87,7 @@ class MatchTestCase(unittest.TestCase):
def test_invalid(self):
for invalid in self.invalid_specs:
- with self.assertRaises(ValueError, msg="Spec(%r) should be invalid" % invalid):
- semantic_version.Spec(invalid)
+ self.assertRaises(ValueError, semantic_version.Spec, invalid)
def test_simple(self):
for valid in self.valid_specs:
@@ -126,9 +122,11 @@ class MatchTestCase(unittest.TestCase):
self.assertFalse(version in strict_spec, "%r should not be in %r" % (version, strict_spec))
def test_build_check(self):
- spec = semantic_version.Spec('<=0.1.1-rc1')
+ strict_spec = semantic_version.Spec('<=0.1.1-rc1+')
+ lax_spec = semantic_version.Spec('<=0.1.1-rc1')
version = semantic_version.Version('0.1.1-rc1+4.2')
- self.assertTrue(version in spec, "%r should be in %r" % (version, spec))
+ self.assertTrue(version in lax_spec, "%r should be in %r" % (version, lax_spec))
+ self.assertFalse(version in strict_spec, "%r should not be in %r" % (version, strict_spec))
if __name__ == '__main__': # pragma: no cover
diff --git a/tests/test_parsing.py b/tests/test_parsing.py
index c7651d2..5112ca5 100755
--- a/tests/test_parsing.py
+++ b/tests/test_parsing.py
@@ -3,7 +3,6 @@
# Copyright (c) 2012-2014 The python-semanticversion project
# This code is distributed under the two-clause BSD License.
-import itertools
import unittest
import semantic_version
@@ -45,8 +44,12 @@ class ComparisonTestCase(unittest.TestCase):
'1.0.0-beta.2',
'1.0.0-beta.11',
'1.0.0-rc.1',
+ '1.0.0-rc.1+build.1',
'1.0.0',
+ '1.0.0+0.3.7',
'1.3.7+build',
+ '1.3.7+build.2.b8f12d7',
+ '1.3.7+build.11.e0f985a',
]
def test_comparisons(self):
@@ -64,36 +67,6 @@ class ComparisonTestCase(unittest.TestCase):
cmp_res = -1 if i < j else (1 if i > j else 0)
self.assertEqual(cmp_res, semantic_version.compare(first, second))
- unordered = [
- [
- '1.0.0-rc.1',
- '1.0.0-rc.1+build.1',
- ],
- [
- '1.0.0',
- '1.0.0+0.3.7',
- ],
- [
- '1.3.7',
- '1.3.7+build',
- '1.3.7+build.2.b8f12d7',
- '1.3.7+build.11.e0f985a',
- ],
- ]
-
- def test_unordered(self):
- for group in self.unordered:
- for a, b in itertools.combinations(group, 2):
- v1 = semantic_version.Version(a)
- v2 = semantic_version.Version(b)
- self.assertTrue(v1 == v1, "%r != %r" % (v1, v1))
- self.assertFalse(v1 != v1, "%r != %r" % (v1, v1))
- self.assertFalse(v1 == v2, "%r == %r" % (v1, v2))
- self.assertTrue(v1 != v2, "%r !!= %r" % (v1, v2))
- self.assertFalse(v1 < v2, "%r !< %r" % (v1, v2))
- self.assertFalse(v1 <= v2, "%r !<= %r" % (v1, v2))
- self.assertFalse(v2 > v1, "%r !> %r" % (v2, v1))
- self.assertFalse(v2 >= v1, "%r !>= %r" % (v2, v1))
if __name__ == '__main__': # pragma: no cover
unittest.main()
diff --git a/tests/test_spec.py b/tests/test_spec.py
index a13cb0b..7a645f9 100644
--- a/tests/test_spec.py
+++ b/tests/test_spec.py
@@ -154,3 +154,10 @@ class FormatTests(unittest.TestCase):
self.assertLess(Version('1.0.0-beta.2'), Version('1.0.0-beta.11'))
self.assertLess(Version('1.0.0-beta.11'), Version('1.0.0-rc.1'))
self.assertLess(Version('1.0.0-rc.1'), Version('1.0.0'))
+
+
+
+class PrecedenceTestCase(unittest.TestCase):
+ pass
+
+
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 1,
"issue_text_score": 0,
"test_score": 0
},
"num_modified_files": 6
} | 2.4 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[dev]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest",
"coverage"
],
"pre_install": null,
"python": "3.4",
"reqs_path": [
"requirements.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | attrs==22.2.0
certifi==2021.5.30
coverage==6.2
importlib-metadata==4.8.3
iniconfig==1.1.1
packaging==21.3
pluggy==1.0.0
py==1.11.0
pyparsing==3.1.4
pytest==7.0.1
-e git+https://github.com/rbarrois/python-semanticversion.git@2ed3d39c291080c61edd9139370939e1fdc3209a#egg=semantic_version
tomli==1.2.3
typing_extensions==4.1.1
zipp==3.6.0
| name: python-semanticversion
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2021.5.30=py36h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.3=he6710b0_2
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- pip=21.2.2=py36h06a4308_0
- python=3.6.13=h12debd9_1
- readline=8.2=h5eee18b_0
- setuptools=58.0.4=py36h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- wheel=0.37.1=pyhd3eb1b0_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- attrs==22.2.0
- coverage==6.2
- importlib-metadata==4.8.3
- iniconfig==1.1.1
- packaging==21.3
- pluggy==1.0.0
- py==1.11.0
- pyparsing==3.1.4
- pytest==7.0.1
- tomli==1.2.3
- typing-extensions==4.1.1
- zipp==3.6.0
prefix: /opt/conda/envs/python-semanticversion
| [
"tests/test_base.py::TopLevelTestCase::test_compare",
"tests/test_base.py::VersionTestCase::test_bump_prerelease_versions",
"tests/test_base.py::SpecItemTestCase::test_components",
"tests/test_base.py::SpecItemTestCase::test_matches",
"tests/test_base.py::SpecTestCase::test_matches",
"tests/test_match.py::MatchTestCase::test_build_check",
"tests/test_match.py::MatchTestCase::test_match",
"tests/test_match.py::MatchTestCase::test_simple",
"tests/test_parsing.py::ComparisonTestCase::test_comparisons"
] | [] | [
"tests/test_base.py::ComparisonTestCase::test_identifier_cmp",
"tests/test_base.py::ComparisonTestCase::test_identifier_list_cmp",
"tests/test_base.py::TopLevelTestCase::test_match",
"tests/test_base.py::TopLevelTestCase::test_validate_invalid",
"tests/test_base.py::TopLevelTestCase::test_validate_valid",
"tests/test_base.py::VersionTestCase::test_bump_clean_versions",
"tests/test_base.py::VersionTestCase::test_compare_partial_to_self",
"tests/test_base.py::VersionTestCase::test_compare_to_self",
"tests/test_base.py::VersionTestCase::test_hash",
"tests/test_base.py::VersionTestCase::test_invalid_comparisons",
"tests/test_base.py::VersionTestCase::test_parsing",
"tests/test_base.py::VersionTestCase::test_parsing_partials",
"tests/test_base.py::VersionTestCase::test_str",
"tests/test_base.py::VersionTestCase::test_str_partials",
"tests/test_base.py::SpecItemTestCase::test_equality",
"tests/test_base.py::SpecItemTestCase::test_hash",
"tests/test_base.py::SpecItemTestCase::test_to_string",
"tests/test_base.py::CoerceTestCase::test_coerce",
"tests/test_base.py::CoerceTestCase::test_invalid",
"tests/test_base.py::SpecTestCase::test_contains",
"tests/test_base.py::SpecTestCase::test_equality",
"tests/test_base.py::SpecTestCase::test_filter_compatible",
"tests/test_base.py::SpecTestCase::test_filter_empty",
"tests/test_base.py::SpecTestCase::test_filter_incompatible",
"tests/test_base.py::SpecTestCase::test_hash",
"tests/test_base.py::SpecTestCase::test_parsing",
"tests/test_base.py::SpecTestCase::test_parsing_split",
"tests/test_base.py::SpecTestCase::test_select_compatible",
"tests/test_base.py::SpecTestCase::test_select_empty",
"tests/test_base.py::SpecTestCase::test_select_incompatible",
"tests/test_match.py::MatchTestCase::test_contains",
"tests/test_match.py::MatchTestCase::test_invalid",
"tests/test_match.py::MatchTestCase::test_prerelease_check",
"tests/test_parsing.py::ParsingTestCase::test_invalid",
"tests/test_parsing.py::ParsingTestCase::test_simple",
"tests/test_spec.py::FormatTests::test_build",
"tests/test_spec.py::FormatTests::test_major_minor_patch",
"tests/test_spec.py::FormatTests::test_precedence",
"tests/test_spec.py::FormatTests::test_prerelease"
] | [] | BSD 2-Clause "Simplified" License | 240 |
|
pypa__twine-131 | a0c87357d9d5d588082c9a59f6efc6f6bc3d3498 | 2015-09-19 01:38:19 | f487b7da9c42e4932bc33bf10d70cdc59fd16fd5 | diff --git a/twine/package.py b/twine/package.py
index 230e5ac..e80116a 100644
--- a/twine/package.py
+++ b/twine/package.py
@@ -143,9 +143,10 @@ class PackageFile(object):
def sign(self, sign_with, identity):
print("Signing {0}".format(self.basefilename))
- gpg_args = (sign_with, "--detach-sign", "-a", self.filename)
+ gpg_args = (sign_with, "--detach-sign")
if identity:
gpg_args += ("--local-user", identity)
+ gpg_args += ("-a", self.filename)
subprocess.check_call(gpg_args)
with open(self.signed_filename, "rb") as gpg:
| Signing fails in version 1.6.0
Signing has stopped to function in the latest version, with the following message:
```
You need a passphrase to unlock the secret key for
user: "foo bar <[email protected]>"
1024-bit DSA key, ID ABCDEFGH, created 2015-01-01
gpg: can't open `--local-user': No such file or directory
gpg: signing failed: file open error
```
1.5.0 is ok. | pypa/twine | diff --git a/tests/test_package.py b/tests/test_package.py
index 7b15ba9..fcc827a 100644
--- a/tests/test_package.py
+++ b/tests/test_package.py
@@ -53,5 +53,5 @@ def test_sign_file_with_identity(monkeypatch):
pkg.sign('gpg', 'identity')
except IOError:
pass
- args = ('gpg', '--detach-sign', '-a', filename, '--local-user', 'identity')
+ args = ('gpg', '--detach-sign', '--local-user', 'identity', '-a', filename)
assert replaced_check_call.calls == [pretend.call(args)]
| {
"commit_name": "head_commit",
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true,
"llm_score": {
"difficulty_score": 0,
"issue_text_score": 1,
"test_score": 0
},
"num_modified_files": 1
} | 1.6 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "pytest",
"pip_packages": [
"pytest",
"coverage",
"pretend",
"flake8"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.9",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | certifi==2025.1.31
charset-normalizer==3.4.1
coverage==7.8.0
exceptiongroup @ file:///croot/exceptiongroup_1706031385326/work
flake8==7.2.0
idna==3.10
iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work
mccabe==0.7.0
packaging @ file:///croot/packaging_1734472117206/work
pkginfo==1.12.1.2
pluggy @ file:///croot/pluggy_1733169602837/work
pretend==1.0.9
pycodestyle==2.13.0
pyflakes==3.3.1
pytest @ file:///croot/pytest_1738938843180/work
requests==2.32.3
requests-toolbelt==1.0.0
tomli @ file:///opt/conda/conda-bld/tomli_1657175507142/work
-e git+https://github.com/pypa/twine.git@a0c87357d9d5d588082c9a59f6efc6f6bc3d3498#egg=twine
urllib3==2.3.0
| name: twine
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- exceptiongroup=1.2.0=py39h06a4308_0
- iniconfig=1.1.1=pyhd3eb1b0_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=3.0.16=h5eee18b_0
- packaging=24.2=py39h06a4308_0
- pip=25.0=py39h06a4308_0
- pluggy=1.5.0=py39h06a4308_0
- pytest=8.3.4=py39h06a4308_0
- python=3.9.21=he870216_1
- readline=8.2=h5eee18b_0
- setuptools=75.8.0=py39h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- tomli=2.0.1=py39h06a4308_0
- tzdata=2025a=h04d1e81_0
- wheel=0.45.1=py39h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- certifi==2025.1.31
- charset-normalizer==3.4.1
- coverage==7.8.0
- flake8==7.2.0
- idna==3.10
- mccabe==0.7.0
- pkginfo==1.12.1.2
- pretend==1.0.9
- pycodestyle==2.13.0
- pyflakes==3.3.1
- requests==2.32.3
- requests-toolbelt==1.0.0
- urllib3==2.3.0
prefix: /opt/conda/envs/twine
| [
"tests/test_package.py::test_sign_file_with_identity"
] | [] | [
"tests/test_package.py::test_sign_file"
] | [] | Apache License 2.0 | 241 |
|
tomerfiliba__plumbum-225 | 8d19a7b6c1f1a9caa2eb03f461e9a31a085d7ad5 | 2015-09-21 23:27:31 | 8d19a7b6c1f1a9caa2eb03f461e9a31a085d7ad5 | diff --git a/docs/cli.rst b/docs/cli.rst
index 559fa94..18e46a5 100644
--- a/docs/cli.rst
+++ b/docs/cli.rst
@@ -198,6 +198,28 @@ these values. Here's an example ::
All of these convert the argument to a :ref:`local path <guide-paths>`.
+Positional Arguements
+^^^^^^^^^^^^^^^^^^^^^
+
+You can supply positional argument validators using the ``cli.positional`` decorator. Simply
+pass the validators in the decorator matching the names in the main function. For example::
+
+ class MyApp(cli.Application):
+ @positional(cli.ExistingFile, cli.NonexistantPath)
+ def main(self, infile, *outfiles):
+ "infile is a path, outfiles are a list of paths, proper errors are given"
+
+If you only want to run your application in Python 3, you can also use annotations to
+specify the validators. For example::
+
+ class MyApp(cli.Application):
+ def main(self, infile : cli.ExistingFile, *outfiles : cli.NonexistantPath):
+ "Identical to above MyApp"
+
+Annotations are ignored if the positional decorator is present.
+
+.. versionadded:: 1.5.0
+
Repeatable Switches
^^^^^^^^^^^^^^^^^^^
Many times, you would like to allow a certain switch to be given multiple times. For instance,
diff --git a/plumbum/cli/__init__.py b/plumbum/cli/__init__.py
index 7ac0e6e..068aaef 100644
--- a/plumbum/cli/__init__.py
+++ b/plumbum/cli/__init__.py
@@ -1,3 +1,3 @@
-from plumbum.cli.switches import SwitchError, switch, autoswitch, SwitchAttr, Flag, CountOf
+from plumbum.cli.switches import SwitchError, switch, autoswitch, SwitchAttr, Flag, CountOf, positional
from plumbum.cli.switches import Range, Set, ExistingDirectory, ExistingFile, NonexistentPath, Predicate
from plumbum.cli.application import Application, ColorfulApplication
diff --git a/plumbum/cli/application.py b/plumbum/cli/application.py
index 3600683..8d7786a 100644
--- a/plumbum/cli/application.py
+++ b/plumbum/cli/application.py
@@ -1,7 +1,6 @@
from __future__ import division, print_function, absolute_import
import os
import sys
-import inspect
import functools
from textwrap import TextWrapper
from collections import defaultdict
@@ -299,7 +298,7 @@ class Application(object):
continue
# handle argument
- val = self._handle_argument(val, swinfo, name)
+ val = self._handle_argument(val, swinfo.argtype, name)
if swinfo.func in swfuncs:
if swinfo.list:
@@ -329,7 +328,7 @@ class Application(object):
if swinfo.func in swfuncs:
continue # skip if overridden by command line arguments
- val = self._handle_argument(envval, swinfo, env)
+ val = self._handle_argument(envval, swinfo.argtype, env)
envname = "$%s" % (env,)
if swinfo.list:
# multiple values over environment variables are not supported,
@@ -343,18 +342,19 @@ class Application(object):
return swfuncs, tailargs
@classmethod
- def autocomplete(self, argv):
+ def autocomplete(cls, argv):
"""This is supplied to make subclassing and testing argument completion methods easier"""
pass
- def _handle_argument(self, val, swinfo, name):
- if swinfo.argtype:
+ @staticmethod
+ def _handle_argument(val, argtype, name):
+ if argtype:
try:
- return swinfo.argtype(val)
+ return argtype(val)
except (TypeError, ValueError):
ex = sys.exc_info()[1] # compat
raise WrongArgumentType("Argument of %s expected to be %r, not %r:\n %r" % (
- name, swinfo.argtype, val, ex))
+ name, argtype, val, ex))
else:
return NotImplemented
@@ -388,20 +388,58 @@ class Application(object):
raise SwitchCombinationError("Given %s, the following are invalid %r" %
(swfuncs[func].swname, [swfuncs[f].swname for f in invalid]))
- m_args, m_varargs, _, m_defaults = six.getargspec(self.main)
- max_args = six.MAXSIZE if m_varargs else len(m_args) - 1
- min_args = len(m_args) - 1 - (len(m_defaults) if m_defaults else 0)
+ m = six.getfullargspec(self.main)
+ max_args = six.MAXSIZE if m.varargs else len(m.args) - 1
+ min_args = len(m.args) - 1 - (len(m.defaults) if m.defaults else 0)
if len(tailargs) < min_args:
raise PositionalArgumentsError("Expected at least %d positional arguments, got %r" %
(min_args, tailargs))
elif len(tailargs) > max_args:
raise PositionalArgumentsError("Expected at most %d positional arguments, got %r" %
- (max_args, tailargs))
+ (max_args, tailargs))
+
+ # Positional arguement validataion
+ if hasattr(self.main, 'positional'):
+ tailargs = self._positional_validate(tailargs, self.main.positional, self.main.positional_varargs, m.args[1:], m.varargs)
+
+ elif hasattr(m, 'annotations'):
+ args_names = list(m.args[1:])
+ positional = [None]*len(args_names)
+ varargs = None
+
+
+ # All args are positional, so convert kargs to positional
+ for item in m.annotations:
+ if item == m.varargs:
+ varargs = m.annotations[item]
+ else:
+ positional[args_names.index(item)] = m.annotations[item]
+
+ tailargs = self._positional_validate(tailargs, positional, varargs,
+ m.args[1:], m.varargs)
ordered = [(f, a) for _, f, a in
sorted([(sf.index, f, sf.val) for f, sf in swfuncs.items()])]
return ordered, tailargs
+ def _positional_validate(self, args, validator_list, varargs, argnames, varargname):
+ """Makes sure args follows the validation given input"""
+ out_args = list(args)
+
+ for i in range(min(len(args),len(validator_list))):
+
+ if validator_list[i] is not None:
+ out_args[i] = self._handle_argument(args[i], validator_list[i], argnames[i])
+
+ if len(args) > len(validator_list):
+ if varargs is not None:
+ out_args[len(validator_list):] = [
+ self._handle_argument(a, varargs, varargname) for a in args[len(validator_list):]]
+ else:
+ out_args[len(validator_list):] = args[len(validator_list):]
+
+ return out_args
+
@classmethod
def run(cls, argv = None, exit = True): # @ReservedAssignment
"""
@@ -473,23 +511,8 @@ class Application(object):
"""
inst = cls("")
- swfuncs = {}
- for index, (swname, val) in enumerate(switches.items(), 1):
- switch = getattr(cls, swname)
- swinfo = inst._switches_by_func[switch._switch_info.func]
- if isinstance(switch, CountOf):
- p = (range(val),)
- elif swinfo.list and not hasattr(val, "__iter__"):
- raise SwitchError("Switch %r must be a sequence (iterable)" % (swname,))
- elif not swinfo.argtype:
- # a flag
- if val not in (True, False, None, Flag):
- raise SwitchError("Switch %r is a boolean flag" % (swname,))
- p = ()
- else:
- p = (val,)
- swfuncs[swinfo.func] = SwitchParseInfo(swname, p, index)
-
+
+ swfuncs = inst._parse_kwd_args(switches)
ordered, tailargs = inst._validate_args(swfuncs, args)
for f, a in ordered:
f(inst, *a)
@@ -508,6 +531,26 @@ class Application(object):
return inst, retcode
+ def _parse_kwd_args(self, switches):
+ """Parses keywords (positional arguments), used by invoke."""
+ swfuncs = {}
+ for index, (swname, val) in enumerate(switches.items(), 1):
+ switch = getattr(type(self), swname)
+ swinfo = self._switches_by_func[switch._switch_info.func]
+ if isinstance(switch, CountOf):
+ p = (range(val),)
+ elif swinfo.list and not hasattr(val, "__iter__"):
+ raise SwitchError("Switch %r must be a sequence (iterable)" % (swname,))
+ elif not swinfo.argtype:
+ # a flag
+ if val not in (True, False, None, Flag):
+ raise SwitchError("Switch %r is a boolean flag" % (swname,))
+ p = ()
+ else:
+ p = (val,)
+ swfuncs[swinfo.func] = SwitchParseInfo(swname, p, index)
+ return swfuncs
+
def main(self, *args):
"""Implement me (no need to call super)"""
if self._subcommands:
@@ -555,13 +598,13 @@ class Application(object):
if self.DESCRIPTION:
print(self.COLOR_DISCRIPTION[self.DESCRIPTION.strip() + '\n'])
- m_args, m_varargs, _, m_defaults = six.getargspec(self.main)
- tailargs = m_args[1:] # skip self
- if m_defaults:
- for i, d in enumerate(reversed(m_defaults)):
+ m = six.getfullargspec(self.main)
+ tailargs = m.args[1:] # skip self
+ if m.defaults:
+ for i, d in enumerate(reversed(m.defaults)):
tailargs[-i - 1] = "[%s=%r]" % (tailargs[-i - 1], d)
- if m_varargs:
- tailargs.append("%s..." % (m_varargs,))
+ if m.varargs:
+ tailargs.append("%s..." % (m.varargs,))
tailargs = " ".join(tailargs)
with self.COLOR_USAGE:
diff --git a/plumbum/cli/switches.py b/plumbum/cli/switches.py
index e3fc915..2512b77 100644
--- a/plumbum/cli/switches.py
+++ b/plumbum/cli/switches.py
@@ -1,7 +1,8 @@
-import inspect
from plumbum.lib import six, getdoc
from plumbum import local
+from abc import abstractmethod
+
class SwitchError(Exception):
"""A general switch related-error (base class of all other switch errors)"""
@@ -133,7 +134,7 @@ def switch(names, argtype = None, argname = None, list = False, mandatory = Fals
def deco(func):
if argname is None:
- argspec = six.getargspec(func)[0]
+ argspec = six.getfullargspec(func).args
if len(argspec) == 2:
argname2 = argspec[1]
else:
@@ -252,10 +253,95 @@ class CountOf(SwitchAttr):
def __call__(self, inst, v):
self.__set__(inst, len(v))
+#===================================================================================================
+# Decorator for function that adds argument checking
+#===================================================================================================
+
+
+
+class positional(object):
+ """
+ Runs a validator on the main function for a class.
+ This should be used like this:
+
+ class MyApp(cli.Application):
+ @cli.positional(cli.Range(1,10), cli.ExistingFile)
+ def main(self, x, *f):
+ # x is a range, f's are all ExistingFile's)
+
+ Or, Python 3 only:
+
+ class MyApp(cli.Application):
+ def main(self, x : cli.Range(1,10), *f : cli.ExistingFile):
+ # x is a range, f's are all ExistingFile's)
+
+
+ If you do not want to validate on the annotations, use this decorator (
+ even if empty) to override annotation validation.
+
+ Validators should be callable, and should have a .choices() function with
+ possible choices. (For future argument completion, for example)
+
+ Default arguments do not go through the validator.
+
+ #TODO: Check with MyPy
+
+ """
+
+ def __init__(self, *args, **kargs):
+ self.args = args
+ self.kargs = kargs
+
+ def __call__(self, function):
+ m = six.getfullargspec(function)
+ args_names = list(m.args[1:])
+
+ positional = [None]*len(args_names)
+ varargs = None
+
+ for i in range(min(len(positional),len(self.args))):
+ positional[i] = self.args[i]
+
+ if len(args_names) + 1 == len(self.args):
+ varargs = self.args[-1]
+
+ # All args are positional, so convert kargs to positional
+ for item in self.kargs:
+ if item == m.varargs:
+ varargs = self.kargs[item]
+ else:
+ positional[args_names.index(item)] = self.kargs[item]
+
+ function.positional = positional
+ function.positional_varargs = varargs
+ return function
+
+class Validator(six.ABC):
+ __slots__ = ()
+
+ @abstractmethod
+ def __call__(self, obj):
+ "Must be implemented for a Validator to work"
+
+ def choices(self, partial=""):
+ """Should return set of valid choices, can be given optional partial info"""
+ return set()
+
+ def __repr__(self):
+ """If not overridden, will print the slots as args"""
+
+ slots = {}
+ for cls in self.__mro__:
+ for prop in getattr(cls, "__slots__", ()):
+ if prop[0] != '_':
+ slots[prop] = getattr(self, prop)
+ mystrs = ("{0} = {1}".format(name, slots[name]) for name in slots)
+ return "{0}({1})".format(self.__class__.__name__, ", ".join(mystrs))
+
#===================================================================================================
# Switch type validators
#===================================================================================================
-class Range(object):
+class Range(Validator):
"""
A switch-type validator that checks for the inclusion of a value in a certain range.
Usage::
@@ -266,6 +352,8 @@ class Range(object):
:param start: The minimal value
:param end: The maximal value
"""
+ __slots__ = ("start", "end")
+
def __init__(self, start, end):
self.start = start
self.end = end
@@ -276,18 +364,21 @@ class Range(object):
if obj < self.start or obj > self.end:
raise ValueError("Not in range [%d..%d]" % (self.start, self.end))
return obj
+ def choices(self, partial=""):
+ # TODO: Add partial handling
+ return set(range(self.start, self.end+1))
-class Set(object):
+class Set(Validator):
"""
A switch-type validator that checks that the value is contained in a defined
set of values. Usage::
class MyApp(Application):
- mode = SwitchAttr(["--mode"], Set("TCP", "UDP", case_insensitive = False))
+ mode = SwitchAttr(["--mode"], Set("TCP", "UDP", case_sensitive = False))
:param values: The set of values (strings)
- :param case_insensitive: A keyword argument that indicates whether to use case-sensitive
- comparison or not. The default is ``True``
+ :param case_sensitive: A keyword argument that indicates whether to use case-sensitive
+ comparison or not. The default is ``False``
"""
def __init__(self, *values, **kwargs):
self.case_sensitive = kwargs.pop("case_sensitive", False)
@@ -302,6 +393,9 @@ class Set(object):
if obj not in self.values:
raise ValueError("Expected one of %r" % (list(self.values.values()),))
return self.values[obj]
+ def choices(self, partial=""):
+ # TODO: Add case sensitive/insensitive parital completion
+ return set(self.values)
class Predicate(object):
"""A wrapper for a single-argument function with pretty printing"""
@@ -311,6 +405,8 @@ class Predicate(object):
return self.func.__name__
def __call__(self, val):
return self.func(val)
+ def choices(self, partial=""):
+ return set()
@Predicate
def ExistingDirectory(val):
diff --git a/plumbum/colorlib/styles.py b/plumbum/colorlib/styles.py
index 73c7938..1c5e4f3 100644
--- a/plumbum/colorlib/styles.py
+++ b/plumbum/colorlib/styles.py
@@ -10,7 +10,6 @@ With the ``Style`` class, any color can be directly called or given to a with st
from __future__ import print_function
import sys
import os
-import platform
import re
from copy import copy
from plumbum.colorlib.names import color_names, color_html
@@ -127,9 +126,6 @@ class Color(ABC):
self.exact = True
'This is false if the named color does not match the real color'
- self.use_color = True
- 'This is a toggle for color (or max representation)'
-
if None in (g,b):
if not r_or_color:
return
diff --git a/plumbum/lib.py b/plumbum/lib.py
index 35c3fc6..77c6f06 100644
--- a/plumbum/lib.py
+++ b/plumbum/lib.py
@@ -27,14 +27,13 @@ class six(object):
A light-weight version of six (which works on IronPython)
"""
PY3 = sys.version_info[0] >= 3
- ABC = ABCMeta('ABC', (object,), {'__module__':__name__})
+ ABC = ABCMeta('ABC', (object,), {'__module__':__name__, '__slots__':()})
- # Be sure to use named-tuple access, so that different order doesn't affect usage
+ # Be sure to use named-tuple access, so that usage is not affected
try:
- getargspec = staticmethod(inspect.getargspec)
+ getfullargspec = staticmethod(inspect.getfullargspec)
except AttributeError:
- getargspec = staticmethod(lambda func: inspect.getfullargspec(func)[:4])
-
+ getfullargspec = staticmethod(inspect.getargspec) # extra fields will not be available
if PY3:
integer_types = (int,)
| Feature request: Validator on main args
I've been digging around in the src, and I don't see a way to provide validators on the positional input arguments. Since the validators are cleanly implemented, this seems to work pretty well:
```python
def main(self, outfile, *srcfiles):
outfile = cli.ExistingFile(outfile)
srcfiles = map(cli.ExistingFile, srcfiles)
```
But is there a better, integrated way of doing this? I can think of two options. First, a python3 only way would be to use annotations, like so:
```python
def main(self, outfile : cli.ExistingFile , *srcfiles : cli.ExistingFile):
```
This has the advantage of being clean and integrated, and looks to be pretty easy to implement without affecting the library usage in Python2 (just try getargspec, and if there's an annotation, that fails, so then getfullargspec works), but has the minor downfall that the application now is Python3 only. Another minor downfall is this is a use of annotations that does not fall under PEP 0484.
Second, a decorator, similar to the switches, but for the main function and built for multiple args (a little like Slots in PyQT):
```python
@cli.main_validators(cli.ExistingFile, cli.ExistingFile)
def main(self, outfile, *srcfiles):
```
A very simple, incomplete implementation to show that this is possible:
```python
import decorator
def main_validator(*types)
@decorator.decorator
def main_validator(func, *args, **kargs):
newargs = []
for i in range(len(args)):
if isinstance(args[i], str):
newargs.append(types[i](args[i]))
else:
newargs.append(list(map(types[i],args[i])))
return func(*newargs, **kargs)
```
Just a suggestion! Thanks for such a great library. | tomerfiliba/plumbum | diff --git a/tests/test_cli.py b/tests/test_cli.py
index 22d2f01..674074f 100644
--- a/tests/test_cli.py
+++ b/tests/test_cli.py
@@ -1,11 +1,11 @@
-import sys
import unittest
-from plumbum import cli
import time
from plumbum import cli, local
from plumbum.cli.terminal import ask, choose, hexdump, Progress
-from plumbum.lib import six, captured_stdout, StringIO
+from plumbum.lib import captured_stdout, ensure_skipIf
+
+ensure_skipIf(unittest)
class TestApp(cli.Application):
@cli.switch(["a"])
@@ -28,6 +28,8 @@ class TestApp(cli.Application):
self.eggs = "lalala"
self.eggs = old
self.tailargs = args
+
+
class Geet(cli.Application):
debug = cli.Flag("--debug")
diff --git a/tests/test_validate.py b/tests/test_validate.py
new file mode 100644
index 0000000..42f60ea
--- /dev/null
+++ b/tests/test_validate.py
@@ -0,0 +1,107 @@
+# -*- coding: utf-8 -*-
+from __future__ import print_function, division
+import unittest
+from plumbum import cli
+from plumbum.lib import captured_stdout
+from plumbum.lib import six
+
+class TestValidator(unittest.TestCase):
+ def test_named(self):
+ class Try(object):
+ @cli.positional(x=abs, y=str)
+ def main(selfy, x, y):
+ pass
+
+ self.assertEqual(Try.main.positional, [abs, str])
+ self.assertEqual(Try.main.positional_varargs, None)
+
+ def test_position(self):
+ class Try(object):
+ @cli.positional(abs, str)
+ def main(selfy, x, y):
+ pass
+
+ self.assertEqual(Try.main.positional, [abs, str])
+ self.assertEqual(Try.main.positional_varargs, None)
+
+ def test_mix(self):
+ class Try(object):
+ @cli.positional(abs, str, d=bool)
+ def main(selfy, x, y, z, d):
+ pass
+
+ self.assertEqual(Try.main.positional, [abs, str, None, bool])
+ self.assertEqual(Try.main.positional_varargs, None)
+
+ def test_var(self):
+ class Try(object):
+ @cli.positional(abs, str, int)
+ def main(selfy, x, y, *g):
+ pass
+
+ self.assertEqual(Try.main.positional, [abs, str])
+ self.assertEqual(Try.main.positional_varargs, int)
+
+ def test_defaults(self):
+ class Try(object):
+ @cli.positional(abs, str)
+ def main(selfy, x, y = 'hello'):
+ pass
+
+ self.assertEqual(Try.main.positional, [abs, str])
+
+
+class TestProg(unittest.TestCase):
+ def test_prog(self):
+ class MainValidator(cli.Application):
+ @cli.positional(int, int, int)
+ def main(self, myint, myint2, *mylist):
+ print(repr(myint), myint2, mylist)
+
+ with captured_stdout() as stream:
+ _, rc = MainValidator.run(["prog", "1", "2", '3', '4', '5'], exit = False)
+ self.assertEqual(rc, 0)
+ self.assertEqual("1 2 (3, 4, 5)", stream.getvalue().strip())
+
+
+ def test_failure(self):
+ class MainValidator(cli.Application):
+ @cli.positional(int, int, int)
+ def main(self, myint, myint2, *mylist):
+ print(myint, myint2, mylist)
+ with captured_stdout() as stream:
+ _, rc = MainValidator.run(["prog", "1.2", "2", '3', '4', '5'], exit = False)
+ self.assertEqual(rc, 2)
+ value = stream.getvalue().strip()
+ self.assertTrue("'int'>, not '1.2':" in value)
+ self.assertTrue(" 'int'>, not '1.2':" in value)
+ self.assertTrue('''ValueError("invalid literal for int() with base 10: '1.2'"''' in value)
+
+ def test_defaults(self):
+ class MainValidator(cli.Application):
+ @cli.positional(int, int)
+ def main(self, myint, myint2=2):
+ print(repr(myint), repr(myint2))
+
+ with captured_stdout() as stream:
+ _, rc = MainValidator.run(["prog", "1"], exit = False)
+ self.assertEqual(rc, 0)
+ self.assertEqual("1 2", stream.getvalue().strip())
+
+ with captured_stdout() as stream:
+ _, rc = MainValidator.run(["prog", "1", "3"], exit = False)
+ self.assertEqual(rc, 0)
+ self.assertEqual("1 3", stream.getvalue().strip())
+
+# Unfortionatly, Py3 anotations are a syntax error in Py2, so using exec to add test for Py3
+if six.PY3:
+ exec("""
+class Main3Validator(cli.Application):
+ def main(self, myint:int, myint2:int, *mylist:int):
+ print(myint, myint2, mylist)
+class TestProg3(unittest.TestCase):
+ def test_prog(self):
+ with captured_stdout() as stream:
+ _, rc = Main3Validator.run(["prog", "1", "2", '3', '4', '5'], exit = False)
+ self.assertEqual(rc, 0)
+ self.assertIn("1 2 (3, 4, 5)", stream.getvalue())""")
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 2,
"issue_text_score": 2,
"test_score": 3
},
"num_modified_files": 6
} | 1.5 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "paramiko",
"pip_packages": [
"pytest",
"pytest-cov",
"pytest-xdist",
"pytest-mock",
"pytest-asyncio",
"paramiko"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.5",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | attrs==22.2.0
bcrypt @ file:///tmp/build/80754af9/bcrypt_1597936153616/work
certifi==2021.5.30
cffi @ file:///tmp/build/80754af9/cffi_1625814693874/work
coverage==6.2
cryptography @ file:///tmp/build/80754af9/cryptography_1635366128178/work
execnet==1.9.0
importlib-metadata==4.8.3
iniconfig==1.1.1
packaging==21.3
paramiko @ file:///opt/conda/conda-bld/paramiko_1640109032755/work
pluggy==1.0.0
-e git+https://github.com/tomerfiliba/plumbum.git@8d19a7b6c1f1a9caa2eb03f461e9a31a085d7ad5#egg=plumbum
py==1.11.0
pycparser @ file:///tmp/build/80754af9/pycparser_1636541352034/work
PyNaCl @ file:///tmp/build/80754af9/pynacl_1595009112226/work
pyparsing==3.1.4
pytest==7.0.1
pytest-asyncio==0.16.0
pytest-cov==4.0.0
pytest-mock==3.6.1
pytest-xdist==3.0.2
six @ file:///tmp/build/80754af9/six_1644875935023/work
tomli==1.2.3
typing_extensions==4.1.1
zipp==3.6.0
| name: plumbum
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- bcrypt=3.2.0=py36h7b6447c_0
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2021.5.30=py36h06a4308_0
- cffi=1.14.6=py36h400218f_0
- cryptography=35.0.0=py36hd23ed53_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.3=he6710b0_2
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libsodium=1.0.18=h7b6447c_0
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- paramiko=2.8.1=pyhd3eb1b0_0
- pip=21.2.2=py36h06a4308_0
- pycparser=2.21=pyhd3eb1b0_0
- pynacl=1.4.0=py36h7b6447c_1
- python=3.6.13=h12debd9_1
- readline=8.2=h5eee18b_0
- setuptools=58.0.4=py36h06a4308_0
- six=1.16.0=pyhd3eb1b0_1
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- wheel=0.37.1=pyhd3eb1b0_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- attrs==22.2.0
- coverage==6.2
- execnet==1.9.0
- importlib-metadata==4.8.3
- iniconfig==1.1.1
- packaging==21.3
- pluggy==1.0.0
- py==1.11.0
- pyparsing==3.1.4
- pytest==7.0.1
- pytest-asyncio==0.16.0
- pytest-cov==4.0.0
- pytest-mock==3.6.1
- pytest-xdist==3.0.2
- tomli==1.2.3
- typing-extensions==4.1.1
- zipp==3.6.0
prefix: /opt/conda/envs/plumbum
| [
"tests/test_validate.py::TestValidator::test_defaults",
"tests/test_validate.py::TestValidator::test_mix",
"tests/test_validate.py::TestValidator::test_named",
"tests/test_validate.py::TestValidator::test_position",
"tests/test_validate.py::TestValidator::test_var",
"tests/test_validate.py::TestProg::test_defaults",
"tests/test_validate.py::TestProg::test_failure",
"tests/test_validate.py::TestProg::test_prog",
"tests/test_validate.py::TestProg3::test_prog"
] | [] | [
"tests/test_cli.py::CLITest::test_default_main",
"tests/test_cli.py::CLITest::test_env_var",
"tests/test_cli.py::CLITest::test_failures",
"tests/test_cli.py::CLITest::test_invoke",
"tests/test_cli.py::CLITest::test_lazy_subcommand",
"tests/test_cli.py::CLITest::test_mandatory_env_var",
"tests/test_cli.py::CLITest::test_meta_switches",
"tests/test_cli.py::CLITest::test_okay",
"tests/test_cli.py::CLITest::test_reset_switchattr",
"tests/test_cli.py::CLITest::test_subcommands",
"tests/test_cli.py::CLITest::test_unbind",
"tests/test_cli.py::TestTerminal::test_ask",
"tests/test_cli.py::TestTerminal::test_choose",
"tests/test_cli.py::TestTerminal::test_hexdump",
"tests/test_cli.py::TestTerminal::test_progress"
] | [] | MIT License | 242 |
|
ipython__ipykernel-59 | 4cda22a855a3e6833fac5ea1ee229eea0a444be6 | 2015-09-22 00:21:05 | 4cda22a855a3e6833fac5ea1ee229eea0a444be6 | diff --git a/ipykernel/kernelspec.py b/ipykernel/kernelspec.py
index 1d8541f..0203a87 100644
--- a/ipykernel/kernelspec.py
+++ b/ipykernel/kernelspec.py
@@ -153,7 +153,7 @@ class InstallIPythonKernelSpecApp(Application):
opts = parser.parse_args(self.argv)
try:
dest = install(user=opts.user, kernel_name=opts.name, prefix=opts.prefix,
- dispay_name=opts.display_name,
+ display_name=opts.display_name,
)
except OSError as e:
if e.errno == errno.EACCES:
| Typo in install_kernelspec causes to break
#57 causes
`The command "python -m ipykernel.kernelspec --user" failed and exited with 1 during .`
as reported in https://travis-ci.org/jupyter/nbconvert/jobs/81479990.
Working on a fix + test now. | ipython/ipykernel | diff --git a/ipykernel/tests/test_kernelspec.py b/ipykernel/tests/test_kernelspec.py
index 409802c..c849436 100644
--- a/ipykernel/tests/test_kernelspec.py
+++ b/ipykernel/tests/test_kernelspec.py
@@ -7,7 +7,7 @@ import os
import shutil
import sys
import tempfile
-
+
try:
from unittest import mock
except ImportError:
@@ -20,6 +20,7 @@ from ipykernel.kernelspec import (
get_kernel_dict,
write_kernel_spec,
install,
+ InstallIPythonKernelSpecApp,
KERNEL_NAME,
RESOURCES,
)
@@ -75,6 +76,17 @@ def test_write_kernel_spec_path():
shutil.rmtree(path)
+def test_install_kernelspec():
+
+ path = tempfile.mkdtemp()
+ try:
+ test = InstallIPythonKernelSpecApp.launch_instance(argv=['--prefix', path])
+ assert_is_spec(os.path.join(
+ path, 'share', 'jupyter', 'kernels', KERNEL_NAME))
+ finally:
+ shutil.rmtree(path)
+
+
def test_install_user():
tmp = tempfile.mkdtemp()
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_short_problem_statement",
"has_hyperlinks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 0,
"issue_text_score": 3,
"test_score": 0
},
"num_modified_files": 1
} | 4.0 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "pytest",
"pip_packages": [
"nose",
"nose-warnings-filters",
"pytest"
],
"pre_install": null,
"python": "3.5",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | attrs @ file:///opt/conda/conda-bld/attrs_1642510447205/work
backcall==0.2.0
certifi==2021.5.30
decorator==5.1.1
entrypoints==0.4
importlib-metadata @ file:///tmp/build/80754af9/importlib-metadata_1631916693255/work
iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work
-e git+https://github.com/ipython/ipykernel.git@4cda22a855a3e6833fac5ea1ee229eea0a444be6#egg=ipykernel
ipython==7.16.3
ipython-genutils==0.2.0
jedi==0.17.2
jupyter-client==7.1.2
jupyter-core==4.9.2
more-itertools @ file:///tmp/build/80754af9/more-itertools_1637733554872/work
nest-asyncio==1.6.0
nose==1.3.7
nose-warnings-filters==0.1.5
packaging @ file:///tmp/build/80754af9/packaging_1637314298585/work
parso==0.7.1
pexpect==4.9.0
pickleshare==0.7.5
pluggy @ file:///tmp/build/80754af9/pluggy_1615976315926/work
prompt-toolkit==3.0.36
ptyprocess==0.7.0
py @ file:///opt/conda/conda-bld/py_1644396412707/work
Pygments==2.14.0
pyparsing @ file:///tmp/build/80754af9/pyparsing_1635766073266/work
pytest==6.2.4
python-dateutil==2.9.0.post0
pyzmq==25.1.2
six==1.17.0
toml @ file:///tmp/build/80754af9/toml_1616166611790/work
tornado==6.1
traitlets==4.3.3
typing_extensions @ file:///opt/conda/conda-bld/typing_extensions_1647553014482/work
wcwidth==0.2.13
zipp @ file:///tmp/build/80754af9/zipp_1633618647012/work
| name: ipykernel
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- attrs=21.4.0=pyhd3eb1b0_0
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2021.5.30=py36h06a4308_0
- importlib-metadata=4.8.1=py36h06a4308_0
- importlib_metadata=4.8.1=hd3eb1b0_0
- iniconfig=1.1.1=pyhd3eb1b0_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.3=he6710b0_2
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- more-itertools=8.12.0=pyhd3eb1b0_0
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- packaging=21.3=pyhd3eb1b0_0
- pip=21.2.2=py36h06a4308_0
- pluggy=0.13.1=py36h06a4308_0
- py=1.11.0=pyhd3eb1b0_0
- pyparsing=3.0.4=pyhd3eb1b0_0
- pytest=6.2.4=py36h06a4308_2
- python=3.6.13=h12debd9_1
- readline=8.2=h5eee18b_0
- setuptools=58.0.4=py36h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- toml=0.10.2=pyhd3eb1b0_0
- typing_extensions=4.1.1=pyh06a4308_0
- wheel=0.37.1=pyhd3eb1b0_0
- xz=5.6.4=h5eee18b_1
- zipp=3.6.0=pyhd3eb1b0_0
- zlib=1.2.13=h5eee18b_1
- pip:
- backcall==0.2.0
- decorator==5.1.1
- entrypoints==0.4
- ipython==7.16.3
- ipython-genutils==0.2.0
- jedi==0.17.2
- jupyter-client==7.1.2
- jupyter-core==4.9.2
- nest-asyncio==1.6.0
- nose==1.3.7
- nose-warnings-filters==0.1.5
- parso==0.7.1
- pexpect==4.9.0
- pickleshare==0.7.5
- prompt-toolkit==3.0.36
- ptyprocess==0.7.0
- pygments==2.14.0
- python-dateutil==2.9.0.post0
- pyzmq==25.1.2
- six==1.17.0
- tornado==6.1
- traitlets==4.3.3
- wcwidth==0.2.13
prefix: /opt/conda/envs/ipykernel
| [
"ipykernel/tests/test_kernelspec.py::test_install_kernelspec"
] | [] | [
"ipykernel/tests/test_kernelspec.py::test_make_ipkernel_cmd",
"ipykernel/tests/test_kernelspec.py::test_get_kernel_dict",
"ipykernel/tests/test_kernelspec.py::test_write_kernel_spec",
"ipykernel/tests/test_kernelspec.py::test_write_kernel_spec_path",
"ipykernel/tests/test_kernelspec.py::test_install_user",
"ipykernel/tests/test_kernelspec.py::test_install"
] | [] | BSD 3-Clause "New" or "Revised" License | 243 |
|
keleshev__schema-73 | e5c489cbbbbb8671ee32c43d518fea0076563da4 | 2015-09-22 18:04:16 | eb7670f0f4615195393dc5350d49fa9a33304137 | diff --git a/README.rst b/README.rst
index b9d5d9d..b5a9ffd 100644
--- a/README.rst
+++ b/README.rst
@@ -85,7 +85,7 @@ otherwise it will raise ``SchemaError``.
>>> Schema(int).validate('123')
Traceback (most recent call last):
...
- SchemaError: '123' should be instance of 'int'
+ SchemaError: '123' should be instance of <type 'int'>
>>> Schema(object).validate('hai')
'hai'
@@ -172,7 +172,7 @@ against schemas listed inside that container:
Traceback (most recent call last):
...
SchemaError: Or(<type 'int'>, <type 'float'>) did not validate 'not int or float here'
- 'not int or float here' should be instance of 'float'
+ 'not int or float here' should be instance of <type 'float'>
Dictionaries
~~~~~~~~~~~~
@@ -232,9 +232,8 @@ data matches:
>>> from schema import Optional
>>> Schema({Optional('color', default='blue'): str,
- ... str: str}).validate({'texture': 'furry'}
- ... ) == {'color': 'blue', 'texture': 'furry'}
- True
+ ... str: str}).validate({'texture': 'furry'})
+ {'color': 'blue', 'texture': 'furry'}
Defaults are used verbatim, not passed through any validators specified in the
value.
diff --git a/schema.py b/schema.py
index bd9d4dd..9158c68 100644
--- a/schema.py
+++ b/schema.py
@@ -140,15 +140,15 @@ class Schema(object):
new[nkey] = nvalue
elif skey is not None:
if x is not None:
- raise SchemaError(['Invalid value for key %r' % key] +
+ raise SchemaError(['invalid value for key %r' % key] +
x.autos, [e] + x.errors)
required = set(k for k in s if type(k) is not Optional)
if coverage != required:
- raise SchemaError('Missing keys: %s' % ", ".join(required - coverage), e)
+ raise SchemaError('missed keys %r' % (required - coverage), e)
if len(new) != len(data):
wrong_keys = set(data.keys()) - set(new.keys())
s_wrong_keys = ', '.join('%r' % (k,) for k in sorted(wrong_keys))
- raise SchemaError('Wrong keys %s in %r' % (s_wrong_keys, data),
+ raise SchemaError('wrong keys %s in %r' % (s_wrong_keys, data),
e)
# Apply default-having optionals that haven't been used:
@@ -162,7 +162,7 @@ class Schema(object):
if isinstance(data, s):
return data
else:
- raise SchemaError('%r should be instance of %r' % (data, s.__name__), e)
+ raise SchemaError('%r should be instance of %r' % (data, s), e)
if flavor == VALIDATOR:
try:
return s.validate(data)
diff --git a/setup.py b/setup.py
index a539f6e..1bfb248 100644
--- a/setup.py
+++ b/setup.py
@@ -1,5 +1,6 @@
from setuptools import setup
+import codecs
import schema
@@ -13,7 +14,7 @@ setup(
keywords="schema json validation",
url="http://github.com/halst/schema",
py_modules=['schema'],
- long_description=open('README.rst').read(),
+ long_description=codecs.open('README.rst', 'r', 'utf-8').read(),
classifiers=[
"Development Status :: 3 - Alpha",
"Topic :: Utilities",
| Cannot install with pip3 -- README.rst contains non-ascii character.
```bash
$ pip3 install schema
Downloading/unpacking schema
Downloading schema-0.3.1.tar.gz
Running setup.py (path:/private/tmp/pip_build_bla/schema/setup.py) egg_info for package schema
Traceback (most recent call last):
File "<string>", line 17, in <module>
File "/private/tmp/pip_build_bla/schema/setup.py", line 16, in <module>
long_description=open('README.rst').read(),
File "/usr/local/Cellar/python3/3.4.2_1/Frameworks/Python.framework/Versions/3.4/lib/python3.4/encodings/ascii.py", line 26, in decode
return codecs.ascii_decode(input, self.errors)[0]
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 2360: ordinal not in range(128)
Complete output from command python setup.py egg_info:
Traceback (most recent call last):
File "<string>", line 17, in <module>
File "/private/tmp/pip_build_bla/schema/setup.py", line 16, in <module>
long_description=open('README.rst').read(),
File "/usr/local/Cellar/python3/3.4.2_1/Frameworks/Python.framework/Versions/3.4/lib/python3.4/encodings/ascii.py", line 26, in decode
return codecs.ascii_decode(input, self.errors)[0]
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 2360: ordinal not in range(128)
----------------------------------------
Cleaning up...
Command python setup.py egg_info failed with error code 1 in /private/tmp/pip_build_bla/schema
Storing debug log for failure in /Users/bla/.pip/pip.log
```
The culprit line in the readme is here:
```
Alternatively, you can just drop `schema.py` file into your project—it is self-contained.
```
(The m-width dash)
If I set LANG=utf-8, it works:
```bash
$ LANG=utf-8 pip install schema
Downloading/unpacking schema
Downloading schema-0.3.1.tar.gz
Running setup.py (path:/Users/bla/tmpvenv/build/schema/setup.py) egg_info for package schema
Installing collected packages: schema
Running setup.py install for schema
Successfully installed schema
Cleaning up...
``` | keleshev/schema | diff --git a/test_schema.py b/test_schema.py
index aee25dc..4ec9993 100644
--- a/test_schema.py
+++ b/test_schema.py
@@ -106,33 +106,35 @@ def test_dict():
try:
Schema({'key': 5}).validate({})
except SchemaError as e:
- assert e.args[0] == "Missing keys: key"
+ assert e.args[0] in ["missed keys set(['key'])",
+ "missed keys {'key'}"] # Python 3 style
raise
with SE:
try:
Schema({'key': 5}).validate({'n': 5})
except SchemaError as e:
- assert e.args[0] == "Missing keys: key"
+ assert e.args[0] in ["missed keys set(['key'])",
+ "missed keys {'key'}"] # Python 3 style
raise
with SE:
try:
Schema({}).validate({'n': 5})
except SchemaError as e:
- assert e.args[0] == "Wrong keys 'n' in {'n': 5}"
+ assert e.args[0] == "wrong keys 'n' in {'n': 5}"
raise
with SE:
try:
Schema({'key': 5}).validate({'key': 5, 'bad': 5})
except SchemaError as e:
- assert e.args[0] in ["Wrong keys 'bad' in {'key': 5, 'bad': 5}",
- "Wrong keys 'bad' in {'bad': 5, 'key': 5}"]
+ assert e.args[0] in ["wrong keys 'bad' in {'key': 5, 'bad': 5}",
+ "wrong keys 'bad' in {'bad': 5, 'key': 5}"]
raise
with SE:
try:
Schema({}).validate({'a': 5, 'b': 5})
except SchemaError as e:
- assert e.args[0] in ["Wrong keys 'a', 'b' in {'a': 5, 'b': 5}",
- "Wrong keys 'a', 'b' in {'b': 5, 'a': 5}"]
+ assert e.args[0] in ["wrong keys 'a', 'b' in {'a': 5, 'b': 5}",
+ "wrong keys 'a', 'b' in {'b': 5, 'a': 5}"]
raise
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 0,
"issue_text_score": 0,
"test_score": 3
},
"num_modified_files": 3
} | 0.3 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "pytest",
"pip_packages": [
"pytest",
"pytest-cov"
],
"pre_install": null,
"python": "3.9",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | coverage==7.8.0
exceptiongroup @ file:///croot/exceptiongroup_1706031385326/work
iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work
packaging @ file:///croot/packaging_1734472117206/work
pluggy @ file:///croot/pluggy_1733169602837/work
pytest @ file:///croot/pytest_1738938843180/work
pytest-cov==6.0.0
-e git+https://github.com/keleshev/schema.git@e5c489cbbbbb8671ee32c43d518fea0076563da4#egg=schema
tomli @ file:///opt/conda/conda-bld/tomli_1657175507142/work
| name: schema
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- exceptiongroup=1.2.0=py39h06a4308_0
- iniconfig=1.1.1=pyhd3eb1b0_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=3.0.16=h5eee18b_0
- packaging=24.2=py39h06a4308_0
- pip=25.0=py39h06a4308_0
- pluggy=1.5.0=py39h06a4308_0
- pytest=8.3.4=py39h06a4308_0
- python=3.9.21=he870216_1
- readline=8.2=h5eee18b_0
- setuptools=75.8.0=py39h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- tomli=2.0.1=py39h06a4308_0
- tzdata=2025a=h04d1e81_0
- wheel=0.45.1=py39h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- coverage==7.8.0
- pytest-cov==6.0.0
prefix: /opt/conda/envs/schema
| [
"test_schema.py::test_dict"
] | [] | [
"test_schema.py::test_schema",
"test_schema.py::test_validate_file",
"test_schema.py::test_and",
"test_schema.py::test_or",
"test_schema.py::test_validate_list",
"test_schema.py::test_list_tuple_set_frozenset",
"test_schema.py::test_strictly",
"test_schema.py::test_dict_keys",
"test_schema.py::test_dict_optional_keys",
"test_schema.py::test_dict_optional_defaults",
"test_schema.py::test_complex",
"test_schema.py::test_nice_errors",
"test_schema.py::test_use_error_handling",
"test_schema.py::test_or_error_handling",
"test_schema.py::test_and_error_handling",
"test_schema.py::test_schema_error_handling",
"test_schema.py::test_use_json",
"test_schema.py::test_error_reporting",
"test_schema.py::test_schema_repr",
"test_schema.py::test_validate_object",
"test_schema.py::test_issue_9_prioritized_key_comparison",
"test_schema.py::test_issue_9_prioritized_key_comparison_in_dicts"
] | [] | MIT License | 244 |
|
Turbo87__utm-16 | a121973a02f2e24cfc9d45a24cd37b7c0bef3af9 | 2015-09-23 19:42:26 | 4c7c13f2b2b9c01a8581392641aeb8bbda6aba6f | diff --git a/utm/conversion.py b/utm/conversion.py
index ec30333..33fbfe9 100644
--- a/utm/conversion.py
+++ b/utm/conversion.py
@@ -176,7 +176,7 @@ def latitude_to_zone_letter(latitude):
def latlon_to_zone_number(latitude, longitude):
- if 56 <= latitude <= 64 and 3 <= longitude <= 12:
+ if 56 <= latitude < 64 and 3 <= longitude < 12:
return 32
if 72 <= latitude <= 84 and longitude >= 0:
| Borders of zones 31V and 32V
In `latlon_to_zone_number` you handle the zones 31V and 32V different from all the other zones.
Usually, you compute the zone number `[left..right)` and the zone letter `[bottom..top)`. But for the corrections of 31V and 32V you use `[left..right]` and `[bottom..top]`.
This leads to the following behavior:
* for 52°N 12°E, 33U is returned. (which, in my opinion is correct)
* for 60°N 12°E, 32V is returned. Shouldn't it be 33V?
* for 64°N 5°E, 32W is returned. Shouldn't it be 31W?
I would replace line 179 by
```python
if 56 <= latitude < 64 and 3 <= longitude < 12:
```
I didn't check your code for the corrections in the X-band in detail. (I'm not interrested in places this far north...) But I believe, we have the same issue there.
| Turbo87/utm | diff --git a/test/test_utm.py b/test/test_utm.py
index 1ffcab2..5cbabe8 100644
--- a/test/test_utm.py
+++ b/test/test_utm.py
@@ -173,5 +173,57 @@ class BadInput(UTMTestCase):
self.assertRaises(
UTM.OutOfRangeError, UTM.to_latlon, 500000, 5000000, 32, 'Z')
+
+class Zone32V(unittest.TestCase):
+
+ def assert_zone_equal(self, result, expected_number, expected_letter):
+ self.assertEqual(result[2], expected_number)
+ self.assertEqual(result[3].upper(), expected_letter.upper())
+
+ def test_inside(self):
+ self.assert_zone_equal(UTM.from_latlon(56, 3), 32, 'V')
+ self.assert_zone_equal(UTM.from_latlon(56, 6), 32, 'V')
+ self.assert_zone_equal(UTM.from_latlon(56, 9), 32, 'V')
+ self.assert_zone_equal(UTM.from_latlon(56, 11.999999), 32, 'V')
+
+ self.assert_zone_equal(UTM.from_latlon(60, 3), 32, 'V')
+ self.assert_zone_equal(UTM.from_latlon(60, 6), 32, 'V')
+ self.assert_zone_equal(UTM.from_latlon(60, 9), 32, 'V')
+ self.assert_zone_equal(UTM.from_latlon(60, 11.999999), 32, 'V')
+
+ self.assert_zone_equal(UTM.from_latlon(63.999999, 3), 32, 'V')
+ self.assert_zone_equal(UTM.from_latlon(63.999999, 6), 32, 'V')
+ self.assert_zone_equal(UTM.from_latlon(63.999999, 9), 32, 'V')
+ self.assert_zone_equal(UTM.from_latlon(63.999999, 11.999999), 32, 'V')
+
+ def test_left_of(self):
+ self.assert_zone_equal(UTM.from_latlon(55.999999, 2.999999), 31, 'U')
+ self.assert_zone_equal(UTM.from_latlon(56, 2.999999), 31, 'V')
+ self.assert_zone_equal(UTM.from_latlon(60, 2.999999), 31, 'V')
+ self.assert_zone_equal(UTM.from_latlon(63.999999, 2.999999), 31, 'V')
+ self.assert_zone_equal(UTM.from_latlon(64, 2.999999), 31, 'W')
+
+ def test_right_of(self):
+ self.assert_zone_equal(UTM.from_latlon(55.999999, 12), 33, 'U')
+ self.assert_zone_equal(UTM.from_latlon(56, 12), 33, 'V')
+ self.assert_zone_equal(UTM.from_latlon(60, 12), 33, 'V')
+ self.assert_zone_equal(UTM.from_latlon(63.999999, 12), 33, 'V')
+ self.assert_zone_equal(UTM.from_latlon(64, 12), 33, 'W')
+
+ def test_below(self):
+ self.assert_zone_equal(UTM.from_latlon(55.999999, 3), 31, 'U')
+ self.assert_zone_equal(UTM.from_latlon(55.999999, 6), 32, 'U')
+ self.assert_zone_equal(UTM.from_latlon(55.999999, 9), 32, 'U')
+ self.assert_zone_equal(UTM.from_latlon(55.999999, 11.999999), 32, 'U')
+ self.assert_zone_equal(UTM.from_latlon(55.999999, 12), 33, 'U')
+
+ def test_above(self):
+ self.assert_zone_equal(UTM.from_latlon(64, 3), 31, 'W')
+ self.assert_zone_equal(UTM.from_latlon(64, 6), 32, 'W')
+ self.assert_zone_equal(UTM.from_latlon(64, 9), 32, 'W')
+ self.assert_zone_equal(UTM.from_latlon(64, 11.999999), 32, 'W')
+ self.assert_zone_equal(UTM.from_latlon(64, 12), 33, 'W')
+
+
if __name__ == '__main__':
unittest.main()
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 0,
"issue_text_score": 1,
"test_score": 3
},
"num_modified_files": 1
} | 0.4 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.9",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | exceptiongroup==1.2.2
iniconfig==2.1.0
packaging==24.2
pluggy==1.5.0
pytest==8.3.5
tomli==2.2.1
-e git+https://github.com/Turbo87/utm.git@a121973a02f2e24cfc9d45a24cd37b7c0bef3af9#egg=utm
| name: utm
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=3.0.16=h5eee18b_0
- pip=25.0=py39h06a4308_0
- python=3.9.21=he870216_1
- readline=8.2=h5eee18b_0
- setuptools=75.8.0=py39h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- tzdata=2025a=h04d1e81_0
- wheel=0.45.1=py39h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- exceptiongroup==1.2.2
- iniconfig==2.1.0
- packaging==24.2
- pluggy==1.5.0
- pytest==8.3.5
- tomli==2.2.1
prefix: /opt/conda/envs/utm
| [
"test/test_utm.py::Zone32V::test_above",
"test/test_utm.py::Zone32V::test_right_of"
] | [] | [
"test/test_utm.py::KnownValues::test_from_latlon",
"test/test_utm.py::KnownValues::test_to_latlon",
"test/test_utm.py::BadInput::test_from_latlon_range_checks",
"test/test_utm.py::BadInput::test_to_latlon_range_checks",
"test/test_utm.py::Zone32V::test_below",
"test/test_utm.py::Zone32V::test_inside",
"test/test_utm.py::Zone32V::test_left_of"
] | [] | MIT License | 245 |
|
docker__docker-py-787 | 5e331a55a8e8e10354693172dce1aa63f58ebe97 | 2015-09-23 21:07:40 | f479720d517a7db7f886916190b3032d29d18f10 | shin-: @aanand Thanks, didn't know about `six.u`. PTAL?
aanand: Cool. Perhaps the first test should be rewritten so it tests byte string input on all Python versions:
```python
def test_convert_volume_bindings_binary_input(self):
expected = [six.u('/mnt/지연:/unicode/박:rw')]
data = {
b'/mnt/지연': {
'bind': b'/unicode/박',
'mode': 'rw'
}
}
self.assertEqual(
convert_volume_binds(data), expected
)
```
shin-: Okay, I've tried all sorts of combination, I've settled on just separating py2 and py3 tests completely (so it's 2+2 now). On the bright side, results were consistent all along (and we have tests to prove it)!
aanand: OK, I see the rationale, but instead of entirely separate test methods, could we just switch on the Python version *inside* the method?
```python
def test_convert_volume_binds_unicode_bytes_input(self):
if six.PY2:
expected = [unicode('/mnt/지연:/unicode/박:rw', 'utf-8')]
data = {
'/mnt/지연': {
'bind': '/unicode/박',
'mode': 'rw'
}
}
else:
expected = ['/mnt/지연:/unicode/박:rw']
data = {
bytes('/mnt/지연', 'utf-8'): {
'bind': bytes('/unicode/박', 'utf-8'),
'mode': 'rw'
}
}
self.assertEqual(convert_volume_binds(data), expected)
def test_convert_volume_binds_unicode_unicode_input(self):
if six.PY2:
expected = [unicode('/mnt/지연:/unicode/박:rw', 'utf-8')]
data = {
unicode('/mnt/지연', 'utf-8'): {
'bind': unicode('/unicode/박', 'utf-8'),
'mode': 'rw'
}
}
else:
expected = ['/mnt/지연:/unicode/박:rw']
data = {
'/mnt/지연': {
'bind': '/unicode/박',
'mode': 'rw'
}
}
self.assertEqual(convert_volume_binds(data), expected)
``` | diff --git a/docker/utils/utils.py b/docker/utils/utils.py
index 36edf8de..1fce1377 100644
--- a/docker/utils/utils.py
+++ b/docker/utils/utils.py
@@ -242,6 +242,9 @@ def convert_volume_binds(binds):
result = []
for k, v in binds.items():
+ if isinstance(k, six.binary_type):
+ k = k.decode('utf-8')
+
if isinstance(v, dict):
if 'ro' in v and 'mode' in v:
raise ValueError(
@@ -249,6 +252,10 @@ def convert_volume_binds(binds):
.format(repr(v))
)
+ bind = v['bind']
+ if isinstance(bind, six.binary_type):
+ bind = bind.decode('utf-8')
+
if 'ro' in v:
mode = 'ro' if v['ro'] else 'rw'
elif 'mode' in v:
@@ -256,11 +263,15 @@ def convert_volume_binds(binds):
else:
mode = 'rw'
- result.append('{0}:{1}:{2}'.format(
- k, v['bind'], mode
- ))
+ result.append(
+ six.text_type('{0}:{1}:{2}').format(k, bind, mode)
+ )
else:
- result.append('{0}:{1}:rw'.format(k, v))
+ if isinstance(v, six.binary_type):
+ v = v.decode('utf-8')
+ result.append(
+ six.text_type('{0}:{1}:rw').format(k, v)
+ )
return result
| Create container bind volume with Unicode folder name
If bind volume folder name is Unicode, for example Japanese, It will raise exception:
Host volume and container volume both should handle Unicode.
```
File "/home/vagrant/.local/share/virtualenvs/qnap/local/lib/python2.7/site-packages/docker/utils/utils.py", line 461, in create_host_config
host_config['Binds'] = convert_volume_binds(binds)
File "/home/vagrant/.local/share/virtualenvs/qnap/local/lib/python2.7/site-packages/docker/utils/utils.py", line 208, in convert_volume_binds
k, v['bind'], mode
``` | docker/docker-py | diff --git a/tests/utils_test.py b/tests/utils_test.py
index 45929f73..8ac1dcb9 100644
--- a/tests/utils_test.py
+++ b/tests/utils_test.py
@@ -1,15 +1,20 @@
+# -*- coding: utf-8 -*-
+
import os
import os.path
import shutil
import tempfile
+import pytest
+import six
+
from docker.client import Client
from docker.constants import DEFAULT_DOCKER_API_VERSION
from docker.errors import DockerException
from docker.utils import (
parse_repository_tag, parse_host, convert_filters, kwargs_from_env,
create_host_config, Ulimit, LogConfig, parse_bytes, parse_env_file,
- exclude_paths,
+ exclude_paths, convert_volume_binds,
)
from docker.utils.ports import build_port_bindings, split_port
from docker.auth import resolve_repository_name, resolve_authconfig
@@ -17,7 +22,6 @@ from docker.auth import resolve_repository_name, resolve_authconfig
from . import base
from .helpers import make_tree
-import pytest
TEST_CERT_DIR = os.path.join(
os.path.dirname(__file__),
@@ -192,6 +196,89 @@ class UtilsTest(base.BaseTestCase):
local_tempfile.close()
return local_tempfile.name
+ def test_convert_volume_binds_empty(self):
+ self.assertEqual(convert_volume_binds({}), [])
+ self.assertEqual(convert_volume_binds([]), [])
+
+ def test_convert_volume_binds_list(self):
+ data = ['/a:/a:ro', '/b:/c:z']
+ self.assertEqual(convert_volume_binds(data), data)
+
+ def test_convert_volume_binds_complete(self):
+ data = {
+ '/mnt/vol1': {
+ 'bind': '/data',
+ 'mode': 'ro'
+ }
+ }
+ self.assertEqual(convert_volume_binds(data), ['/mnt/vol1:/data:ro'])
+
+ def test_convert_volume_binds_compact(self):
+ data = {
+ '/mnt/vol1': '/data'
+ }
+ self.assertEqual(convert_volume_binds(data), ['/mnt/vol1:/data:rw'])
+
+ def test_convert_volume_binds_no_mode(self):
+ data = {
+ '/mnt/vol1': {
+ 'bind': '/data'
+ }
+ }
+ self.assertEqual(convert_volume_binds(data), ['/mnt/vol1:/data:rw'])
+
+ def test_convert_volume_binds_unicode_bytes_input(self):
+ if six.PY2:
+ expected = [unicode('/mnt/지연:/unicode/박:rw', 'utf-8')]
+
+ data = {
+ '/mnt/지연': {
+ 'bind': '/unicode/박',
+ 'mode': 'rw'
+ }
+ }
+ self.assertEqual(
+ convert_volume_binds(data), expected
+ )
+ else:
+ expected = ['/mnt/지연:/unicode/박:rw']
+
+ data = {
+ bytes('/mnt/지연', 'utf-8'): {
+ 'bind': bytes('/unicode/박', 'utf-8'),
+ 'mode': 'rw'
+ }
+ }
+ self.assertEqual(
+ convert_volume_binds(data), expected
+ )
+
+ def test_convert_volume_binds_unicode_unicode_input(self):
+ if six.PY2:
+ expected = [unicode('/mnt/지연:/unicode/박:rw', 'utf-8')]
+
+ data = {
+ unicode('/mnt/지연', 'utf-8'): {
+ 'bind': unicode('/unicode/박', 'utf-8'),
+ 'mode': 'rw'
+ }
+ }
+ self.assertEqual(
+ convert_volume_binds(data), expected
+ )
+ else:
+ expected = ['/mnt/지연:/unicode/박:rw']
+
+ data = {
+ '/mnt/지연': {
+ 'bind': '/unicode/박',
+ 'mode': 'rw'
+ }
+ }
+ self.assertEqual(
+ convert_volume_binds(data), expected
+ )
+
def test_parse_repository_tag(self):
self.assertEqual(parse_repository_tag("root"),
("root", None))
| {
"commit_name": "head_commit",
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true,
"llm_score": {
"difficulty_score": 1,
"issue_text_score": 1,
"test_score": 0
},
"num_modified_files": 1
} | 1.4 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[dev]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest pytest-cov",
"pytest"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.7",
"reqs_path": [
"requirements.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | certifi @ file:///croot/certifi_1671487769961/work/certifi
coverage==7.2.7
-e git+https://github.com/docker/docker-py.git@5e331a55a8e8e10354693172dce1aa63f58ebe97#egg=docker_py
exceptiongroup==1.2.2
importlib-metadata==6.7.0
iniconfig==2.0.0
packaging==24.0
pluggy==1.2.0
pytest==7.4.4
pytest-cov==4.1.0
requests==2.5.3
six==1.17.0
tomli==2.0.1
typing_extensions==4.7.1
websocket-client==0.32.0
zipp==3.15.0
| name: docker-py
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2022.12.7=py37h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- pip=22.3.1=py37h06a4308_0
- python=3.7.16=h7a1cb2a_0
- readline=8.2=h5eee18b_0
- setuptools=65.6.3=py37h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- wheel=0.38.4=py37h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- coverage==7.2.7
- exceptiongroup==1.2.2
- importlib-metadata==6.7.0
- iniconfig==2.0.0
- packaging==24.0
- pluggy==1.2.0
- pytest==7.4.4
- pytest-cov==4.1.0
- requests==2.5.3
- six==1.17.0
- tomli==2.0.1
- typing-extensions==4.7.1
- websocket-client==0.32.0
- zipp==3.15.0
prefix: /opt/conda/envs/docker-py
| [
"tests/utils_test.py::UtilsTest::test_convert_volume_binds_unicode_bytes_input"
] | [] | [
"tests/utils_test.py::HostConfigTest::test_create_host_config_invalid_cpu_cfs_types",
"tests/utils_test.py::HostConfigTest::test_create_host_config_no_options",
"tests/utils_test.py::HostConfigTest::test_create_host_config_no_options_newer_api_version",
"tests/utils_test.py::HostConfigTest::test_create_host_config_with_cpu_period",
"tests/utils_test.py::HostConfigTest::test_create_host_config_with_cpu_quota",
"tests/utils_test.py::UlimitTest::test_create_host_config_dict_ulimit",
"tests/utils_test.py::UlimitTest::test_create_host_config_dict_ulimit_capitals",
"tests/utils_test.py::UlimitTest::test_create_host_config_obj_ulimit",
"tests/utils_test.py::UlimitTest::test_ulimit_invalid_type",
"tests/utils_test.py::LogConfigTest::test_create_host_config_dict_logconfig",
"tests/utils_test.py::LogConfigTest::test_create_host_config_obj_logconfig",
"tests/utils_test.py::LogConfigTest::test_logconfig_invalid_config_type",
"tests/utils_test.py::KwargsFromEnvTest::test_kwargs_from_env_empty",
"tests/utils_test.py::KwargsFromEnvTest::test_kwargs_from_env_no_cert_path",
"tests/utils_test.py::KwargsFromEnvTest::test_kwargs_from_env_tls",
"tests/utils_test.py::UtilsTest::test_convert_filters",
"tests/utils_test.py::UtilsTest::test_convert_volume_binds_compact",
"tests/utils_test.py::UtilsTest::test_convert_volume_binds_complete",
"tests/utils_test.py::UtilsTest::test_convert_volume_binds_empty",
"tests/utils_test.py::UtilsTest::test_convert_volume_binds_list",
"tests/utils_test.py::UtilsTest::test_convert_volume_binds_no_mode",
"tests/utils_test.py::UtilsTest::test_convert_volume_binds_unicode_unicode_input",
"tests/utils_test.py::UtilsTest::test_parse_bytes",
"tests/utils_test.py::UtilsTest::test_parse_env_file_commented_line",
"tests/utils_test.py::UtilsTest::test_parse_env_file_invalid_line",
"tests/utils_test.py::UtilsTest::test_parse_env_file_proper",
"tests/utils_test.py::UtilsTest::test_parse_host",
"tests/utils_test.py::UtilsTest::test_parse_host_empty_value",
"tests/utils_test.py::UtilsTest::test_parse_repository_tag",
"tests/utils_test.py::UtilsTest::test_resolve_authconfig",
"tests/utils_test.py::UtilsTest::test_resolve_registry_and_auth",
"tests/utils_test.py::UtilsTest::test_resolve_repository_name",
"tests/utils_test.py::PortsTest::test_build_port_bindings_with_matching_internal_port_ranges",
"tests/utils_test.py::PortsTest::test_build_port_bindings_with_matching_internal_ports",
"tests/utils_test.py::PortsTest::test_build_port_bindings_with_nonmatching_internal_port_ranges",
"tests/utils_test.py::PortsTest::test_build_port_bindings_with_nonmatching_internal_ports",
"tests/utils_test.py::PortsTest::test_build_port_bindings_with_one_port",
"tests/utils_test.py::PortsTest::test_build_port_bindings_with_port_range",
"tests/utils_test.py::PortsTest::test_host_only_with_colon",
"tests/utils_test.py::PortsTest::test_non_matching_length_port_ranges",
"tests/utils_test.py::PortsTest::test_port_and_range_invalid",
"tests/utils_test.py::PortsTest::test_port_only_with_colon",
"tests/utils_test.py::PortsTest::test_split_port_invalid",
"tests/utils_test.py::PortsTest::test_split_port_no_host_port",
"tests/utils_test.py::PortsTest::test_split_port_range_no_host_port",
"tests/utils_test.py::PortsTest::test_split_port_range_with_host_ip_no_port",
"tests/utils_test.py::PortsTest::test_split_port_range_with_host_port",
"tests/utils_test.py::PortsTest::test_split_port_range_with_protocol",
"tests/utils_test.py::PortsTest::test_split_port_with_host_ip",
"tests/utils_test.py::PortsTest::test_split_port_with_host_ip_no_port",
"tests/utils_test.py::PortsTest::test_split_port_with_host_port",
"tests/utils_test.py::PortsTest::test_split_port_with_protocol",
"tests/utils_test.py::ExcludePathsTest::test_directory",
"tests/utils_test.py::ExcludePathsTest::test_directory_with_single_exception",
"tests/utils_test.py::ExcludePathsTest::test_directory_with_subdir_exception",
"tests/utils_test.py::ExcludePathsTest::test_directory_with_trailing_slash",
"tests/utils_test.py::ExcludePathsTest::test_directory_with_wildcard_exception",
"tests/utils_test.py::ExcludePathsTest::test_exclude_custom_dockerfile",
"tests/utils_test.py::ExcludePathsTest::test_exclude_dockerfile_dockerignore",
"tests/utils_test.py::ExcludePathsTest::test_no_dupes",
"tests/utils_test.py::ExcludePathsTest::test_no_excludes",
"tests/utils_test.py::ExcludePathsTest::test_question_mark",
"tests/utils_test.py::ExcludePathsTest::test_single_filename",
"tests/utils_test.py::ExcludePathsTest::test_single_filename_trailing_slash",
"tests/utils_test.py::ExcludePathsTest::test_single_subdir_single_filename",
"tests/utils_test.py::ExcludePathsTest::test_single_subdir_wildcard_filename",
"tests/utils_test.py::ExcludePathsTest::test_subdirectory",
"tests/utils_test.py::ExcludePathsTest::test_wildcard_exclude",
"tests/utils_test.py::ExcludePathsTest::test_wildcard_filename_end",
"tests/utils_test.py::ExcludePathsTest::test_wildcard_filename_start",
"tests/utils_test.py::ExcludePathsTest::test_wildcard_subdir_single_filename",
"tests/utils_test.py::ExcludePathsTest::test_wildcard_subdir_wildcard_filename",
"tests/utils_test.py::ExcludePathsTest::test_wildcard_with_exception",
"tests/utils_test.py::ExcludePathsTest::test_wildcard_with_wildcard_exception"
] | [] | Apache License 2.0 | 246 |
MITLibraries__oastats-backend-46 | ed278663c240daf3a71571f94812bc9f5b2da9dd | 2015-09-24 20:20:13 | ed278663c240daf3a71571f94812bc9f5b2da9dd | diff --git a/pipeline/summary.py b/pipeline/summary.py
index 982c7f5..c3a4360 100644
--- a/pipeline/summary.py
+++ b/pipeline/summary.py
@@ -29,6 +29,7 @@ def index(requests, solr_url):
request.get('authors', []))),
'author_name': list(map(itemgetter('name'),
request.get('authors', []))),
+ 'author': list(map(join_author, request.get('authors', [])))
}
solr.write(doc)
@@ -209,4 +210,8 @@ def split_author(author):
except ValueError:
return
if mitid and name:
- return {'mitid': int(mitid), 'name': name}
+ return {'mitid': mitid, 'name': name}
+
+
+def join_author(author):
+ return "%s:%s" % (author.get('mitid', ''), author.get('name', ''))
| Add combined author/mit id field to solr during summary
Changes in the summary script depend on a string field with `author:mitid`. This is in addition to the two separate `author` and `mitid` fields. | MITLibraries/oastats-backend | diff --git a/tests/integration/test_cli.py b/tests/integration/test_cli.py
index 34933b2..757d504 100644
--- a/tests/integration/test_cli.py
+++ b/tests/integration/test_cli.py
@@ -62,7 +62,13 @@ def test_index_adds_mongo_records_to_solr(runner, solr_port, mongo_port):
r = solr.search('*:*')
assert len(r) == 2
doc = next(iter(r))
- assert doc['title'] == 'The Foobar'
+ assert doc == {'title': 'The Foobar', 'handle': 'foobar', 'country': 'USA',
+ 'time': '2015-01-01T00:00:00Z',
+ 'dlc_display': ['Stuff', 'Things'],
+ 'dlc_canonical': ['Dept of Stuff', 'Dept of Things'],
+ 'author_id': ['1234', '5678'],
+ 'author_name': ['Bar, Foo', 'Baz, Foo'],
+ 'author': ['1234:Bar, Foo', '5678:Baz, Foo']}
@pytest.mark.usefixtures('load_mongo_records', 'load_solr_records')
diff --git a/tests/unit/test_summary.py b/tests/unit/test_summary.py
index b86c192..034d163 100644
--- a/tests/unit/test_summary.py
+++ b/tests/unit/test_summary.py
@@ -75,7 +75,8 @@ def test_index_maps_mongo_request_to_solr(solr, mongo_req):
'dlc_display': ['Stuff n Such', 'Other Things'],
'dlc_canonical': ['Dept of Stuff', 'Dept of Things'],
'author_id': ['1234', '7890'],
- 'author_name': ['Captain Snuggles', 'Muffinpants']
+ 'author_name': ['Captain Snuggles', 'Muffinpants'],
+ 'author': ['1234:Captain Snuggles', '7890:Muffinpants']
}]
@@ -126,7 +127,7 @@ def test_authors_filters_out_authors_with_empty_mitid(mongo):
def test_get_author_returns_solr_query():
- assert get_author({'mitid': 1234, 'name': 'Fluffy'}) == \
+ assert get_author({'mitid': '1234', 'name': 'Fluffy'}) == \
('author_id:"1234"', {'rows': 0, 'group': 'true',
'group.field': 'handle', 'group.ngroups': 'true'})
@@ -181,8 +182,8 @@ def test_create_handle_creates_mongo_insert(handle_result):
{'country': 'ISL', 'downloads': 4}],
'dates': [{'date': '2015-01-01', 'downloads': 3},
{'date': '2015-02-01', 'downloads': 5}],
- 'parents': [{'mitid': 1234, 'name': 'Fluffy'},
- {'mitid': 5678, 'name': 'Captain Snuggles'}]
+ 'parents': [{'mitid': '1234', 'name': 'Fluffy'},
+ {'mitid': '5678', 'name': 'Captain Snuggles'}]
}
}
@@ -214,9 +215,17 @@ def test_dictify_converts_facet_count_to_dictionary():
def test_split_author_turns_string_into_compound_field():
- assert split_author('1234:Foo Bar') == {'mitid': 1234, 'name': 'Foo Bar'}
+ assert split_author('1234:Foo Bar') == {'mitid': '1234', 'name': 'Foo Bar'}
def test_split_author_returns_none_for_invalid_author():
assert split_author(':Foo Bar') is None
assert split_author('Foo Bar') is None
+
+
+def test_join_author_joins_author_parts():
+ assert join_author({'name': 'Cat, Lucy', 'mitid': '1234'}) == \
+ '1234:Cat, Lucy'
+
+def test_join_author_uses_empty_string_for_missing_items():
+ assert join_author({'name': 'Cat, Lucy'}) == ':Cat, Lucy'
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_short_problem_statement"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 2,
"issue_text_score": 2,
"test_score": 0
},
"num_modified_files": 1
} | unknown | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest",
"mock",
"mongobox"
],
"pre_install": null,
"python": "3.4",
"reqs_path": [
"requirements.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | apache-log-parser==1.7.0
arrow==0.6.0
attrs==22.2.0
certifi==2021.5.30
click==5.1
futures==2.2.0
geoip2==2.2.0
importlib-metadata==4.8.3
iniconfig==1.1.1
maxminddb==1.2.0
mock==5.2.0
mongobox==0.1.8
-e git+https://github.com/MITLibraries/oastats-backend.git@ed278663c240daf3a71571f94812bc9f5b2da9dd#egg=OAStats_Pipeline
packaging==21.3
pluggy==1.0.0
py==1.11.0
pycountry==1.15
pymongo==3.0.3
pyparsing==3.1.4
pysolr==3.3.2
pytest==7.0.1
python-dateutil==2.4.2
PyYAML==3.11
requests==2.7.0
six==1.9.0
tomli==1.2.3
typing_extensions==4.1.1
ua-parser==0.4.1
user-agents==1.0.1
zipp==3.6.0
| name: oastats-backend
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2021.5.30=py36h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.3=he6710b0_2
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- pip=21.2.2=py36h06a4308_0
- python=3.6.13=h12debd9_1
- readline=8.2=h5eee18b_0
- setuptools=58.0.4=py36h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- apache-log-parser==1.7.0
- arrow==0.6.0
- attrs==22.2.0
- click==5.1
- futures==2.2.0
- geoip2==2.2.0
- importlib-metadata==4.8.3
- iniconfig==1.1.1
- maxminddb==1.2.0
- mock==5.2.0
- mongobox==0.1.8
- packaging==21.3
- pluggy==1.0.0
- py==1.11.0
- pycountry==1.15
- pymongo==3.0.3
- pyparsing==3.1.4
- pysolr==3.3.2
- pytest==7.0.1
- python-dateutil==2.4.2
- pyyaml==3.11
- requests==2.7.0
- six==1.9.0
- tomli==1.2.3
- typing-extensions==4.1.1
- ua-parser==0.4.1
- user-agents==1.0.1
- wheel==0.24.0
- zipp==3.6.0
prefix: /opt/conda/envs/oastats-backend
| [
"tests/unit/test_summary.py::test_index_maps_mongo_request_to_solr",
"tests/unit/test_summary.py::test_create_handle_creates_mongo_insert",
"tests/unit/test_summary.py::test_split_author_turns_string_into_compound_field",
"tests/unit/test_summary.py::test_join_author_joins_author_parts",
"tests/unit/test_summary.py::test_join_author_uses_empty_string_for_missing_items"
] | [] | [
"tests/unit/test_summary.py::test_index_adds_requests_to_solr",
"tests/unit/test_summary.py::test_query_solr_merges_query_params",
"tests/unit/test_summary.py::test_query_solr_queries_solr",
"tests/unit/test_summary.py::test_query_solr_sets_default_params",
"tests/unit/test_summary.py::test_get_author_returns_solr_query",
"tests/unit/test_summary.py::test_create_author_creates_mongo_insert",
"tests/unit/test_summary.py::test_get_dlc_returns_solr_query",
"tests/unit/test_summary.py::test_create_dlc_creates_mongo_insert",
"tests/unit/test_summary.py::test_get_handle_returns_solr_query",
"tests/unit/test_summary.py::test_get_overall_returns_solr_query",
"tests/unit/test_summary.py::test_create_overall_creates_mongo_insert",
"tests/unit/test_summary.py::test_dictify_converts_facet_count_to_dictionary",
"tests/unit/test_summary.py::test_split_author_returns_none_for_invalid_author"
] | [] | Apache License 2.0 | 247 |
|
sympy__sympy-9930 | b157c4295076e0cf94319138cec1c1a5402abcbd | 2015-09-25 14:00:37 | 0241b35cae5f2adc04dc37b25f7dc9c5f00bd746 | gxyd: @aktech @jksuom Please let me know what you think?
gxyd: ping @aktech @leosartaj
leosartaj: You have merge conflicts. You should fix theses.
gxyd: ping @smichr @leosartaj
leosartaj: +1
ping @aktech @hargup
aktech: +1 except for a minor [nitpick](https://github.com/sympy/sympy/pull/9930#discussion_r41956443). | diff --git a/AUTHORS b/AUTHORS
index 762ab4cd26..d7057ad342 100644
--- a/AUTHORS
+++ b/AUTHORS
@@ -419,4 +419,3 @@ Dustin Gadal <[email protected]>
Yu Kobayashi <[email protected]>
Shashank Kumar <[email protected]>
Devyani Kota <[email protected]>
-Keval Shah <[email protected]>
diff --git a/doc/src/aboutus.rst b/doc/src/aboutus.rst
index ee954a9c14..8a3a87f2b3 100644
--- a/doc/src/aboutus.rst
+++ b/doc/src/aboutus.rst
@@ -423,7 +423,6 @@ want to be mentioned here, so see our repository history for a full list).
#. Yu Kobayashi: Tuple constructor should not take the argument `**assumptions`
#. Shashank Kumar: Fixed indenation error in summations.py and added test for issue #9908
#. Devyani Kota: Fixed issue 9953: linsolve([ ], ...) now returns S.EmptySet
-#. Keval Shah: Union with subset of S.Complexes now evaluated
Up-to-date list in the order of the first contribution is given in the `AUTHORS
<https://github.com/sympy/sympy/blob/master/AUTHORS>`_ file.
diff --git a/sympy/matrices/matrices.py b/sympy/matrices/matrices.py
index 80a6a9c1a5..06c7b173fe 100644
--- a/sympy/matrices/matrices.py
+++ b/sympy/matrices/matrices.py
@@ -519,8 +519,7 @@ def __rmul__(self, a):
return self._new(self.rows, self.cols, [a*i for i in self._mat])
def __pow__(self, num):
- from sympy.matrices import eye, diag, MutableMatrix
- from sympy import binomial
+ from sympy.matrices import eye
if not self.is_square:
raise NonSquareMatrixError()
@@ -539,27 +538,18 @@ def __pow__(self, num):
s *= s
n //= 2
return self._new(a)
- elif isinstance(num, (Expr, float)):
-
- def jordan_cell_power(jc, n):
- N = jc.shape[0]
- l = jc[0, 0]
- for i in range(N):
- for j in range(N-i):
- bn = binomial(n, i)
- if isinstance(bn, binomial):
- bn = bn._eval_expand_func()
- jc[j, i+j] = l**(n-i)*bn
-
- P, jordan_cells = self.jordan_cells()
- # Make sure jordan_cells matrices are mutable:
- jordan_cells = [MutableMatrix(j) for j in jordan_cells]
- for j in jordan_cells:
- jordan_cell_power(j, num)
- return self._new(P*diag(*jordan_cells)*P.inv())
+ elif isinstance(num, Rational):
+ try:
+ P, D = self.diagonalize()
+ except MatrixError:
+ raise NotImplementedError(
+ "Implemented only for diagonalizable matrices")
+ for i in range(D.rows):
+ D[i, i] = D[i, i]**num
+ return self._new(P*D*P.inv())
else:
- raise TypeError(
- "Only SymPy expressions or int objects are supported as exponent for matrices")
+ raise NotImplementedError(
+ "Only integer and rational values are supported")
def __add__(self, other):
"""Return self + other, raising ShapeError if shapes don't match."""
diff --git a/sympy/physics/units.py b/sympy/physics/units.py
index c294f8663c..937aed6136 100644
--- a/sympy/physics/units.py
+++ b/sympy/physics/units.py
@@ -226,7 +226,6 @@ def free_symbols(self):
tropical_year = tropical_years = Rational('365.24219')*day
common_year = common_years = Rational('365')*day
julian_year = julian_years = Rational('365.25')*day
-draconic_year = draconic_years = Rational('346.62')*day
year = years = tropical_year
diff --git a/sympy/sets/fancysets.py b/sympy/sets/fancysets.py
index dc8b409185..64c45366a7 100644
--- a/sympy/sets/fancysets.py
+++ b/sympy/sets/fancysets.py
@@ -903,7 +903,7 @@ def _union(self, other):
elif self.polar and other.polar:
return ComplexRegion(Union(self.sets, other.sets), polar=True)
- if other.is_subset(S.Reals):
+ if other is S.Reals:
return self
return None
diff --git a/sympy/solvers/solveset.py b/sympy/solvers/solveset.py
index 216e58364f..ddc8a54b6b 100644
--- a/sympy/solvers/solveset.py
+++ b/sympy/solvers/solveset.py
@@ -455,6 +455,12 @@ def solveset_real(f, symbol):
original_eq = f
f = together(f)
+ # In this, unlike in solveset_complex, expression should only
+ # be expanded when fraction(f)[1] does not contain the symbol
+ # for which we are solving
+ if not symbol in fraction(f)[1].free_symbols and f.is_rational_function():
+ f = expand(f)
+
if f.has(Piecewise):
f = piecewise_fold(f)
result = EmptySet()
| solveset(2*x + 1/(x - 10)**2, x, S.Reals) raises RuntimeError
```
>>> from sympy.solvers.solveset import solveset
>>> x = Symbol('x')
>>> 2*x + 1/(x - 10)**2
>>> solveset(_, x, S.Reals) # some part of Traceback
---------------------------------------------------------------------------
RuntimeError Traceback (most recent call last)
<ipython-input-6-3aabfc8b6183> in <module>()
----> 1 solveset(expr, x, S.Reals)
/home/gxyd/Public/sympy/sympy/solvers/solveset.py in solveset(f, symbol, domain)
937 if isinstance(f, (Expr, Number)):
938 if domain is S.Reals:
--> 939 return solveset_real(f, symbol)
940 elif domain is S.Complexes:
941 return solveset_complex(f, symbol)
/home/gxyd/Public/sympy/sympy/solvers/solveset.py in solveset_real(f, symbol)
499 result += _solve_as_rational(equation, symbol,
500 solveset_solver=solveset_real,
--> 501 as_poly_solver=_solve_as_poly_real)
502 else:
503 result += solveset_real(equation, symbol)
/home/gxyd/Public/sympy/sympy/solvers/solveset.py in _solve_as_rational(f, symbol, solveset_solver, as_poly_solver)
521 return as_poly_solver(g, symbol)
522 else:
--> 523 valid_solns = solveset_solver(g, symbol)
524 invalid_solns = solveset_solver(h, symbol)
525 return valid_solns - invalid_solns
/home/gxyd/Public/sympy/sympy/solvers/solveset.py in solveset_real(f, symbol)
501 as_poly_solver=_solve_as_poly_real)
502 else:
--> 503 result += solveset_real(equation, symbol)
504 else:
505 result = ConditionSet(symbol, Eq(f, 0), S.Reals)
/home/gxyd/Public/sympy/sympy/solvers/solveset.py in solveset_real(f, symbol)
471 # wrong solutions we are using this technique only if both f and g are
472 # finite for a finite input.
--> 473 result = Union(*[solveset_real(m, symbol) for m in f.args])
474 elif _is_function_class_equation(TrigonometricFunction, f, symbol) or \
475 _is_function_class_equation(HyperbolicFunction, f, symbol):
/home/gxyd/Public/sympy/sympy/solvers/solveset.py in <listcomp>(.0)
471 # wrong solutions we are using this technique only if both f and g are
472 # finite for a finite input.
--> 473 result = Union(*[solveset_real(m, symbol) for m in f.args])
474 elif _is_function_class_equation(TrigonometricFunction, f, symbol) or \
475 _is_function_class_equation(HyperbolicFunction, f, symbol):
/home/gxyd/Public/sympy/sympy/solvers/solveset.py in solveset_real(f, symbol)
501 as_poly_solver=_solve_as_poly_real)
502 else:
--> 503 result += solveset_real(equation, symbol)
504 else:
505 result = ConditionSet(symbol, Eq(f, 0), S.Reals)
/home/gxyd/Public/sympy/sympy/solvers/solveset.py in solveset_real(f, symbol)
471 # wrong solutions we are using this technique only if both f and g are
472 # finite for a finite input.
--> 473 result = Union(*[solveset_real(m, symbol) for m in f.args])
474 elif _is_function_class_equation(TrigonometricFunction, f, symbol) or \
475 _is_function_class_equation(HyperbolicFunction, f, symbol):
/home/gxyd/Public/sympy/sympy/solvers/solveset.py in <listcomp>(.0)
471 # wrong solutions we are using this technique only if both f and g are
472 # finite for a finite input.
--> 473 result = Union(*[solveset_real(m, symbol) for m in f.args])
474 elif _is_function_class_equation(TrigonometricFunction, f, symbol) or \
475 _is_function_class_equation(HyperbolicFunction, f, symbol):
/home/gxyd/Public/sympy/sympy/solvers/solveset.py in solveset_real(f, symbol)
501 as_poly_solver=_solve_as_poly_real)
502 else:
--> 503 result += solveset_real(equation, symbol)
504 else:
505 result = ConditionSet(symbol, Eq(f, 0), S.Reals)
/home/gxyd/Public/sympy/sympy/solvers/solveset.py in solveset_real(f, symbol)
471 # wrong solutions we are using this technique only if both f and g are
472 # finite for a finite input.
--> 473 result = Union(*[solveset_real(m, symbol) for m in f.args])
474 elif _is_function_class_equation(TrigonometricFunction, f, symbol) or \
475 _is_function_class_equation(HyperbolicFunction, f, symbol):
/home/gxyd/Public/sympy/sympy/solvers/solveset.py in <listcomp>(.0)
471 # wrong solutions we are using this technique only if both f and g are
472 # finite for a finite input.
--> 473 result = Union(*[solveset_real(m, symbol) for m in f.args])
474 elif _is_function_class_equation(TrigonometricFunction, f, symbol) or \
475 _is_function_class_equation(HyperbolicFunction, f, symbol):
/home/gxyd/Public/sympy/sympy/solvers/solveset.py in solveset_real(f, symbol)
501 as_poly_solver=_solve_as_poly_real)
502 else:
--> 503 result += solveset_real(equation, symbol)
504 else:
505 result = ConditionSet(symbol, Eq(f, 0), S.Reals)
/home/gxyd/Public/sympy/sympy/solvers/solveset.py in solveset_real(f, symbol)
471 # wrong solutions we are using this technique only if both f and g are
472 # finite for a finite input.
--> 473 result = Union(*[solveset_real(m, symbol) for m in f.args])
474 elif _is_function_class_equation(TrigonometricFunction, f, symbol) or \
475 _is_function_class_equation(HyperbolicFunction, f, symbol):
/home/gxyd/Public/sympy/sympy/solvers/solveset.py in <listcomp>(.0)
471 # wrong solutions we are using this technique only if both f and g are
472 # finite for a finite input.
--> 473 result = Union(*[solveset_real(m, symbol) for m in f.args])
474 elif _is_function_class_equation(TrigonometricFunction, f, symbol) or \
475 _is_function_class_equation(HyperbolicFunction, f, symbol):
/home/gxyd/Public/sympy/sympy/solvers/solveset.py in solveset_real(f, symbol)
501 as_poly_solver=_solve_as_poly_real)
502 else:
--> 503 result += solveset_real(equation, symbol)
504 else:
505 result = ConditionSet(symbol, Eq(f, 0), S.Reals)
/home/gxyd/Public/sympy/sympy/solvers/solveset.py in solveset_real(f, symbol)
471 # wrong solutions we are using this technique only if both f and g are
472 # finite for a finite input.
--> 473 result = Union(*[solveset_real(m, symbol) for m in f.args])
474 elif _is_function_class_equation(TrigonometricFunction, f, symbol) or \
475 _is_function_class_equation(HyperbolicFunction, f, symbol):
/home/gxyd/Public/sympy/sympy/solvers/solveset.py in <listcomp>(.0)
471 # wrong solutions we are using this technique only if both f and g are
472 # finite for a finite input.
--> 473 result = Union(*[solveset_real(m, symbol) for m in f.args])
474 elif _is_function_class_equation(TrigonometricFunction, f, symbol) or \
475 _is_function_class_equation(HyperbolicFunction, f, symbol):
/home/gxyd/Public/sympy/sympy/solvers/solveset.py in solveset_real(f, symbol)
501 as_poly_solver=_solve_as_poly_real)
502 else:
--> 503 result += solveset_real(equation, symbol)
504 else:
505 result = ConditionSet(symbol, Eq(f, 0), S.Reals)
/home/gxyd/Public/sympy/sympy/solvers/solveset.py in solveset_real(f, symbol)
471 # wrong solutions we are using this technique only if both f and g are
472 # finite for a finite input.
--> 473 result = Union(*[solveset_real(m, symbol) for m in f.args])
474 elif _is_function_class_equation(TrigonometricFunction, f, symbol) or \
475 _is_function_class_equation(HyperbolicFunction, f, symbol):
/home/gxyd/Public/sympy/sympy/solvers/solveset.py in <listcomp>(.0)
471 # wrong solutions we are using this technique only if both f and g are
472 # finite for a finite input.
--> 473 result = Union(*[solveset_real(m, symbol) for m in f.args])
474 elif _is_function_class_equation(TrigonometricFunction, f, symbol) or \
475 _is_function_class_equation(HyperbolicFunction, f, symbol):
/home/gxyd/Public/sympy/sympy/solvers/solveset.py in solveset_real(f, symbol)
501 as_poly_solver=_solve_as_poly_real)
502 else:
--> 503 result += solveset_real(equation, symbol)
504 else:
505 result = ConditionSet(symbol, Eq(f, 0), S.Reals)
/home/gxyd/Public/sympy/sympy/solvers/solveset.py in solveset_real(f, symbol)
471 # wrong solutions we are using this technique only if both f and g are
472 # finite for a finite input.
--> 473 result = Union(*[solveset_real(m, symbol) for m in f.args])
474 elif _is_function_class_equation(TrigonometricFunction, f, symbol) or \
475 _is_function_class_equation(HyperbolicFunction, f, symbol):
/home/gxyd/Public/sympy/sympy/solvers/solveset.py in <listcomp>(.0)
471 # wrong solutions we are using this technique only if both f and g are
472 # finite for a finite input.
--> 473 result = Union(*[solveset_real(m, symbol) for m in f.args])
474 elif _is_function_class_equation(TrigonometricFunction, f, symbol) or \
475 _is_function_class_equation(HyperbolicFunction, f, symbol):
/home/gxyd/Public/sympy/sympy/solvers/solveset.py in solveset_real(f, symbol)
501 as_poly_solver=_solve_as_poly_real)
502 else:
--> 503 result += solveset_real(equation, symbol)
504 else:
505 result = ConditionSet(symbol, Eq(f, 0), S.Reals)
/home/gxyd/Public/sympy/sympy/solvers/solveset.py in solveset_real(f, symbol)
471 # wrong solutions we are using this technique only if both f and g are
472 # finite for a finite input.
--> 473 result = Union(*[solveset_real(m, symbol) for m in f.args])
474 elif _is_function_class_equation(TrigonometricFunction, f, symbol) or \
475 _is_function_class_equation(HyperbolicFunction, f, symbol):
/home/gxyd/Public/sympy/sympy/solvers/solveset.py in <listcomp>(.0)
471 # wrong solutions we are using this technique only if both f and g are
472 # finite for a finite input.
--> 473 result = Union(*[solveset_real(m, symbol) for m in f.args])
474 elif _is_function_class_equation(TrigonometricFunction, f, symbol) or \
475 _is_function_class_equation(HyperbolicFunction, f, symbol):
/home/gxyd/Public/sympy/sympy/solvers/solveset.py in solveset_real(f, symbol)
501 as_poly_solver=_solve_as_poly_real)
502 else:
--> 503 result += solveset_real(equation, symbol)
504 else:
505 result = ConditionSet(symbol, Eq(f, 0), S.Reals)
/home/gxyd/Public/sympy/sympy/solvers/solveset.py in solveset_real(f, symbol)
471 # wrong solutions we are using this technique only if both f and g are
472 # finite for a finite input.
--> 473 result = Union(*[solveset_real(m, symbol) for m in f.args])
474 elif _is_function_class_equation(TrigonometricFunction, f, symbol) or \
475 _is_function_class_equation(HyperbolicFunction, f, symbol):
/home/gxyd/Public/sympy/sympy/solvers/solveset.py in <listcomp>(.0)
471 # wrong solutions we are using this technique only if both f and g are
472 # finite for a finite input.
--> 473 result = Union(*[solveset_real(m, symbol) for m in f.args])
474 elif _is_function_class_equation(TrigonometricFunction, f, symbol) or \
475 _is_function_class_equation(HyperbolicFunction, f, symbol):
/home/gxyd/Public/sympy/sympy/solvers/solveset.py in solveset_real(f, symbol)
501 as_poly_solver=_solve_as_poly_real)
502 else:
--> 503 result += solveset_real(equation, symbol)
504 else:
505 result = ConditionSet(symbol, Eq(f, 0), S.Reals)
/home/gxyd/Public/sympy/sympy/solvers/solveset.py in solveset_real(f, symbol)
471 # wrong solutions we are using this technique only if both f and g are
472 # finite for a finite input.
--> 473 result = Union(*[solveset_real(m, symbol) for m in f.args])
474 elif _is_function_class_equation(TrigonometricFunction, f, symbol) or \
475 _is_function_class_equation(HyperbolicFunction, f, symbol):
/home/gxyd/Public/sympy/sympy/solvers/solveset.py in <listcomp>(.0)
471 # wrong solutions we are using this technique only if both f and g are
472 # finite for a finite input.
--> 473 result = Union(*[solveset_real(m, symbol) for m in f.args])
474 elif _is_function_class_equation(TrigonometricFunction, f, symbol) or \
475 _is_function_class_equation(HyperbolicFunction, f, symbol):
/home/gxyd/Public/sympy/sympy/solvers/solveset.py in solveset_real(f, symbol)
501 as_poly_solver=_solve_as_poly_real)
502 else:
--> 503 result += solveset_real(equation, symbol)
504 else:
505 result = ConditionSet(symbol, Eq(f, 0), S.Reals)
/home/gxyd/Public/sympy/sympy/solvers/solveset.py in solveset_real(f, symbol)
471 # wrong solutions we are using this technique only if both f and g are
472 # finite for a finite input.
--> 473 result = Union(*[solveset_real(m, symbol) for m in f.args])
474 elif _is_function_class_equation(TrigonometricFunction, f, symbol) or \
475 _is_function_class_equation(HyperbolicFunction, f, symbol):
/home/gxyd/Public/sympy/sympy/solvers/solveset.py in <listcomp>(.0)
471 # wrong solutions we are using this technique only if both f and g are
472 # finite for a finite input.
--> 473 result = Union(*[solveset_real(m, symbol) for m in f.args])
474 elif _is_function_class_equation(TrigonometricFunction, f, symbol) or \
475 _is_function_class_equation(HyperbolicFunction, f, symbol):
/home/gxyd/Public/sympy/sympy/solvers/solveset.py in solveset_real(f, symbol)
501 as_poly_solver=_solve_as_poly_real)
502 else:
--> 503 result += solveset_real(equation, symbol)
504 else:
505 result = ConditionSet(symbol, Eq(f, 0), S.Reals)
/home/gxyd/Public/sympy/sympy/solvers/solveset.py in solveset_real(f, symbol)
471 # wrong solutions we are using this technique only if both f and g are
472 # finite for a finite input.
--> 473 result = Union(*[solveset_real(m, symbol) for m in f.args])
474 elif _is_function_class_equation(TrigonometricFunction, f, symbol) or \
475 _is_function_class_equation(HyperbolicFunction, f, symbol):
/home/gxyd/Public/sympy/sympy/solvers/solveset.py in <listcomp>(.0)
471 # wrong solutions we are using this technique only if both f and g are
472 # finite for a finite input.
--> 473 result = Union(*[solveset_real(m, symbol) for m in f.args])
474 elif _is_function_class_equation(TrigonometricFunction, f, symbol) or \
475 _is_function_class_equation(HyperbolicFunction, f, symbol):
/home/gxyd/Public/sympy/sympy/solvers/solveset.py in solveset_real(f, symbol)
501 as_poly_solver=_solve_as_poly_real)
502 else:
--> 503 result += solveset_real(equation, symbol)
504 else:
505 result = ConditionSet(symbol, Eq(f, 0), S.Reals)
/home/gxyd/Public/sympy/sympy/solvers/solveset.py in solveset_real(f, symbol)
471 # wrong solutions we are using this technique only if both f and g are
472 # finite for a finite input.
--> 473 result = Union(*[solveset_real(m, symbol) for m in f.args])
474 elif _is_function_class_equation(TrigonometricFunction, f, symbol) or \
475 _is_function_class_equation(HyperbolicFunction, f, symbol):
/home/gxyd/Public/sympy/sympy/solvers/solveset.py in <listcomp>(.0)
471 # wrong solutions we are using this technique only if both f and g are
472 # finite for a finite input.
--> 473 result = Union(*[solveset_real(m, symbol) for m in f.args])
474 elif _is_function_class_equation(TrigonometricFunction, f, symbol) or \
475 _is_function_class_equation(HyperbolicFunction, f, symbol):
/home/gxyd/Public/sympy/sympy/solvers/solveset.py in solveset_real(f, symbol)
501 as_poly_solver=_solve_as_poly_real)
502 else:
--> 503 result += solveset_real(equation, symbol)
504 else:
505 result = ConditionSet(symbol, Eq(f, 0), S.Reals)
```
[Edit]
Problem seems to be with
```
>>> solveset_real(2*x*(x - 10)**2 + 1, x)
# Raises RunTimeError
``` | sympy/sympy | diff --git a/sympy/matrices/tests/test_matrices.py b/sympy/matrices/tests/test_matrices.py
index e84dafec6f..9abd1303af 100644
--- a/sympy/matrices/tests/test_matrices.py
+++ b/sympy/matrices/tests/test_matrices.py
@@ -175,20 +175,6 @@ def test_power():
A = Matrix([[0, 4], [-1, 5]])
assert (A**(S(1)/2))**2 == A
- assert Matrix([[1, 0], [1, 1]])**(S(1)/2) == Matrix([[1, 0], [S.Half, 1]])
- assert Matrix([[1, 0], [1, 1]])**0.5 == Matrix([[1.0, 0], [0.5, 1.0]])
- from sympy.abc import a, b, n
- assert Matrix([[1, a], [0, 1]])**n == Matrix([[1, a*n], [0, 1]])
- assert Matrix([[b, a], [0, b]])**n == Matrix([[b**n, a*b**(n-1)*n], [0, b**n]])
- assert Matrix([[a, 1, 0], [0, a, 1], [0, 0, a]])**n == Matrix([
- [a**n, a**(n-1)*n, a**(n-2)*(n-1)*n/2],
- [0, a**n, a**(n-1)*n],
- [0, 0, a**n]])
- assert Matrix([[a, 1, 0], [0, a, 0], [0, 0, b]])**n == Matrix([
- [a**n, a**(n-1)*n, 0],
- [0, a**n, 0],
- [0, 0, b**n]])
-
def test_creation():
raises(ValueError, lambda: Matrix(5, 5, range(20)))
@@ -1710,6 +1696,9 @@ def test_errors():
raises(ValueError,
lambda: Matrix([[5, 10, 7], [0, -1, 2], [8, 3, 4]]
).LUdecomposition_Simple(iszerofunc=lambda x: abs(x) <= 4))
+ raises(NotImplementedError, lambda: Matrix([[1, 0], [1, 1]])**(S(1)/2))
+ raises(NotImplementedError,
+ lambda: Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])**(0.5))
raises(IndexError, lambda: eye(3)[5, 2])
raises(IndexError, lambda: eye(3)[2, 5])
M = Matrix(((1, 2, 3, 4), (5, 6, 7, 8), (9, 10, 11, 12), (13, 14, 15, 16)))
diff --git a/sympy/sets/tests/test_fancysets.py b/sympy/sets/tests/test_fancysets.py
index a8eab7fe7e..a15a09e22b 100644
--- a/sympy/sets/tests/test_fancysets.py
+++ b/sympy/sets/tests/test_fancysets.py
@@ -424,8 +424,3 @@ def test_ComplexRegion_FiniteSet():
FiniteSet(a + I*x, a + I*y, a + I*z, b + I*x, b + I*y,
b + I*z, c + I*x, c + I*y, c + I*z)
assert ComplexRegion(FiniteSet(2)*FiniteSet(3)) == FiniteSet(2 + 3*I)
-
-
-def test_union_RealSubSet():
- assert (S.Complexes).union(Interval(1, 2)) == S.Complexes
- assert (S.Complexes).union(S.Integers) == S.Complexes
diff --git a/sympy/solvers/tests/test_solveset.py b/sympy/solvers/tests/test_solveset.py
index fdfb75e5a3..2ccd876be9 100644
--- a/sympy/solvers/tests/test_solveset.py
+++ b/sympy/solvers/tests/test_solveset.py
@@ -1017,3 +1017,9 @@ def test_issue_9849():
def test_issue_9953():
assert linsolve([ ], x) == S.EmptySet
+
+
+def test_issue_9913():
+ assert solveset(2*x + 1/(x - 10)**2, x, S.Reals) == \
+ FiniteSet(-(3*sqrt(24081)/4 + S(4027)/4)**(S(1)/3)/3 - 100/
+ (3*(3*sqrt(24081)/4 + S(4027)/4)**(S(1)/3)) + S(20)/3)
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 1,
"issue_text_score": 1,
"test_score": 2
},
"num_modified_files": 6
} | 0.7 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "pytest",
"pip_packages": [
"pytest"
],
"pre_install": null,
"python": "3.4",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | attrs @ file:///opt/conda/conda-bld/attrs_1642510447205/work
certifi==2021.5.30
importlib-metadata @ file:///tmp/build/80754af9/importlib-metadata_1631916693255/work
iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work
more-itertools @ file:///tmp/build/80754af9/more-itertools_1637733554872/work
mpmath==1.3.0
packaging @ file:///tmp/build/80754af9/packaging_1637314298585/work
pluggy @ file:///tmp/build/80754af9/pluggy_1615976315926/work
py @ file:///opt/conda/conda-bld/py_1644396412707/work
pyparsing @ file:///tmp/build/80754af9/pyparsing_1635766073266/work
pytest==6.2.4
-e git+https://github.com/sympy/sympy.git@b157c4295076e0cf94319138cec1c1a5402abcbd#egg=sympy
toml @ file:///tmp/build/80754af9/toml_1616166611790/work
typing_extensions @ file:///opt/conda/conda-bld/typing_extensions_1647553014482/work
zipp @ file:///tmp/build/80754af9/zipp_1633618647012/work
| name: sympy
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- attrs=21.4.0=pyhd3eb1b0_0
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2021.5.30=py36h06a4308_0
- importlib-metadata=4.8.1=py36h06a4308_0
- importlib_metadata=4.8.1=hd3eb1b0_0
- iniconfig=1.1.1=pyhd3eb1b0_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.3=he6710b0_2
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- more-itertools=8.12.0=pyhd3eb1b0_0
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- packaging=21.3=pyhd3eb1b0_0
- pip=21.2.2=py36h06a4308_0
- pluggy=0.13.1=py36h06a4308_0
- py=1.11.0=pyhd3eb1b0_0
- pyparsing=3.0.4=pyhd3eb1b0_0
- pytest=6.2.4=py36h06a4308_2
- python=3.6.13=h12debd9_1
- readline=8.2=h5eee18b_0
- setuptools=58.0.4=py36h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- toml=0.10.2=pyhd3eb1b0_0
- typing_extensions=4.1.1=pyh06a4308_0
- wheel=0.37.1=pyhd3eb1b0_0
- xz=5.6.4=h5eee18b_1
- zipp=3.6.0=pyhd3eb1b0_0
- zlib=1.2.13=h5eee18b_1
- pip:
- mpmath==1.3.0
prefix: /opt/conda/envs/sympy
| [
"sympy/matrices/tests/test_matrices.py::test_errors",
"sympy/solvers/tests/test_solveset.py::test_issue_9913"
] | [] | [
"sympy/matrices/tests/test_matrices.py::test_args",
"sympy/matrices/tests/test_matrices.py::test_division",
"sympy/matrices/tests/test_matrices.py::test_sum",
"sympy/matrices/tests/test_matrices.py::test_addition",
"sympy/matrices/tests/test_matrices.py::test_fancy_index_matrix",
"sympy/matrices/tests/test_matrices.py::test_multiplication",
"sympy/matrices/tests/test_matrices.py::test_power",
"sympy/matrices/tests/test_matrices.py::test_creation",
"sympy/matrices/tests/test_matrices.py::test_tolist",
"sympy/matrices/tests/test_matrices.py::test_as_mutable",
"sympy/matrices/tests/test_matrices.py::test_determinant",
"sympy/matrices/tests/test_matrices.py::test_det_LU_decomposition",
"sympy/matrices/tests/test_matrices.py::test_berkowitz_minors",
"sympy/matrices/tests/test_matrices.py::test_slicing",
"sympy/matrices/tests/test_matrices.py::test_submatrix_assignment",
"sympy/matrices/tests/test_matrices.py::test_extract",
"sympy/matrices/tests/test_matrices.py::test_reshape",
"sympy/matrices/tests/test_matrices.py::test_applyfunc",
"sympy/matrices/tests/test_matrices.py::test_expand",
"sympy/matrices/tests/test_matrices.py::test_random",
"sympy/matrices/tests/test_matrices.py::test_LUdecomp",
"sympy/matrices/tests/test_matrices.py::test_LUsolve",
"sympy/matrices/tests/test_matrices.py::test_QRsolve",
"sympy/matrices/tests/test_matrices.py::test_inverse",
"sympy/matrices/tests/test_matrices.py::test_matrix_inverse_mod",
"sympy/matrices/tests/test_matrices.py::test_util",
"sympy/matrices/tests/test_matrices.py::test_jacobian_hessian",
"sympy/matrices/tests/test_matrices.py::test_QR",
"sympy/matrices/tests/test_matrices.py::test_QR_non_square",
"sympy/matrices/tests/test_matrices.py::test_nullspace",
"sympy/matrices/tests/test_matrices.py::test_columnspace",
"sympy/matrices/tests/test_matrices.py::test_wronskian",
"sympy/matrices/tests/test_matrices.py::test_eigen",
"sympy/matrices/tests/test_matrices.py::test_subs",
"sympy/matrices/tests/test_matrices.py::test_simplify",
"sympy/matrices/tests/test_matrices.py::test_transpose",
"sympy/matrices/tests/test_matrices.py::test_conjugate",
"sympy/matrices/tests/test_matrices.py::test_conj_dirac",
"sympy/matrices/tests/test_matrices.py::test_trace",
"sympy/matrices/tests/test_matrices.py::test_shape",
"sympy/matrices/tests/test_matrices.py::test_col_row_op",
"sympy/matrices/tests/test_matrices.py::test_zip_row_op",
"sympy/matrices/tests/test_matrices.py::test_issue_3950",
"sympy/matrices/tests/test_matrices.py::test_issue_3981",
"sympy/matrices/tests/test_matrices.py::test_evalf",
"sympy/matrices/tests/test_matrices.py::test_is_symbolic",
"sympy/matrices/tests/test_matrices.py::test_is_upper",
"sympy/matrices/tests/test_matrices.py::test_is_lower",
"sympy/matrices/tests/test_matrices.py::test_is_nilpotent",
"sympy/matrices/tests/test_matrices.py::test_zeros_ones_fill",
"sympy/matrices/tests/test_matrices.py::test_empty_zeros",
"sympy/matrices/tests/test_matrices.py::test_issue_3749",
"sympy/matrices/tests/test_matrices.py::test_inv_iszerofunc",
"sympy/matrices/tests/test_matrices.py::test_jacobian_metrics",
"sympy/matrices/tests/test_matrices.py::test_jacobian2",
"sympy/matrices/tests/test_matrices.py::test_issue_4564",
"sympy/matrices/tests/test_matrices.py::test_nonvectorJacobian",
"sympy/matrices/tests/test_matrices.py::test_vec",
"sympy/matrices/tests/test_matrices.py::test_vech",
"sympy/matrices/tests/test_matrices.py::test_vech_errors",
"sympy/matrices/tests/test_matrices.py::test_diag",
"sympy/matrices/tests/test_matrices.py::test_get_diag_blocks1",
"sympy/matrices/tests/test_matrices.py::test_get_diag_blocks2",
"sympy/matrices/tests/test_matrices.py::test_inv_block",
"sympy/matrices/tests/test_matrices.py::test_creation_args",
"sympy/matrices/tests/test_matrices.py::test_diagonal_symmetrical",
"sympy/matrices/tests/test_matrices.py::test_diagonalization",
"sympy/matrices/tests/test_matrices.py::test_jordan_form",
"sympy/matrices/tests/test_matrices.py::test_jordan_form_complex_issue_9274",
"sympy/matrices/tests/test_matrices.py::test_Matrix_berkowitz_charpoly",
"sympy/matrices/tests/test_matrices.py::test_exp",
"sympy/matrices/tests/test_matrices.py::test_has",
"sympy/matrices/tests/test_matrices.py::test_len",
"sympy/matrices/tests/test_matrices.py::test_integrate",
"sympy/matrices/tests/test_matrices.py::test_limit",
"sympy/matrices/tests/test_matrices.py::test_diff",
"sympy/matrices/tests/test_matrices.py::test_getattr",
"sympy/matrices/tests/test_matrices.py::test_hessenberg",
"sympy/matrices/tests/test_matrices.py::test_cholesky",
"sympy/matrices/tests/test_matrices.py::test_LDLdecomposition",
"sympy/matrices/tests/test_matrices.py::test_cholesky_solve",
"sympy/matrices/tests/test_matrices.py::test_LDLsolve",
"sympy/matrices/tests/test_matrices.py::test_lower_triangular_solve",
"sympy/matrices/tests/test_matrices.py::test_upper_triangular_solve",
"sympy/matrices/tests/test_matrices.py::test_diagonal_solve",
"sympy/matrices/tests/test_matrices.py::test_matrix_norm",
"sympy/matrices/tests/test_matrices.py::test_singular_values",
"sympy/matrices/tests/test_matrices.py::test_condition_number",
"sympy/matrices/tests/test_matrices.py::test_equality",
"sympy/matrices/tests/test_matrices.py::test_col_join",
"sympy/matrices/tests/test_matrices.py::test_row_insert",
"sympy/matrices/tests/test_matrices.py::test_col_insert",
"sympy/matrices/tests/test_matrices.py::test_normalized",
"sympy/matrices/tests/test_matrices.py::test_print_nonzero",
"sympy/matrices/tests/test_matrices.py::test_zeros_eye",
"sympy/matrices/tests/test_matrices.py::test_is_zero",
"sympy/matrices/tests/test_matrices.py::test_rotation_matrices",
"sympy/matrices/tests/test_matrices.py::test_DeferredVector",
"sympy/matrices/tests/test_matrices.py::test_DeferredVector_not_iterable",
"sympy/matrices/tests/test_matrices.py::test_DeferredVector_Matrix",
"sympy/matrices/tests/test_matrices.py::test_GramSchmidt",
"sympy/matrices/tests/test_matrices.py::test_casoratian",
"sympy/matrices/tests/test_matrices.py::test_zero_dimension_multiply",
"sympy/matrices/tests/test_matrices.py::test_slice_issue_2884",
"sympy/matrices/tests/test_matrices.py::test_slice_issue_3401",
"sympy/matrices/tests/test_matrices.py::test_copyin",
"sympy/matrices/tests/test_matrices.py::test_invertible_check",
"sympy/matrices/tests/test_matrices.py::test_issue_5964",
"sympy/matrices/tests/test_matrices.py::test_issue_7604",
"sympy/matrices/tests/test_matrices.py::test_is_Identity",
"sympy/matrices/tests/test_matrices.py::test_dot",
"sympy/matrices/tests/test_matrices.py::test_dual",
"sympy/matrices/tests/test_matrices.py::test_anti_symmetric",
"sympy/matrices/tests/test_matrices.py::test_normalize_sort_diogonalization",
"sympy/matrices/tests/test_matrices.py::test_issue_5321",
"sympy/matrices/tests/test_matrices.py::test_issue_5320",
"sympy/matrices/tests/test_matrices.py::test_cross",
"sympy/matrices/tests/test_matrices.py::test_hash",
"sympy/matrices/tests/test_matrices.py::test_adjoint",
"sympy/matrices/tests/test_matrices.py::test_simplify_immutable",
"sympy/matrices/tests/test_matrices.py::test_rank",
"sympy/matrices/tests/test_matrices.py::test_replace",
"sympy/matrices/tests/test_matrices.py::test_replace_map",
"sympy/matrices/tests/test_matrices.py::test_atoms",
"sympy/matrices/tests/test_matrices.py::test_pinv",
"sympy/matrices/tests/test_matrices.py::test_pinv_solve",
"sympy/matrices/tests/test_matrices.py::test_gauss_jordan_solve",
"sympy/matrices/tests/test_matrices.py::test_issue_7201",
"sympy/matrices/tests/test_matrices.py::test_free_symbols",
"sympy/matrices/tests/test_matrices.py::test_hermitian",
"sympy/matrices/tests/test_matrices.py::test_doit",
"sympy/matrices/tests/test_matrices.py::test_issue_9457_9467_9876",
"sympy/matrices/tests/test_matrices.py::test_issue_9422",
"sympy/sets/tests/test_fancysets.py::test_naturals",
"sympy/sets/tests/test_fancysets.py::test_naturals0",
"sympy/sets/tests/test_fancysets.py::test_integers",
"sympy/sets/tests/test_fancysets.py::test_ImageSet",
"sympy/sets/tests/test_fancysets.py::test_image_is_ImageSet",
"sympy/sets/tests/test_fancysets.py::test_ImageSet_iterator_not_injetive",
"sympy/sets/tests/test_fancysets.py::test_Range",
"sympy/sets/tests/test_fancysets.py::test_range_interval_intersection",
"sympy/sets/tests/test_fancysets.py::test_fun",
"sympy/sets/tests/test_fancysets.py::test_Reals",
"sympy/sets/tests/test_fancysets.py::test_Complex",
"sympy/sets/tests/test_fancysets.py::test_intersections",
"sympy/sets/tests/test_fancysets.py::test_infinitely_indexed_set_1",
"sympy/sets/tests/test_fancysets.py::test_infinitely_indexed_set_2",
"sympy/sets/tests/test_fancysets.py::test_imageset_intersect_real",
"sympy/sets/tests/test_fancysets.py::test_ImageSet_simplification",
"sympy/sets/tests/test_fancysets.py::test_ComplexRegion_contains",
"sympy/sets/tests/test_fancysets.py::test_ComplexRegion_intersect",
"sympy/sets/tests/test_fancysets.py::test_ComplexRegion_union",
"sympy/sets/tests/test_fancysets.py::test_ComplexRegion_measure",
"sympy/sets/tests/test_fancysets.py::test_normalize_theta_set",
"sympy/sets/tests/test_fancysets.py::test_ComplexRegion_FiniteSet",
"sympy/solvers/tests/test_solveset.py::test_invert_real",
"sympy/solvers/tests/test_solveset.py::test_invert_complex",
"sympy/solvers/tests/test_solveset.py::test_domain_check",
"sympy/solvers/tests/test_solveset.py::test_is_function_class_equation",
"sympy/solvers/tests/test_solveset.py::test_garbage_input",
"sympy/solvers/tests/test_solveset.py::test_solve_mul",
"sympy/solvers/tests/test_solveset.py::test_solve_invert",
"sympy/solvers/tests/test_solveset.py::test_errorinverses",
"sympy/solvers/tests/test_solveset.py::test_solve_polynomial",
"sympy/solvers/tests/test_solveset.py::test_return_root_of",
"sympy/solvers/tests/test_solveset.py::test__has_rational_power",
"sympy/solvers/tests/test_solveset.py::test_solveset_sqrt_1",
"sympy/solvers/tests/test_solveset.py::test_solveset_sqrt_2",
"sympy/solvers/tests/test_solveset.py::test_solve_sqrt_3",
"sympy/solvers/tests/test_solveset.py::test_solve_polynomial_symbolic_param",
"sympy/solvers/tests/test_solveset.py::test_solve_rational",
"sympy/solvers/tests/test_solveset.py::test_solveset_real_gen_is_pow",
"sympy/solvers/tests/test_solveset.py::test_no_sol",
"sympy/solvers/tests/test_solveset.py::test_sol_zero_real",
"sympy/solvers/tests/test_solveset.py::test_no_sol_rational_extragenous",
"sympy/solvers/tests/test_solveset.py::test_solve_polynomial_cv_1a",
"sympy/solvers/tests/test_solveset.py::test_solveset_real_rational",
"sympy/solvers/tests/test_solveset.py::test_solveset_real_log",
"sympy/solvers/tests/test_solveset.py::test_poly_gens",
"sympy/solvers/tests/test_solveset.py::test_solve_abs",
"sympy/solvers/tests/test_solveset.py::test_real_imag_splitting",
"sympy/solvers/tests/test_solveset.py::test_units",
"sympy/solvers/tests/test_solveset.py::test_solve_only_exp_1",
"sympy/solvers/tests/test_solveset.py::test_atan2",
"sympy/solvers/tests/test_solveset.py::test_piecewise",
"sympy/solvers/tests/test_solveset.py::test_solveset_complex_polynomial",
"sympy/solvers/tests/test_solveset.py::test_sol_zero_complex",
"sympy/solvers/tests/test_solveset.py::test_solveset_complex_rational",
"sympy/solvers/tests/test_solveset.py::test_solveset_complex_exp",
"sympy/solvers/tests/test_solveset.py::test_solve_complex_log",
"sympy/solvers/tests/test_solveset.py::test_solve_complex_sqrt",
"sympy/solvers/tests/test_solveset.py::test_solveset_complex_tan",
"sympy/solvers/tests/test_solveset.py::test_solve_trig",
"sympy/solvers/tests/test_solveset.py::test_solve_invalid_sol",
"sympy/solvers/tests/test_solveset.py::test_solve_complex_unsolvable",
"sympy/solvers/tests/test_solveset.py::test_solveset",
"sympy/solvers/tests/test_solveset.py::test_conditonset",
"sympy/solvers/tests/test_solveset.py::test_solveset_domain",
"sympy/solvers/tests/test_solveset.py::test_improve_coverage",
"sympy/solvers/tests/test_solveset.py::test_issue_9522",
"sympy/solvers/tests/test_solveset.py::test_linear_eq_to_matrix",
"sympy/solvers/tests/test_solveset.py::test_linsolve",
"sympy/solvers/tests/test_solveset.py::test_issue_9556",
"sympy/solvers/tests/test_solveset.py::test_issue_9611",
"sympy/solvers/tests/test_solveset.py::test_issue_9557",
"sympy/solvers/tests/test_solveset.py::test_issue_9778",
"sympy/solvers/tests/test_solveset.py::test_issue_9849",
"sympy/solvers/tests/test_solveset.py::test_issue_9953"
] | [] | BSD | 248 |
peterbe__premailer-138 | e5e1feb7d63fc7499702d70e3197ad3d293e90bf | 2015-09-25 22:24:07 | e5e1feb7d63fc7499702d70e3197ad3d293e90bf | lavr: csstext_to_pairs results are stripped and sorted again. | diff --git a/premailer/merge_style.py b/premailer/merge_style.py
index 0fe93f7..9842e63 100644
--- a/premailer/merge_style.py
+++ b/premailer/merge_style.py
@@ -1,5 +1,6 @@
import cssutils
import threading
+from operator import itemgetter
def csstext_to_pairs(csstext):
@@ -10,11 +11,10 @@ def csstext_to_pairs(csstext):
# The lock is required to avoid ``cssutils`` concurrency
# issues documented in issue #65
with csstext_to_pairs._lock:
- parsed = cssutils.css.CSSVariablesDeclaration(csstext)
- return [
- (key.strip(), parsed.getVariableValue(key).strip())
- for key in sorted(parsed)
- ]
+ return sorted([(prop.name.strip(), prop.propertyValue.cssText.strip())
+ for prop in cssutils.parseStyle(csstext)],
+ key=itemgetter(0))
+
csstext_to_pairs._lock = threading.RLock()
| SyntaxErr on <h1> with !important
Feeding the following into ```transform()``` results in a ```SyntaxErr```:
```
<style type="text/css">
h1 { border:1px solid black }
p { color:red;}
</style>
<p>Hey</p>
<h1 style="display: block;font-family: Helvetica;font-size: 26px;font-style: normal;font-weight: bold;line-height: 100%;letter-spacing: normal;margin-top: 0;margin-right: 0;margin-bottom: 10px;margin-left: 0;text-align: left;color: #202020 !important;">Some Stuff</h1>
```
Results in:
```
SyntaxErr: PropertyValue: Missing token for production Choice(ColorValue, Dimension, URIValue, Value, variable, MSValue, CSSCalc, function): ('CHAR', '!', 1, 230)
```
Removing the ```!important``` from the inline style on the H1 allows it to be inlined as expected. | peterbe/premailer | diff --git a/premailer/tests/test_merge_style.py b/premailer/tests/test_merge_style.py
index 7a8a215..0d4d11f 100644
--- a/premailer/tests/test_merge_style.py
+++ b/premailer/tests/test_merge_style.py
@@ -1,7 +1,5 @@
from __future__ import absolute_import, unicode_literals
import unittest
-import xml
-from nose.tools import raises
from premailer.merge_style import csstext_to_pairs, merge_styles
@@ -14,9 +12,13 @@ class TestMergeStyle(unittest.TestCase):
parsed_csstext = csstext_to_pairs(csstext)
self.assertEqual(('font-size', '1px'), parsed_csstext[0])
- @raises(xml.dom.SyntaxErr)
def test_inline_invalid_syntax(self):
- # inline shouldn't have those as I understand
- # but keep the behaviour
+ # Invalid syntax does not raise
inline = '{color:pink} :hover{color:purple} :active{color:red}'
merge_styles(inline, [], [])
+
+ def test_important_rule(self):
+ # No exception after #133
+ csstext = 'font-size:1px !important'
+ parsed_csstext = csstext_to_pairs(csstext)
+ self.assertEqual(('font-size', '1px'), parsed_csstext[0])
| {
"commit_name": "head_commit",
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true,
"llm_score": {
"difficulty_score": 0,
"issue_text_score": 1,
"test_score": 0
},
"num_modified_files": 1
} | unknown | {
"env_vars": null,
"env_yml_path": [],
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"nose",
"mock",
"coverage",
"pytest"
],
"pre_install": [],
"python": "3.4",
"reqs_path": [
"requirements/base.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | attrs==22.2.0
certifi==2021.5.30
coverage==6.2
cssselect==1.1.0
cssutils==2.3.1
importlib-metadata==4.8.3
iniconfig==1.1.1
lxml==5.3.1
mock==5.2.0
nose==1.3.7
packaging==21.3
pluggy==1.0.0
-e git+https://github.com/peterbe/premailer.git@e5e1feb7d63fc7499702d70e3197ad3d293e90bf#egg=premailer
py==1.11.0
pyparsing==3.1.4
pytest==7.0.1
tomli==1.2.3
typing_extensions==4.1.1
zipp==3.6.0
| name: premailer
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2021.5.30=py36h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.3=he6710b0_2
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- pip=21.2.2=py36h06a4308_0
- python=3.6.13=h12debd9_1
- readline=8.2=h5eee18b_0
- setuptools=58.0.4=py36h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- wheel=0.37.1=pyhd3eb1b0_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- attrs==22.2.0
- coverage==6.2
- cssselect==1.1.0
- cssutils==2.3.1
- importlib-metadata==4.8.3
- iniconfig==1.1.1
- lxml==5.3.1
- mock==5.2.0
- nose==1.3.7
- packaging==21.3
- pluggy==1.0.0
- py==1.11.0
- pyparsing==3.1.4
- pytest==7.0.1
- tomli==1.2.3
- typing-extensions==4.1.1
- zipp==3.6.0
prefix: /opt/conda/envs/premailer
| [
"premailer/tests/test_merge_style.py::TestMergeStyle::test_important_rule",
"premailer/tests/test_merge_style.py::TestMergeStyle::test_inline_invalid_syntax"
] | [] | [
"premailer/tests/test_merge_style.py::TestMergeStyle::test_csstext_to_pairs"
] | [] | BSD 3-Clause "New" or "Revised" License | 249 |
keleshev__schema-85 | 29286c1f9cce20cf70f2b15d9247f2ca6ef1d6c9 | 2015-09-26 00:20:07 | eb7670f0f4615195393dc5350d49fa9a33304137 | codecov-io: ## [Current coverage][1] is `98.07%`
> Merging **#85** into **master** will increase coverage by **+0.05%** as of [`ea3e9e6`][3]
```diff
@@ master #85 diff @@
======================================
Files 1 1
Stmts 152 156 +4
Branches 0 0
Methods 0 0
======================================
+ Hit 149 153 +4
Partial 0 0
Missed 3 3
```
> Review entire [Coverage Diff][4] as of [`ea3e9e6`][3]
[1]: https://codecov.io/github/keleshev/schema?ref=ea3e9e6de11ed22e995df1b30ede806b9912bba5
[2]: https://codecov.io/github/keleshev/schema/features/suggestions?ref=ea3e9e6de11ed22e995df1b30ede806b9912bba5
[3]: https://codecov.io/github/keleshev/schema/commit/ea3e9e6de11ed22e995df1b30ede806b9912bba5
[4]: https://codecov.io/github/keleshev/schema/compare/e94b7144f3016654d1360eb1c070fd2db0d54a43...ea3e9e6de11ed22e995df1b30ede806b9912bba5
> Powered by [Codecov](https://codecov.io). Updated on successful CI builds.
sjakobi: Anybody know a better name than `callable_str`?
And does that function possibly need `_` as a prefix?
skorokithakis: I think that the method does need an underscore as a prefix, it's not meant to be exported by the module. Other than that, I'm ready to merge this.
skorokithakis: Oops, looks like there's a merge conflict. Can you resolve that so I can merge this? | diff --git a/schema.py b/schema.py
index 1ecf845..d24744d 100644
--- a/schema.py
+++ b/schema.py
@@ -70,7 +70,7 @@ class Use(object):
except SchemaError as x:
raise SchemaError([None] + x.autos, [self._error] + x.errors)
except BaseException as x:
- f = self._callable.__name__
+ f = _callable_str(self._callable)
raise SchemaError('%s(%r) raised %r' % (f, data, x), self._error)
@@ -176,7 +176,7 @@ class Schema(object):
raise SchemaError('%r.validate(%r) raised %r' % (s, data, x),
self._error)
if flavor == CALLABLE:
- f = s.__name__
+ f = _callable_str(s)
try:
if s(data):
return data
@@ -211,3 +211,9 @@ class Optional(Schema):
'"%r" is too complex.' % (self._schema,))
self.default = default
self.key = self._schema
+
+
+def _callable_str(callable_):
+ if hasattr(callable_, '__name__'):
+ return callable_.__name__
+ return str(callable_)
| doesn't work with operator.methodcaller
from operator import methodcaller
from schema import Schema
f = methodcaller('endswith', '.csv')
assert f('test.csv')
Schema(f).validate('test.csv')
AttributeError: 'operator.methodcaller' object has no attribute '__name__'
We can't assume that all callables have a `__name__`, it would seem. | keleshev/schema | diff --git a/test_schema.py b/test_schema.py
index ad49343..967dec0 100644
--- a/test_schema.py
+++ b/test_schema.py
@@ -1,5 +1,6 @@
from __future__ import with_statement
from collections import defaultdict, namedtuple
+from operator import methodcaller
import os
from pytest import raises
@@ -383,8 +384,18 @@ def test_missing_keys_exception_with_non_str_dict_keys():
try:
Schema({1: 'x'}).validate(dict())
except SchemaError as e:
- assert (e.args[0] ==
- "Missing keys: 1")
+ assert e.args[0] == "Missing keys: 1"
+ raise
+
+
+def test_issue_56_cant_rely_on_callables_to_have_name():
+ s = Schema(methodcaller('endswith', '.csv'))
+ assert s.validate('test.csv') == 'test.csv'
+ with SE:
+ try:
+ s.validate('test.py')
+ except SchemaError as e:
+ assert "operator.methodcaller" in e.args[0]
raise
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_short_problem_statement"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 1,
"issue_text_score": 2,
"test_score": 0
},
"num_modified_files": 1
} | 0.3 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest",
"pytest-cov"
],
"pre_install": null,
"python": "3.9",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | coverage==7.8.0
exceptiongroup==1.2.2
iniconfig==2.1.0
packaging==24.2
pluggy==1.5.0
pytest==8.3.5
pytest-cov==6.0.0
-e git+https://github.com/keleshev/schema.git@29286c1f9cce20cf70f2b15d9247f2ca6ef1d6c9#egg=schema
tomli==2.2.1
| name: schema
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=3.0.16=h5eee18b_0
- pip=25.0=py39h06a4308_0
- python=3.9.21=he870216_1
- readline=8.2=h5eee18b_0
- setuptools=75.8.0=py39h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- tzdata=2025a=h04d1e81_0
- wheel=0.45.1=py39h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- coverage==7.8.0
- exceptiongroup==1.2.2
- iniconfig==2.1.0
- packaging==24.2
- pluggy==1.5.0
- pytest==8.3.5
- pytest-cov==6.0.0
- tomli==2.2.1
prefix: /opt/conda/envs/schema
| [
"test_schema.py::test_issue_56_cant_rely_on_callables_to_have_name"
] | [] | [
"test_schema.py::test_schema",
"test_schema.py::test_validate_file",
"test_schema.py::test_and",
"test_schema.py::test_or",
"test_schema.py::test_validate_list",
"test_schema.py::test_list_tuple_set_frozenset",
"test_schema.py::test_strictly",
"test_schema.py::test_dict",
"test_schema.py::test_dict_keys",
"test_schema.py::test_dict_optional_keys",
"test_schema.py::test_dict_optional_defaults",
"test_schema.py::test_dict_subtypes",
"test_schema.py::test_complex",
"test_schema.py::test_nice_errors",
"test_schema.py::test_use_error_handling",
"test_schema.py::test_or_error_handling",
"test_schema.py::test_and_error_handling",
"test_schema.py::test_schema_error_handling",
"test_schema.py::test_use_json",
"test_schema.py::test_error_reporting",
"test_schema.py::test_schema_repr",
"test_schema.py::test_validate_object",
"test_schema.py::test_issue_9_prioritized_key_comparison",
"test_schema.py::test_issue_9_prioritized_key_comparison_in_dicts",
"test_schema.py::test_missing_keys_exception_with_non_str_dict_keys",
"test_schema.py::test_exception_handling_with_bad_validators"
] | [] | MIT License | 250 |
mne-tools__mne-python-2495 | a9cc9c9b5e9433fd06258e05e41cc7edacfe4391 | 2015-09-26 16:48:32 | 632e49f0470fc9526936dbb474fd6aa46501fe4d | diff --git a/doc/manual/cookbook.rst b/doc/manual/cookbook.rst
index ac96a2780..17a256d13 100644
--- a/doc/manual/cookbook.rst
+++ b/doc/manual/cookbook.rst
@@ -347,9 +347,9 @@ ways:
- Employ empty room data (collected without the subject) to
calculate the full noise covariance matrix. This is recommended
for analyzing ongoing spontaneous activity. This can be done using
- :func:`mne.compute_raw_data_covariance` as::
+ :func:`mne.compute_raw_covariance` as::
- >>> cov = mne.compute_raw_data_covariance(raw_erm)
+ >>> cov = mne.compute_raw_covariance(raw_erm)
- Employ a section of continuous raw data collected in the presence
of the subject to calculate the full noise covariance matrix. This
@@ -360,7 +360,7 @@ ways:
(``*> 200 s``) segment of data with epileptic spikes present provided
that the spikes occur infrequently and that the segment is apparently
stationary with respect to background brain activity. This can also
- use :func:`mne.compute_raw_data_covariance`.
+ use :func:`mne.compute_raw_covariance`.
See :ref:`covariance` for more information.
diff --git a/doc/python_reference.rst b/doc/python_reference.rst
index e700b9131..4a9df6655 100644
--- a/doc/python_reference.rst
+++ b/doc/python_reference.rst
@@ -512,7 +512,7 @@ Covariance
:template: function.rst
compute_covariance
- compute_raw_data_covariance
+ compute_raw_covariance
make_ad_hoc_cov
read_cov
write_cov
diff --git a/examples/preprocessing/plot_estimate_covariance_matrix_raw.py b/examples/preprocessing/plot_estimate_covariance_matrix_raw.py
index a0d799cc0..efafce8e8 100644
--- a/examples/preprocessing/plot_estimate_covariance_matrix_raw.py
+++ b/examples/preprocessing/plot_estimate_covariance_matrix_raw.py
@@ -29,7 +29,7 @@ picks = mne.pick_types(raw.info, meg=True, eeg=True, stim=False, eog=True,
reject = dict(eeg=80e-6, eog=150e-6)
# Compute the covariance from the raw data
-cov = mne.compute_raw_data_covariance(raw, picks=picks, reject=reject)
+cov = mne.compute_raw_covariance(raw, picks=picks, reject=reject)
print(cov)
###############################################################################
diff --git a/examples/preprocessing/plot_xdawn_denoising.py b/examples/preprocessing/plot_xdawn_denoising.py
index b861a7cd0..76b7ce824 100644
--- a/examples/preprocessing/plot_xdawn_denoising.py
+++ b/examples/preprocessing/plot_xdawn_denoising.py
@@ -31,7 +31,7 @@ efficient sensor selection in a P300 BCI. In Signal Processing Conference,
# License: BSD (3-clause)
-from mne import (io, compute_raw_data_covariance, read_events, pick_types,
+from mne import (io, compute_raw_covariance, read_events, pick_types,
Epochs)
from mne.datasets import sample
from mne.preprocessing import Xdawn
@@ -65,7 +65,7 @@ epochs = Epochs(raw, events, event_id, tmin, tmax, proj=False,
plot_epochs_image(epochs['vis_r'], picks=[230], vmin=-500, vmax=500)
# Estimates signal covariance
-signal_cov = compute_raw_data_covariance(raw, picks=picks)
+signal_cov = compute_raw_covariance(raw, picks=picks)
# Xdawn instance
xd = Xdawn(n_components=2, signal_cov=signal_cov)
diff --git a/mne/__init__.py b/mne/__init__.py
index 43e82ce21..19cc4a46c 100644
--- a/mne/__init__.py
+++ b/mne/__init__.py
@@ -36,7 +36,7 @@ from .bem import (make_sphere_model, make_bem_model, make_bem_solution,
read_bem_solution, write_bem_solution)
from .cov import (read_cov, write_cov, Covariance,
compute_covariance, compute_raw_data_covariance,
- whiten_evoked, make_ad_hoc_cov)
+ compute_raw_covariance, whiten_evoked, make_ad_hoc_cov)
from .event import (read_events, write_events, find_events, merge_events,
pick_events, make_fixed_length_events, concatenate_events,
find_stim_steps)
diff --git a/mne/cov.py b/mne/cov.py
index 0cd17ab27..bbf7fff5e 100644
--- a/mne/cov.py
+++ b/mne/cov.py
@@ -33,6 +33,7 @@ from .defaults import _handle_default
from .epochs import _is_good
from .utils import (check_fname, logger, verbose, estimate_rank,
_compute_row_norms, check_sklearn_version, _time_mask)
+from .utils import deprecated
from .externals.six.moves import zip
from .externals.six import string_types
@@ -100,7 +101,7 @@ class Covariance(dict):
See Also
--------
compute_covariance
- compute_raw_data_covariance
+ compute_raw_covariance
make_ad_hoc_cov
read_cov
"""
@@ -275,7 +276,7 @@ def read_cov(fname, verbose=None):
See Also
--------
- write_cov, compute_covariance, compute_raw_data_covariance
+ write_cov, compute_covariance, compute_raw_covariance
"""
check_fname(fname, 'covariance', ('-cov.fif', '-cov.fif.gz'))
f, tree = fiff_open(fname)[:2]
@@ -338,10 +339,20 @@ def _check_n_samples(n_samples, n_chan):
logger.warning(text)
+@deprecated('"compute_raw_data_covariance" is deprecated and will be '
+ 'removed in MNE-0.11. Please use compute_raw_covariance instead')
@verbose
def compute_raw_data_covariance(raw, tmin=None, tmax=None, tstep=0.2,
reject=None, flat=None, picks=None,
verbose=None):
+ return compute_raw_covariance(raw, tmin, tmax, tstep,
+ reject, flat, picks, verbose)
+
+
+@verbose
+def compute_raw_covariance(raw, tmin=None, tmax=None, tstep=0.2,
+ reject=None, flat=None, picks=None,
+ verbose=None):
"""Estimate noise covariance matrix from a continuous segment of raw data.
It is typically useful to estimate a noise covariance
@@ -557,7 +568,7 @@ def compute_covariance(epochs, keep_sample_mean=True, tmin=None, tmax=None,
See Also
--------
- compute_raw_data_covariance : Estimate noise covariance from raw data
+ compute_raw_covariance : Estimate noise covariance from raw data
References
----------
| rename compute_raw_data_covariance to compute_raw_covariance
any objection to rename compute_raw_data_covariance to compute_raw_covariance ?
the _data is not consistent. See eg compute_raw_psd etc... | mne-tools/mne-python | diff --git a/mne/beamformer/tests/test_lcmv.py b/mne/beamformer/tests/test_lcmv.py
index b9435b236..d92c60a11 100644
--- a/mne/beamformer/tests/test_lcmv.py
+++ b/mne/beamformer/tests/test_lcmv.py
@@ -205,7 +205,7 @@ def test_lcmv_raw():
picks = mne.pick_types(raw.info, meg=True, exclude='bads',
selection=left_temporal_channels)
- data_cov = mne.compute_raw_data_covariance(raw, tmin=tmin, tmax=tmax)
+ data_cov = mne.compute_raw_covariance(raw, tmin=tmin, tmax=tmax)
stc = lcmv_raw(raw, forward, noise_cov, data_cov, reg=0.01, label=label,
start=start, stop=stop, picks=picks)
diff --git a/mne/preprocessing/tests/test_maxwell.py b/mne/preprocessing/tests/test_maxwell.py
index 118f74aa9..c7f07ff0a 100644
--- a/mne/preprocessing/tests/test_maxwell.py
+++ b/mne/preprocessing/tests/test_maxwell.py
@@ -9,7 +9,7 @@ from numpy.testing import (assert_equal, assert_allclose,
assert_array_almost_equal)
from nose.tools import assert_true, assert_raises
-from mne import compute_raw_data_covariance, pick_types
+from mne import compute_raw_covariance, pick_types
from mne.cov import _estimate_rank_meeg_cov
from mne.datasets import testing
from mne.forward._make_forward import _prep_meg_channels
@@ -142,8 +142,8 @@ def test_maxwell_filter_additional():
rtol=1e-6, atol=1e-20)
# Test rank of covariance matrices for raw and SSS processed data
- cov_raw = compute_raw_data_covariance(raw)
- cov_sss = compute_raw_data_covariance(raw_sss)
+ cov_raw = compute_raw_covariance(raw)
+ cov_sss = compute_raw_covariance(raw_sss)
scalings = None
cov_raw_rank = _estimate_rank_meeg_cov(cov_raw['data'], raw.info, scalings)
diff --git a/mne/preprocessing/tests/test_xdawn.py b/mne/preprocessing/tests/test_xdawn.py
index 3be444350..453ead003 100644
--- a/mne/preprocessing/tests/test_xdawn.py
+++ b/mne/preprocessing/tests/test_xdawn.py
@@ -7,7 +7,7 @@ import os.path as op
from nose.tools import (assert_equal, assert_raises)
from numpy.testing import assert_array_equal
from mne import (io, Epochs, read_events, pick_types,
- compute_raw_data_covariance)
+ compute_raw_covariance)
from mne.utils import requires_sklearn, run_tests_if_main
from mne.preprocessing.xdawn import Xdawn
@@ -56,7 +56,7 @@ def test_xdawn_fit():
# ========== with signal cov provided ====================
# provide covariance object
- signal_cov = compute_raw_data_covariance(raw, picks=picks)
+ signal_cov = compute_raw_covariance(raw, picks=picks)
xd = Xdawn(n_components=2, correct_overlap=False,
signal_cov=signal_cov, reg=None)
xd.fit(epochs)
diff --git a/mne/tests/test_cov.py b/mne/tests/test_cov.py
index 3f9fc1dd2..6619b047c 100644
--- a/mne/tests/test_cov.py
+++ b/mne/tests/test_cov.py
@@ -18,7 +18,7 @@ from mne.cov import (regularize, whiten_evoked, _estimate_rank_meeg_cov,
_undo_scaling_cov)
from mne import (read_cov, write_cov, Epochs, merge_events,
- find_events, compute_raw_data_covariance,
+ find_events, compute_raw_covariance,
compute_covariance, read_evokeds, compute_proj_raw,
pick_channels_cov, pick_channels, pick_types, pick_info,
make_ad_hoc_cov)
@@ -98,7 +98,7 @@ def test_cov_estimation_on_raw_segment():
"""
tempdir = _TempDir()
raw = Raw(raw_fname, preload=False)
- cov = compute_raw_data_covariance(raw)
+ cov = compute_raw_covariance(raw)
cov_mne = read_cov(erm_cov_fname)
assert_true(cov_mne.ch_names == cov.ch_names)
assert_true(linalg.norm(cov.data - cov_mne.data, ord='fro') /
@@ -113,7 +113,7 @@ def test_cov_estimation_on_raw_segment():
# test with a subset of channels
picks = pick_channels(raw.ch_names, include=raw.ch_names[:5])
- cov = compute_raw_data_covariance(raw, picks=picks)
+ cov = compute_raw_covariance(raw, picks=picks)
assert_true(cov_mne.ch_names[:5] == cov.ch_names)
assert_true(linalg.norm(cov.data - cov_mne.data[picks][:, picks],
ord='fro') / linalg.norm(cov.data, ord='fro') < 1e-4)
@@ -121,7 +121,7 @@ def test_cov_estimation_on_raw_segment():
raw_2 = raw.crop(0, 1)
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter('always')
- cov = compute_raw_data_covariance(raw_2)
+ cov = compute_raw_covariance(raw_2)
assert_true(len(w) == 1)
@@ -264,12 +264,12 @@ def test_rank():
raw_sss = Raw(hp_fif_fname)
raw_sss.add_proj(compute_proj_raw(raw_sss))
- cov_sample = compute_raw_data_covariance(raw_sample)
- cov_sample_proj = compute_raw_data_covariance(
+ cov_sample = compute_raw_covariance(raw_sample)
+ cov_sample_proj = compute_raw_covariance(
raw_sample.copy().apply_proj())
- cov_sss = compute_raw_data_covariance(raw_sss)
- cov_sss_proj = compute_raw_data_covariance(
+ cov_sss = compute_raw_covariance(raw_sss)
+ cov_sss_proj = compute_raw_covariance(
raw_sss.copy().apply_proj())
picks_all_sample = pick_types(raw_sample.info, meg=True, eeg=True)
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 0,
"issue_text_score": 0,
"test_score": 0
},
"num_modified_files": 6
} | 0.9 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[dev]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"numpy>=1.16.0",
"pandas>=1.0.0",
"scikit-learn",
"h5py",
"pysurfer",
"nose",
"nose-timer",
"pytest"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.7",
"reqs_path": [
"requirements/base.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | apptools==5.2.1
certifi @ file:///croot/certifi_1671487769961/work/certifi
configobj==5.0.9
cycler==0.11.0
envisage==7.0.3
exceptiongroup==1.2.2
fonttools==4.38.0
h5py==3.8.0
importlib-metadata==6.7.0
importlib-resources==5.12.0
iniconfig==2.0.0
joblib==1.3.2
kiwisolver==1.4.5
matplotlib==3.5.3
mayavi==4.8.1
-e git+https://github.com/mne-tools/mne-python.git@a9cc9c9b5e9433fd06258e05e41cc7edacfe4391#egg=mne
nibabel==4.0.2
nose==1.3.7
nose-timer==1.0.1
numpy==1.21.6
packaging==24.0
pandas==1.3.5
Pillow==9.5.0
pluggy==1.2.0
pyface==8.0.0
Pygments==2.17.2
pyparsing==3.1.4
pysurfer==0.11.2
pytest==7.4.4
python-dateutil==2.9.0.post0
pytz==2025.2
scikit-learn==1.0.2
scipy==1.7.3
six==1.17.0
threadpoolctl==3.1.0
tomli==2.0.1
traits==6.4.3
traitsui==8.0.0
typing_extensions==4.7.1
vtk==9.3.1
zipp==3.15.0
| name: mne-python
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2022.12.7=py37h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- pip=22.3.1=py37h06a4308_0
- python=3.7.16=h7a1cb2a_0
- readline=8.2=h5eee18b_0
- setuptools=65.6.3=py37h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- wheel=0.38.4=py37h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- apptools==5.2.1
- configobj==5.0.9
- cycler==0.11.0
- envisage==7.0.3
- exceptiongroup==1.2.2
- fonttools==4.38.0
- h5py==3.8.0
- importlib-metadata==6.7.0
- importlib-resources==5.12.0
- iniconfig==2.0.0
- joblib==1.3.2
- kiwisolver==1.4.5
- matplotlib==3.5.3
- mayavi==4.8.1
- nibabel==4.0.2
- nose==1.3.7
- nose-timer==1.0.1
- numpy==1.21.6
- packaging==24.0
- pandas==1.3.5
- pillow==9.5.0
- pluggy==1.2.0
- pyface==8.0.0
- pygments==2.17.2
- pyparsing==3.1.4
- pysurfer==0.11.2
- pytest==7.4.4
- python-dateutil==2.9.0.post0
- pytz==2025.2
- scikit-learn==1.0.2
- scipy==1.7.3
- six==1.17.0
- threadpoolctl==3.1.0
- tomli==2.0.1
- traits==6.4.3
- traitsui==8.0.0
- typing-extensions==4.7.1
- vtk==9.3.1
- zipp==3.15.0
prefix: /opt/conda/envs/mne-python
| [
"mne/preprocessing/tests/test_xdawn.py::test_xdawn_init",
"mne/preprocessing/tests/test_xdawn.py::test_xdawn_fit",
"mne/preprocessing/tests/test_xdawn.py::test_xdawn_apply_transform",
"mne/preprocessing/tests/test_xdawn.py::test_xdawn_regularization",
"mne/tests/test_cov.py::test_ad_hoc_cov",
"mne/tests/test_cov.py::test_arithmetic_cov",
"mne/tests/test_cov.py::test_regularize_cov",
"mne/tests/test_cov.py::test_evoked_whiten",
"mne/tests/test_cov.py::test_rank",
"mne/tests/test_cov.py::test_cov_scaling"
] | [
"mne/tests/test_cov.py::test_io_cov",
"mne/tests/test_cov.py::test_cov_estimation_on_raw_segment",
"mne/tests/test_cov.py::test_cov_estimation_with_triggers",
"mne/tests/test_cov.py::test_auto_low_rank",
"mne/tests/test_cov.py::test_compute_covariance_auto_reg"
] | [] | [] | BSD 3-Clause "New" or "Revised" License | 251 |
|
tornadoweb__tornado-1526 | 7493c94369299020eda0d452e7dda793073b7f63 | 2015-09-27 17:43:48 | 4ee9ba94de11aaa4f932560fa2b3d8ceb8c61d2a | diff --git a/.travis.yml b/.travis.yml
index 4b199eb8..0a184314 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -35,6 +35,7 @@ install:
# codecov tries to install the latest.
- if [[ $TRAVIS_PYTHON_VERSION == '3.2' ]]; then travis_retry pip install 'coverage<4.0'; fi
- travis_retry pip install codecov
+ - curl-config --version; pip freeze
script:
# Get out of the source directory before running tests to avoid PYTHONPATH
diff --git a/tornado/simple_httpclient.py b/tornado/simple_httpclient.py
index 81ed8873..074d18b8 100644
--- a/tornado/simple_httpclient.py
+++ b/tornado/simple_httpclient.py
@@ -462,9 +462,12 @@ class _HTTPConnection(httputil.HTTPMessageDelegate):
if self.request.expect_100_continue and first_line.code == 100:
self._write_body(False)
return
- self.headers = headers
self.code = first_line.code
self.reason = first_line.reason
+ self.headers = headers
+
+ if self._should_follow_redirect():
+ return
if self.request.header_callback is not None:
# Reassemble the start line.
@@ -473,14 +476,17 @@ class _HTTPConnection(httputil.HTTPMessageDelegate):
self.request.header_callback("%s: %s\r\n" % (k, v))
self.request.header_callback('\r\n')
+ def _should_follow_redirect(self):
+ return (self.request.follow_redirects and
+ self.request.max_redirects > 0 and
+ self.code in (301, 302, 303, 307))
+
def finish(self):
data = b''.join(self.chunks)
self._remove_timeout()
original_request = getattr(self.request, "original_request",
self.request)
- if (self.request.follow_redirects and
- self.request.max_redirects > 0 and
- self.code in (301, 302, 303, 307)):
+ if self._should_follow_redirect():
assert isinstance(self.request, _RequestProxy)
new_request = copy.copy(self.request.request)
new_request.url = urlparse.urljoin(self.request.url,
@@ -527,6 +533,9 @@ class _HTTPConnection(httputil.HTTPMessageDelegate):
self.stream.close()
def data_received(self, chunk):
+ if self._should_follow_redirect():
+ # We're going to follow a redirect so just discard the body.
+ return
if self.request.streaming_callback is not None:
self.request.streaming_callback(chunk)
else:
diff --git a/tornado/web.py b/tornado/web.py
index afa9ca58..aa203495 100644
--- a/tornado/web.py
+++ b/tornado/web.py
@@ -1065,33 +1065,12 @@ class RequestHandler(object):
def current_user(self):
"""The authenticated user for this request.
- This is set in one of two ways:
+ This is a cached version of `get_current_user`, which you can
+ override to set the user based on, e.g., a cookie. If that
+ method is not overridden, this method always returns None.
- * A subclass may override `get_current_user()`, which will be called
- automatically the first time ``self.current_user`` is accessed.
- `get_current_user()` will only be called once per request,
- and is cached for future access::
-
- def get_current_user(self):
- user_cookie = self.get_secure_cookie("user")
- if user_cookie:
- return json.loads(user_cookie)
- return None
-
- * It may be set as a normal variable, typically from an overridden
- `prepare()`::
-
- @gen.coroutine
- def prepare(self):
- user_id_cookie = self.get_secure_cookie("user_id")
- if user_id_cookie:
- self.current_user = yield load_user(user_id_cookie)
-
- Note that `prepare()` may be a coroutine while `get_current_user()`
- may not, so the latter form is necessary if loading the user requires
- asynchronous operations.
-
- The user object may any type of the application's choosing.
+ We lazy-load the current user the first time this method is called
+ and cache the result after that.
"""
if not hasattr(self, "_current_user"):
self._current_user = self.get_current_user()
@@ -1102,10 +1081,7 @@ class RequestHandler(object):
self._current_user = value
def get_current_user(self):
- """Override to determine the current user from, e.g., a cookie.
-
- This method may not be a coroutine.
- """
+ """Override to determine the current user from, e.g., a cookie."""
return None
def get_login_url(self):
| tornado.httpclient.HTTPClient.fetch() executes callback on contents of redirect response
Assume the following example of using the HTTPClient to retrieve a file:
```python
>>> tornado.version
'4.2.1'
>>> try:
... fh = open('/tmp/foo.msi', 'wb')
... def handle_chunk(chunk):
... fh.write(chunk)
... tornado.httpclient.HTTPClient(max_body_size=107374182400).fetch('http://download.macromedia.com/get/flashplayer/current/licensing/win/install_flash_player_18_plugin.msi', method='GET', streaming_callback=handle_chunk)
... finally:
... fh.close()
...
HTTPResponse(_body=None,buffer=<_io.BytesIO object at 0x7f933e4a7470>,code=200,effective_url='http://fpdownload.macromedia.com/get/flashplayer/current/licensing/win/install_flash_player_18_plugin.msi',error=None,headers={'Content-Length': '19924480', 'Accept-Ranges': 'bytes', 'Server': 'Apache', 'Last-Modified': 'Fri, 07 Aug 2015 12:22:31 GMT', 'Connection': 'close', 'Etag': '"1300600-51cb7b0998fc0"', 'Date': 'Mon, 14 Sep 2015 17:24:22 GMT', 'Content-Type': 'application/x-msi'},reason='OK',request=<tornado.httpclient.HTTPRequest object at 0x7f933e196250>,request_time=4.273449897766113,time_info={})
>>> with open('/tmp/foo.msi', 'rb') as fh:
... first_288_bytes = fh.read(288)
...
>>> first_288_bytes
'<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">\n<html><head>\n<title>302 Found</title>\n</head><body>\n<h1>Found</h1>\n<p>The document has moved <a href="http://fpdownload.macromedia.com/get/flashplayer/current/licensing/win/install_flash_player_18_plugin.msi">here</a>.</p>\n</body></html>'
```
This results in a corrupted file, as the HTTP response from the 302 redirect is written to the destination file via the callback.
It's entirely possible that I am doing something wrong, but this looks like a bug. I can conceive of no way to reliably determine that the callback is being executed on a 302 redirect response, since the raw data from the chunk of the file is what is passed to the callback function, leaving nothing from the HTTPResponse object to be examined in order to determine whether or not to write the chunk to the destination file. | tornadoweb/tornado | diff --git a/tornado/test/httpclient_test.py b/tornado/test/httpclient_test.py
index ecc63e4a..6254c266 100644
--- a/tornado/test/httpclient_test.py
+++ b/tornado/test/httpclient_test.py
@@ -48,6 +48,7 @@ class PutHandler(RequestHandler):
class RedirectHandler(RequestHandler):
def prepare(self):
+ self.write('redirects can have bodies too')
self.redirect(self.get_argument("url"),
status=int(self.get_argument("status", "302")))
diff --git a/tornado/test/simple_httpclient_test.py b/tornado/test/simple_httpclient_test.py
index dc4c865b..5214c1e4 100644
--- a/tornado/test/simple_httpclient_test.py
+++ b/tornado/test/simple_httpclient_test.py
@@ -11,14 +11,15 @@ import socket
import ssl
import sys
+from tornado.escape import to_unicode
from tornado import gen
from tornado.httpclient import AsyncHTTPClient
from tornado.httputil import HTTPHeaders, ResponseStartLine
from tornado.ioloop import IOLoop
from tornado.log import gen_log
from tornado.netutil import Resolver, bind_sockets
-from tornado.simple_httpclient import SimpleAsyncHTTPClient, _default_ca_certs
-from tornado.test.httpclient_test import ChunkHandler, CountdownHandler, HelloWorldHandler
+from tornado.simple_httpclient import SimpleAsyncHTTPClient
+from tornado.test.httpclient_test import ChunkHandler, CountdownHandler, HelloWorldHandler, RedirectHandler
from tornado.test import httpclient_test
from tornado.testing import AsyncHTTPTestCase, AsyncHTTPSTestCase, AsyncTestCase, ExpectLog
from tornado.test.util import skipOnTravis, skipIfNoIPv6, refusing_port, unittest
@@ -145,6 +146,7 @@ class SimpleHTTPClientTestMixin(object):
url("/no_content_length", NoContentLengthHandler),
url("/echo_post", EchoPostHandler),
url("/respond_in_prepare", RespondInPrepareHandler),
+ url("/redirect", RedirectHandler),
], gzip=True)
def test_singleton(self):
@@ -416,6 +418,24 @@ class SimpleHTTPClientTestMixin(object):
expect_100_continue=True)
self.assertEqual(response.code, 403)
+ def test_streaming_follow_redirects(self):
+ # When following redirects, header and streaming callbacks
+ # should only be called for the final result.
+ # TODO(bdarnell): this test belongs in httpclient_test instead of
+ # simple_httpclient_test, but it fails with the version of libcurl
+ # available on travis-ci. Move it when that has been upgraded
+ # or we have a better framework to skip tests based on curl version.
+ headers = []
+ chunks = []
+ self.fetch("/redirect?url=/hello",
+ header_callback=headers.append,
+ streaming_callback=chunks.append)
+ chunks = list(map(to_unicode, chunks))
+ self.assertEqual(chunks, ['Hello world!'])
+ # Make sure we only got one set of headers.
+ num_start_lines = len([h for h in headers if h.startswith("HTTP/")])
+ self.assertEqual(num_start_lines, 1)
+
class SimpleHTTPClientTestCase(SimpleHTTPClientTestMixin, AsyncHTTPTestCase):
def setUp(self):
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_hyperlinks",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 2,
"issue_text_score": 0,
"test_score": 0
},
"num_modified_files": 3
} | 4.2 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "pytest",
"pip_packages": [
"futures",
"mock",
"monotonic",
"trollius",
"pytest"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.5",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | attrs @ file:///opt/conda/conda-bld/attrs_1642510447205/work
certifi==2021.5.30
futures==2.2.0
importlib-metadata @ file:///tmp/build/80754af9/importlib-metadata_1631916693255/work
iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work
mock==5.2.0
monotonic==1.6
more-itertools @ file:///tmp/build/80754af9/more-itertools_1637733554872/work
packaging @ file:///tmp/build/80754af9/packaging_1637314298585/work
pluggy @ file:///tmp/build/80754af9/pluggy_1615976315926/work
py @ file:///opt/conda/conda-bld/py_1644396412707/work
pyparsing @ file:///tmp/build/80754af9/pyparsing_1635766073266/work
pytest==6.2.4
six==1.17.0
toml @ file:///tmp/build/80754af9/toml_1616166611790/work
-e git+https://github.com/tornadoweb/tornado.git@7493c94369299020eda0d452e7dda793073b7f63#egg=tornado
trollius==2.1.post2
typing_extensions @ file:///opt/conda/conda-bld/typing_extensions_1647553014482/work
zipp @ file:///tmp/build/80754af9/zipp_1633618647012/work
| name: tornado
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- attrs=21.4.0=pyhd3eb1b0_0
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2021.5.30=py36h06a4308_0
- importlib-metadata=4.8.1=py36h06a4308_0
- importlib_metadata=4.8.1=hd3eb1b0_0
- iniconfig=1.1.1=pyhd3eb1b0_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.3=he6710b0_2
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- more-itertools=8.12.0=pyhd3eb1b0_0
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- packaging=21.3=pyhd3eb1b0_0
- pip=21.2.2=py36h06a4308_0
- pluggy=0.13.1=py36h06a4308_0
- py=1.11.0=pyhd3eb1b0_0
- pyparsing=3.0.4=pyhd3eb1b0_0
- pytest=6.2.4=py36h06a4308_2
- python=3.6.13=h12debd9_1
- readline=8.2=h5eee18b_0
- setuptools=58.0.4=py36h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- toml=0.10.2=pyhd3eb1b0_0
- typing_extensions=4.1.1=pyh06a4308_0
- wheel=0.37.1=pyhd3eb1b0_0
- xz=5.6.4=h5eee18b_1
- zipp=3.6.0=pyhd3eb1b0_0
- zlib=1.2.13=h5eee18b_1
- pip:
- futures==2.2.0
- mock==5.2.0
- monotonic==1.6
- six==1.17.0
- trollius==2.1.post2
prefix: /opt/conda/envs/tornado
| [
"tornado/test/simple_httpclient_test.py::SimpleHTTPClientTestCase::test_streaming_follow_redirects",
"tornado/test/simple_httpclient_test.py::SimpleHTTPSClientTestCase::test_streaming_follow_redirects"
] | [
"tornado/test/simple_httpclient_test.py::SimpleHTTPClientTestCase::test_no_content",
"tornado/test/simple_httpclient_test.py::SimpleHTTPSClientTestCase::test_no_content",
"tornado/test/simple_httpclient_test.py::MaxHeaderSizeTest::test_large_headers",
"tornado/test/simple_httpclient_test.py::MaxBodySizeTest::test_large_body"
] | [
"tornado/test/httpclient_test.py::HTTPClientCommonTestCase::test_304_with_content_length",
"tornado/test/httpclient_test.py::HTTPClientCommonTestCase::test_all_methods",
"tornado/test/httpclient_test.py::HTTPClientCommonTestCase::test_basic_auth",
"tornado/test/httpclient_test.py::HTTPClientCommonTestCase::test_basic_auth_explicit_mode",
"tornado/test/httpclient_test.py::HTTPClientCommonTestCase::test_body_encoding",
"tornado/test/httpclient_test.py::HTTPClientCommonTestCase::test_body_sanity_checks",
"tornado/test/httpclient_test.py::HTTPClientCommonTestCase::test_chunked",
"tornado/test/httpclient_test.py::HTTPClientCommonTestCase::test_chunked_close",
"tornado/test/httpclient_test.py::HTTPClientCommonTestCase::test_configure_defaults",
"tornado/test/httpclient_test.py::HTTPClientCommonTestCase::test_credentials_in_url",
"tornado/test/httpclient_test.py::HTTPClientCommonTestCase::test_final_callback_stack_context",
"tornado/test/httpclient_test.py::HTTPClientCommonTestCase::test_follow_redirect",
"tornado/test/httpclient_test.py::HTTPClientCommonTestCase::test_future_http_error",
"tornado/test/httpclient_test.py::HTTPClientCommonTestCase::test_future_http_error_no_raise",
"tornado/test/httpclient_test.py::HTTPClientCommonTestCase::test_future_interface",
"tornado/test/httpclient_test.py::HTTPClientCommonTestCase::test_header_callback",
"tornado/test/httpclient_test.py::HTTPClientCommonTestCase::test_header_callback_stack_context",
"tornado/test/httpclient_test.py::HTTPClientCommonTestCase::test_header_types",
"tornado/test/httpclient_test.py::HTTPClientCommonTestCase::test_hello_world",
"tornado/test/httpclient_test.py::HTTPClientCommonTestCase::test_patch_receives_payload",
"tornado/test/httpclient_test.py::HTTPClientCommonTestCase::test_post",
"tornado/test/httpclient_test.py::HTTPClientCommonTestCase::test_put_307",
"tornado/test/httpclient_test.py::HTTPClientCommonTestCase::test_reuse_request_from_response",
"tornado/test/httpclient_test.py::HTTPClientCommonTestCase::test_streaming_callback",
"tornado/test/httpclient_test.py::HTTPClientCommonTestCase::test_streaming_stack_context",
"tornado/test/httpclient_test.py::HTTPClientCommonTestCase::test_types",
"tornado/test/httpclient_test.py::HTTPClientCommonTestCase::test_unsupported_auth_mode",
"tornado/test/httpclient_test.py::RequestProxyTest::test_bad_attribute",
"tornado/test/httpclient_test.py::RequestProxyTest::test_both_set",
"tornado/test/httpclient_test.py::RequestProxyTest::test_default_set",
"tornado/test/httpclient_test.py::RequestProxyTest::test_defaults_none",
"tornado/test/httpclient_test.py::RequestProxyTest::test_neither_set",
"tornado/test/httpclient_test.py::RequestProxyTest::test_request_set",
"tornado/test/httpclient_test.py::HTTPResponseTestCase::test_str",
"tornado/test/httpclient_test.py::SyncHTTPClientTest::test_sync_client",
"tornado/test/httpclient_test.py::SyncHTTPClientTest::test_sync_client_error",
"tornado/test/httpclient_test.py::HTTPRequestTestCase::test_body",
"tornado/test/httpclient_test.py::HTTPRequestTestCase::test_body_setter",
"tornado/test/httpclient_test.py::HTTPRequestTestCase::test_headers",
"tornado/test/httpclient_test.py::HTTPRequestTestCase::test_headers_setter",
"tornado/test/httpclient_test.py::HTTPRequestTestCase::test_if_modified_since",
"tornado/test/httpclient_test.py::HTTPRequestTestCase::test_null_headers_setter",
"tornado/test/simple_httpclient_test.py::SimpleHTTPClientCommonTestCase::test_304_with_content_length",
"tornado/test/simple_httpclient_test.py::SimpleHTTPClientCommonTestCase::test_all_methods",
"tornado/test/simple_httpclient_test.py::SimpleHTTPClientCommonTestCase::test_basic_auth",
"tornado/test/simple_httpclient_test.py::SimpleHTTPClientCommonTestCase::test_basic_auth_explicit_mode",
"tornado/test/simple_httpclient_test.py::SimpleHTTPClientCommonTestCase::test_body_encoding",
"tornado/test/simple_httpclient_test.py::SimpleHTTPClientCommonTestCase::test_body_sanity_checks",
"tornado/test/simple_httpclient_test.py::SimpleHTTPClientCommonTestCase::test_chunked",
"tornado/test/simple_httpclient_test.py::SimpleHTTPClientCommonTestCase::test_chunked_close",
"tornado/test/simple_httpclient_test.py::SimpleHTTPClientCommonTestCase::test_configure_defaults",
"tornado/test/simple_httpclient_test.py::SimpleHTTPClientCommonTestCase::test_credentials_in_url",
"tornado/test/simple_httpclient_test.py::SimpleHTTPClientCommonTestCase::test_final_callback_stack_context",
"tornado/test/simple_httpclient_test.py::SimpleHTTPClientCommonTestCase::test_follow_redirect",
"tornado/test/simple_httpclient_test.py::SimpleHTTPClientCommonTestCase::test_future_http_error",
"tornado/test/simple_httpclient_test.py::SimpleHTTPClientCommonTestCase::test_future_http_error_no_raise",
"tornado/test/simple_httpclient_test.py::SimpleHTTPClientCommonTestCase::test_future_interface",
"tornado/test/simple_httpclient_test.py::SimpleHTTPClientCommonTestCase::test_header_callback",
"tornado/test/simple_httpclient_test.py::SimpleHTTPClientCommonTestCase::test_header_callback_stack_context",
"tornado/test/simple_httpclient_test.py::SimpleHTTPClientCommonTestCase::test_header_types",
"tornado/test/simple_httpclient_test.py::SimpleHTTPClientCommonTestCase::test_hello_world",
"tornado/test/simple_httpclient_test.py::SimpleHTTPClientCommonTestCase::test_patch_receives_payload",
"tornado/test/simple_httpclient_test.py::SimpleHTTPClientCommonTestCase::test_post",
"tornado/test/simple_httpclient_test.py::SimpleHTTPClientCommonTestCase::test_put_307",
"tornado/test/simple_httpclient_test.py::SimpleHTTPClientCommonTestCase::test_reuse_request_from_response",
"tornado/test/simple_httpclient_test.py::SimpleHTTPClientCommonTestCase::test_streaming_callback",
"tornado/test/simple_httpclient_test.py::SimpleHTTPClientCommonTestCase::test_streaming_stack_context",
"tornado/test/simple_httpclient_test.py::SimpleHTTPClientCommonTestCase::test_types",
"tornado/test/simple_httpclient_test.py::SimpleHTTPClientCommonTestCase::test_unsupported_auth_mode",
"tornado/test/simple_httpclient_test.py::SimpleHTTPClientTestCase::test_100_continue",
"tornado/test/simple_httpclient_test.py::SimpleHTTPClientTestCase::test_100_continue_early_response",
"tornado/test/simple_httpclient_test.py::SimpleHTTPClientTestCase::test_async_body_producer_chunked",
"tornado/test/simple_httpclient_test.py::SimpleHTTPClientTestCase::test_async_body_producer_content_length",
"tornado/test/simple_httpclient_test.py::SimpleHTTPClientTestCase::test_connection_limit",
"tornado/test/simple_httpclient_test.py::SimpleHTTPClientTestCase::test_connection_refused",
"tornado/test/simple_httpclient_test.py::SimpleHTTPClientTestCase::test_gzip",
"tornado/test/simple_httpclient_test.py::SimpleHTTPClientTestCase::test_head_request",
"tornado/test/simple_httpclient_test.py::SimpleHTTPClientTestCase::test_header_reuse",
"tornado/test/simple_httpclient_test.py::SimpleHTTPClientTestCase::test_host_header",
"tornado/test/simple_httpclient_test.py::SimpleHTTPClientTestCase::test_ipv6",
"tornado/test/simple_httpclient_test.py::SimpleHTTPClientTestCase::test_max_redirects",
"tornado/test/simple_httpclient_test.py::SimpleHTTPClientTestCase::test_no_content_length",
"tornado/test/simple_httpclient_test.py::SimpleHTTPClientTestCase::test_options_request",
"tornado/test/simple_httpclient_test.py::SimpleHTTPClientTestCase::test_queue_timeout",
"tornado/test/simple_httpclient_test.py::SimpleHTTPClientTestCase::test_redirect_connection_limit",
"tornado/test/simple_httpclient_test.py::SimpleHTTPClientTestCase::test_request_timeout",
"tornado/test/simple_httpclient_test.py::SimpleHTTPClientTestCase::test_see_other_redirect",
"tornado/test/simple_httpclient_test.py::SimpleHTTPClientTestCase::test_singleton",
"tornado/test/simple_httpclient_test.py::SimpleHTTPClientTestCase::test_sync_body_producer_chunked",
"tornado/test/simple_httpclient_test.py::SimpleHTTPClientTestCase::test_sync_body_producer_content_length",
"tornado/test/simple_httpclient_test.py::SimpleHTTPSClientTestCase::test_100_continue",
"tornado/test/simple_httpclient_test.py::SimpleHTTPSClientTestCase::test_100_continue_early_response",
"tornado/test/simple_httpclient_test.py::SimpleHTTPSClientTestCase::test_async_body_producer_chunked",
"tornado/test/simple_httpclient_test.py::SimpleHTTPSClientTestCase::test_async_body_producer_content_length",
"tornado/test/simple_httpclient_test.py::SimpleHTTPSClientTestCase::test_connection_limit",
"tornado/test/simple_httpclient_test.py::SimpleHTTPSClientTestCase::test_connection_refused",
"tornado/test/simple_httpclient_test.py::SimpleHTTPSClientTestCase::test_error_logging",
"tornado/test/simple_httpclient_test.py::SimpleHTTPSClientTestCase::test_gzip",
"tornado/test/simple_httpclient_test.py::SimpleHTTPSClientTestCase::test_head_request",
"tornado/test/simple_httpclient_test.py::SimpleHTTPSClientTestCase::test_header_reuse",
"tornado/test/simple_httpclient_test.py::SimpleHTTPSClientTestCase::test_host_header",
"tornado/test/simple_httpclient_test.py::SimpleHTTPSClientTestCase::test_ipv6",
"tornado/test/simple_httpclient_test.py::SimpleHTTPSClientTestCase::test_max_redirects",
"tornado/test/simple_httpclient_test.py::SimpleHTTPSClientTestCase::test_no_content_length",
"tornado/test/simple_httpclient_test.py::SimpleHTTPSClientTestCase::test_options_request",
"tornado/test/simple_httpclient_test.py::SimpleHTTPSClientTestCase::test_queue_timeout",
"tornado/test/simple_httpclient_test.py::SimpleHTTPSClientTestCase::test_redirect_connection_limit",
"tornado/test/simple_httpclient_test.py::SimpleHTTPSClientTestCase::test_request_timeout",
"tornado/test/simple_httpclient_test.py::SimpleHTTPSClientTestCase::test_see_other_redirect",
"tornado/test/simple_httpclient_test.py::SimpleHTTPSClientTestCase::test_singleton",
"tornado/test/simple_httpclient_test.py::SimpleHTTPSClientTestCase::test_ssl_context",
"tornado/test/simple_httpclient_test.py::SimpleHTTPSClientTestCase::test_ssl_context_handshake_fail",
"tornado/test/simple_httpclient_test.py::SimpleHTTPSClientTestCase::test_ssl_options",
"tornado/test/simple_httpclient_test.py::SimpleHTTPSClientTestCase::test_ssl_options_handshake_fail",
"tornado/test/simple_httpclient_test.py::SimpleHTTPSClientTestCase::test_sync_body_producer_chunked",
"tornado/test/simple_httpclient_test.py::SimpleHTTPSClientTestCase::test_sync_body_producer_content_length",
"tornado/test/simple_httpclient_test.py::CreateAsyncHTTPClientTestCase::test_max_clients",
"tornado/test/simple_httpclient_test.py::HTTP100ContinueTestCase::test_100_continue",
"tornado/test/simple_httpclient_test.py::HTTP204NoContentTestCase::test_204_no_content",
"tornado/test/simple_httpclient_test.py::HostnameMappingTestCase::test_hostname_mapping",
"tornado/test/simple_httpclient_test.py::HostnameMappingTestCase::test_port_mapping",
"tornado/test/simple_httpclient_test.py::ResolveTimeoutTestCase::test_resolve_timeout",
"tornado/test/simple_httpclient_test.py::MaxHeaderSizeTest::test_small_headers",
"tornado/test/simple_httpclient_test.py::MaxBodySizeTest::test_small_body",
"tornado/test/simple_httpclient_test.py::MaxBufferSizeTest::test_large_body"
] | [] | Apache License 2.0 | 252 |
|
pypa__twine-134 | b34f042da78aed22b6e512df61b495638b06ba03 | 2015-09-27 21:52:01 | f487b7da9c42e4932bc33bf10d70cdc59fd16fd5 | diff --git a/twine/commands/upload.py b/twine/commands/upload.py
index 032cc21..2bd4a52 100644
--- a/twine/commands/upload.py
+++ b/twine/commands/upload.py
@@ -67,11 +67,13 @@ def upload(dists, repository, sign, identity, username, password, comment,
if not sign and identity:
raise ValueError("sign must be given along with identity")
+ dists = find_dists(dists)
+
# Determine if the user has passed in pre-signed distributions
signatures = dict(
(os.path.basename(d), d) for d in dists if d.endswith(".asc")
)
- dists = [i for i in dists if not i.endswith(".asc")]
+ uploads = [i for i in dists if not i.endswith(".asc")]
config = utils.get_repository_from_config(config_file, repository)
@@ -86,24 +88,14 @@ def upload(dists, repository, sign, identity, username, password, comment,
repository = Repository(config["repository"], username, password)
- uploads = find_dists(dists)
-
for filename in uploads:
package = PackageFile.from_filename(filename, comment)
- # Sign the dist if requested
- # if sign:
- # sign_file(sign_with, filename, identity)
- # signed_name = os.path.basename(filename) + ".asc"
- signed_name = package.signed_filename
+ signed_name = package.signed_basefilename
if signed_name in signatures:
- with open(signatures[signed_name], "rb") as gpg:
- package.gpg_signature = (signed_name, gpg.read())
- # data["gpg_signature"] = (signed_name, gpg.read())
+ package.add_gpg_signature(signatures[signed_name], signed_name)
elif sign:
package.sign(sign_with, identity)
- # with open(filename + ".asc", "rb") as gpg:
- # data["gpg_signature"] = (signed_name, gpg.read())
resp = repository.upload(package)
diff --git a/twine/package.py b/twine/package.py
index e80116a..e062c71 100644
--- a/twine/package.py
+++ b/twine/package.py
@@ -49,6 +49,7 @@ class PackageFile(object):
self.filetype = filetype
self.safe_name = pkg_resources.safe_name(metadata.name)
self.signed_filename = self.filename + '.asc'
+ self.signed_basefilename = self.basefilename + '.asc'
self.gpg_signature = None
md5_hash = hashlib.md5()
@@ -141,6 +142,13 @@ class PackageFile(object):
return data
+ def add_gpg_signature(self, signature_filepath, signature_filename):
+ if self.gpg_signature is not None:
+ raise ValueError('GPG Signature can only be added once')
+
+ with open(signature_filepath, "rb") as gpg:
+ self.gpg_signature = (signature_filename, gpg.read())
+
def sign(self, sign_with, identity):
print("Signing {0}".format(self.basefilename))
gpg_args = (sign_with, "--detach-sign")
@@ -149,5 +157,4 @@ class PackageFile(object):
gpg_args += ("-a", self.filename)
subprocess.check_call(gpg_args)
- with open(self.signed_filename, "rb") as gpg:
- self.pg_signature = (self.signed_filename, gpg.read())
+ self.add_gpg_signature(self.signed_filename, self.signed_basefilename)
| "twine upload" usually fails to upload .asc files
On the most recent Foolscap release, I signed the sdist tarballs as usual, and tried to use twine to upload everything:
```
% python setup.py sdist --formats=zip,gztar bdist_wheel
% ls dist
foolscap-0.9.1-py2-none-any.whl foolscap-0.9.1.tar.gz foolscap-0.9.1.zip
% (gpg sign them all)
% ls dist
foolscap-0.9.1-py2-none-any.whl foolscap-0.9.1.tar.gz foolscap-0.9.1.zip
foolscap-0.9.1-py2-none-any.whl.asc foolscap-0.9.1.tar.gz.asc foolscap-0.9.1.zip.asc
% python setup.py register
% twine upload dist/*
```
Twine uploaded the tar/zip/whl files, but ignored the .asc signatures, and the resulting [pypi page](https://pypi.python.org/pypi/foolscap/0.9.1) doesn't show them either.
After some digging, I found that `twine/upload.py upload()` will only use pre-signed .asc files if the command was run like `cd dist; twine upload *`. It won't use them if it was run as `cd dist; twine upload ./*` or `twine upload dist/*`. The problem seems to be that the `signatures` dictionary is indexed by the basename of the signature files, while the lookup key is using the full (original) filename of the tarball/etc with ".asc" appended.
I think it might be simpler and safer to have the code just check for a neighboring .asc file inside the upload loop, something like:
```python
for filename in uploads:
package = PackageFile.from_filename(filename, comment)
maybe_sig = package.signed_filename + ".asc"
if os.path.exists(maybe_sig):
package.gpg_signature = (os.path.basename(maybe_sig), sigdata)
...
```
I'll write up a patch for this. I started to look for a way of adding a test, but the code that looks for signatures happens deep enough in `upload()` that it'd need a oversized mock "Repository" class to exercise the .asc check without actually uploading anything. I'm not sure what the best way to approach the test would be.
| pypa/twine | diff --git a/tests/test_package.py b/tests/test_package.py
index fcc827a..d28eec1 100644
--- a/tests/test_package.py
+++ b/tests/test_package.py
@@ -55,3 +55,18 @@ def test_sign_file_with_identity(monkeypatch):
pass
args = ('gpg', '--detach-sign', '--local-user', 'identity', '-a', filename)
assert replaced_check_call.calls == [pretend.call(args)]
+
+
+def test_package_signed_name_is_correct():
+ filename = 'tests/fixtures/deprecated-pypirc'
+
+ pkg = package.PackageFile(
+ filename=filename,
+ comment=None,
+ metadata=pretend.stub(name="deprecated-pypirc"),
+ python_version=None,
+ filetype=None
+ )
+
+ assert pkg.signed_basefilename == "deprecated-pypirc.asc"
+ assert pkg.signed_filename == (filename + '.asc')
diff --git a/tests/test_upload.py b/tests/test_upload.py
index b40660f..7f99510 100644
--- a/tests/test_upload.py
+++ b/tests/test_upload.py
@@ -66,6 +66,7 @@ def test_find_dists_handles_real_files():
def test_get_config_old_format(tmpdir):
pypirc = os.path.join(str(tmpdir), ".pypirc")
+ dists = ["tests/fixtures/twine-1.5.0-py2.py3-none-any.whl"]
with open(pypirc, "w") as fp:
fp.write(textwrap.dedent("""
@@ -75,7 +76,7 @@ def test_get_config_old_format(tmpdir):
"""))
try:
- upload.upload(dists="foo", repository="pypi", sign=None, identity=None,
+ upload.upload(dists=dists, repository="pypi", sign=None, identity=None,
username=None, password=None, comment=None,
sign_with=None, config_file=pypirc, skip_existing=False)
except KeyError as err:
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_hyperlinks",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 1,
"issue_text_score": 1,
"test_score": 3
},
"num_modified_files": 2
} | 1.6 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "pytest",
"pip_packages": [
"pytest",
"coverage",
"pretend",
"flake8"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.9",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | certifi==2025.1.31
charset-normalizer==3.4.1
coverage==7.8.0
exceptiongroup @ file:///croot/exceptiongroup_1706031385326/work
flake8==7.2.0
idna==3.10
iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work
mccabe==0.7.0
packaging @ file:///croot/packaging_1734472117206/work
pkginfo==1.12.1.2
pluggy @ file:///croot/pluggy_1733169602837/work
pretend==1.0.9
pycodestyle==2.13.0
pyflakes==3.3.1
pytest @ file:///croot/pytest_1738938843180/work
requests==2.32.3
requests-toolbelt==1.0.0
tomli @ file:///opt/conda/conda-bld/tomli_1657175507142/work
-e git+https://github.com/pypa/twine.git@b34f042da78aed22b6e512df61b495638b06ba03#egg=twine
urllib3==2.3.0
| name: twine
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- exceptiongroup=1.2.0=py39h06a4308_0
- iniconfig=1.1.1=pyhd3eb1b0_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=3.0.16=h5eee18b_0
- packaging=24.2=py39h06a4308_0
- pip=25.0=py39h06a4308_0
- pluggy=1.5.0=py39h06a4308_0
- pytest=8.3.4=py39h06a4308_0
- python=3.9.21=he870216_1
- readline=8.2=h5eee18b_0
- setuptools=75.8.0=py39h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- tomli=2.0.1=py39h06a4308_0
- tzdata=2025a=h04d1e81_0
- wheel=0.45.1=py39h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- certifi==2025.1.31
- charset-normalizer==3.4.1
- coverage==7.8.0
- flake8==7.2.0
- idna==3.10
- mccabe==0.7.0
- pkginfo==1.12.1.2
- pretend==1.0.9
- pycodestyle==2.13.0
- pyflakes==3.3.1
- requests==2.32.3
- requests-toolbelt==1.0.0
- urllib3==2.3.0
prefix: /opt/conda/envs/twine
| [
"tests/test_package.py::test_package_signed_name_is_correct"
] | [] | [
"tests/test_package.py::test_sign_file",
"tests/test_package.py::test_sign_file_with_identity",
"tests/test_upload.py::test_ensure_wheel_files_uploaded_first",
"tests/test_upload.py::test_ensure_if_no_wheel_files",
"tests/test_upload.py::test_find_dists_expands_globs",
"tests/test_upload.py::test_find_dists_errors_on_invalid_globs",
"tests/test_upload.py::test_find_dists_handles_real_files",
"tests/test_upload.py::test_get_config_old_format",
"tests/test_upload.py::test_skip_existing_skips_files_already_on_PyPI",
"tests/test_upload.py::test_skip_upload_respects_skip_existing"
] | [] | Apache License 2.0 | 253 |
|
twisted__tubes-26 | 71894325180c6337d257e457d96e85075a560020 | 2015-09-28 08:11:28 | 71894325180c6337d257e457d96e85075a560020 | diff --git a/docs/listings/echoflow.py b/docs/listings/echoflow.py
index beea5b3..d2f3c1a 100644
--- a/docs/listings/echoflow.py
+++ b/docs/listings/echoflow.py
@@ -1,15 +1,18 @@
-from tubes.protocol import factoryFromFlow
+from tubes.protocol import flowFountFromEndpoint
+from tubes.listening import Listener
from twisted.internet.endpoints import serverFromString
-from twisted.internet.defer import Deferred
+from twisted.internet.defer import Deferred, inlineCallbacks
-def echoFlow(fount, drain):
- fount.flowTo(drain)
+def echoFlow(flow):
+ flow.fount.flowTo(flow.drain)
+@inlineCallbacks
def main(reactor, listenOn="stdio:"):
endpoint = serverFromString(reactor, listenOn)
- endpoint.listen(factoryFromFlow(echoFlow))
- return Deferred()
+ flowFount = yield flowFountFromEndpoint(endpoint)
+ flowFount.flowTo(Listener(echoFlow))
+ yield Deferred()
if __name__ == '__main__':
from twisted.internet.task import react
diff --git a/docs/listings/echonetstrings.py b/docs/listings/echonetstrings.py
index bf05626..1287f0f 100644
--- a/docs/listings/echonetstrings.py
+++ b/docs/listings/echonetstrings.py
@@ -1,17 +1,21 @@
from tubes.tube import Tube
from tubes.framing import stringsToNetstrings
-from tubes.protocol import factoryFromFlow
+from tubes.protocol import flowFountFromEndpoint
+from tubes.listening import Listener
+
from twisted.internet.endpoints import TCP4ServerEndpoint
-from twisted.internet.defer import Deferred
+from twisted.internet.defer import inlineCallbacks, Deferred()
-def echoTubeFactory(fount, drain):
- return (fount.flowTo(Tube(stringsToNetstrings()))
- .flowTo(drain))
+def echoTubeFactory(flow):
+ return (flow.fount.flowTo(Tube(stringsToNetstrings()))
+ .flowTo(flow.drain))
+@inlineCallbacks
def main(reactor):
endpoint = TCP4ServerEndpoint(reactor, 4321)
- endpoint.listen(factoryFromFlow(echoTubeFactory))
- return Deferred()
+ flowFount = yield flowFountFromEndpoint(endpoint)
+ flowFount.flowTo(Listener(echoTubeFactory))
+ yield Deferred()
if __name__ == '__main__':
from twisted.internet.task import react
diff --git a/docs/listings/portforward.py b/docs/listings/portforward.py
index ec723dc..0941743 100644
--- a/docs/listings/portforward.py
+++ b/docs/listings/portforward.py
@@ -1,21 +1,22 @@
-import os
+from tubes.protocol import flowFountFromEndpoint, flowFromEndpoint
+from tubes.listening import Listener
-from tubes.protocol import factoryFromFlow
from twisted.internet.endpoints import serverFromString, clientFromString
-from twisted.internet.defer import Deferred
+from twisted.internet.defer import Deferred, inlineCallbacks
+@inlineCallbacks
def main(reactor, listen="tcp:4321", connect="tcp:localhost:6543"):
clientEndpoint = clientFromString(reactor, connect)
serverEndpoint = serverFromString(reactor, listen)
- def incomingTubeFactory(listeningFount, listeningDrain):
- def outgoingTubeFactory(connectingFount, connectingDrain):
- listeningFount.flowTo(connectingDrain)
- connectingFount.flowTo(listeningDrain)
- clientEndpoint.connect(factoryFromFlow(outgoingTubeFactory))
-
- serverEndpoint.listen(factoryFromFlow(incomingTubeFactory))
- return Deferred()
+ def incoming(listening):
+ def outgoing(connecting):
+ listening.fount.flowTo(connecting.drain)
+ connecting.fount.flowTo(listening.drain)
+ flowFromEndpoint(clientEndpoint).addCallback(outgoing)
+ flowFount = yield flowFountFromEndpoint(serverEndpoint)
+ flowFount.flowTo(Listener(incoming))
+ yield Deferred()
if __name__ == '__main__':
from twisted.internet.task import react
diff --git a/docs/listings/reversetube.py b/docs/listings/reversetube.py
index cf99b0c..4e9096b 100644
--- a/docs/listings/reversetube.py
+++ b/docs/listings/reversetube.py
@@ -1,6 +1,8 @@
-from tubes.protocol import factoryFromFlow
from twisted.internet.endpoints import serverFromString
-from twisted.internet.defer import Deferred
+from twisted.internet.defer import Deferred, inlineCallbacks
+
+from tubes.protocol import flowFountFromEndpoint
+from tubes.listening import Listener
from tubes.tube import tube, series
@tube
@@ -8,15 +10,17 @@ class Reverser(object):
def received(self, item):
yield b"".join(reversed(item))
-def reverseFlow(fount, drain):
+def reverseFlow(flow):
from tubes.framing import bytesToLines, linesToBytes
lineReverser = series(bytesToLines(), Reverser(), linesToBytes())
- fount.flowTo(lineReverser).flowTo(drain)
+ flow.fount.flowTo(lineReverser).flowTo(flow.drain)
+@inlineCallbacks
def main(reactor, listenOn="stdio:"):
endpoint = serverFromString(reactor, listenOn)
- endpoint.listen(factoryFromFlow(reverseFlow))
- return Deferred()
+ flowFount = yield flowFountFromEndpoint(endpoint)
+ flowFount.flowTo(Listener(reverseFlow))
+ yield Deferred()
if __name__ == '__main__':
from twisted.internet.task import react
diff --git a/docs/listings/rpn.py b/docs/listings/rpn.py
index fe6f96c..697957e 100644
--- a/docs/listings/rpn.py
+++ b/docs/listings/rpn.py
@@ -1,9 +1,10 @@
-from tubes.protocol import factoryFromFlow
from tubes.itube import IFrame, ISegment
from tubes.tube import tube, receiver
+from tubes.listening import Listener
from twisted.internet.endpoints import serverFromString
-from twisted.internet.defer import Deferred
+from twisted.internet.defer import Deferred, inlineCallbacks
+from tubes.protocol import flowFountFromEndpoint
class Calculator(object):
def __init__(self):
@@ -79,15 +80,17 @@ def calculatorSeries():
linesToBytes()
)
-def mathFlow(fount, drain):
+def mathFlow(flow):
processor = calculatorSeries()
- nextDrain = fount.flowTo(processor)
- nextDrain.flowTo(drain)
+ nextDrain = flow.fount.flowTo(processor)
+ nextDrain.flowTo(flow.drain)
+@inlineCallbacks
def main(reactor, port="stdio:"):
endpoint = serverFromString(reactor, port)
- endpoint.listen(factoryFromFlow(mathFlow))
- return Deferred()
+ flowFount = yield flowFountFromEndpoint(endpoint)
+ flowFount.flowTo(Listener(mathFlow))
+ yield Deferred()
if __name__ == '__main__':
from twisted.internet.task import react
diff --git a/sketches/amptube.py b/sketches/amptube.py
index 128d183..0a7e8e9 100644
--- a/sketches/amptube.py
+++ b/sketches/amptube.py
@@ -1,18 +1,19 @@
-
-
from zope.interface import implementer
from ampserver import Math
-from twisted.tubes.protocol import factoryFromFlow
from twisted.internet.endpoints import serverFromString
+from twisted.internet.defer import Deferred, inlineCallbacks
from twisted.internet import reactor
from twisted.protocols.amp import AmpBox, IBoxSender
-from twisted.tubes.itube import ISegment
-from twisted.tubes.tube import Pump, series
-from twisted.tubes.framing import packedPrefixToStrings
+
+from tubes.protocol import flowFountFromEndpoint
+from tubes.listening import Listener
+from tubes.itube import ISegment
+from tubes.tube import Pump, series
+from tubes.framing import packedPrefixToStrings
class StringsToBoxes(Pump):
@@ -96,14 +97,22 @@ class BoxConsumer(Pump):
-def mathFlow(fount, drain):
+def mathFlow(fount):
fount.flowTo(series(packedPrefixToStrings(16), StringsToBoxes(),
- BoxConsumer(Math()), BoxesToData(), drain))
+ BoxConsumer(Math()), BoxesToData(), fount.drain))
-serverEndpoint = serverFromString(reactor, "tcp:1234")
-serverEndpoint.listen(factoryFromFlow(mathFlow))
-from twisted.internet import reactor
-reactor.run()
+
+@inlineCallbacks
+def main():
+ serverEndpoint = serverFromString(reactor, "tcp:1234")
+ flowFount = yield flowFountFromEndpoint(serverEndpoint)
+ flowFount.flowTo(Listener(mathFlow))
+ yield Deferred()
+
+
+from twisted.interne.task import react
+from sys import argv
+react(main, argv[1:])
diff --git a/sketches/fanchat.py b/sketches/fanchat.py
index c26a013..92cdcb3 100644
--- a/sketches/fanchat.py
+++ b/sketches/fanchat.py
@@ -5,14 +5,15 @@ from json import loads, dumps
from zope.interface.common import IMapping
from twisted.internet.endpoints import serverFromString
-from twisted.internet.defer import Deferred
+from twisted.internet.defer import Deferred, inlineCallbacks
-from twisted.tubes.routing import Router, Routed, to
-from twisted.tubes.protocol import factoryFromFlow
-from twisted.tubes.itube import IFrame
-from twisted.tubes.tube import series, tube, receiver
-from twisted.tubes.framing import bytesToLines, linesToBytes
-from twisted.tubes.fan import Out, In
+from tubes.routing import Router, Routed, to
+from tubes.itube import IFrame
+from tubes.tube import series, tube, receiver
+from tubes.framing import bytesToLines, linesToBytes
+from tubes.fan import Out, In
+from tubes.listening import Listener
+from tubes.protocol import flowFountFromEndpoint
@@ -130,12 +131,12 @@ class Hub(object):
self.participants = []
self.channels = defaultdict(Channel)
- def newParticipantFlow(self, fount, drain):
- commandFount = fount.flowTo(
+ def newParticipantFlow(self, flow):
+ commandFount = flow.fount.flowTo(
series(OnStop(lambda: self.participants.remove(participant)),
bytesToLines(), linesToCommands)
)
- commandDrain = series(commandsToLines, linesToBytes(), drain)
+ commandDrain = series(commandsToLines, linesToBytes(), flow.drain)
participant = Participant(self, commandFount, commandDrain)
self.participants.append(participant)
@@ -144,10 +145,12 @@ class Hub(object):
+@inlineCallbacks
def main(reactor, port="stdio:"):
endpoint = serverFromString(reactor, port)
- endpoint.listen(factoryFromFlow(Hub().newParticipantFlow))
- return Deferred()
+ flowFount = yield flowFountFromEndpoint(endpoint)
+ flowFount.flowTo(Listener(Hub().newParticipantFlow))
+ yield Deferred()
diff --git a/sketches/notes.rst b/sketches/notes.rst
index 91e3587..7425177 100644
--- a/sketches/notes.rst
+++ b/sketches/notes.rst
@@ -3,18 +3,18 @@ In the interst of making this branch more accessible to additional contributors,
Framing needs a ton of tests.
It hasn't changed a whole lot so documenting and testing this module might be a good way to get started.
-``twisted.tubes.protocol`` is pretty well tested and roughly complete but could really use some docstrings, and improve the ones it has.
-See for example the docstring for factoryFromFlow.
+``tubes.protocol`` is pretty well tested and roughly complete but could really use some docstrings, and improve the ones it has.
+See for example the docstring for flowFountFromEndpoint.
-The objects in ``twisted.tubes.protocol``, especially those that show up in log messages, could really use nicer reprs that indicate what they're doing.
+The objects in ``tubes.protocol``, especially those that show up in log messages, could really use nicer reprs that indicate what they're doing.
For example ``_ProtocolPlumbing`` and ``_FlowFactory`` should both include information about the flow function they're working on behalf of.
-Similarly, ``twisted.tubes.fan`` is a pretty rough sketch, although it's a bit less self-evident what is going on there since it's not fully implemented.
+Similarly, ``tubes.fan`` is a pretty rough sketch, although it's a bit less self-evident what is going on there since it's not fully implemented.
(*Hopefully* it's straightforward, but let's not count on hope.)
There are a bunch of un-covered `__repr__`s, probably.
-`twisted.tubes.tube.Diverter` could use some better docstrings, as could its helpers `_DrainingFount` and `_DrainingTube`.
+`tubes.tube.Diverter` could use some better docstrings, as could its helpers `_DrainingFount` and `_DrainingTube`.
We need a decorator for a function so that this:
diff --git a/tox.ini b/tox.ini
index ac04142..e689da0 100644
--- a/tox.ini
+++ b/tox.ini
@@ -1,5 +1,5 @@
[tox]
-envlist = py26, py27, pypy, docs, lint
+envlist = py26, py27, pypy, docs, lint, apidocs
[testenv]
deps =
diff --git a/tubes/_siphon.py b/tubes/_siphon.py
index ad4c542..665c901 100644
--- a/tubes/_siphon.py
+++ b/tubes/_siphon.py
@@ -10,8 +10,8 @@ from collections import deque
from zope.interface import implementer
-from .itube import IPause, IDrain, IFount, ITube
-from .kit import Pauser, beginFlowingFrom, beginFlowingTo
+from .itube import IDrain, IFount, ITube
+from .kit import Pauser, beginFlowingFrom, beginFlowingTo, NoPause, OncePause
from ._components import _registryAdapting
from twisted.python.failure import Failure
@@ -214,10 +214,7 @@ class _SiphonFount(_SiphonPiece):
siphon's tube.
"""
result = beginFlowingTo(self, drain)
- if self._siphon._pauseBecauseNoDrain:
- pbnd = self._siphon._pauseBecauseNoDrain
- self._siphon._pauseBecauseNoDrain = None
- pbnd.unpause()
+ self._siphon._pauseBecauseNoDrain.maybeUnpause()
self._siphon._unbufferIterator()
return result
@@ -245,19 +242,6 @@ class _SiphonFount(_SiphonPiece):
-@implementer(IPause)
-class _PlaceholderPause(object):
- """
- L{IPause} provider that does nothing.
- """
-
- def unpause(self):
- """
- No-op.
- """
-
-
-
@implementer(IDrain)
class _SiphonDrain(_SiphonPiece):
"""
@@ -295,7 +279,7 @@ class _SiphonDrain(_SiphonPiece):
pbpc = self._siphon._pauseBecausePauseCalled
self._siphon._pauseBecausePauseCalled = None
if fount is None:
- pauseFlow = _PlaceholderPause
+ pauseFlow = NoPause
else:
pauseFlow = fount.pauseFlow
self._siphon._pauseBecausePauseCalled = pauseFlow()
@@ -382,9 +366,9 @@ class _Siphon(object):
self._everStarted = False
self._unbuffering = False
self._flowStoppingReason = None
- self._pauseBecauseNoDrain = None
self._tfount = _SiphonFount(self)
+ self._pauseBecauseNoDrain = OncePause(self._tfount._pauser)
self._tdrain = _SiphonDrain(self)
self._tube = tube
self._pending = SiphonPendingValues()
@@ -433,9 +417,7 @@ class _Siphon(object):
return
self._pending.append(iter(iterableOrNot))
if self._tfount.drain is None:
- if self._pauseBecauseNoDrain is None:
- self._pauseBecauseNoDrain = self._tfount.pauseFlow()
-
+ self._pauseBecauseNoDrain.pauseOnce()
self._unbufferIterator()
diff --git a/tubes/itube.py b/tubes/itube.py
index 9656155..8bfd04a 100644
--- a/tubes/itube.py
+++ b/tubes/itube.py
@@ -9,8 +9,8 @@ Interfaces related to data flows.
from zope.interface import Interface, Attribute
if 0:
- from zope.interface.interfaces import IInterface
- IInterface
+ from zope.interface.interfaces import ISpecification
+ ISpecification
from twisted.python.failure import Failure
Failure
@@ -60,7 +60,7 @@ class IFount(Interface):
"""
The type of output produced by this Fount.
- This may be an L{IInterface} provider.
+ This may be an L{ISpecification} provider.
""")
drain = Attribute(
@@ -126,6 +126,8 @@ class IDrain(Interface):
inputType = Attribute(
"""
Similar to L{IFount.outputType}.
+
+ This is an L{ISpecification} provider.
""")
fount = Attribute(
@@ -175,7 +177,7 @@ class IDrain(Interface):
class ITube(Interface):
"""
- A tube translates input to output.
+ A tube transforms input into output.
Look at this awesome ASCII art::
diff --git a/tubes/kit.py b/tubes/kit.py
index 7ac796f..ee73633 100644
--- a/tubes/kit.py
+++ b/tubes/kit.py
@@ -132,3 +132,46 @@ def beginFlowingFrom(drain, fount):
(oldFount.drain is drain) ):
oldFount.flowTo(None)
+
+
+@implementer(IPause)
+class NoPause(object):
+ """
+ A null implementation of L{IPause} that does nothing.
+ """
+
+ def unpause(self):
+ """
+ No-op.
+ """
+
+
+
+class OncePause(object):
+ """
+ Pause a pauser once, unpause it if necessary.
+ """
+ def __init__(self, pauser):
+ """
+ Create a L{OncePause} with the given L{Pauser}.
+ """
+ self._pauser = pauser
+ self._currentlyPaused = False
+
+
+ def pauseOnce(self):
+ """
+ If this L{OncePause} is not currently paused, pause its pauser.
+ """
+ if not self._currentlyPaused:
+ self._currentlyPaused = True
+ self._pause = self._pauser.pause()
+
+
+ def maybeUnpause(self):
+ """
+ If this L{OncePause} is currently paused, unpause it.
+ """
+ if self._currentlyPaused:
+ self._currentlyPaused = False
+ self._pause.unpause()
diff --git a/tubes/listening.py b/tubes/listening.py
new file mode 100644
index 0000000..5b2657a
--- /dev/null
+++ b/tubes/listening.py
@@ -0,0 +1,135 @@
+# -*- test-case-name: tubes.test.test_listening -*-
+# Copyright (c) Twisted Matrix Laboratories.
+# See LICENSE for details.
+"""
+Listening.
+"""
+
+from zope.interface import implementer, implementedBy
+
+from .itube import IDrain
+from .kit import beginFlowingFrom, NoPause
+from .tube import tube, series
+
+class Flow(object):
+ """
+ A L{Flow} is a combination of a Fount and a Drain, representing a
+ bi-directional communication channel such as a TCP connection.
+
+ @ivar fount: A fount.
+ @type fount: L{IFount}
+
+ @ivar drain: A drain.
+ @type drain: L{IDrain}
+ """
+
+ def __init__(self, fount, drain):
+ """
+ @param fount: Fount.
+ @type fount: L{IFount}
+
+ @param drain: Drain.
+ @type drain: L{IDrain}
+ """
+ self.fount = fount
+ self.drain = drain
+
+
+
+@implementer(IDrain)
+class Listener(object):
+ """
+ A L{Listener} is a drain that accepts L{Flow}s and sets them up.
+ """
+
+ inputType = implementedBy(Flow)
+
+ def __init__(self, flowConnector, maxConnections=100):
+ """
+ @param flowConnector: a 1-argument callable taking a L{Flow} and
+ returning nothing, which connects the flow.
+
+ @param maxConnections: The number of concurrent L{Flow} objects
+ to maintain active at once.
+ @type maxConnections: L{int}
+ """
+ self.fount = None
+ self._flowConnector = flowConnector
+ self._maxConnections = maxConnections
+ self._currentConnections = 0
+ self._paused = NoPause()
+
+
+ def flowingFrom(self, fount):
+ """
+ The flow has begun from the given L{fount} of L{Flow}s.
+
+ @param fount: A fount of flows. One example of such a suitable fount
+ would be the return value of
+ L{tubes.protocol.flowFountFromEndpoint}.
+
+ @return: L{None}, since this is a "terminal" drain, where founts of
+ L{Flow} must end up in order for more new connections to be
+ established.
+ """
+ beginFlowingFrom(self, fount)
+
+
+ def receive(self, item):
+ """
+ Receive the given flow, applying backpressure if too many connections
+ are active.
+
+ @param item: The inbound L{Flow}.
+ """
+ self._currentConnections += 1
+ if self._currentConnections >= self._maxConnections:
+ self._paused = self.fount.pauseFlow()
+ def dec():
+ self._currentConnections -= 1
+ self._paused.unpause()
+ self._paused = NoPause()
+ self._flowConnector(Flow(item.fount.flowTo(series(_OnStop(dec))),
+ item.drain))
+
+
+ def flowStopped(self, reason):
+ """
+ No more L{Flow}s are incoming; nothing to do.
+
+ @param reason: the reason the flow stopped.
+ """
+
+
+
+@tube
+class _OnStop(object):
+ """
+ Call a callback when the flow stops.
+ """
+ def __init__(self, callback):
+ """
+ Call the given callback.
+ """
+ self.callback = callback
+
+
+ def received(self, item):
+ """
+ Pass through all received items.
+
+ @param item: An item being passed through (type unknown).
+ """
+ yield item
+
+
+ def stopped(self, reason):
+ """
+ Call the callback on stop.
+
+ @param reason: the reason that the flow stopped; ignored.
+
+ @return: no items.
+ """
+ self.callback()
+ return ()
diff --git a/tubes/protocol.py b/tubes/protocol.py
index 6577f4c..6d44259 100644
--- a/tubes/protocol.py
+++ b/tubes/protocol.py
@@ -5,28 +5,34 @@
"""
Objects to connect L{real data <_Protocol>} to L{tubes}.
-@see: L{factoryFromFlow}
+@see: L{flowFountFromEndpoint}
"""
__all__ = [
- 'factoryFromFlow',
+ 'flowFountFromEndpoint',
+ 'flowFromEndpoint',
]
-from zope.interface import implementer
+from zope.interface import implementer, implementedBy
-from .kit import Pauser, beginFlowingFrom, beginFlowingTo
-from .itube import IDrain, IFount, ISegment
+from .kit import Pauser, beginFlowingFrom, beginFlowingTo, OncePause
+from .itube import StopFlowCalled, IDrain, IFount, ISegment
+from .listening import Flow
-from twisted.internet.interfaces import IPushProducer
+from twisted.python.failure import Failure
+from twisted.internet.interfaces import IPushProducer, IListeningPort
from twisted.internet.protocol import Protocol as _Protocol
if 0:
# Workaround for inability of pydoctor to resolve references.
from twisted.internet.interfaces import (
- IProtocol, ITransport, IConsumer, IProtocolFactory, IProducer)
- IProtocol, ITransport, IConsumer, IProtocolFactory, IProducer
- from twisted.python.failure import Failure
- Failure
+ IProtocol, ITransport, IConsumer, IProtocolFactory, IProducer,
+ IStreamServerEndpoint
+ )
+ (IProtocol, ITransport, IConsumer, IProtocolFactory, IProducer,
+ IStreamServerEndpoint)
+ from twisted.internet.defer import Deferred
+ Deferred
@@ -205,7 +211,7 @@ class _ProtocolPlumbing(_Protocol):
A L{_ProtocolPlumbing} implements L{IProtocol} to deliver all incoming data
to the drain associated with its L{fount <IFount>}.
- @ivar _flow: A flow function, as described in L{factoryFromFlow}.
+ @ivar _flow: A flow function, as described in L{_factoryFromFlow}.
@type _flow: L{callable}
@ivar _drain: The drain that is passed on to the application, created after
@@ -267,17 +273,17 @@ class _ProtocolPlumbing(_Protocol):
-def factoryFromFlow(flow):
+def _factoryFromFlow(flow):
"""
Convert a flow function into an L{IProtocolFactory}.
A "flow function" is a function which takes a L{fount <IFount>} and an
L{drain <IDrain>}.
- L{factoryFromFlow} takes such a function and creates an L{IProtocolFactory}
- which, upon each new connection, provides the flow function with an
- L{IFount} and an L{IDrain} representing the read end and the write end of
- the incoming connection, respectively.
+ L{_factoryFromFlow} takes such a function and creates an
+ L{IProtocolFactory} which, upon each new connection, provides the flow
+ function with an L{IFount} and an L{IDrain} representing the read end and
+ the write end of the incoming connection, respectively.
@param flow: a 2-argument callable, taking (fount, drain).
@type flow: L{callable}
@@ -287,3 +293,134 @@ def factoryFromFlow(flow):
"""
from twisted.internet.protocol import Factory
return Factory.forProtocol(lambda: _ProtocolPlumbing(flow))
+
+
+
+@implementer(IFount)
+class _FountImpl(object):
+ """
+ Implementation of fount for listening port.
+ """
+
+ outputType = implementedBy(Flow)
+
+ def __init__(self, portObject, aFlowFunction, preListen):
+ """
+ Create a fount implementation from a provider of L{IPushProducer} and a
+ function that takes a fount and a drain.
+
+ @param portObject: the result of the L{Deferred} from
+ L{IStreamServerEndpoint.listen}
+ @type portObject: L{IListeningPort} and L{IPushProducer} provider
+ (probably; workarounds are in place for other cases)
+
+ @param aFlowFunction: a 2-argument callable, invoked when a connection
+ arrives, with a fount and drain.
+ @type aFlowFunction: L{callable}
+
+ @param preListen: the founts and drains accepted before the C{listen}
+ L{Deferred} has fired. Because these might be arriving before this
+ L{_FountImpl} even I{exists}, this needs to be passed in. That is
+ OK because L{_FountImpl} is very tightly coupled to
+ L{flowFountFromEndpoint}, which is the only thing that constructs
+ it.
+ @type preListen: L{list} of 2-L{tuple}s of C{(fount, drain)}
+ """
+ self.drain = None
+ self._preListen = preListen
+ self._pauser = Pauser(portObject.pauseProducing,
+ portObject.resumeProducing)
+ self._noDrainPause = OncePause(self._pauser)
+ self._aFlowFunction = aFlowFunction
+ self._portObject = portObject
+ if preListen:
+ self._noDrainPause.pauseOnce()
+
+
+ def flowTo(self, drain):
+ """
+ Start flowing to the given drain.
+
+ @param drain: The drain to send flows to.
+
+ @return: the next fount in the chain.
+ """
+ result = beginFlowingTo(self, drain)
+ self._noDrainPause.maybeUnpause()
+ for f, d in self._preListen:
+ self._aFlowFunction(f, d)
+ return result
+
+
+ def pauseFlow(self):
+ """
+ Allow backpressure to build up in the listening socket; ask Twisted to
+ stop calling C{accept}.
+
+ @return: An L{IPause}.
+ """
+ return self._pauser.pause()
+
+
+ def stopFlow(self):
+ """
+ Stop the delivery of L{Flow} objects to this L{_FountImpl}'s drain, and
+ stop listening on the port represented by this fount.
+ """
+ self.drain.flowStopped(Failure(StopFlowCalled()))
+ self.drain = None
+ if IListeningPort.providedBy(self._portObject):
+ self._portObject.stopListening()
+
+
+
+def flowFountFromEndpoint(endpoint):
+ """
+ Listen on the given endpoint, and thereby create a L{fount <IFount>} which
+ outputs a new L{Flow} for each connection.
+
+ @note: L{IStreamServerEndpoint} formally specifies that its C{connect}
+ method returns a L{Deferred} that fires with an L{IListeningPort}.
+ However, L{IListeningPort} is insufficient to express the requisite
+ flow-control to implement a fount; so the C{endpoint} parameter must be
+ an extended endpoint whose C{listen} L{Deferred} fires with a provider
+ of both L{IListeningPort} and L{IPushProducer}. Luckily, the
+ real-world implementations of L{IListeningPort} within Twisted are all
+ L{IPushProducer}s as well, so practically speaking you will not notice
+ this, but for testing it is important to know this is necessary.
+
+ @param endpoint: a server endpoint.
+ @type endpoint: L{IStreamServerEndpoint}
+
+ @return: a L{twisted.internet.defer.Deferred} that fires with a L{IFount}
+ whose C{outputType} is L{Flow}.
+ """
+ preListen = []
+ def listening(portObject):
+ listening.impl = _FountImpl(portObject, aFlowFunction, preListen)
+ return listening.impl
+ listening.impl = None
+ def aFlowFunction(fount, drain):
+ if listening.impl is None or listening.impl.drain is None:
+ preListen.append((fount, drain))
+ if listening.impl is not None:
+ listening.impl._pauseForNoDrain()
+ else:
+ listening.impl.drain.receive(Flow(fount, drain))
+ aFactory = _factoryFromFlow(aFlowFunction)
+ return endpoint.listen(aFactory).addCallback(listening)
+
+
+
+def flowFromEndpoint(endpoint):
+ """
+ Convert a client endpoint into a L{Deferred} that fires with a L{Flow}.
+
+ @param endpoint: a client endpoint that will be connected to, once.
+
+ @return: a L{Deferred} that fires with a L{Flow}.
+ """
+ def cb(fount, drain):
+ cb.result = Flow(fount, drain)
+ return (endpoint.connect(_factoryFromFlow(cb))
+ .addCallback(lambda whatever: cb.result))
diff --git a/tubes/tube.py b/tubes/tube.py
index df954ef..fe23b49 100644
--- a/tubes/tube.py
+++ b/tubes/tube.py
@@ -15,8 +15,9 @@ from twisted.python.components import proxyForInterface
from twisted.python.failure import Failure
from .itube import IDrain, ITube, IDivertable, IFount, StopFlowCalled
-from ._siphon import _tubeRegistry, _Siphon, _PlaceholderPause, skip
+from ._siphon import _tubeRegistry, _Siphon, skip
from ._components import _registryActive
+from .kit import NoPause as _PlaceholderPause
__all__ = [
"Diverter",
| replace conversion of flow-function → factory with conversion of endpoint → fount of founts
Presently on trunk, tubes are hooked up to the outside world (i.e.: Twisted) by converting a "flow function", a function taking a fount and drain, to a Factory, which is then hooked up to Twisted.
However, this is limiting in one major regard: the backpressure of *not accepting future connections* is impossible to model properly.
A better way to conceptualize a listening socket is a fount whose `outputType` is an object with both `Fount` and `Drain` attributes. This way, we can flow the stream of incoming connections to a "listening" drain, which can exert backpressure (most obviously by simply limiting the number of concurrently active connections).
As it happens, this is also a feature missing from Twisted which makes it hard to implement fairness in queueing. By making tubes treat listening sockets and connected sockets consistently, we can open up a whole new area of correct-by-default behavior under high levels of load. | twisted/tubes | diff --git a/tubes/test/test_listening.py b/tubes/test/test_listening.py
new file mode 100644
index 0000000..5b0b3e3
--- /dev/null
+++ b/tubes/test/test_listening.py
@@ -0,0 +1,56 @@
+# -*- test-case-name: tubes.test.test_listening -*-
+# Copyright (c) Twisted Matrix Laboratories.
+# See LICENSE for details.
+
+"""
+Tests for L{tubes.listening}.
+"""
+
+from unittest import TestCase
+
+from ..listening import Flow, Listener
+from ..memory import iteratorFount
+
+from .util import FakeDrain
+
+class ListeningTests(TestCase):
+ """
+ Test cases for listening.
+ """
+
+ def test_listenerCallsFlowConnector(self):
+ """
+ A L{Listener} is a drain which calls the function given to it to
+ connect a flow
+ """
+ drained = FakeDrain()
+ flow = Flow(iteratorFount([1, 2, 3]),
+ drained)
+ flows = []
+ fi = iteratorFount([flow])
+ listener = Listener(flows.append)
+ fi.flowTo(listener)
+ self.assertEqual(len(flows), 1)
+ results = FakeDrain()
+ flows[0].fount.flowTo(results)
+ # The listener might need to (and in fact does) interpose a different
+ # value for 'fount' and 'drain' to add hooks to them. We assert about
+ # the values passed through them.
+ self.assertEqual(results.received, [1, 2, 3])
+ iteratorFount([4, 5, 6]).flowTo(flows[0].drain)
+ self.assertEqual(drained.received, [4, 5, 6])
+
+
+ def test_listenerLimitsConcurrentConnections(self):
+ """
+ L{Listener} will pause its fount when too many connections are
+ received.
+ """
+ connectorCalled = []
+ listener = Listener(connectorCalled.append, maxConnections=3)
+ tenFlows = iteratorFount([Flow(iteratorFount([1, 2, 3]),
+ FakeDrain())
+ for each in range(10)])
+ tenFlows.flowTo(listener)
+ self.assertEqual(len(connectorCalled), 3)
+ connectorCalled[0].fount.flowTo(connectorCalled[0].drain)
diff --git a/tubes/test/test_protocol.py b/tubes/test/test_protocol.py
index 8c64452..9586f82 100644
--- a/tubes/test/test_protocol.py
+++ b/tubes/test/test_protocol.py
@@ -6,14 +6,20 @@
Tests for L{tubes.protocol}.
"""
+from zope.interface import implementer
+
from twisted.trial.unittest import SynchronousTestCase as TestCase
from twisted.python.failure import Failure
+from twisted.test.proto_helpers import StringTransport
+from twisted.internet.interfaces import IStreamServerEndpoint
-from ..protocol import factoryFromFlow
+from ..protocol import flowFountFromEndpoint, flowFromEndpoint
from ..tube import tube, series
+from ..listening import Flow, Listener
+from ..itube import IFount
-from ..test.util import StringEndpoint, FakeDrain, FakeFount
+from .util import StringEndpoint, FakeDrain, FakeFount, fakeEndpointWithPorts
@tube
class RememberingTube(object):
@@ -50,9 +56,9 @@ class RememberingTube(object):
-class FlowingAdapterTests(TestCase):
+class FlowConnectorTests(TestCase):
"""
- Tests for L{factoryFromFlow} and the drain/fount/factory adapters it
+ Tests for L{flowFromEndpoint} and the drain/fount/factory adapters it
constructs.
"""
@@ -61,17 +67,25 @@ class FlowingAdapterTests(TestCase):
Sert up these tests.
"""
self.endpoint = StringEndpoint()
- def flowFunction(fount, drain):
- self.adaptedDrain = drain
- self.adaptedFount = fount
- self.adaptedProtocol = self.successResultOf(
- self.endpoint.connect(factoryFromFlow(flowFunction))
- )
-
+ flow = self.successResultOf(flowFromEndpoint(self.endpoint))
+ self.adaptedDrain = flow.drain
+ self.adaptedFount = flow.fount
self.tube = RememberingTube()
self.drain = series(self.tube)
+ def adaptedProtocol(self):
+ """
+ Retrieve a protocol for testing with.
+
+ @return: the first protocol instance to have been created by making the
+ virtual outbound connection associated with the call to
+ L{flowFromEndpoint} performed in L{FlowConnectorTests.setUp}.
+ @rtype: L{IProtocol}
+ """
+ return self.endpoint.transports[0].protocol
+
+
def test_flowToSetsDrain(self):
"""
L{_ProtocolFount.flowTo} will set the C{drain} attribute of the
@@ -87,7 +101,7 @@ class FlowingAdapterTests(TestCase):
L{_ProtocolFount.dataReceived} to invoke L{receive} on its drain.
"""
self.adaptedFount.flowTo(self.drain)
- self.adaptedProtocol.dataReceived("some data")
+ self.adaptedProtocol().dataReceived("some data")
self.assertEqual(self.tube.items, ["some data"])
@@ -108,7 +122,7 @@ class FlowingAdapterTests(TestCase):
"""
self.adaptedFount.flowTo(self.drain)
self.adaptedFount.stopFlow()
- self.assertEqual(self.adaptedProtocol.transport.disconnecting, True)
+ self.assertEqual(self.adaptedProtocol().transport.disconnecting, True)
# The connection has not been closed yet; we *asked* the flow to stop,
# but it may not have done.
self.assertEqual(self.tube.wasStopped, False)
@@ -121,7 +135,7 @@ class FlowingAdapterTests(TestCase):
"""
self.adaptedFount.flowTo(self.drain)
self.adaptedDrain.flowStopped(Failure(ZeroDivisionError()))
- self.assertEqual(self.adaptedProtocol.transport.disconnecting, True)
+ self.assertEqual(self.adaptedProtocol().transport.disconnecting, True)
self.assertEqual(self.tube.wasStopped, False)
@@ -137,7 +151,7 @@ class FlowingAdapterTests(TestCase):
class MyFunException(Exception):
pass
f = Failure(MyFunException())
- self.adaptedProtocol.connectionLost(f)
+ self.adaptedProtocol().connectionLost(f)
self.assertEqual(self.tube.wasStopped, True)
self.assertIdentical(f, self.tube.reason)
@@ -150,7 +164,7 @@ class FlowingAdapterTests(TestCase):
ff = FakeFount()
ff.flowTo(self.adaptedDrain)
self.assertEqual(ff.flowIsStopped, False)
- self.adaptedProtocol.connectionLost(Failure(ZeroDivisionError))
+ self.adaptedProtocol().connectionLost(Failure(ZeroDivisionError))
self.assertEqual(ff.flowIsStopped, True)
@@ -160,16 +174,16 @@ class FlowingAdapterTests(TestCase):
L{_ProtocolFount} is flowing to anything, then it will pause the
transport but only until the L{_ProtocolFount} is flowing to something.
"""
- self.adaptedProtocol.dataReceived("hello, ")
- self.assertEqual(self.adaptedProtocol.transport.producerState,
+ self.adaptedProtocol().dataReceived("hello, ")
+ self.assertEqual(self.adaptedProtocol().transport.producerState,
'paused')
# It would be invalid to call dataReceived again in this state, so no
# need to test that...
fd = FakeDrain()
self.adaptedFount.flowTo(fd)
- self.assertEqual(self.adaptedProtocol.transport.producerState,
+ self.assertEqual(self.adaptedProtocol().transport.producerState,
'producing')
- self.adaptedProtocol.dataReceived("world!")
+ self.adaptedProtocol().dataReceived("world!")
self.assertEqual(fd.received, ["hello, ", "world!"])
@@ -181,7 +195,7 @@ class FlowingAdapterTests(TestCase):
self.test_dataReceivedBeforeFlowing()
fd2 = FakeDrain()
self.adaptedFount.flowTo(fd2)
- self.adaptedProtocol.dataReceived("hooray")
+ self.adaptedProtocol().dataReceived("hooray")
self.assertEqual(fd2.received, ["hooray"])
@@ -201,7 +215,7 @@ class FlowingAdapterTests(TestCase):
"""
fd = FakeDrain()
self.adaptedFount.flowTo(fd)
- self.adaptedProtocol.dataReceived("a")
+ self.adaptedProtocol().dataReceived("a")
self.adaptedFount.flowTo(None)
self.assertEqual(fd.fount, None)
self.test_dataReceivedBeforeFlowing()
@@ -231,10 +245,10 @@ class FlowingAdapterTests(TestCase):
self.assertEqual(ff.flowIsPaused, False)
self.adaptedDrain.flowingFrom(ff)
# The connection is too full! Back off!
- self.adaptedProtocol.transport.producer.pauseProducing()
+ self.adaptedProtocol().transport.producer.pauseProducing()
self.assertEqual(ff.flowIsPaused, True)
# All clear, start writing again.
- self.adaptedProtocol.transport.producer.resumeProducing()
+ self.adaptedProtocol().transport.producer.resumeProducing()
self.assertEqual(ff.flowIsPaused, False)
@@ -249,17 +263,17 @@ class FlowingAdapterTests(TestCase):
producing = 'producing'
paused = 'paused'
# Sanity check.
- self.assertEqual(self.adaptedProtocol.transport.producerState,
+ self.assertEqual(self.adaptedProtocol().transport.producerState,
producing)
self.adaptedFount.flowTo(fd)
# Steady as she goes.
- self.assertEqual(self.adaptedProtocol.transport.producerState,
+ self.assertEqual(self.adaptedProtocol().transport.producerState,
producing)
anPause = fd.fount.pauseFlow()
- self.assertEqual(self.adaptedProtocol.transport.producerState,
+ self.assertEqual(self.adaptedProtocol().transport.producerState,
paused)
anPause.unpause()
- self.assertEqual(self.adaptedProtocol.transport.producerState,
+ self.assertEqual(self.adaptedProtocol().transport.producerState,
producing)
@@ -288,3 +302,99 @@ class FlowingAdapterTests(TestCase):
return another
anotherOther = self.adaptedFount.flowTo(ReflowingFakeDrain())
self.assertIdentical(another, anotherOther)
+
+
+
+class FlowListenerTests(TestCase):
+ """
+ Tests for L{flowFountFromEndpoint} and the fount adapter it constructs.
+ """
+
+ def test_fromEndpoint(self):
+ """
+ L{flowFountFromEndpoint} returns a L{Deferred} that fires when the
+ listening port is ready.
+ """
+ endpoint, ports = fakeEndpointWithPorts()
+ deferred = flowFountFromEndpoint(endpoint)
+ self.assertNoResult(deferred)
+ deferred.callback(None)
+ result = self.successResultOf(deferred)
+ self.assertTrue(IFount.providedBy(result))
+ self.assertEqual(result.outputType.implementedBy(Flow), True)
+
+
+ def test_oneConnectionAccepted(self):
+ """
+ When a connection comes in to a listening L{flowFountFromEndpoint}, the
+ L{Listener} that it's flowing to's callback is called.
+ """
+ endpoint, ports = fakeEndpointWithPorts()
+ deferred = flowFountFromEndpoint(endpoint)
+ self.assertNoResult(deferred)
+ deferred.callback(None)
+ result = self.successResultOf(deferred)
+ connected = []
+ result.flowTo(Listener(connected.append))
+ protocol = ports[0].factory.buildProtocol(None)
+ self.assertEqual(len(connected), 0)
+ protocol.makeConnection(StringTransport())
+ self.assertEqual(len(connected), 1)
+
+
+ def test_acceptBeforeActuallyListening(self):
+ """
+ Sometimes a connection is established reentrantly by C{listen}, without
+ waiting for the L{Deferred} returned to fire. In this case the
+ connection will be buffered until said L{Deferred} fires.
+ """
+ immediateTransport = StringTransport()
+ subEndpoint, ports = fakeEndpointWithPorts()
+ @implementer(IStreamServerEndpoint)
+ class ImmediateFakeEndpoint(object):
+ def listen(self, factory):
+ protocol = factory.buildProtocol(None)
+ protocol.makeConnection(immediateTransport)
+ return subEndpoint.listen(factory)
+ endpoint = ImmediateFakeEndpoint()
+ deferred = flowFountFromEndpoint(endpoint)
+ deferred.callback(None)
+ fount = self.successResultOf(deferred)
+ connected = []
+ self.assertEqual(ports[0].currentlyProducing, False)
+ fount.flowTo(Listener(connected.append))
+ self.assertEqual(ports[0].currentlyProducing, True)
+ self.assertEqual(len(connected), 1)
+
+
+ def test_backpressure(self):
+ """
+ When the L{IFount} returned by L{flowFountFromEndpoint} is paused, it
+ removes its listening port from the reactor. When resumed, it re-adds
+ it.
+ """
+ endpoint, ports = fakeEndpointWithPorts()
+ deferred = flowFountFromEndpoint(endpoint)
+ deferred.callback(None)
+ fount = self.successResultOf(deferred)
+ fount.flowTo(FakeDrain())
+ pause = fount.pauseFlow()
+ self.assertEqual(ports[0].currentlyProducing, False)
+ pause.unpause()
+ self.assertEqual(ports[0].currentlyProducing, True)
+
+
+ def test_stopping(self):
+ """
+ The L{IFount} returned by L{flowFountFromEndpoint} will stop listening
+ on the endpoint
+ """
+ endpoint, ports = fakeEndpointWithPorts()
+ deferred = flowFountFromEndpoint(endpoint)
+ deferred.callback(None)
+ fount = self.successResultOf(deferred)
+ fd = FakeDrain()
+ fount.flowTo(fd)
+ fount.stopFlow()
+ self.assertEqual(ports[0].listenStopping, True)
+ self.assertEqual(len(fd.stopped), 1)
diff --git a/tubes/test/util.py b/tubes/test/util.py
index 2c29c0e..dd36224 100644
--- a/tubes/test/util.py
+++ b/tubes/test/util.py
@@ -11,12 +11,15 @@ from zope.interface.verify import verifyClass
from twisted.test.proto_helpers import StringTransport
from twisted.internet.defer import succeed
-from twisted.internet.interfaces import IStreamClientEndpoint
+from twisted.internet.interfaces import (
+ IStreamClientEndpoint, IStreamServerEndpoint, IListeningPort, IPushProducer
+)
from ..itube import IDrain, IFount, IDivertable
from ..tube import tube
from ..kit import Pauser, beginFlowingFrom, beginFlowingTo
+from twisted.internet.defer import Deferred
@implementer(IStreamClientEndpoint)
class StringEndpoint(object):
@@ -311,3 +314,123 @@ class NullTube(object):
+@implementer(IListeningPort, IPushProducer)
+class FakeListeningProducerPort(object):
+ """
+ This is a fake L{IListeningPort}, also implementing L{IPushProducer}, which
+ L{flowFountFromEndpoint} needs to make backpressure work.
+ """
+ def __init__(self, factory):
+ """
+ Create a L{FakeListeningProducerPort} with the given protocol
+ factory.
+ """
+ self.factory = factory
+ self.stopper = Deferred()
+ self.listenStopping = False
+ self.currentlyProducing = True
+
+
+ def pauseProducing(self):
+ """
+ Pause producing new connections.
+ """
+ self.currentlyProducing = False
+
+
+ def resumeProducing(self):
+ """
+ Resume producing new connections.
+ """
+ self.currentlyProducing = True
+
+
+ def startListening(self):
+ """
+ Start listening on this port.
+
+ @raise CannotListenError: If it cannot listen on this port (e.g., it is
+ a TCP port and it cannot bind to the required port number).
+ """
+
+
+ def stopListening(self):
+ """
+ Stop listening on this fake port.
+
+ @return: a L{Deferred} that should be fired when the test wants to
+ complete stopping listening.
+ """
+ self.listenStopping = True
+ return self.stopper
+
+
+ def stopProducing(self):
+ """
+ Stop producing more data.
+ """
+ self.stopListening()
+
+
+ def getHost(self):
+ """
+ Get the host that this port is listening for.
+
+ @return: An L{IAddress} provider.
+ """
+
+verifyClass(IListeningPort, FakeListeningProducerPort)
+verifyClass(IPushProducer, FakeListeningProducerPort)
+
+
+@implementer(IStreamServerEndpoint)
+class FakeEndpoint(object):
+ """
+ A fake implementation of L{IStreamServerEndpoint} with a L{Deferred} that
+ fires controllably.
+
+ @ivar _listening: deferreds that will fire with listening ports when their
+ C{.callback} is invoked (input to C{.callback} ignored); added to when
+ C{listen} is called.
+ @type _listening: L{list} of L{Deferred}
+
+ @ivar _ports: list of ports that have already started listening
+ @type _ports: L{list} of L{IListeningPort}
+ """
+ def __init__(self):
+ """
+ Create a L{FakeEndpoint}.
+ """
+ self._listening = []
+ self._ports = []
+
+
+ def listen(self, factory):
+ """
+ Listen with the given factory.
+
+ @param factory: The factory to use for future connections.
+
+ @return: a L{Deferred} that fires with a new listening port.
+ """
+ self._listening.append(Deferred())
+ def newListener(ignored):
+ result = FakeListeningProducerPort(factory)
+ self._ports.append(result)
+ return result
+ return self._listening[-1].addCallback(newListener)
+
+
+
+def fakeEndpointWithPorts():
+ """
+ Create a L{FakeEndpoint} and expose the list of ports that it uses.
+
+ @return: a fake endpoint and a list of the ports it has listened on
+ @rtype: a 2-tuple of C{(endpoint, ports)}, where C{ports} is a L{list} of
+ L{IListeningPort}.
+ """
+ self = FakeEndpoint()
+ return self, self._ports
+
+verifyClass(IStreamServerEndpoint, FakeEndpoint)
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_added_files",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 3,
"issue_text_score": 1,
"test_score": 3
},
"num_modified_files": 14
} | unknown | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[dev]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest pytest-cov pytest-xdist pytest-mock pytest-asyncio",
"pytest"
],
"pre_install": null,
"python": "3.9",
"reqs_path": [
"requirements/base.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | attrs==25.3.0
Automat==24.8.1
characteristic==14.3.0
constantly==23.10.4
coverage==7.8.0
exceptiongroup==1.2.2
execnet==2.1.1
hyperlink==21.0.0
idna==3.10
incremental==24.7.2
iniconfig==2.1.0
packaging==24.2
pluggy==1.5.0
pytest==8.3.5
pytest-asyncio==0.26.0
pytest-cov==6.0.0
pytest-mock==3.14.0
pytest-xdist==3.6.1
six==1.17.0
tomli==2.2.1
-e git+https://github.com/twisted/tubes.git@71894325180c6337d257e457d96e85075a560020#egg=Tubes
Twisted==24.11.0
typing_extensions==4.13.0
zope.interface==7.2
| name: tubes
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=3.0.16=h5eee18b_0
- pip=25.0=py39h06a4308_0
- python=3.9.21=he870216_1
- readline=8.2=h5eee18b_0
- setuptools=75.8.0=py39h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- tzdata=2025a=h04d1e81_0
- wheel=0.45.1=py39h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- attrs==25.3.0
- automat==24.8.1
- characteristic==14.3.0
- constantly==23.10.4
- coverage==7.8.0
- exceptiongroup==1.2.2
- execnet==2.1.1
- hyperlink==21.0.0
- idna==3.10
- incremental==24.7.2
- iniconfig==2.1.0
- packaging==24.2
- pluggy==1.5.0
- pytest==8.3.5
- pytest-asyncio==0.26.0
- pytest-cov==6.0.0
- pytest-mock==3.14.0
- pytest-xdist==3.6.1
- six==1.17.0
- tomli==2.2.1
- twisted==24.11.0
- typing-extensions==4.13.0
- zope-interface==7.2
prefix: /opt/conda/envs/tubes
| [
"tubes/test/test_listening.py::ListeningTests::test_listenerCallsFlowConnector",
"tubes/test/test_listening.py::ListeningTests::test_listenerLimitsConcurrentConnections",
"tubes/test/test_protocol.py::FlowConnectorTests::test_connectionLostSendsFlowStopped",
"tubes/test/test_protocol.py::FlowConnectorTests::test_connectionLostSendsStopFlow",
"tubes/test/test_protocol.py::FlowConnectorTests::test_dataReceivedBeforeFlowing",
"tubes/test/test_protocol.py::FlowConnectorTests::test_dataReceivedBeforeFlowingThenFlowTo",
"tubes/test/test_protocol.py::FlowConnectorTests::test_dataReceivedWhenFlowingToNone",
"tubes/test/test_protocol.py::FlowConnectorTests::test_drainReceivingWritesToTransport",
"tubes/test/test_protocol.py::FlowConnectorTests::test_flowStoppedStopsConnection",
"tubes/test/test_protocol.py::FlowConnectorTests::test_flowToDeliversData",
"tubes/test/test_protocol.py::FlowConnectorTests::test_flowToSetsDrain",
"tubes/test/test_protocol.py::FlowConnectorTests::test_flowingFrom",
"tubes/test/test_protocol.py::FlowConnectorTests::test_flowingFromAttribute",
"tubes/test/test_protocol.py::FlowConnectorTests::test_flowingToNoneAfterFlowingToSomething",
"tubes/test/test_protocol.py::FlowConnectorTests::test_pauseUnpauseFromOtherDrain",
"tubes/test/test_protocol.py::FlowConnectorTests::test_pauseUnpauseFromTransport",
"tubes/test/test_protocol.py::FlowConnectorTests::test_stopFlowStopsConnection",
"tubes/test/test_protocol.py::FlowConnectorTests::test_stopProducing",
"tubes/test/test_protocol.py::FlowListenerTests::test_acceptBeforeActuallyListening",
"tubes/test/test_protocol.py::FlowListenerTests::test_backpressure",
"tubes/test/test_protocol.py::FlowListenerTests::test_fromEndpoint",
"tubes/test/test_protocol.py::FlowListenerTests::test_oneConnectionAccepted",
"tubes/test/test_protocol.py::FlowListenerTests::test_stopping"
] | [] | [] | [] | MIT License | 254 |
|
tornadoweb__tornado-1533 | 4ee9ba94de11aaa4f932560fa2b3d8ceb8c61d2a | 2015-09-29 02:40:11 | 4ee9ba94de11aaa4f932560fa2b3d8ceb8c61d2a | diff --git a/tornado/auth.py b/tornado/auth.py
index 32d0e226..ff7172aa 100644
--- a/tornado/auth.py
+++ b/tornado/auth.py
@@ -75,7 +75,7 @@ import hmac
import time
import uuid
-from tornado.concurrent import TracebackFuture, return_future
+from tornado.concurrent import TracebackFuture, return_future, chain_future
from tornado import gen
from tornado import httpclient
from tornado import escape
@@ -985,7 +985,7 @@ class FacebookGraphMixin(OAuth2Mixin):
future.set_exception(AuthError('Facebook auth error: %s' % str(response)))
return
- args = escape.parse_qs_bytes(escape.native_str(response.body))
+ args = urlparse.parse_qs(escape.native_str(response.body))
session = {
"access_token": args["access_token"][-1],
"expires": args.get("expires")
@@ -1062,8 +1062,13 @@ class FacebookGraphMixin(OAuth2Mixin):
Added the ability to override ``self._FACEBOOK_BASE_URL``.
"""
url = self._FACEBOOK_BASE_URL + path
- return self.oauth2_request(url, callback, access_token,
- post_args, **args)
+ # Thanks to the _auth_return_future decorator, our "callback"
+ # argument is a Future, which we cannot pass as a callback to
+ # oauth2_request. Instead, have oauth2_request return a
+ # future and chain them together.
+ oauth_future = self.oauth2_request(url, access_token=access_token,
+ post_args=post_args, **args)
+ chain_future(oauth_future, callback)
def _oauth_signature(consumer_token, method, url, parameters={}, token=None):
| FacebookGraphMixin failing
I had to modify `_on_access_token` so that it did not attempt to make a `facebook_request` to `/me`. With the code as it stands, I get this error:
`TypeError: 'Future' object is not callable`
However, removing that extra request fixes this, and I can use the access_token in the next part of my auth pipeline. | tornadoweb/tornado | diff --git a/tornado/test/auth_test.py b/tornado/test/auth_test.py
index 56de93a5..3ed40e45 100644
--- a/tornado/test/auth_test.py
+++ b/tornado/test/auth_test.py
@@ -5,7 +5,7 @@
from __future__ import absolute_import, division, print_function, with_statement
-from tornado.auth import OpenIdMixin, OAuthMixin, OAuth2Mixin, TwitterMixin, AuthError, GoogleOAuth2Mixin
+from tornado.auth import OpenIdMixin, OAuthMixin, OAuth2Mixin, TwitterMixin, AuthError, GoogleOAuth2Mixin, FacebookGraphMixin
from tornado.concurrent import Future
from tornado.escape import json_decode
from tornado import gen
@@ -126,6 +126,38 @@ class OAuth2ClientLoginHandler(RequestHandler, OAuth2Mixin):
assert res.done()
+class FacebookClientLoginHandler(RequestHandler, FacebookGraphMixin):
+ def initialize(self, test):
+ self._OAUTH_AUTHORIZE_URL = test.get_url('/facebook/server/authorize')
+ self._OAUTH_ACCESS_TOKEN_URL = test.get_url('/facebook/server/access_token')
+ self._FACEBOOK_BASE_URL = test.get_url('/facebook/server')
+
+ @gen.coroutine
+ def get(self):
+ if self.get_argument("code", None):
+ user = yield self.get_authenticated_user(
+ redirect_uri=self.request.full_url(),
+ client_id=self.settings["facebook_api_key"],
+ client_secret=self.settings["facebook_secret"],
+ code=self.get_argument("code"))
+ self.write(user)
+ else:
+ yield self.authorize_redirect(
+ redirect_uri=self.request.full_url(),
+ client_id=self.settings["facebook_api_key"],
+ extra_params={"scope": "read_stream,offline_access"})
+
+
+class FacebookServerAccessTokenHandler(RequestHandler):
+ def get(self):
+ self.write('access_token=asdf')
+
+
+class FacebookServerMeHandler(RequestHandler):
+ def get(self):
+ self.write('{}')
+
+
class TwitterClientHandler(RequestHandler, TwitterMixin):
def initialize(self, test):
self._OAUTH_REQUEST_TOKEN_URL = test.get_url('/oauth1/server/request_token')
@@ -260,6 +292,8 @@ class AuthTest(AsyncHTTPTestCase):
dict(version='1.0a')),
('/oauth2/client/login', OAuth2ClientLoginHandler, dict(test=self)),
+ ('/facebook/client/login', FacebookClientLoginHandler, dict(test=self)),
+
('/twitter/client/login', TwitterClientLoginHandler, dict(test=self)),
('/twitter/client/login_gen_engine', TwitterClientLoginGenEngineHandler, dict(test=self)),
('/twitter/client/login_gen_coroutine', TwitterClientLoginGenCoroutineHandler, dict(test=self)),
@@ -271,13 +305,17 @@ class AuthTest(AsyncHTTPTestCase):
('/oauth1/server/request_token', OAuth1ServerRequestTokenHandler),
('/oauth1/server/access_token', OAuth1ServerAccessTokenHandler),
+ ('/facebook/server/access_token', FacebookServerAccessTokenHandler),
+ ('/facebook/server/me', FacebookServerMeHandler),
('/twitter/server/access_token', TwitterServerAccessTokenHandler),
(r'/twitter/api/users/show/(.*)\.json', TwitterServerShowUserHandler),
(r'/twitter/api/account/verify_credentials\.json', TwitterServerVerifyCredentialsHandler),
],
http_client=self.http_client,
twitter_consumer_key='test_twitter_consumer_key',
- twitter_consumer_secret='test_twitter_consumer_secret')
+ twitter_consumer_secret='test_twitter_consumer_secret',
+ facebook_api_key='test_facebook_api_key',
+ facebook_secret='test_facebook_secret')
def test_openid_redirect(self):
response = self.fetch('/openid/client/login', follow_redirects=False)
@@ -358,6 +396,13 @@ class AuthTest(AsyncHTTPTestCase):
self.assertEqual(response.code, 302)
self.assertTrue('/oauth2/server/authorize?' in response.headers['Location'])
+ def test_facebook_login(self):
+ response = self.fetch('/facebook/client/login', follow_redirects=False)
+ self.assertEqual(response.code, 302)
+ self.assertTrue('/facebook/server/authorize?' in response.headers['Location'])
+ response = self.fetch('/facebook/client/login?code=1234', follow_redirects=False)
+ self.assertEqual(response.code, 200)
+
def base_twitter_redirect(self, url):
# Same as test_oauth10a_redirect
response = self.fetch(url, follow_redirects=False)
| {
"commit_name": "head_commit",
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true,
"llm_score": {
"difficulty_score": 2,
"issue_text_score": 2,
"test_score": 2
},
"num_modified_files": 1
} | 4.2 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "pytest",
"pip_packages": [
"futures",
"mock",
"monotonic",
"trollius",
"pytest"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.5",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | attrs @ file:///opt/conda/conda-bld/attrs_1642510447205/work
certifi==2021.5.30
futures==2.2.0
importlib-metadata @ file:///tmp/build/80754af9/importlib-metadata_1631916693255/work
iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work
mock==5.2.0
monotonic==1.6
more-itertools @ file:///tmp/build/80754af9/more-itertools_1637733554872/work
packaging @ file:///tmp/build/80754af9/packaging_1637314298585/work
pluggy @ file:///tmp/build/80754af9/pluggy_1615976315926/work
py @ file:///opt/conda/conda-bld/py_1644396412707/work
pyparsing @ file:///tmp/build/80754af9/pyparsing_1635766073266/work
pytest==6.2.4
six==1.17.0
toml @ file:///tmp/build/80754af9/toml_1616166611790/work
-e git+https://github.com/tornadoweb/tornado.git@4ee9ba94de11aaa4f932560fa2b3d8ceb8c61d2a#egg=tornado
trollius==2.1.post2
typing_extensions @ file:///opt/conda/conda-bld/typing_extensions_1647553014482/work
zipp @ file:///tmp/build/80754af9/zipp_1633618647012/work
| name: tornado
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- attrs=21.4.0=pyhd3eb1b0_0
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2021.5.30=py36h06a4308_0
- importlib-metadata=4.8.1=py36h06a4308_0
- importlib_metadata=4.8.1=hd3eb1b0_0
- iniconfig=1.1.1=pyhd3eb1b0_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.3=he6710b0_2
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- more-itertools=8.12.0=pyhd3eb1b0_0
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- packaging=21.3=pyhd3eb1b0_0
- pip=21.2.2=py36h06a4308_0
- pluggy=0.13.1=py36h06a4308_0
- py=1.11.0=pyhd3eb1b0_0
- pyparsing=3.0.4=pyhd3eb1b0_0
- pytest=6.2.4=py36h06a4308_2
- python=3.6.13=h12debd9_1
- readline=8.2=h5eee18b_0
- setuptools=58.0.4=py36h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- toml=0.10.2=pyhd3eb1b0_0
- typing_extensions=4.1.1=pyh06a4308_0
- wheel=0.37.1=pyhd3eb1b0_0
- xz=5.6.4=h5eee18b_1
- zipp=3.6.0=pyhd3eb1b0_0
- zlib=1.2.13=h5eee18b_1
- pip:
- futures==2.2.0
- mock==5.2.0
- monotonic==1.6
- six==1.17.0
- trollius==2.1.post2
prefix: /opt/conda/envs/tornado
| [
"tornado/test/auth_test.py::AuthTest::test_facebook_login"
] | [] | [
"tornado/test/auth_test.py::AuthTest::test_oauth10_get_user",
"tornado/test/auth_test.py::AuthTest::test_oauth10_redirect",
"tornado/test/auth_test.py::AuthTest::test_oauth10_request_parameters",
"tornado/test/auth_test.py::AuthTest::test_oauth10a_get_user",
"tornado/test/auth_test.py::AuthTest::test_oauth10a_get_user_coroutine_exception",
"tornado/test/auth_test.py::AuthTest::test_oauth10a_redirect",
"tornado/test/auth_test.py::AuthTest::test_oauth10a_request_parameters",
"tornado/test/auth_test.py::AuthTest::test_oauth2_redirect",
"tornado/test/auth_test.py::AuthTest::test_openid_get_user",
"tornado/test/auth_test.py::AuthTest::test_openid_redirect",
"tornado/test/auth_test.py::AuthTest::test_twitter_get_user",
"tornado/test/auth_test.py::AuthTest::test_twitter_redirect",
"tornado/test/auth_test.py::AuthTest::test_twitter_redirect_gen_coroutine",
"tornado/test/auth_test.py::AuthTest::test_twitter_redirect_gen_engine",
"tornado/test/auth_test.py::AuthTest::test_twitter_show_user",
"tornado/test/auth_test.py::AuthTest::test_twitter_show_user_error",
"tornado/test/auth_test.py::AuthTest::test_twitter_show_user_future",
"tornado/test/auth_test.py::AuthTest::test_twitter_show_user_future_error",
"tornado/test/auth_test.py::GoogleOAuth2Test::test_google_login"
] | [] | Apache License 2.0 | 255 |
|
networkx__networkx-1781 | 328d899fb17bac857eedd9ec3e03f4ede9b11c63 | 2015-09-29 20:34:48 | bd19b43751b5bd433ebc5a9ab173938f721af2dd | diff --git a/networkx/readwrite/gml.py b/networkx/readwrite/gml.py
index d9e49d336..d3c8b8527 100644
--- a/networkx/readwrite/gml.py
+++ b/networkx/readwrite/gml.py
@@ -286,7 +286,7 @@ def parse_gml_lines(lines, label, destringizer):
"""
def tokenize():
patterns = [
- r'[A-Za-z][0-9A-Za-z]*\s+', # keys
+ r'[A-Za-z][0-9A-Za-z_]*\s+', # keys
r'[+-]?(?:[0-9]*\.[0-9]+|[0-9]+\.[0-9]*)(?:[Ee][+-]?[0-9]+)?', # reals
r'[+-]?[0-9]+', # ints
r'".*?"', # strings
| Cannot parse GML files from Cytoscape, possible regression?
This does not appear to be a duplicate of #321 -- I cannot parse .GML files produced from Cytoscape, including the "simple.gml" [file](https://networkx.lanl.gov/trac/attachment/ticket/324/simple.gml) as reported in #321. Below is the output I receive if parsing the file provided in that issue.
From reading the comments, it looks like the suggestion is to either modify the GML parser directly in networkx (allowing slightly out of format GML files), or to modify the output from Cytoscape. If I issue a PR for the GML parser modification, would there be support for it?
```python
10:20:28 (mcdonadt@8086):~> nx.__version__
Out[5]: '1.10'
10:20:32 (mcdonadt@8086):~> g = nx.read_gml('Downloads/simple.gml')
---------------------------------------------------------------------------
NetworkXError Traceback (most recent call last)
<ipython-input-6-e05f5232526f> in <module>()
----> 1 g = nx.read_gml('Downloads/simple.gml')
/Users/mcdonadt/miniconda3/envs/unifrac-network/lib/python3.4/site-packages/networkx/readwrite/gml.py in read_gml(path, label, destringizer)
/Users/mcdonadt/miniconda3/envs/unifrac-network/lib/python3.4/site-packages/networkx/utils/decorators.py in _open_file(func, *args, **kwargs)
218 # Finally, we call the original function, making sure to close the fobj.
219 try:
--> 220 result = func(*new_args, **kwargs)
221 finally:
222 if close_fobj:
/Users/mcdonadt/miniconda3/envs/unifrac-network/lib/python3.4/site-packages/networkx/readwrite/gml.py in read_gml(path, label, destringizer)
208 yield line
209
--> 210 G = parse_gml_lines(filter_lines(path), label, destringizer)
211 return G
212
/Users/mcdonadt/miniconda3/envs/unifrac-network/lib/python3.4/site-packages/networkx/readwrite/gml.py in parse_gml_lines(lines, label, destringizer)
381
382 tokens = tokenize()
--> 383 graph = parse_graph()
384
385 directed = graph.pop('directed', False)
/Users/mcdonadt/miniconda3/envs/unifrac-network/lib/python3.4/site-packages/networkx/readwrite/gml.py in parse_graph()
370
371 def parse_graph():
--> 372 curr_token, dct = parse_kv(next(tokens))
373 if curr_token[0] is not None: # EOF
374 unexpected(curr_token, 'EOF')
/Users/mcdonadt/miniconda3/envs/unifrac-network/lib/python3.4/site-packages/networkx/readwrite/gml.py in parse_kv(curr_token)
355 curr_token = next(tokens)
356 elif type == 4: # dict start
--> 357 curr_token, value = parse_dict(curr_token)
358 else:
359 unexpected(curr_token, "an int, float, string or '['")
/Users/mcdonadt/miniconda3/envs/unifrac-network/lib/python3.4/site-packages/networkx/readwrite/gml.py in parse_dict(curr_token)
365 def parse_dict(curr_token):
366 curr_token = consume(curr_token, 4, "'['") # dict start
--> 367 curr_token, dct = parse_kv(curr_token)
368 curr_token = consume(curr_token, 5, "']'") # dict end
369 return curr_token, dct
/Users/mcdonadt/miniconda3/envs/unifrac-network/lib/python3.4/site-packages/networkx/readwrite/gml.py in parse_kv(curr_token)
355 curr_token = next(tokens)
356 elif type == 4: # dict start
--> 357 curr_token, value = parse_dict(curr_token)
358 else:
359 unexpected(curr_token, "an int, float, string or '['")
/Users/mcdonadt/miniconda3/envs/unifrac-network/lib/python3.4/site-packages/networkx/readwrite/gml.py in parse_dict(curr_token)
364
365 def parse_dict(curr_token):
--> 366 curr_token = consume(curr_token, 4, "'['") # dict start
367 curr_token, dct = parse_kv(curr_token)
368 curr_token = consume(curr_token, 5, "']'") # dict end
/Users/mcdonadt/miniconda3/envs/unifrac-network/lib/python3.4/site-packages/networkx/readwrite/gml.py in consume(curr_token, type, expected)
334 def consume(curr_token, type, expected):
335 if curr_token[0] == type:
--> 336 return next(tokens)
337 unexpected(curr_token, expected)
338
/Users/mcdonadt/miniconda3/envs/unifrac-network/lib/python3.4/site-packages/networkx/readwrite/gml.py in tokenize()
321 else:
322 raise NetworkXError('cannot tokenize %r at (%d, %d)' %
--> 323 (line[pos:], lineno + 1, pos + 1))
324 lineno += 1
325 yield (None, None, lineno + 1, 1) # EOF
NetworkXError: cannot tokenize 'root_index\t-3' at (5, 3)
``` | networkx/networkx | diff --git a/networkx/readwrite/tests/test_gml.py b/networkx/readwrite/tests/test_gml.py
index 85b069127..042061032 100644
--- a/networkx/readwrite/tests/test_gml.py
+++ b/networkx/readwrite/tests/test_gml.py
@@ -65,6 +65,90 @@ graph [
]
]
"""
+ def test_parse_gml_cytoscape_bug(self):
+ # example from issue #321, originally #324 in trac
+ cytoscape_example = """
+Creator "Cytoscape"
+Version 1.0
+graph [
+ node [
+ root_index -3
+ id -3
+ graphics [
+ x -96.0
+ y -67.0
+ w 40.0
+ h 40.0
+ fill "#ff9999"
+ type "ellipse"
+ outline "#666666"
+ outline_width 1.5
+ ]
+ label "node2"
+ ]
+ node [
+ root_index -2
+ id -2
+ graphics [
+ x 63.0
+ y 37.0
+ w 40.0
+ h 40.0
+ fill "#ff9999"
+ type "ellipse"
+ outline "#666666"
+ outline_width 1.5
+ ]
+ label "node1"
+ ]
+ node [
+ root_index -1
+ id -1
+ graphics [
+ x -31.0
+ y -17.0
+ w 40.0
+ h 40.0
+ fill "#ff9999"
+ type "ellipse"
+ outline "#666666"
+ outline_width 1.5
+ ]
+ label "node0"
+ ]
+ edge [
+ root_index -2
+ target -2
+ source -1
+ graphics [
+ width 1.5
+ fill "#0000ff"
+ type "line"
+ Line [
+ ]
+ source_arrow 0
+ target_arrow 3
+ ]
+ label "DirectedEdge"
+ ]
+ edge [
+ root_index -1
+ target -1
+ source -3
+ graphics [
+ width 1.5
+ fill "#0000ff"
+ type "line"
+ Line [
+ ]
+ source_arrow 0
+ target_arrow 3
+ ]
+ label "DirectedEdge"
+ ]
+]
+"""
+ nx.parse_gml(cytoscape_example)
def test_parse_gml(self):
G = nx.parse_gml(self.simple_data, label='label')
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_hyperlinks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 0,
"issue_text_score": 2,
"test_score": 2
},
"num_modified_files": 1
} | 1.102 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"nose",
"pytest"
],
"pre_install": [
"apt-get update",
"apt-get install -y libgdal-dev graphviz"
],
"python": "3.6",
"reqs_path": [
"requirements/default.txt",
"requirements/test.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | attrs==22.2.0
certifi==2021.5.30
decorator==5.1.1
importlib-metadata==4.8.3
iniconfig==1.1.1
-e git+https://github.com/networkx/networkx.git@328d899fb17bac857eedd9ec3e03f4ede9b11c63#egg=networkx
nose==1.3.7
packaging==21.3
pluggy==1.0.0
py==1.11.0
pyparsing==3.1.4
pytest==7.0.1
tomli==1.2.3
typing_extensions==4.1.1
zipp==3.6.0
| name: networkx
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2021.5.30=py36h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.3=he6710b0_2
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- pip=21.2.2=py36h06a4308_0
- python=3.6.13=h12debd9_1
- readline=8.2=h5eee18b_0
- setuptools=58.0.4=py36h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- wheel=0.37.1=pyhd3eb1b0_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- attrs==22.2.0
- decorator==5.1.1
- importlib-metadata==4.8.3
- iniconfig==1.1.1
- nose==1.3.7
- packaging==21.3
- pluggy==1.0.0
- py==1.11.0
- pyparsing==3.1.4
- pytest==7.0.1
- tomli==1.2.3
- typing-extensions==4.1.1
- zipp==3.6.0
prefix: /opt/conda/envs/networkx
| [
"networkx/readwrite/tests/test_gml.py::TestGraph::test_parse_gml_cytoscape_bug"
] | [
"networkx/readwrite/tests/test_gml.py::TestGraph::test_parse_gml",
"networkx/readwrite/tests/test_gml.py::TestGraph::test_read_gml"
] | [
"networkx/readwrite/tests/test_gml.py::TestGraph::test_relabel_duplicate",
"networkx/readwrite/tests/test_gml.py::TestGraph::test_tuplelabels",
"networkx/readwrite/tests/test_gml.py::TestGraph::test_quotes",
"networkx/readwrite/tests/test_gml.py::TestGraph::test_name",
"networkx/readwrite/tests/test_gml.py::TestGraph::test_graph_types",
"networkx/readwrite/tests/test_gml.py::TestGraph::test_data_types",
"networkx/readwrite/tests/test_gml.py::TestGraph::test_escape_unescape",
"networkx/readwrite/tests/test_gml.py::TestGraph::test_exceptions"
] | [] | BSD 3-Clause | 256 |
|
keleshev__schema-91 | eb7670f0f4615195393dc5350d49fa9a33304137 | 2015-09-30 21:18:29 | eb7670f0f4615195393dc5350d49fa9a33304137 | diff --git a/schema.py b/schema.py
index b8abee4..f4f5460 100644
--- a/schema.py
+++ b/schema.py
@@ -109,7 +109,7 @@ class Schema(object):
if flavor == ITERABLE:
data = Schema(type(s), error=e).validate(data)
o = Or(*s, error=e)
- return type(s)(o.validate(d) for d in data)
+ return type(data)(o.validate(d) for d in data)
if flavor == DICT:
data = Schema(dict, error=e).validate(data)
new = type(data)() # new - is a dict of the validated values
| Inconsistent return types for validate: type(schema) or type(data)?
I've noted a small inconsistency when validating with iterable and dict schemas:
```python
if flavor == ITERABLE:
data = Schema(type(s), error=e).validate(data)
return type(s)(Or(*s, error=e).validate(d) for d in data)
if flavor == DICT:
data = Schema(dict, error=e).validate(data)
new = type(data)() # new - is a dict of the validated values
...
return new
```
Briefly, when validating with iterable schemas the return type is that of the schema, when validating with dict schemas it's that of the input.
Personally I think that it's more flexible to have the return type match the one of the input.
Ideas, preferences? | keleshev/schema | diff --git a/test_schema.py b/test_schema.py
index 967dec0..e124fc9 100644
--- a/test_schema.py
+++ b/test_schema.py
@@ -408,3 +408,10 @@ def test_exception_handling_with_bad_validators():
except SchemaError as e:
assert "TypeError" in e.args[0]
raise
+
+
+def test_issue_83_iterable_validation_return_type():
+ TestSetType = type("TestSetType", (set,), dict())
+ data = TestSetType(["test", "strings"])
+ s = Schema(set([str]))
+ assert isinstance(s.validate(data), TestSetType)
| {
"commit_name": "head_commit",
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true,
"llm_score": {
"difficulty_score": 0,
"issue_text_score": 0,
"test_score": 0
},
"num_modified_files": 1
} | 0.3 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest",
"pytest-cov",
"coverage"
],
"pre_install": [],
"python": "3.5",
"reqs_path": null,
"test_cmd": "pytest --doctest-glob=README.rst --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | attrs==22.2.0
certifi==2021.5.30
coverage==6.2
importlib-metadata==4.8.3
iniconfig==1.1.1
packaging==21.3
pluggy==1.0.0
py==1.11.0
pyparsing==3.1.4
pytest==7.0.1
pytest-cov==4.0.0
-e git+https://github.com/keleshev/schema.git@eb7670f0f4615195393dc5350d49fa9a33304137#egg=schema
tomli==1.2.3
typing_extensions==4.1.1
zipp==3.6.0
| name: schema
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2021.5.30=py36h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.3=he6710b0_2
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- pip=21.2.2=py36h06a4308_0
- python=3.6.13=h12debd9_1
- readline=8.2=h5eee18b_0
- setuptools=58.0.4=py36h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- wheel=0.37.1=pyhd3eb1b0_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- attrs==22.2.0
- coverage==6.2
- importlib-metadata==4.8.3
- iniconfig==1.1.1
- packaging==21.3
- pluggy==1.0.0
- py==1.11.0
- pyparsing==3.1.4
- pytest==7.0.1
- pytest-cov==4.0.0
- tomli==1.2.3
- typing-extensions==4.1.1
- zipp==3.6.0
prefix: /opt/conda/envs/schema
| [
"test_schema.py::test_issue_83_iterable_validation_return_type"
] | [] | [
"test_schema.py::test_schema",
"test_schema.py::test_validate_file",
"test_schema.py::test_and",
"test_schema.py::test_or",
"test_schema.py::test_validate_list",
"test_schema.py::test_list_tuple_set_frozenset",
"test_schema.py::test_strictly",
"test_schema.py::test_dict",
"test_schema.py::test_dict_keys",
"test_schema.py::test_dict_optional_keys",
"test_schema.py::test_dict_optional_defaults",
"test_schema.py::test_dict_subtypes",
"test_schema.py::test_complex",
"test_schema.py::test_nice_errors",
"test_schema.py::test_use_error_handling",
"test_schema.py::test_or_error_handling",
"test_schema.py::test_and_error_handling",
"test_schema.py::test_schema_error_handling",
"test_schema.py::test_use_json",
"test_schema.py::test_error_reporting",
"test_schema.py::test_schema_repr",
"test_schema.py::test_validate_object",
"test_schema.py::test_issue_9_prioritized_key_comparison",
"test_schema.py::test_issue_9_prioritized_key_comparison_in_dicts",
"test_schema.py::test_missing_keys_exception_with_non_str_dict_keys",
"test_schema.py::test_issue_56_cant_rely_on_callables_to_have_name",
"test_schema.py::test_exception_handling_with_bad_validators"
] | [] | MIT License | 257 |
|
Stranger6667__pyanyapi-22 | e5b7aadff6d02eac82e27cb4ad1f8bc9a4fb2eb0 | 2015-10-01 09:10:15 | fef649317fa4d2717c35a697bf10941691c4b3fe | diff --git a/README.rst b/README.rst
index b01d832..35babdf 100644
--- a/README.rst
+++ b/README.rst
@@ -31,7 +31,7 @@ Usage
-----
Library provides an ability to create API over various content.
-Currently there are bundled tools to work with HTML, XML, JSON.
+Currently there are bundled tools to work with HTML, XML, JSON and YAML.
Initially it was created to work with ``requests`` library.
Basic setup
@@ -139,6 +139,22 @@ Settings attribute is merged from all ancestors of current parser.
>>> SecondChildParser({'child': '//more'}).settings['child']
//more
+Results stripping
+~~~~~~~~~~~~~~~~~
+
+Parsers can automagically strip trailing whitespaces with ``strip=True`` option.
+
+.. code:: python
+
+ from pyanyapi import RegExpParser
+
+
+ >>> settings = {'p': 'string(//p)'}
+ >>> XMLParser(settings).parse('<p> Pcontent </p>').p
+ Pcontent
+ >>> XMLParser(settings, strip=True).parse('<p> Pcontent </p>).p
+ Pcontent
+
HTML & XML
~~~~~~~~~~
diff --git a/pyanyapi/_compat.py b/pyanyapi/_compat.py
index 6ef744e..6322456 100644
--- a/pyanyapi/_compat.py
+++ b/pyanyapi/_compat.py
@@ -16,3 +16,9 @@ try:
import ujson as json
except ImportError:
import json
+
+
+try:
+ string_types = (str, unicode)
+except NameError:
+ string_types = (str, )
diff --git a/pyanyapi/interfaces.py b/pyanyapi/interfaces.py
index 88122a4..7dfb67b 100644
--- a/pyanyapi/interfaces.py
+++ b/pyanyapi/interfaces.py
@@ -6,7 +6,7 @@ import re
import yaml
-from ._compat import json, etree, objectify, XMLParser, HTMLParser
+from ._compat import json, etree, objectify, XMLParser, HTMLParser, string_types
from .exceptions import ResponseParseError
from .helpers import memoize
@@ -21,8 +21,9 @@ class BaseInterface(object):
content = None
empty_result = None
- def __init__(self, content):
+ def __init__(self, content, strip=False):
self.content = content
+ self.strip = strip
self.parse = memoize(self.parse)
@classmethod
@@ -58,6 +59,11 @@ class BaseInterface(object):
if hasattr(attr, '_attached') and type(attr).__name__ == 'cached_property'
)
+ def maybe_strip(self, value):
+ if self.strip and isinstance(value, string_types):
+ return value.strip()
+ return value
+
# Uses as fallback. None - can be obtained from JSON's null, any string also can be, so unique object is a best choice
EMPTY_RESULT = object()
@@ -132,15 +138,13 @@ class XPathInterface(BaseInterface):
result = self.parse(settings['base'])
child_query = settings.get('children')
if child_query:
- return [''.join(element.xpath(child_query)).strip() for element in result]
- elif isinstance(result, list):
- return result
- return result.strip()
+ return [self.maybe_strip(''.join(element.xpath(child_query))) for element in result]
+ return result
return self.parse(settings)
def parse(self, query):
- return self.parsed_content.xpath(query)
+ return self.maybe_strip(self.parsed_content.xpath(query))
class XMLInterface(XPathInterface):
@@ -209,7 +213,7 @@ class DictInterface(BaseInterface):
return self.empty_result
else:
return target
- return target
+ return self.maybe_strip(target)
def execute_method(self, settings):
if isinstance(settings, dict):
@@ -266,7 +270,7 @@ class AJAXInterface(JSONInterface):
def get_inner_interface(self, text, json_part):
if json_part not in self._inner_cache:
inner_content = super(AJAXInterface, self).get_from_dict(text, json_part)
- self._inner_cache[json_part] = self.inner_interface_class(inner_content)
+ self._inner_cache[json_part] = self.inner_interface_class(inner_content, self.strip)
return self._inner_cache[json_part]
def get_from_dict(self, target, query):
@@ -292,14 +296,14 @@ class RegExpInterface(BaseInterface):
So, response will be like 'ok' or 'Error 100'.
"""
- def __init__(self, content, flags=0):
+ def __init__(self, content, strip=False, flags=0):
self.flags = flags
- super(RegExpInterface, self).__init__(content)
+ super(RegExpInterface, self).__init__(content, strip)
def execute_method(self, settings):
matches = re.findall(settings, self.content, self.flags)
if matches:
- return matches[0]
+ return self.maybe_strip(matches[0])
return self.empty_result
def parse(self, query):
diff --git a/pyanyapi/parsers.py b/pyanyapi/parsers.py
index 05fceef..25c009f 100644
--- a/pyanyapi/parsers.py
+++ b/pyanyapi/parsers.py
@@ -23,7 +23,8 @@ class BaseParser(object):
"""
interface_class = None
- def __init__(self, settings=None):
+ def __init__(self, settings=None, strip=False):
+ self.strip = strip
parents_settings = self.get_parents_settings()
if settings:
parents_settings.update(settings)
@@ -68,7 +69,7 @@ class BaseParser(object):
return self.parse(content).parse_all()
def get_interface_kwargs(self):
- return {'content': self.content}
+ return {'content': self.content, 'strip': self.strip}
def prepare_content(self, content):
"""
@@ -165,9 +166,9 @@ class AJAXParser(LXMLParser):
class RegExpParser(BaseParser):
interface_class = RegExpInterface
- def __init__(self, settings=None, flags=0):
+ def __init__(self, settings=None, strip=False, flags=0):
self.flags = flags
- super(RegExpParser, self).__init__(settings)
+ super(RegExpParser, self).__init__(settings, strip)
def get_interface_kwargs(self):
kwargs = super(RegExpParser, self).get_interface_kwargs()
| Add option to strip results
At parser level, False by default | Stranger6667/pyanyapi | diff --git a/tests/test_parsers.py b/tests/test_parsers.py
index 25e54b3..85f4471 100644
--- a/tests/test_parsers.py
+++ b/tests/test_parsers.py
@@ -179,7 +179,7 @@ def test_complex_config():
parsed = XMLParser({'test': {'base': '//test', 'children': 'text()|*//text()'}}).parse(
'<xml><test>123 </test><test><inside> 234</inside></test></xml>'
)
- assert parsed.test == ['123', '234']
+ assert parsed.test == ['123 ', ' 234']
def test_json_parse():
diff --git a/tests/test_strip.py b/tests/test_strip.py
new file mode 100644
index 0000000..d649312
--- /dev/null
+++ b/tests/test_strip.py
@@ -0,0 +1,34 @@
+# coding: utf-8
+from .conftest import lxml_is_supported
+from pyanyapi import RegExpParser, JSONParser, AJAXParser, XMLParser
+
+
+JSON_CONTENT = '{"container":" 1 "}'
+AJAX_CONTENT = '{"content": "<p> Pcontent </p>"}'
+XML_CONTENT = '<p> Pcontent </p>'
+
+
+def test_strip_regexp_parser():
+ settings = {'all': '.+'}
+ assert RegExpParser(settings).parse(' 1 ').all == ' 1 '
+ assert RegExpParser(settings, strip=True).parse(' 1 ').all == '1'
+
+
+def test_strip_json_parser():
+ settings = {'all': 'container'}
+ assert JSONParser(settings).parse(JSON_CONTENT).all == ' 1 '
+ assert JSONParser(settings, strip=True).parse(JSON_CONTENT).all == '1'
+
+
+@lxml_is_supported
+def test_strip_ajax_parser():
+ settings = {'all': 'content > string(//p)'}
+ assert AJAXParser(settings).parse(AJAX_CONTENT).all == ' Pcontent '
+ assert AJAXParser(settings, strip=True).parse(AJAX_CONTENT).all == 'Pcontent'
+
+
+@lxml_is_supported
+def test_strip_xml_parser():
+ settings = {'all': 'string(//p)'}
+ assert XMLParser(settings).parse(XML_CONTENT).all == ' Pcontent '
+ assert XMLParser(settings, strip=True).parse(XML_CONTENT).all == 'Pcontent'
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 2,
"issue_text_score": 2,
"test_score": 0
},
"num_modified_files": 4
} | 0.4 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest",
"pytest-cov"
],
"pre_install": null,
"python": "3.5",
"reqs_path": [
"requirements.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | attrs==22.2.0
certifi==2021.5.30
coverage==6.2
importlib-metadata==4.8.3
iniconfig==1.1.1
lxml==5.3.1
packaging==21.3
pluggy==1.0.0
py==1.11.0
-e git+https://github.com/Stranger6667/pyanyapi.git@e5b7aadff6d02eac82e27cb4ad1f8bc9a4fb2eb0#egg=pyanyapi
pyparsing==3.1.4
pytest==7.0.1
pytest-cov==4.0.0
PyYAML==3.11
tomli==1.2.3
typing_extensions==4.1.1
ujson==4.3.0
zipp==3.6.0
| name: pyanyapi
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2021.5.30=py36h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.3=he6710b0_2
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- pip=21.2.2=py36h06a4308_0
- python=3.6.13=h12debd9_1
- readline=8.2=h5eee18b_0
- setuptools=58.0.4=py36h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- wheel=0.37.1=pyhd3eb1b0_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- attrs==22.2.0
- coverage==6.2
- importlib-metadata==4.8.3
- iniconfig==1.1.1
- lxml==5.3.1
- packaging==21.3
- pluggy==1.0.0
- py==1.11.0
- pyparsing==3.1.4
- pytest==7.0.1
- pytest-cov==4.0.0
- pyyaml==3.11
- tomli==1.2.3
- typing-extensions==4.1.1
- ujson==4.3.0
- zipp==3.6.0
prefix: /opt/conda/envs/pyanyapi
| [
"tests/test_parsers.py::test_complex_config",
"tests/test_strip.py::test_strip_regexp_parser",
"tests/test_strip.py::test_strip_json_parser",
"tests/test_strip.py::test_strip_ajax_parser",
"tests/test_strip.py::test_strip_xml_parser"
] | [] | [
"tests/test_parsers.py::test_xml_objectify_parser",
"tests/test_parsers.py::test_xml_objectify_parser_error",
"tests/test_parsers.py::test_xml_parser_error",
"tests/test_parsers.py::test_yaml_parser_error",
"tests/test_parsers.py::test_xml_parsed[settings0]",
"tests/test_parsers.py::test_xml_parsed[settings1]",
"tests/test_parsers.py::test_xml_simple_settings",
"tests/test_parsers.py::test_json_parsed",
"tests/test_parsers.py::test_multiple_parser_join",
"tests/test_parsers.py::test_multiply_parsers_declaration",
"tests/test_parsers.py::test_empty_values[{\"container\":{\"test\":\"value\"}}-test-value]",
"tests/test_parsers.py::test_empty_values[{\"container\":{\"test\":\"value\"}}-second-None]",
"tests/test_parsers.py::test_empty_values[{\"container\":{\"fail\":[1]}}-second-None]",
"tests/test_parsers.py::test_empty_values[{\"container\":[[1],[],[3]]}-third-expected3]",
"tests/test_parsers.py::test_empty_values[{\"container\":null}-null-None]",
"tests/test_parsers.py::test_empty_values[{\"container\":[1,2]}-test-1,2]",
"tests/test_parsers.py::test_attributes",
"tests/test_parsers.py::test_efficient_parsing",
"tests/test_parsers.py::test_simple_config_xml_parser",
"tests/test_parsers.py::test_simple_config_json_parser",
"tests/test_parsers.py::test_settings_inheritance",
"tests/test_parsers.py::test_json_parse",
"tests/test_parsers.py::test_json_value_error_parse",
"tests/test_parsers.py::test_regexp_parse",
"tests/test_parsers.py::test_yaml_parse",
"tests/test_parsers.py::test_ajax_parser",
"tests/test_parsers.py::test_ajax_parser_cache",
"tests/test_parsers.py::test_ajax_parser_invalid_settings",
"tests/test_parsers.py::test_parse_memoization",
"tests/test_parsers.py::test_regexp_settings",
"tests/test_parsers.py::test_parse_all",
"tests/test_parsers.py::test_parse_all_combined_parser"
] | [] | MIT License | 258 |
|
pypa__twine-138 | 5c06ed2049b633fe7f0b0e27df32d2715614ab3a | 2015-10-01 16:31:50 | f487b7da9c42e4932bc33bf10d70cdc59fd16fd5 | diff --git a/twine/repository.py b/twine/repository.py
index dc473aa..ae57821 100644
--- a/twine/repository.py
+++ b/twine/repository.py
@@ -17,6 +17,9 @@ import requests
from requests_toolbelt.multipart import MultipartEncoder
+KEYWORDS_TO_NOT_FLATTEN = set(["gpg_signature", "content"])
+
+
class Repository(object):
def __init__(self, repository_url, username, password):
self.url = repository_url
@@ -30,11 +33,12 @@ class Repository(object):
def _convert_data_to_list_of_tuples(data):
data_to_send = []
for key, value in data.items():
- if isinstance(value, (list, tuple)):
+ if (key in KEYWORDS_TO_NOT_FLATTEN or
+ not isinstance(value, (list, tuple))):
+ data_to_send.append((key, value))
+ else:
for item in value:
data_to_send.append((key, item))
- else:
- data_to_send.append((key, value))
return data_to_send
def register(self, package):
| Bug in uploading signatures (again)
This time the bug originates from https://github.com/a-tal/twine/commit/13c83237246fe00c67b2e4ce72e8a935f89f9ee0 and the refactor.
Because that flattens all values that are sequences, it happens to flatten the `gpg_signature` field. That causes two parts to be for the `gpg_signature` which in turn translates to a list when parsed by PyPI and causes a 500 because PyPI tries to call a string operation on a list. | pypa/twine | diff --git a/tests/test_repository.py b/tests/test_repository.py
new file mode 100644
index 0000000..3b8d84b
--- /dev/null
+++ b/tests/test_repository.py
@@ -0,0 +1,49 @@
+# Copyright 2015 Ian Cordasco
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from twine import repository
+
+
+def test_gpg_signature_structure_is_preserved():
+ data = {
+ 'gpg_signature': ('filename.asc', 'filecontent'),
+ }
+
+ tuples = repository.Repository._convert_data_to_list_of_tuples(data)
+ assert tuples == [('gpg_signature', ('filename.asc', 'filecontent'))]
+
+
+def test_content_structure_is_preserved():
+ data = {
+ 'content': ('filename', 'filecontent'),
+ }
+
+ tuples = repository.Repository._convert_data_to_list_of_tuples(data)
+ assert tuples == [('content', ('filename', 'filecontent'))]
+
+
+def test_iterables_are_flattened():
+ data = {
+ 'platform': ['UNKNOWN'],
+ }
+
+ tuples = repository.Repository._convert_data_to_list_of_tuples(data)
+ assert tuples == [('platform', 'UNKNOWN')]
+
+ data = {
+ 'platform': ['UNKNOWN', 'ANOTHERPLATFORM'],
+ }
+
+ tuples = repository.Repository._convert_data_to_list_of_tuples(data)
+ assert tuples == [('platform', 'UNKNOWN'),
+ ('platform', 'ANOTHERPLATFORM')]
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_hyperlinks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 0,
"issue_text_score": 2,
"test_score": 0
},
"num_modified_files": 1
} | 1.6 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "pytest",
"pip_packages": [
"pytest",
"pytest-cov",
"pytest-xdist",
"pytest-mock",
"pytest-asyncio"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.9",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | certifi==2025.1.31
charset-normalizer==3.4.1
coverage==7.8.0
exceptiongroup @ file:///croot/exceptiongroup_1706031385326/work
execnet==2.1.1
idna==3.10
iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work
packaging @ file:///croot/packaging_1734472117206/work
pkginfo==1.12.1.2
pluggy @ file:///croot/pluggy_1733169602837/work
pytest @ file:///croot/pytest_1738938843180/work
pytest-asyncio==0.26.0
pytest-cov==6.0.0
pytest-mock==3.14.0
pytest-xdist==3.6.1
requests==2.32.3
requests-toolbelt==1.0.0
tomli @ file:///opt/conda/conda-bld/tomli_1657175507142/work
-e git+https://github.com/pypa/twine.git@5c06ed2049b633fe7f0b0e27df32d2715614ab3a#egg=twine
typing_extensions==4.13.0
urllib3==2.3.0
| name: twine
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- exceptiongroup=1.2.0=py39h06a4308_0
- iniconfig=1.1.1=pyhd3eb1b0_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=3.0.16=h5eee18b_0
- packaging=24.2=py39h06a4308_0
- pip=25.0=py39h06a4308_0
- pluggy=1.5.0=py39h06a4308_0
- pytest=8.3.4=py39h06a4308_0
- python=3.9.21=he870216_1
- readline=8.2=h5eee18b_0
- setuptools=75.8.0=py39h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- tomli=2.0.1=py39h06a4308_0
- tzdata=2025a=h04d1e81_0
- wheel=0.45.1=py39h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- certifi==2025.1.31
- charset-normalizer==3.4.1
- coverage==7.8.0
- execnet==2.1.1
- idna==3.10
- pkginfo==1.12.1.2
- pytest-asyncio==0.26.0
- pytest-cov==6.0.0
- pytest-mock==3.14.0
- pytest-xdist==3.6.1
- requests==2.32.3
- requests-toolbelt==1.0.0
- typing-extensions==4.13.0
- urllib3==2.3.0
prefix: /opt/conda/envs/twine
| [
"tests/test_repository.py::test_gpg_signature_structure_is_preserved",
"tests/test_repository.py::test_content_structure_is_preserved"
] | [] | [
"tests/test_repository.py::test_iterables_are_flattened"
] | [] | Apache License 2.0 | 259 |
|
sympy__sympy-9951 | 0067acad3f6d438461100d4f96ec3dd227c1331c | 2015-10-02 20:08:37 | 0241b35cae5f2adc04dc37b25f7dc9c5f00bd746 | leosartaj: This doesn't work ``is_increasing(1, x)``. Similarly for the others. This can be fixed by adding a ``sympify`` call.
leosartaj: The ``symbol`` argument can be made a ``kwarg``. So that it is not necessary to write symbol for univariate functions.
This should work
```
>>> is_increasing(x)
True
```
leosartaj: Some examples for multivariate functions can be added in the docstrings.
gxyd: @leosartaj thank you very much for all the points you made. I was though waiting for @aktech to get on to verify. But now you have seen that's really nice.
gxyd: @leosartaj @aktech i think this is ready for review.
leosartaj: Please do not update the PR, when someone is reviewing. It gets confusing. :smile:
gxyd: I have updated the error message. And addressed other comments.
leosartaj: You can use tools like flake8 to catch issues with indentation and such.
leosartaj: This looks good, +1 to merge if tests pass. | diff --git a/doc/src/modules/polys/index.rst b/doc/src/modules/polys/index.rst
index d7249b538d..be212828af 100644
--- a/doc/src/modules/polys/index.rst
+++ b/doc/src/modules/polys/index.rst
@@ -25,5 +25,4 @@ Contents
reference.rst
agca.rst
internals.rst
- ringseries.rst
literature.rst
diff --git a/doc/src/modules/polys/internals.rst b/doc/src/modules/polys/internals.rst
index 46c53d7532..b4a2f2ca7f 100644
--- a/doc/src/modules/polys/internals.rst
+++ b/doc/src/modules/polys/internals.rst
@@ -751,6 +751,29 @@ Modular GCD
.. autofunction:: modgcd_multivariate
.. autofunction:: func_field_modgcd
+Manipulation of power series
+****************************************************************************
+.. currentmodule:: sympy.polys.ring_series
+
+Functions in this module carry the prefix ``rs_``, standing for "ring series".
+They manipulate finite power series in the sparse representation provided
+by ``polys.ring.ring``.
+
+
+.. autofunction:: rs_trunc
+.. autofunction:: rs_mul
+.. autofunction:: rs_square
+.. autofunction:: rs_pow
+.. autofunction:: rs_series_inversion
+.. autofunction:: rs_series_from_list
+.. autofunction:: rs_integrate
+.. autofunction:: rs_log
+.. autofunction:: rs_exp
+.. autofunction:: rs_newton
+.. autofunction:: rs_hadamard_exp
+.. autofunction:: rs_compose_add
+
+
Undocumented
============
diff --git a/doc/src/modules/polys/ringseries.rst b/doc/src/modules/polys/ringseries.rst
deleted file mode 100644
index 4a810a2687..0000000000
--- a/doc/src/modules/polys/ringseries.rst
+++ /dev/null
@@ -1,215 +0,0 @@
-.. _polys-ringseries:
-
-=====================================
-Series Manipulation using Polynomials
-=====================================
-
-Any finite Taylor series, for all practical purposes is, in fact a polynomial.
-This module makes use of the efficient representation and operations of sparse
-polynomials for very fast multivariate series manipulations. Typical speedups
-compared to SymPy's ``series`` method are in the range 20-100, with the gap
-widening as the series being handled gets larger.
-
-All the functions expand any given series on some ring specified by the user.
-Thus, the coefficients of the calculated series depend on the ring being used.
-For example::
-
- >>> from sympy.polys import ring, QQ, RR
- >>> from sympy.polys.ring_series import rs_sin
- >>> R, x, y = ring('x, y', QQ)
- >>> rs_sin(x*y, x, 5)
- -1/6*x**3*y**3 + x*y
-
-``QQ`` stands for the Rational domain. Here all coefficients are rationals. It
-is recommended to use ``QQ`` with ring series as it automatically chooses the
-fastest Rational type.
-
-Similarly, if a Real domain is used::
-
- >>> R, x, y = ring('x, y', RR)
- >>> rs_sin(x*y, x, 5)
- -0.166666666666667*x**3*y**3 + x*y
-
-Though the definition of a polynomial limits the use of Polynomial module to
-Taylor series, we extend it to allow Laurent and even Puiseux series (with
-fractional exponents)::
-
- >>> from sympy.polys.ring_series import rs_cos, rs_tan
- >>> R, x, y = ring('x, y', QQ)
-
- >>> rs_cos(x + x*y, x, 3)/x**3
- -1/2*x**(-1)*y**2 - x**(-1)*y - 1/2*x**(-1) + x**(-3)
-
- >>> rs_tan(x**QQ(2, 5)*y**QQ(1, 2), x, 2)
- 1/3*x**(6/5)*y**(3/2) + x**(2/5)*y**(1/2)
-
-By default, ``PolyElement`` did not allow non-natural numbers as exponents. It
-converted a fraction to an integer and raised an error on getting negative
-exponents. The goal of the ``ring series`` module is fast series expansion, and
-not to use the ``polys`` module. The reason we use it as our backend is simply
-because it implements a sparse representation and most of the basic functions
-that we need. However, this default behaviour of ``polys`` was limiting for
-``ring series``.
-
-Note that there is no such constraint (in having rational exponents) in the
-data-structure used by ``polys``- ``dict``. Sparse polynomials
-(``PolyElement``) use the Python dict to store a polynomial term by term, where
-a tuple of exponents is the key and the coefficient of that term is the value.
-There is no reason why we can't have rational values in the ``dict`` so as to
-support rational exponents.
-
-So the approach we took was to modify sparse ``polys`` to allow non-natural
-exponents. And it turned out to be quite simple. We only had to delete the
-conversion to ``int`` of exponents in the ``__pow__`` method of
-``PolyElement``. So::
-
- >>> x**QQ(3, 4)
- x**(3/4)
-
-and not ``1`` as was the case earlier.
-
-Though this change violates the definition of a polynomial, it doesn't break
-anything yet. Ideally, we shouldn't modify ``polys`` in any way. But to have
-all the ``series`` capabilities we want, no other simple way was found. If need
-be, we can separate the modified part of ``polys`` from core ``polys``. It
-would be great if any other elegant solution is found.
-
-All series returned by the functions of this module are instances of the
-``PolyElement`` class. To use them with other SymPy types, convert them to
-``Expr``::
-
- >>> from sympy.polys.ring_series import rs_exp
- >>> from sympy.abc import a, b, c
- >>> series = rs_exp(x, x, 5)
- >>> a + series.as_expr()
- a + x**4/24 + x**3/6 + x**2/2 + x + 1
-
-rs_series
-=========
-
-Direct use of elementary ring series functions does give more control, but is
-limiting at the same time. Creating an appropriate ring for the desired series
-expansion and knowing which ring series function to call, are things not
-everyone might be familiar with.
-
-`rs\_series` is a function that takes an arbitrary ``Expr`` and returns its
-expansion by calling the appropriate ring series functions. The returned series
-is a polynomial over the simplest (almost) possible ring that does the job. It
-recursively builds the ring as it parses the given expression, adding
-generators to the ring when it needs them. Some examples::
-
- >>> rs_series(sin(a + b), a, 5) # doctest: +SKIP
- 1/24*sin(b)*a**4 - 1/2*sin(b)*a**2 + sin(b) - 1/6*cos(b)*a**3 + cos(b)*a
-
- >>> rs_series(sin(exp(a*b) + cos(a + c)), a, 2) # doctest: +SKIP
- -sin(c)*cos(cos(c) + 1)*a + cos(cos(c) + 1)*a*b + sin(cos(c) + 1)
-
- >>> rs_series(sin(a + b)*cos(a + c)*tan(a**2 + b), a, 2) # doctest: +SKIP
- cos(b)*cos(c)*tan(b)*a - sin(b)*sin(c)*tan(b)*a + sin(b)*cos(c)*tan(b)
-
-It can expand complicated multivariate expressions involving multiple functions
-and most importantly, it does so blazingly fast::
-
- >>> %timeit ((sin(a) + cos(a))**10).series(a, 0, 5) # doctest: +SKIP
- 1 loops, best of 3: 1.33 s per loop
-
- >>> %timeit rs_series((sin(a) + cos(a))**10, a, 5) # doctest: +SKIP
- 100 loops, best of 3: 4.13 ms per loop
-
-`rs\_series` is over 300 times faster. Given an expression to expand, there is
-some fixed overhead to parse it. Thus, for larger orders, the speed
-improvement becomes more prominent::
-
- >>> %timeit rs_series((sin(a) + cos(a))**10, a, 100) # doctest: +SKIP
- 10 loops, best of 3: 32.8 ms per loop
-
-To figure out the right ring for a given expression, `rs\_series` uses the
-``sring`` function, which in turn uses other functions of ``polys``. As
-explained above, non-natural exponents are not allowed. But the restriction is
-on exponents and not generators. So, ``polys`` allows all sorts of symbolic
-terms as generators to make sure that the exponent is a natural number::
-
- >>> from sympy.polys.rings import sring
- >>> R, expr = sring(1/a**3 + a**QQ(3, 7)); R
- Polynomial ring in 1/a, a**(1/7) over ZZ with lex order
-
-In the above example, `1/a` and `a**(1/7)` will be treated as completely
-different atoms. For all practical purposes, we could let `b = 1/a` and `c =
-a**(1/7)` and do the manipulations. Effectively, expressions involving `1/a`
-and `a**(1/7)` (and their powers) will never simplify::
-
- >>> expr*R(1/a) # doctest: +SKIP
- (1/a)**2 + (1/a)*(a**(1/7))**3
-
-This leads to similar issues with manipulating Laurent and Puiseux series as
-faced earlier. Fortunately, this time we have an elegant solution and are able
-to isolate the ``series`` and ``polys`` behaviour from one another. We
-introduce a boolean flag ``series`` in the list of allowed ``Options`` for
-polynomials (see :class:`sympy.polys.polyoptions.Options`). Thus, when we want
-``sring`` to allow rational exponents we supply a ``series=True`` flag to
-``sring``.
-
-Contribute
-==========
-
-`rs\_series` is not fully implemented yet. As of now, it supports only
-multivariate Taylor expansions of expressions involving ``sin``, ``cos``,
-``exp`` and ``tan``. Adding the remaining functions is not at all difficult and
-they will be gradually added. If you are interested in helping, read the
-comments in ``ring_series.py``. Currently, it does not support Puiseux series
-(though the elementary functions do). This is expected to be fixed soon.
-
-You can also add more functions to ``ring_series.py``. Only elementary
-functions are supported currently. The long term goal is to replace SymPy's
-current ``series`` method with ``rs_series``.
-
-Manipulation of power series
-****************************************************************************
-.. currentmodule:: sympy.polys.ring_series
-
-Functions in this module carry the prefix ``rs_``, standing for "ring series".
-They manipulate finite power series in the sparse representation provided
-by ``polys.ring.ring``.
-
-**Elementary functions**
-
-.. autofunction:: rs_log
-.. autofunction:: rs_LambertW
-.. autofunction:: rs_exp
-.. autofunction:: rs_atan
-.. autofunction:: rs_asin
-.. autofunction:: rs_tan
-.. autofunction:: rs_cot
-.. autofunction:: rs_sin
-.. autofunction:: rs_cos
-.. autofunction:: rs_cos_sin
-.. autofunction:: rs_atanh
-.. autofunction:: rs_sinh
-.. autofunction:: rs_cosh
-.. autofunction:: rs_tanh
-.. autofunction:: rs_hadamard_exp
-
-**Operations**
-
-.. autofunction:: rs_mul
-.. autofunction:: rs_square
-.. autofunction:: rs_pow
-.. autofunction:: rs_series_inversion
-.. autofunction:: rs_series_reversion
-.. autofunction:: rs_nth_root
-.. autofunction:: rs_trunc
-.. autofunction:: rs_subs
-.. autofunction:: rs_diff
-.. autofunction:: rs_integrate
-.. autofunction:: rs_newton
-.. autofunction:: rs_compose_add
-
-**Utility functions**
-
-.. autofunction:: rs_is_puiseux
-.. autofunction:: rs_puiseux
-.. autofunction:: rs_puiseux2
-.. autofunction:: rs_series_from_list
-.. autofunction:: rs_fun
-.. autofunction:: mul_xin
-.. autofunction:: pow_xin
diff --git a/sympy/calculus/singularities.py b/sympy/calculus/singularities.py
index 5ae0d11aee..b1ac1031dc 100644
--- a/sympy/calculus/singularities.py
+++ b/sympy/calculus/singularities.py
@@ -1,3 +1,4 @@
+from sympy.core.sympify import sympify
from sympy.solvers.solveset import solveset
from sympy.simplify import simplify
from sympy import S
@@ -38,7 +39,7 @@ def singularities(expr, sym):
###########################################################################
-def is_increasing(f, interval=S.Reals):
+def is_increasing(f, interval=S.Reals, symbol=None):
"""
Returns if a function is increasing or not, in the given
``Interval``.
@@ -47,7 +48,7 @@ def is_increasing(f, interval=S.Reals):
========
>>> from sympy import is_increasing
- >>> from sympy.abc import x
+ >>> from sympy.abc import x, y
>>> from sympy import S, Interval, oo
>>> is_increasing(x**3 - 3*x**2 + 4*x, S.Reals)
True
@@ -57,18 +58,27 @@ def is_increasing(f, interval=S.Reals):
False
>>> is_increasing(4*x**3 - 6*x**2 - 72*x + 30, Interval(-2, 3))
False
+ >>> is_increasing(x**2 + y, Interval(1, 2), x)
+ True
"""
- if len(f.free_symbols) > 1:
- raise NotImplementedError('is_increasing has not yet been implemented '
- 'for multivariate expressions')
- symbol = f.free_symbols.pop()
+ f = sympify(f)
+ free_sym = f.free_symbols
+
+ if symbol is None:
+ if len(free_sym) > 1:
+ raise NotImplementedError('is_increasing has not yet been implemented '
+ 'for all multivariate expressions')
+ if len(free_sym) == 0:
+ return True
+ symbol = free_sym.pop()
+
df = f.diff(symbol)
df_nonneg_interval = solveset(df >= 0, symbol, domain=S.Reals)
return interval.is_subset(df_nonneg_interval)
-def is_strictly_increasing(f, interval=S.Reals):
+def is_strictly_increasing(f, interval=S.Reals, symbol=None):
"""
Returns if a function is strictly increasing or not, in the given
``Interval``.
@@ -77,7 +87,7 @@ def is_strictly_increasing(f, interval=S.Reals):
========
>>> from sympy import is_strictly_increasing
- >>> from sympy.abc import x
+ >>> from sympy.abc import x, y
>>> from sympy import Interval, oo
>>> is_strictly_increasing(4*x**3 - 6*x**2 - 72*x + 30, Interval.Ropen(-oo, -2))
True
@@ -87,18 +97,27 @@ def is_strictly_increasing(f, interval=S.Reals):
False
>>> is_strictly_increasing(-x**2, Interval(0, oo))
False
+ >>> is_strictly_increasing(-x**2 + y, Interval(-oo, 0), x)
+ False
"""
- if len(f.free_symbols) > 1:
- raise NotImplementedError('is_strictly_increasing has not yet been '
- 'implemented for multivariate expressions')
- symbol = f.free_symbols.pop()
+ f = sympify(f)
+ free_sym = f.free_symbols
+
+ if symbol is None:
+ if len(free_sym) > 1:
+ raise NotImplementedError('is_strictly_increasing has not yet been implemented '
+ 'for all multivariate expressions')
+ elif len(free_sym) == 0:
+ return False
+ symbol = free_sym.pop()
+
df = f.diff(symbol)
df_pos_interval = solveset(df > 0, symbol, domain=S.Reals)
return interval.is_subset(df_pos_interval)
-def is_decreasing(f, interval=S.Reals):
+def is_decreasing(f, interval=S.Reals, symbol=None):
"""
Returns if a function is decreasing or not, in the given
``Interval``.
@@ -107,7 +126,7 @@ def is_decreasing(f, interval=S.Reals):
========
>>> from sympy import is_decreasing
- >>> from sympy.abc import x
+ >>> from sympy.abc import x, y
>>> from sympy import S, Interval, oo
>>> is_decreasing(1/(x**2 - 3*x), Interval.open(1.5, 3))
True
@@ -117,48 +136,66 @@ def is_decreasing(f, interval=S.Reals):
False
>>> is_decreasing(-x**2, Interval(-oo, 0))
False
+ >>> is_decreasing(-x**2 + y, Interval(-oo, 0), x)
+ False
"""
- if len(f.free_symbols) > 1:
- raise NotImplementedError('is_decreasing has not yet been implemented '
- 'for multivariate expressions')
- symbol = f.free_symbols.pop()
+ f = sympify(f)
+ free_sym = f.free_symbols
+
+ if symbol is None:
+ if len(free_sym) > 1:
+ raise NotImplementedError('is_decreasing has not yet been implemented '
+ 'for all multivariate expressions')
+ elif len(free_sym) == 0:
+ return True
+ symbol = free_sym.pop()
+
df = f.diff(symbol)
df_nonpos_interval = solveset(df <= 0, symbol, domain=S.Reals)
return interval.is_subset(df_nonpos_interval)
-def is_strictly_decreasing(f, interval=S.Reals):
+def is_strictly_decreasing(f, interval=S.Reals, symbol=None):
"""
- Returns if a function is decreasing or not, in the given
+ Returns if a function is strictly decreasing or not, in the given
``Interval``.
Examples
========
- >>> from sympy import is_decreasing
- >>> from sympy.abc import x
+ >>> from sympy import is_strictly_decreasing
+ >>> from sympy.abc import x, y
>>> from sympy import S, Interval, oo
- >>> is_decreasing(1/(x**2 - 3*x), Interval.open(1.5, 3))
+ >>> is_strictly_decreasing(1/(x**2 - 3*x), Interval.open(1.5, 3))
True
- >>> is_decreasing(1/(x**2 - 3*x), Interval.Lopen(3, oo))
+ >>> is_strictly_decreasing(1/(x**2 - 3*x), Interval.Lopen(3, oo))
True
- >>> is_decreasing(1/(x**2 - 3*x), Interval.Ropen(-oo, S(3)/2))
+ >>> is_strictly_decreasing(1/(x**2 - 3*x), Interval.Ropen(-oo, S(3)/2))
False
- >>> is_decreasing(-x**2, Interval(-oo, 0))
+ >>> is_strictly_decreasing(-x**2, Interval(-oo, 0))
+ False
+ >>> is_strictly_decreasing(-x**2 + y, Interval(-oo, 0), x)
False
"""
- if len(f.free_symbols) > 1:
- raise NotImplementedError('is_strictly_decreasing has not yet been '
- 'implemented for multivariate expressions')
- symbol = f.free_symbols.pop()
+ f = sympify(f)
+ free_sym = f.free_symbols
+
+ if symbol is None:
+ if len(free_sym) > 1:
+ raise NotImplementedError('is_strictly_decreasing has not yet been implemented '
+ 'for all multivariate expressions')
+ elif len(free_sym) == 0:
+ return False
+ symbol = free_sym.pop()
+
df = f.diff(symbol)
df_neg_interval = solveset(df < 0, symbol, domain=S.Reals)
return interval.is_subset(df_neg_interval)
-def is_monotonic(f, interval=S.Reals):
+def is_monotonic(f, interval=S.Reals, symbol=None):
"""
Returns if a function is monotonic or not, in the given
``Interval``.
@@ -167,7 +204,7 @@ def is_monotonic(f, interval=S.Reals):
========
>>> from sympy import is_monotonic
- >>> from sympy.abc import x
+ >>> from sympy.abc import x, y
>>> from sympy import S, Interval, oo
>>> is_monotonic(1/(x**2 - 3*x), Interval.open(1.5, 3))
True
@@ -177,13 +214,19 @@ def is_monotonic(f, interval=S.Reals):
True
>>> is_monotonic(-x**2, S.Reals)
False
+ >>> is_monotonic(x**2 + y + 1, Interval(1, 2), x)
+ True
"""
from sympy.core.logic import fuzzy_or
- if len(f.free_symbols) > 1:
+ f = sympify(f)
+ free_sym = f.free_symbols
+
+ if symbol is None and len(free_sym) > 1:
raise NotImplementedError('is_monotonic has not yet been '
- 'implemented for multivariate expressions')
- inc = is_increasing(f, interval)
- dec = is_decreasing(f, interval)
+ 'for all multivariate expressions')
+
+ inc = is_increasing(f, interval, symbol)
+ dec = is_decreasing(f, interval, symbol)
return fuzzy_or([inc, dec])
diff --git a/sympy/polys/ring_series.py b/sympy/polys/ring_series.py
index 0de3d8f6b8..166a936325 100644
--- a/sympy/polys/ring_series.py
+++ b/sympy/polys/ring_series.py
@@ -1,46 +1,3 @@
-"""Power series evaluation and manipulation using sparse Polynomials
-
-Implementing a new function
----------------------------
-
-There are a few things to be kept in mind when adding a new function here::
-
- - The implementation should work on all possible input domains/rings.
- Special cases include the ``EX`` ring and a constant term in the series
- to be expanded. There can be two types of constant terms in the series:
-
- + A constant value or symbol.
- + A term of a multivariate series not involving the generator, with
- respect to which the series is to expanded.
-
- Strictly speaking, a generator of a ring should not be considered a
- constant. However, for series expansion both the cases need similar
- treatment (as the user doesn't care about inner details), i.e, use an
- addition formula to separate the constant part and the variable part (see
- rs_sin for reference).
-
- - All the algorithms used here are primarily designed to work for Taylor
- series (number of iterations in the algo equals the required order).
- Hence, it becomes tricky to get the series of the right order if a
- Puiseux series is input. Use rs_puiseux? in your function if your
- algorithm is not designed to handle fractional powers.
-
-Extending rs_series
--------------------
-
-To make a function work with rs_series you need to do two things::
-
- - Many sure it works with a constant term (as explained above).
- - If the series contains constant terms, you might need to extend its ring.
- You do so by adding the new terms to the rings as generators.
- ``PolyRing.compose`` and ``PolyRing.add_gens`` are two functions that do
- so and need to be called every time you expand a series containing a
- constant term.
-
-Look at rs_sin and rs_series for further reference.
-
-"""
-
from sympy.polys.domains import QQ, EX
from sympy.polys.rings import PolyElement, ring, sring
from sympy.polys.polyerrors import DomainError
@@ -57,7 +14,7 @@
def _invert_monoms(p1):
"""
- Compute ``x**n * p1(1/x)`` for a univariate polynomial ``p1`` in ``x``.
+ Compute ``x**n * p1(1/x)`` for a univariate polynomial ``p1`` in x.
Examples
========
@@ -122,9 +79,8 @@ def rs_trunc(p1, x, prec):
def rs_is_puiseux(p, x):
"""
- Test if ``p`` is Puiseux series in ``x``.
-
- Raise an exception if it has a negative power in ``x``.
+ Test if `p` is Puiseux series in `x`; raise an exception if it has
+ negative powers in `x`.
Examples
========
@@ -147,9 +103,9 @@ def rs_is_puiseux(p, x):
def rs_puiseux(f, p, x, prec):
"""
- Return the puiseux series for `f(p, x, prec)`.
+ Return the puiseux series for `f(p, x, prec)`
- To be used when function ``f`` is implemented only for regular series.
+ To be used when function`f` is implemented only for regular series
Examples
========
@@ -186,9 +142,9 @@ def rs_puiseux(f, p, x, prec):
def rs_puiseux2(f, p, q, x, prec):
"""
- Return the puiseux series for `f(p, q, x, prec)`.
+ Return the puiseux series for `f(p, q, x, prec)`
- To be used when function ``f`` is implemented only for regular series.
+ To be used when function `f` is implemented only for regular series
"""
index = p.ring.gens.index(x)
n = 1
@@ -211,7 +167,7 @@ def rs_puiseux2(f, p, q, x, prec):
def rs_mul(p1, p2, x, prec):
"""
- Return the product of the given two series, modulo ``O(x**prec)``.
+ Return the product of the given two series, modulo ``O(x**prec)``
``x`` is the series variable or its position in the generators.
@@ -357,9 +313,13 @@ def rs_pow(p1, n, x, prec):
def rs_subs(p, rules, x, prec):
"""
- Substitution with truncation according to the mapping in ``rules``.
+ Substitution with truncation according to the mapping in `rules`.
+ Returns a series with precision `prec` in the generator `x`
- Return a series with precision ``prec`` in the generator ``x``
+ p: input polynomial
+ rules: dict with substitution mappings
+ x: variable in which the series truncation is done
+ prec: order of the truncation
Note that substitutions are not done one after the other
@@ -378,13 +338,6 @@ def rs_subs(p, rules, x, prec):
>>> rs_subs(rs_subs(p, {x: x+ y}, x, 3), {y: x+ 2*y}, x, 3)
5*x**2 + 12*x*y + 8*y**2
- Parameters
- ----------
- p : :class:`PolyElement` Input series.
- rules : :class:`dict` with substitution mappings.
- x : :class:`PolyElement` in which the series truncation is to be done.
- prec : :class:`Integer` order of the series after truncation.
-
Examples
========
@@ -479,7 +432,7 @@ def _check_series_var(p, x, name):
def _series_inversion1(p, x, prec):
"""
- Univariate series inversion ``1/p`` modulo ``O(x**prec)``.
+ Univariate series inversion ``1/p`` modulo ``O(x**prec)``
The Newton method is used.
@@ -525,7 +478,7 @@ def _series_inversion1(p, x, prec):
def rs_series_inversion(p, x, prec):
"""
- Multivariate series inversion ``1/p`` modulo ``O(x**prec)``.
+ Multivariate series inversion ``1/p`` modulo ``O(x**prec)``
Examples
========
@@ -562,7 +515,7 @@ def rs_series_inversion(p, x, prec):
return r
def _coefficient_t(p, t):
- """Coefficient of `x\_i**j` in p, where ``t`` = (i, j)"""
+ """Coefficient of `x_i**j` in p, where t = (i, j)"""
i, j = t
R = p.ring
expv1 = [0]*R.ngens
@@ -576,35 +529,35 @@ def _coefficient_t(p, t):
def rs_series_reversion(p, x, n, y):
"""
- Reversion of a series.
+ Reversion of a series
- ``p`` is a series with ``O(x**n)`` of the form `p = a*x + f(x)`
- where `a` is a number different from 0.
+ p is a series with O(x**n) of the form p = a*x + f(x)
+ where `a` is a number different from 0
- `f(x) = sum( a\_k*x\_k, k in range(2, n))`
+ f(x) = sum( a_k*x_k, k in range(2, n))
- a_k : Can depend polynomially on other variables, not indicated.
- x : Variable with name x.
- y : Variable with name y.
+ a_k can depend polynomially on other variables, not indicated.
+ x: variable with name x
+ y: variable with name y
- Solve `p = y`, that is, given `a*x + f(x) - y = 0`,
+ Solve p = y, that is, given a*x + f(x) - y = 0,
find the solution x = r(y) up to O(y**n)
Algorithm:
- If `r\_i` is the solution at order i, then:
- `a*r\_i + f(r\_i) - y = O(y**(i + 1))`
+ If r_i is the solution at order i, then:
+ a*r_i + f(r_i) - y = O(y**(i + 1))
and if r_(i + 1) is the solution at order i + 1, then:
- `a*r\_(i + 1) + f(r\_(i + 1)) - y = O(y**(i + 2))`
+ a*r_(i + 1) + f(r_(i + 1)) - y = O(y**(i + 2))
We have, r_(i + 1) = r_i + e, such that,
- `a*e + f(r\_i) = O(y**(i + 2))`
- or `e = -f(r\_i)/a`
+ a*e + f(r_i) = O(y**(i + 2))
+ or e = -f(r_i)/a
So we use the recursion relation:
- `r\_(i + 1) = r\_i - f(r\_i)/a`
- with the boundary condition: `r\_1 = y`
+ r_(i + 1) = r_i -f(r_i)/a
+ with the boundary condition: r_1 = y
Examples
========
@@ -641,13 +594,12 @@ def rs_series_reversion(p, x, n, y):
def rs_series_from_list(p, c, x, prec, concur=1):
"""
- Return a series `sum c[n]*p**n` modulo `O(x**prec)`.
-
- It reduces the number of multiplications by summing concurrently.
+ Return a series ``sum c[n]*p**n`` modulo ``O(x**prec)``
- `ax = [1, p, p**2, .., p**(J - 1)]`
- `s = sum(c[i]*ax[i]` for i in `range(r, (r + 1)*J))*p**((K - 1)*J)`
- with `K >= (n + 1)/J`
+ It reduces the number of multiplications by summing concurrently
+ ``ax = [1, p, p**2, .., p**(J - 1)]``
+ ``s = sum(c[i]*ax[i] for i in range(r, (r + 1)*J)) * p**((K - 1)*J)``
+ with ``K >= (n + 1)/J``
Examples
========
@@ -727,11 +679,9 @@ def rs_series_from_list(p, c, x, prec, concur=1):
def rs_diff(p, x):
"""
- Return partial derivative of ``p`` with respect to ``x``.
+ Computes partial derivative of p with respect to x
- Parameters
- ----------
- x : :class:`PolyElement` with respect to which ``p`` is differentiated.
+ `x`: variable with respect to which p is differentiated,
Examples
========
@@ -758,11 +708,7 @@ def rs_diff(p, x):
def rs_integrate(p, x):
"""
- Integrate ``p`` with respect to ``x``.
-
- Parameters
- ----------
- x : :class:`PolyElement` with respect to which ``p`` is integrated.
+ Integrate ``p`` with respect to ``x``
Examples
========
@@ -789,23 +735,21 @@ def rs_integrate(p, x):
def rs_fun(p, f, *args):
"""
- Function of a multivariate series computed by substitution.
-
- The case with f method name is used to compute `rs\_tan` and `rs\_nth\_root`
- of a multivariate series:
+ Function of a multivariate series computed by substitution
- `rs\_fun(p, tan, iv, prec)`
+ p: multivariate series
+ f: method name or function
+ args[:-2] arguments of f, apart from the first one
+ args[-2] = iv: names of the series variables
+ args[-1] = prec: list of the precisions of the series variables
- tan series is first computed for a dummy variable _x,
- i.e, `rs\_tan(\_x, iv, prec)`. Then we substitute _x with p to get the
- desired series
+ The case with f method name is used to compute rs_tan and rs_nth_root
+ of a multivariate series:
- Parameters
- ----------
- p : :class:`PolyElement` The multivariate series to be expanded.
- f : `ring\_series` function to be applied on `p`.
- args[-2] : :class:`PolyElement` with respect to which, the series is to be expanded.
- args[-1] : Required order of the expanded series.
+ rs_fun(p, tan, iv, prec)
+ tan series is first computed for a dummy variable _x,
+ ie, rs_tan(_x, iv, prec). Then we substitute _x with p to get the
+ desired series
Examples
========
@@ -844,9 +788,9 @@ def rs_fun(p, f, *args):
def mul_xin(p, i, n):
"""
- Return `p*x_i**n`.
+ Computes p*x_i**n
- `x\_i` is the ith variable in ``p``.
+ x_i is the ith variable in p
"""
R = p.ring
q = R(0)
@@ -877,7 +821,13 @@ def pow_xin(p, i, n):
def _nth_root1(p, n, x, prec):
"""
- Univariate series expansion of the nth root of ``p``.
+ Univariate series expansion of the nth root of p
+
+ While passing p, make sure that it is of the form `1 + f(x)`.
+
+ n (integer): compute p**(1/n)
+ x: name of the series variable
+ prec: precision of the series
The Newton method is used.
"""
@@ -912,13 +862,11 @@ def _nth_root1(p, n, x, prec):
def rs_nth_root(p, n, x, prec):
"""
- Multivariate series expansion of the nth root of ``p``.
+ Multivariate series expansion of the nth root of p
- Parameters
- ----------
- n : `p**(1/n)` is returned.
- x : :class:`PolyElement`
- prec : Order of the expanded series.
+ n(integer): compute p**(1/n)
+ x: variable name
+ prec: precision of the series
Notes
=====
@@ -968,14 +916,14 @@ def rs_nth_root(p, n, x, prec):
c_expr = c.as_expr()
const = R(c_expr**(QQ(1, n)))
except ValueError:
- raise DomainError("The given series can't be expanded in "
- "this domain.")
+ raise DomainError("The given series can't be expanded in "
+ "this domain.")
else:
try: # RealElement doesn't support
const = R(c**Rational(1, n)) # exponentiation with mpq object
except ValueError: # as exponent
- raise DomainError("The given series can't be expanded in "
- "this domain.")
+ raise DomainError("The given series can't be expanded in "
+ "this domain.")
res = rs_nth_root(p/c, n, x, prec)*const
else:
res = _nth_root1(p, n, x, prec)
@@ -986,12 +934,12 @@ def rs_nth_root(p, n, x, prec):
def rs_log(p, x, prec):
"""
- The Logarithm of ``p`` modulo ``O(x**prec)``.
+ The Logarithm of ``p`` modulo ``O(x**prec)``
Notes
=====
- Truncation of ``integral dx p**-1*d p/dx`` is used.
+ truncation of ``integral dx p**-1*d p/dx`` is used.
Examples
========
@@ -1025,13 +973,13 @@ def rs_log(p, x, prec):
const = R(log(c_expr))
except ValueError:
raise DomainError("The given series can't be expanded in "
- "this domain.")
+ "this domain.")
else:
try:
const = R(log(c))
except ValueError:
raise DomainError("The given series can't be expanded in "
- "this domain.")
+ "this domain.")
dlog = p.diff(x)
dlog = rs_mul(dlog, _series_inversion1(p, x, prec), x, prec - 1)
@@ -1041,7 +989,7 @@ def rs_log(p, x, prec):
def rs_LambertW(p, x, prec):
"""
- Calculate the series expansion of the principal branch of the Lambert W
+ Calculates the series expansion of the principal branch of the Lambert W
function.
Examples
@@ -1079,7 +1027,7 @@ def rs_LambertW(p, x, prec):
raise NotImplementedError
def _exp1(p, x, prec):
- """Helper function for `rs\_exp`. """
+ """Helper function for ``rs_exp`` """
R = p.ring
p1 = R(1)
for precx in _giant_steps(prec):
@@ -1124,8 +1072,8 @@ def rs_exp(p, x, prec):
try:
const = R(exp(c))
except ValueError:
- raise DomainError("The given series can't be expanded in "
- "this domain.")
+ raise DomainError("The given series can't be expanded in "
+ "this domain.")
p1 = p - c
# Makes use of sympy fuctions to evaluate the values of the cos/sin
@@ -1148,7 +1096,7 @@ def rs_exp(p, x, prec):
def _atan(p, iv, prec):
"""
- Expansion using formula.
+ Expansion using formula
Faster on very small and univariate series.
"""
@@ -1166,7 +1114,7 @@ def rs_atan(p, x, prec):
"""
The arctangent of a series
- Return the series expansion of the atan of ``p``, about 0.
+ Returns the series expansion of the atan of p, about 0.
Examples
========
@@ -1198,14 +1146,14 @@ def rs_atan(p, x, prec):
c_expr = c.as_expr()
const = R(atan(c_expr))
except ValueError:
- raise DomainError("The given series can't be expanded in "
- "this domain.")
+ raise DomainError("The given series can't be expanded in "
+ "this domain.")
else:
try:
const = R(atan(c))
except ValueError:
- raise DomainError("The given series can't be expanded in "
- "this domain.")
+ raise DomainError("The given series can't be expanded in "
+ "this domain.")
# Instead of using a closed form formula, we differentiate atan(p) to get
# `1/(1+p**2) * dp`, whose series expansion is much easier to calculate.
@@ -1220,7 +1168,7 @@ def rs_asin(p, x, prec):
"""
Arcsine of a series
- Return the series expansion of the asin of ``p``, about 0.
+ Returns the series expansion of the asin of p, about 0.
Examples
========
@@ -1263,9 +1211,9 @@ def rs_asin(p, x, prec):
def _tan1(p, x, prec):
"""
- Helper function of `rs\_tan`.
+ Helper function of ``rs_tan``
- Return the series expansion of tan of a univariate series using Newton's
+ Returns the series expansion of tan of a univariate series using Newton's
method. It takes advantage of the fact that series expansion of atan is
easier than that of tan.
@@ -1284,9 +1232,9 @@ def _tan1(p, x, prec):
def rs_tan(p, x, prec):
"""
- Tangent of a series.
+ Tangent of a series
- Return the series expansion of the tan of ``p``, about 0.
+ Returns the series expansion of the tan of p, about 0.
Examples
========
@@ -1301,7 +1249,7 @@ def rs_tan(p, x, prec):
See Also
========
- _tan1, tan
+ tan
"""
if rs_is_puiseux(p, x):
r = rs_puiseux(rs_tan, p, x, prec)
@@ -1327,8 +1275,8 @@ def rs_tan(p, x, prec):
try:
const = R(tan(c))
except ValueError:
- raise DomainError("The given series can't be expanded in "
- "this domain.")
+ raise DomainError("The given series can't be expanded in "
+ "this domain.")
p1 = p - c
# Makes use of sympy fuctions to evaluate the values of the cos/sin
@@ -1346,7 +1294,7 @@ def rs_cot(p, x, prec):
"""
Cotangent of a series
- Return the series expansion of the cot of ``p``, about 0.
+ Returns the series expansion of the cot of p, about 0.
Examples
========
@@ -1382,7 +1330,7 @@ def rs_sin(p, x, prec):
"""
Sine of a series
- Return the series expansion of the sin of ``p``, about 0.
+ Returns the series expansion of the sin of p, about 0.
Examples
========
@@ -1425,8 +1373,8 @@ def rs_sin(p, x, prec):
try:
t1, t2 = R(sin(c)), R(cos(c))
except ValueError:
- raise DomainError("The given series can't be expanded in "
- "this domain.")
+ raise DomainError("The given series can't be expanded in "
+ "this domain.")
p1 = p - c
# Makes use of sympy cos, sin fuctions to evaluate the values of the
@@ -1452,7 +1400,7 @@ def rs_cos(p, x, prec):
"""
Cosine of a series
- Return the series expansion of the cos of ``p``, about 0.
+ Returns the series expansion of the cos of p, about 0.
Examples
========
@@ -1492,8 +1440,8 @@ def rs_cos(p, x, prec):
try:
t1, t2 = R(sin(c)), R(cos(c))
except ValueError:
- raise DomainError("The given series can't be expanded in "
- "this domain.")
+ raise DomainError("The given series can't be expanded in "
+ "this domain.")
p1 = p - c
# Makes use of sympy cos, sin fuctions to evaluate the values of the
@@ -1523,8 +1471,7 @@ def rs_cos(p, x, prec):
def rs_cos_sin(p, x, prec):
"""
- Return the tuple `(rs\_cos(p, x, prec)`, `rs\_sin(p, x, prec))`.
-
+ Returns the tuple (rs_cos(p, x, prec), rs_sin(p, x, prec))
Is faster than calling rs_cos and rs_sin separately
"""
if rs_is_puiseux(p, x):
@@ -1554,7 +1501,7 @@ def rs_atanh(p, x, prec):
"""
Hyperbolic arctangent of a series
- Return the series expansion of the atanh of ``p``, about 0.
+ Returns the series expansion of the atanh of p, about 0.
Examples
========
@@ -1586,14 +1533,14 @@ def rs_atanh(p, x, prec):
c_expr = c.as_expr()
const = R(atanh(c_expr))
except ValueError:
- raise DomainError("The given series can't be expanded in "
- "this domain.")
+ raise DomainError("The given series can't be expanded in "
+ "this domain.")
else:
try:
const = R(atanh(c))
except ValueError:
- raise DomainError("The given series can't be expanded in "
- "this domain.")
+ raise DomainError("The given series can't be expanded in "
+ "this domain.")
# Instead of using a closed form formula, we differentiate atanh(p) to get
# `1/(1-p**2) * dp`, whose series expansion is much easier to calculate.
@@ -1608,7 +1555,7 @@ def rs_sinh(p, x, prec):
"""
Hyperbolic sine of a series
- Return the series expansion of the sinh of ``p``, about 0.
+ Returns the series expansion of the sinh of p, about 0.
Examples
========
@@ -1635,7 +1582,7 @@ def rs_cosh(p, x, prec):
"""
Hyperbolic cosine of a series
- Return the series expansion of the cosh of ``p``, about 0.
+ Returns the series expansion of the cosh of p, about 0.
Examples
========
@@ -1660,9 +1607,9 @@ def rs_cosh(p, x, prec):
def _tanh(p, x, prec):
"""
- Helper function of `rs\_tanh`
+ Helper function of ``rs_tanh``
- Return the series expansion of tanh of a univariate series using Newton's
+ Returns the series expansion of tanh of a univariate series using Newton's
method. It takes advantage of the fact that series expansion of atanh is
easier than that of tanh.
@@ -1683,7 +1630,7 @@ def rs_tanh(p, x, prec):
"""
Hyperbolic tangent of a series
- Return the series expansion of the tanh of ``p``, about 0.
+ Returns the series expansion of the tanh of p, about 0.
Examples
========
@@ -1715,14 +1662,14 @@ def rs_tanh(p, x, prec):
c_expr = c.as_expr()
const = R(tanh(c_expr))
except ValueError:
- raise DomainError("The given series can't be expanded in "
- "this domain.")
+ raise DomainError("The given series can't be expanded in "
+ "this domain.")
else:
try:
const = R(tanh(c))
except ValueError:
- raise DomainError("The given series can't be expanded in "
- "this domain.")
+ raise DomainError("The given series can't be expanded in "
+ "this domain.")
p1 = p - c
t1 = rs_tanh(p1, x, prec)
t = rs_series_inversion(1 + const*t1, x, prec)
@@ -1875,20 +1822,6 @@ def _rs_series(expr, series_rs, a, prec):
raise NotImplementedError
R1, series = sring(arg, domain=QQ, expand=False)
series_inner = _rs_series(arg, series, a, prec)
-
- # Why do we need to compose these three rings?
- #
- # We want to use a simple domain (like ``QQ`` or ``RR``) but they don't
- # support symbolic coefficients. We need a ring that for example lets
- # us have `sin(1)` and `cos(1)` as coefficients if we are expanding
- # `sin(x + 1)`. The ``EX`` domain allows all symbolic coefficients, but
- # that makes it very complex and hence slow.
- #
- # To solve this problem, we add only those symbolic elements as
- # generators to our ring, that we need. Here, series_inner might
- # involve terms like `sin(4)`, `exp(a)`, etc, which are not there in
- # R1 or R. Hence, we compose these three rings to create one that has
- # the generators of all three.
R = R.compose(R1).compose(series_inner.ring)
series_inner = series_inner.set_ring(R)
series = eval(_convert_func[str(expr.func)])(series_inner,
@@ -1941,7 +1874,7 @@ def _rs_series(expr, series_rs, a, prec):
raise NotImplementedError
def rs_series(expr, a, prec):
- """Return the series expansion of an expression about 0.
+ """Return the series expansion of an expression about 0
Parameters
----------
diff --git a/sympy/polys/rings.py b/sympy/polys/rings.py
index cb9df6dfc7..7544bc5d01 100644
--- a/sympy/polys/rings.py
+++ b/sympy/polys/rings.py
@@ -509,7 +509,6 @@ def drop_to_ground(self, *gens):
return self.clone(symbols=symbols, domain=self.drop(*gens))
def compose(self, other):
- """Add the generators of ``other`` to ``self``"""
if self != other:
syms = set(self.symbols).union(set(other.symbols))
return self.clone(symbols=list(syms))
@@ -517,7 +516,6 @@ def compose(self, other):
return self
def add_gens(self, symbols):
- """Add the elements of ``symbols`` as generators to ``self``"""
syms = set(self.symbols).union(set(symbols))
return self.clone(symbols=list(syms))
| is_decreasing(), is_increasing() and strictly functions should have `Symbol` as argument to them
`is_decreasing()`, `is_increasing()`, `is_strictly_increasing()` and `is_strictly_decreasing()` should have `x` or Symbol for as their parameter.
Because of this it will be able to deal expressions like
```
>>> is_decreasing(n + x, n, Interval(1, oo)) # here x is taken as Symbol
True
```
Also we have
```
>>> is_decreasing(1, Interval(1, 2))
AttributeError Traceback (most recent call last)
<ipython-input-37-9dfd81c0bb7d> in <module>()
----> 1 is_decreasing(1, Interval(1, oo))
/home/gxyd/Public/sympy/sympy/calculus/singularities.py in is_decreasing(f, interval)
120
121 """
--> 122 if len(f.free_symbols) > 1:
123 raise NotImplementedError('is_decreasing has not yet been implemented '
124 'for multivariate expressions')
AttributeError: 'int' object has no attribute 'free_symbols'
``` | sympy/sympy | diff --git a/sympy/calculus/tests/test_singularities.py b/sympy/calculus/tests/test_singularities.py
index b4d2056315..65d30d263b 100644
--- a/sympy/calculus/tests/test_singularities.py
+++ b/sympy/calculus/tests/test_singularities.py
@@ -7,8 +7,9 @@
from sympy.utilities.pytest import XFAIL
-x = Symbol('x')
-
+from sympy.abc import x, y
+a = Symbol('a', negative=True)
+b = Symbol('b', positive=True)
def test_singularities():
x = Symbol('x', real=True)
@@ -30,6 +31,9 @@ def test_is_increasing():
assert is_increasing(-x**2, Interval(-oo, 0))
assert is_increasing(-x**2, Interval(0, oo)) is False
assert is_increasing(4*x**3 - 6*x**2 - 72*x + 30, Interval(-2, 3)) is False
+ assert is_increasing(x**2 + y, Interval(1, oo), x) is True
+ assert is_increasing(-x**2*a, Interval(1, oo), x) is True
+ assert is_increasing(1) is True
def test_is_strictly_increasing():
@@ -37,6 +41,7 @@ def test_is_strictly_increasing():
assert is_strictly_increasing(4*x**3 - 6*x**2 - 72*x + 30, Interval.Lopen(3, oo))
assert is_strictly_increasing(4*x**3 - 6*x**2 - 72*x + 30, Interval.open(-2, 3)) is False
assert is_strictly_increasing(-x**2, Interval(0, oo)) is False
+ assert is_strictly_decreasing(1) is False
def test_is_decreasing():
@@ -44,13 +49,15 @@ def test_is_decreasing():
assert is_decreasing(1/(x**2 - 3*x), Interval.Lopen(3, oo))
assert is_decreasing(1/(x**2 - 3*x), Interval.Ropen(-oo, S(3)/2)) is False
assert is_decreasing(-x**2, Interval(-oo, 0)) is False
+ assert is_decreasing(-x**2*b, Interval(-oo, 0), x) is False
def test_is_strictly_decreasing():
- assert is_decreasing(1/(x**2 - 3*x), Interval.open(1.5, 3))
- assert is_decreasing(1/(x**2 - 3*x), Interval.Lopen(3, oo))
- assert is_decreasing(1/(x**2 - 3*x), Interval.Ropen(-oo, S(3)/2)) is False
- assert is_decreasing(-x**2, Interval(-oo, 0)) is False
+ assert is_strictly_decreasing(1/(x**2 - 3*x), Interval.open(1.5, 3))
+ assert is_strictly_decreasing(1/(x**2 - 3*x), Interval.Lopen(3, oo))
+ assert is_strictly_decreasing(1/(x**2 - 3*x), Interval.Ropen(-oo, S(3)/2)) is False
+ assert is_strictly_decreasing(-x**2, Interval(-oo, 0)) is False
+ assert is_strictly_decreasing(1) is False
def test_is_monotonic():
@@ -58,3 +65,4 @@ def test_is_monotonic():
assert is_monotonic(1/(x**2 - 3*x), Interval.Lopen(3, oo))
assert is_monotonic(x**3 - 3*x**2 + 4*x, S.Reals)
assert is_monotonic(-x**2, S.Reals) is False
+ assert is_monotonic(x**2 + y + 1, Interval(1, 2), x) is True
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_removed_files",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 2,
"issue_text_score": 0,
"test_score": 2
},
"num_modified_files": 5
} | 0.7 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "pytest",
"pip_packages": [
"mpmath>=0.19",
"pytest",
"pytest-cov",
"pytest-xdist",
"pytest-mock",
"pytest-asyncio"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.6",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | attrs @ file:///opt/conda/conda-bld/attrs_1642510447205/work
certifi==2021.5.30
coverage==6.2
execnet==1.9.0
importlib-metadata @ file:///tmp/build/80754af9/importlib-metadata_1631916693255/work
iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work
more-itertools @ file:///tmp/build/80754af9/more-itertools_1637733554872/work
mpmath==1.3.0
packaging @ file:///tmp/build/80754af9/packaging_1637314298585/work
pluggy @ file:///tmp/build/80754af9/pluggy_1615976315926/work
py @ file:///opt/conda/conda-bld/py_1644396412707/work
pyparsing @ file:///tmp/build/80754af9/pyparsing_1635766073266/work
pytest==6.2.4
pytest-asyncio==0.16.0
pytest-cov==4.0.0
pytest-mock==3.6.1
pytest-xdist==3.0.2
-e git+https://github.com/sympy/sympy.git@0067acad3f6d438461100d4f96ec3dd227c1331c#egg=sympy
toml @ file:///tmp/build/80754af9/toml_1616166611790/work
tomli==1.2.3
typing_extensions @ file:///opt/conda/conda-bld/typing_extensions_1647553014482/work
zipp @ file:///tmp/build/80754af9/zipp_1633618647012/work
| name: sympy
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- attrs=21.4.0=pyhd3eb1b0_0
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2021.5.30=py36h06a4308_0
- importlib-metadata=4.8.1=py36h06a4308_0
- importlib_metadata=4.8.1=hd3eb1b0_0
- iniconfig=1.1.1=pyhd3eb1b0_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.3=he6710b0_2
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- more-itertools=8.12.0=pyhd3eb1b0_0
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- packaging=21.3=pyhd3eb1b0_0
- pip=21.2.2=py36h06a4308_0
- pluggy=0.13.1=py36h06a4308_0
- py=1.11.0=pyhd3eb1b0_0
- pyparsing=3.0.4=pyhd3eb1b0_0
- pytest=6.2.4=py36h06a4308_2
- python=3.6.13=h12debd9_1
- readline=8.2=h5eee18b_0
- setuptools=58.0.4=py36h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- toml=0.10.2=pyhd3eb1b0_0
- typing_extensions=4.1.1=pyh06a4308_0
- wheel=0.37.1=pyhd3eb1b0_0
- xz=5.6.4=h5eee18b_1
- zipp=3.6.0=pyhd3eb1b0_0
- zlib=1.2.13=h5eee18b_1
- pip:
- coverage==6.2
- execnet==1.9.0
- mpmath==1.3.0
- pytest-asyncio==0.16.0
- pytest-cov==4.0.0
- pytest-mock==3.6.1
- pytest-xdist==3.0.2
- tomli==1.2.3
prefix: /opt/conda/envs/sympy
| [
"sympy/calculus/tests/test_singularities.py::test_is_increasing",
"sympy/calculus/tests/test_singularities.py::test_is_strictly_increasing",
"sympy/calculus/tests/test_singularities.py::test_is_decreasing",
"sympy/calculus/tests/test_singularities.py::test_is_strictly_decreasing",
"sympy/calculus/tests/test_singularities.py::test_is_monotonic"
] | [] | [
"sympy/calculus/tests/test_singularities.py::test_singularities"
] | [] | BSD | 260 |
sympy__sympy-9958 | 886aded45250ae4f3e8158f70a29793f45a9b873 | 2015-10-04 13:35:00 | 0241b35cae5f2adc04dc37b25f7dc9c5f00bd746 | asmeurer: Can we add a direct test for this change as well?
gxyd: > Can we add a direct test for this change as well?
@asmeurer I think no. Since direct test would mean calling `Set._contains(self, other)` which raises `NotImplementedError`. But the corresponding change is tested by the [this test](https://github.com/sympy/sympy/pull/9958/files#diff-e21906560346d439e577d8c1be6b3eceR901) which i have added.
smichr: OK, this time I found this before committing #10036. Which changes do you think are preferred? | diff --git a/sympy/sets/sets.py b/sympy/sets/sets.py
index a447d607cb..424b63febe 100644
--- a/sympy/sets/sets.py
+++ b/sympy/sets/sets.py
@@ -211,7 +211,7 @@ def _complement(self, other):
return S.EmptySet
elif isinstance(other, FiniteSet):
- return FiniteSet(*[el for el in other if self.contains(el) != True])
+ return FiniteSet(*[el for el in other if self.contains(el) is not true])
def symmetric_difference(self, other):
return SymmetricDifference(self, other)
@@ -278,10 +278,10 @@ def contains(self, other):
"""
other = sympify(other, strict=True)
- ret = self._contains(other)
+ ret = sympify(self._contains(other))
if ret is None:
if all(Eq(i, other) == False for i in self):
- return False
+ return false
ret = Contains(other, self, evaluate=False)
return ret
@@ -1461,7 +1461,7 @@ def reduce(args):
if s.is_FiniteSet:
other_args = [a for a in args if a != s]
res = FiniteSet(*[x for x in s
- if all(other.contains(x) == True for other in other_args)])
+ if all(other.contains(x) is true for other in other_args)])
unk = [x for x in s
if any(other.contains(x) not in (True, False) for other in other_args)]
if unk:
@@ -1788,7 +1788,7 @@ def _complement(self, other):
elms_unknown = FiniteSet(*[el for el in self if other.contains(el) not in (True, False)])
if elms_unknown == self:
return
- return Complement(FiniteSet(*[el for el in other if self.contains(el) != True]), elms_unknown)
+ return Complement(FiniteSet(*[el for el in other if self.contains(el) is not true]), elms_unknown)
return Set._complement(self, other)
| Union(Interval(-oo, oo), FiniteSet(1)) not evaluated
```
>>> Union(Interval(-oo, oo), FiniteSet(1))
(-∞, ∞) ∪ {1} # this should return (-∞, ∞) i guess
```
Can some one please verify the validity of issue? | sympy/sympy | diff --git a/sympy/sets/tests/test_fancysets.py b/sympy/sets/tests/test_fancysets.py
index a8eab7fe7e..fe36f2b566 100644
--- a/sympy/sets/tests/test_fancysets.py
+++ b/sympy/sets/tests/test_fancysets.py
@@ -197,7 +197,7 @@ def test_Complex():
assert -I in S.Complexes
assert sqrt(-1) in S.Complexes
assert S.Complexes.intersect(S.Reals) == S.Reals
- assert S.Complexes.union(S.Reals) == S.Complexes
+ # assert S.Complexes.union(S.Reals) == S.Complexes
assert S.Complexes == ComplexRegion(S.Reals*S.Reals)
diff --git a/sympy/sets/tests/test_sets.py b/sympy/sets/tests/test_sets.py
index b841e4be20..5eba935511 100644
--- a/sympy/sets/tests/test_sets.py
+++ b/sympy/sets/tests/test_sets.py
@@ -894,3 +894,8 @@ def test_issue_9808():
assert Complement(FiniteSet(y), FiniteSet(1)) == Complement(FiniteSet(y), FiniteSet(1), evaluate=False)
assert Complement(FiniteSet(1, 2, x), FiniteSet(x, y, 2, 3)) == \
Complement(FiniteSet(1), FiniteSet(y), evaluate=False)
+
+
+def test_issue_9956():
+ assert Union(Interval(-oo, oo), FiniteSet(1)) == Interval(-oo, oo)
+ assert Interval(-oo, oo).contains(1) is S.true
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 0,
"issue_text_score": 2,
"test_score": 0
},
"num_modified_files": 1
} | 0.7 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "mpmath>=0.19",
"pip_packages": [
"pytest"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.6",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | attrs==22.2.0
certifi==2021.5.30
importlib-metadata==4.8.3
iniconfig==1.1.1
mpmath==1.2.1
packaging==21.3
pluggy==1.0.0
py==1.11.0
pyparsing==3.1.4
pytest==7.0.1
-e git+https://github.com/sympy/sympy.git@886aded45250ae4f3e8158f70a29793f45a9b873#egg=sympy
tomli==1.2.3
typing_extensions==4.1.1
zipp==3.6.0
| name: sympy
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2021.5.30=py36h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.3=he6710b0_2
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- mpmath=1.2.1=py36h06a4308_0
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- pip=21.2.2=py36h06a4308_0
- python=3.6.13=h12debd9_1
- readline=8.2=h5eee18b_0
- setuptools=58.0.4=py36h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- wheel=0.37.1=pyhd3eb1b0_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- attrs==22.2.0
- importlib-metadata==4.8.3
- iniconfig==1.1.1
- packaging==21.3
- pluggy==1.0.0
- py==1.11.0
- pyparsing==3.1.4
- pytest==7.0.1
- tomli==1.2.3
- typing-extensions==4.1.1
- zipp==3.6.0
prefix: /opt/conda/envs/sympy
| [
"sympy/sets/tests/test_sets.py::test_issue_9956"
] | [] | [
"sympy/sets/tests/test_fancysets.py::test_naturals",
"sympy/sets/tests/test_fancysets.py::test_naturals0",
"sympy/sets/tests/test_fancysets.py::test_integers",
"sympy/sets/tests/test_fancysets.py::test_ImageSet",
"sympy/sets/tests/test_fancysets.py::test_image_is_ImageSet",
"sympy/sets/tests/test_fancysets.py::test_ImageSet_iterator_not_injetive",
"sympy/sets/tests/test_fancysets.py::test_Range",
"sympy/sets/tests/test_fancysets.py::test_range_interval_intersection",
"sympy/sets/tests/test_fancysets.py::test_fun",
"sympy/sets/tests/test_fancysets.py::test_Reals",
"sympy/sets/tests/test_fancysets.py::test_Complex",
"sympy/sets/tests/test_fancysets.py::test_intersections",
"sympy/sets/tests/test_fancysets.py::test_infinitely_indexed_set_1",
"sympy/sets/tests/test_fancysets.py::test_infinitely_indexed_set_2",
"sympy/sets/tests/test_fancysets.py::test_imageset_intersect_real",
"sympy/sets/tests/test_fancysets.py::test_ImageSet_simplification",
"sympy/sets/tests/test_fancysets.py::test_ComplexRegion_contains",
"sympy/sets/tests/test_fancysets.py::test_ComplexRegion_intersect",
"sympy/sets/tests/test_fancysets.py::test_ComplexRegion_union",
"sympy/sets/tests/test_fancysets.py::test_ComplexRegion_measure",
"sympy/sets/tests/test_fancysets.py::test_normalize_theta_set",
"sympy/sets/tests/test_fancysets.py::test_ComplexRegion_FiniteSet",
"sympy/sets/tests/test_fancysets.py::test_union_RealSubSet",
"sympy/sets/tests/test_sets.py::test_interval_arguments",
"sympy/sets/tests/test_sets.py::test_interval_symbolic_end_points",
"sympy/sets/tests/test_sets.py::test_union",
"sympy/sets/tests/test_sets.py::test_difference",
"sympy/sets/tests/test_sets.py::test_Complement",
"sympy/sets/tests/test_sets.py::test_complement",
"sympy/sets/tests/test_sets.py::test_intersect",
"sympy/sets/tests/test_sets.py::test_intersection",
"sympy/sets/tests/test_sets.py::test_issue_9623",
"sympy/sets/tests/test_sets.py::test_is_disjoint",
"sympy/sets/tests/test_sets.py::test_ProductSet_of_single_arg_is_arg",
"sympy/sets/tests/test_sets.py::test_interval_subs",
"sympy/sets/tests/test_sets.py::test_interval_to_mpi",
"sympy/sets/tests/test_sets.py::test_measure",
"sympy/sets/tests/test_sets.py::test_is_subset",
"sympy/sets/tests/test_sets.py::test_is_proper_subset",
"sympy/sets/tests/test_sets.py::test_is_superset",
"sympy/sets/tests/test_sets.py::test_is_proper_superset",
"sympy/sets/tests/test_sets.py::test_contains",
"sympy/sets/tests/test_sets.py::test_interval_symbolic",
"sympy/sets/tests/test_sets.py::test_union_contains",
"sympy/sets/tests/test_sets.py::test_is_number",
"sympy/sets/tests/test_sets.py::test_Interval_is_left_unbounded",
"sympy/sets/tests/test_sets.py::test_Interval_is_right_unbounded",
"sympy/sets/tests/test_sets.py::test_Interval_as_relational",
"sympy/sets/tests/test_sets.py::test_Finite_as_relational",
"sympy/sets/tests/test_sets.py::test_Union_as_relational",
"sympy/sets/tests/test_sets.py::test_Intersection_as_relational",
"sympy/sets/tests/test_sets.py::test_EmptySet",
"sympy/sets/tests/test_sets.py::test_finite_basic",
"sympy/sets/tests/test_sets.py::test_powerset",
"sympy/sets/tests/test_sets.py::test_product_basic",
"sympy/sets/tests/test_sets.py::test_real",
"sympy/sets/tests/test_sets.py::test_supinf",
"sympy/sets/tests/test_sets.py::test_universalset",
"sympy/sets/tests/test_sets.py::test_Union_of_ProductSets_shares",
"sympy/sets/tests/test_sets.py::test_Interval_free_symbols",
"sympy/sets/tests/test_sets.py::test_image_interval",
"sympy/sets/tests/test_sets.py::test_image_piecewise",
"sympy/sets/tests/test_sets.py::test_image_FiniteSet",
"sympy/sets/tests/test_sets.py::test_image_Union",
"sympy/sets/tests/test_sets.py::test_image_EmptySet",
"sympy/sets/tests/test_sets.py::test_issue_5724_7680",
"sympy/sets/tests/test_sets.py::test_boundary",
"sympy/sets/tests/test_sets.py::test_boundary_Union",
"sympy/sets/tests/test_sets.py::test_boundary_ProductSet",
"sympy/sets/tests/test_sets.py::test_boundary_ProductSet_line",
"sympy/sets/tests/test_sets.py::test_is_open",
"sympy/sets/tests/test_sets.py::test_is_closed",
"sympy/sets/tests/test_sets.py::test_closure",
"sympy/sets/tests/test_sets.py::test_interior",
"sympy/sets/tests/test_sets.py::test_issue_7841",
"sympy/sets/tests/test_sets.py::test_Eq",
"sympy/sets/tests/test_sets.py::test_SymmetricDifference",
"sympy/sets/tests/test_sets.py::test_issue_9536",
"sympy/sets/tests/test_sets.py::test_issue_9637",
"sympy/sets/tests/test_sets.py::test_issue_9808"
] | [] | BSD | 261 |
sympy__sympy-9965 | 81d78a2b22f735957c6686cd98fc3b3117ade162 | 2015-10-05 20:57:02 | 0241b35cae5f2adc04dc37b25f7dc9c5f00bd746 | diff --git a/sympy/core/function.py b/sympy/core/function.py
index ab14b62089..2ca570cbc4 100644
--- a/sympy/core/function.py
+++ b/sympy/core/function.py
@@ -646,14 +646,23 @@ def fdiff(self, argindex=1):
"""
if not (1 <= argindex <= len(self.args)):
raise ArgumentIndexError(self, argindex)
- if not self.args[argindex - 1].is_Symbol:
- # See issue 4624 and issue 4719 and issue 5600
- arg_dummy = Dummy('xi_%i' % argindex)
- arg_dummy.dummy_index = hash(self.args[argindex - 1])
- return Subs(Derivative(
- self.subs(self.args[argindex - 1], arg_dummy),
- arg_dummy), arg_dummy, self.args[argindex - 1])
- return Derivative(self, self.args[argindex - 1], evaluate=False)
+
+ if self.args[argindex - 1].is_Symbol:
+ for i in range(len(self.args)):
+ if i == argindex - 1:
+ continue
+ # See issue 8510
+ if self.args[argindex - 1] in self.args[i].free_symbols:
+ break
+ else:
+ return Derivative(self, self.args[argindex - 1], evaluate=False)
+ # See issue 4624 and issue 4719 and issue 5600
+ arg_dummy = Dummy('xi_%i' % argindex)
+ arg_dummy.dummy_index = hash(self.args[argindex - 1])
+ new_args = [arg for arg in self.args]
+ new_args[argindex-1] = arg_dummy
+ return Subs(Derivative(self.func(*new_args), arg_dummy),
+ arg_dummy, self.args[argindex - 1])
def _eval_as_leading_term(self, x):
"""Stub that should be overridden by new Functions to return
| Differentiation of general functions
```
In [1]:
from sympy import *
var('x, y')
f = Function('f')
In [2]:
f(x + y, x).diff(x)
Out[2]:
Derivative(f(x + y, x), x) + Subs(Derivative(f(_xi_1, x), _xi_1), (_xi_1,), (x + y,))
In [3]:
f(x, x).diff(x)
Out[3]:
2*Derivative(f(x, x), x)
```
For `In [2]`, instead of the result, I would expect,
`Subs(Derivative(f(x+y, _xi_2), _xi_2), (_xi_2,), (x,)) + Subs(Derivative(f(_xi_1, x), _xi_1), (_xi_1,), (x + y,))` | sympy/sympy | diff --git a/sympy/core/tests/test_function.py b/sympy/core/tests/test_function.py
index 86c0b6a723..96a9514932 100644
--- a/sympy/core/tests/test_function.py
+++ b/sympy/core/tests/test_function.py
@@ -289,6 +289,12 @@ def test_deriv1():
assert f(3*sin(x)).diff(x) == 3*cos(x)*Subs(Derivative(f(x), x),
Tuple(x), Tuple(3*sin(x)))
+ # See issue 8510
+ assert f(x, x + z).diff(x) == Subs(Derivative(f(y, x + z), y), Tuple(y), Tuple(x)) \
+ + Subs(Derivative(f(x, y), y), Tuple(y), Tuple(x + z))
+ assert f(x, x**2).diff(x) == Subs(Derivative(f(y, x**2), y), Tuple(y), Tuple(x)) \
+ + 2*x*Subs(Derivative(f(x, y), y), Tuple(y), Tuple(x**2))
+
def test_deriv2():
assert (x**3).diff(x) == 3*x**2
| {
"commit_name": "head_commit",
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true,
"llm_score": {
"difficulty_score": 1,
"issue_text_score": 0,
"test_score": 0
},
"num_modified_files": 1
} | 0.7 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "pytest",
"pip_packages": [
"pytest"
],
"pre_install": [
"apt-get update",
"apt-get install -y libgmp-dev"
],
"python": "3.6",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | attrs @ file:///opt/conda/conda-bld/attrs_1642510447205/work
certifi==2021.5.30
importlib-metadata @ file:///tmp/build/80754af9/importlib-metadata_1631916693255/work
iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work
more-itertools @ file:///tmp/build/80754af9/more-itertools_1637733554872/work
mpmath==1.3.0
packaging @ file:///tmp/build/80754af9/packaging_1637314298585/work
pluggy @ file:///tmp/build/80754af9/pluggy_1615976315926/work
py @ file:///opt/conda/conda-bld/py_1644396412707/work
pyparsing @ file:///tmp/build/80754af9/pyparsing_1635766073266/work
pytest==6.2.4
-e git+https://github.com/sympy/sympy.git@81d78a2b22f735957c6686cd98fc3b3117ade162#egg=sympy
toml @ file:///tmp/build/80754af9/toml_1616166611790/work
typing_extensions @ file:///opt/conda/conda-bld/typing_extensions_1647553014482/work
zipp @ file:///tmp/build/80754af9/zipp_1633618647012/work
| name: sympy
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- attrs=21.4.0=pyhd3eb1b0_0
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2021.5.30=py36h06a4308_0
- importlib-metadata=4.8.1=py36h06a4308_0
- importlib_metadata=4.8.1=hd3eb1b0_0
- iniconfig=1.1.1=pyhd3eb1b0_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.3=he6710b0_2
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- more-itertools=8.12.0=pyhd3eb1b0_0
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- packaging=21.3=pyhd3eb1b0_0
- pip=21.2.2=py36h06a4308_0
- pluggy=0.13.1=py36h06a4308_0
- py=1.11.0=pyhd3eb1b0_0
- pyparsing=3.0.4=pyhd3eb1b0_0
- pytest=6.2.4=py36h06a4308_2
- python=3.6.13=h12debd9_1
- readline=8.2=h5eee18b_0
- setuptools=58.0.4=py36h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- toml=0.10.2=pyhd3eb1b0_0
- typing_extensions=4.1.1=pyh06a4308_0
- wheel=0.37.1=pyhd3eb1b0_0
- xz=5.6.4=h5eee18b_1
- zipp=3.6.0=pyhd3eb1b0_0
- zlib=1.2.13=h5eee18b_1
- pip:
- mpmath==1.3.0
prefix: /opt/conda/envs/sympy
| [
"sympy/core/tests/test_function.py::test_deriv1"
] | [] | [
"sympy/core/tests/test_function.py::test_f_expand_complex",
"sympy/core/tests/test_function.py::test_bug1",
"sympy/core/tests/test_function.py::test_general_function",
"sympy/core/tests/test_function.py::test_derivative_subs_bug",
"sympy/core/tests/test_function.py::test_derivative_subs_self_bug",
"sympy/core/tests/test_function.py::test_derivative_linearity",
"sympy/core/tests/test_function.py::test_derivative_evaluate",
"sympy/core/tests/test_function.py::test_diff_symbols",
"sympy/core/tests/test_function.py::test_Function",
"sympy/core/tests/test_function.py::test_nargs",
"sympy/core/tests/test_function.py::test_Lambda",
"sympy/core/tests/test_function.py::test_IdentityFunction",
"sympy/core/tests/test_function.py::test_Lambda_symbols",
"sympy/core/tests/test_function.py::test_Lambda_arguments",
"sympy/core/tests/test_function.py::test_Lambda_equality",
"sympy/core/tests/test_function.py::test_Subs",
"sympy/core/tests/test_function.py::test_expand_function",
"sympy/core/tests/test_function.py::test_function_comparable",
"sympy/core/tests/test_function.py::test_deriv2",
"sympy/core/tests/test_function.py::test_func_deriv",
"sympy/core/tests/test_function.py::test_suppressed_evaluation",
"sympy/core/tests/test_function.py::test_function_evalf",
"sympy/core/tests/test_function.py::test_extensibility_eval",
"sympy/core/tests/test_function.py::test_function_non_commutative",
"sympy/core/tests/test_function.py::test_function_complex",
"sympy/core/tests/test_function.py::test_function__eval_nseries",
"sympy/core/tests/test_function.py::test_doit",
"sympy/core/tests/test_function.py::test_evalf_default",
"sympy/core/tests/test_function.py::test_issue_5399",
"sympy/core/tests/test_function.py::test_derivative_numerically",
"sympy/core/tests/test_function.py::test_fdiff_argument_index_error",
"sympy/core/tests/test_function.py::test_deriv_wrt_function",
"sympy/core/tests/test_function.py::test_diff_wrt_value",
"sympy/core/tests/test_function.py::test_diff_wrt",
"sympy/core/tests/test_function.py::test_diff_wrt_func_subs",
"sympy/core/tests/test_function.py::test_diff_wrt_not_allowed",
"sympy/core/tests/test_function.py::test_klein_gordon_lagrangian",
"sympy/core/tests/test_function.py::test_sho_lagrangian",
"sympy/core/tests/test_function.py::test_straight_line",
"sympy/core/tests/test_function.py::test_sort_variable",
"sympy/core/tests/test_function.py::test_unhandled",
"sympy/core/tests/test_function.py::test_issue_4711",
"sympy/core/tests/test_function.py::test_nfloat",
"sympy/core/tests/test_function.py::test_issue_7068",
"sympy/core/tests/test_function.py::test_issue_7231",
"sympy/core/tests/test_function.py::test_issue_7687",
"sympy/core/tests/test_function.py::test_issue_7688",
"sympy/core/tests/test_function.py::test_mexpand",
"sympy/core/tests/test_function.py::test_issue_8469",
"sympy/core/tests/test_function.py::test_should_evalf"
] | [] | BSD | 262 |
|
marshmallow-code__marshmallow-293 | 39bed8d628e2d08da5026df2df5ec6b9e9bbadf3 | 2015-10-07 22:51:36 | 1dbcae9c439d1a268717feb089351fc3c5180ac3 | diff --git a/docs/quickstart.rst b/docs/quickstart.rst
index 4e7dcdb5..959e915a 100644
--- a/docs/quickstart.rst
+++ b/docs/quickstart.rst
@@ -303,6 +303,22 @@ Dictionaries or lists are also accepted as the custom error message, in case you
# 'age': ['Age is required.'],
# 'city': {'message': 'City required', 'code': 400}}
+Partial Loading
++++++++++++++++
+
+When using the same schema in multiple places, you may only want to check required fields some of the time when deserializing. You can ignore missing fields entirely by setting ``partial=True``.
+
+.. code-block:: python
+ :emphasize-lines: 5,6
+
+ class UserSchema(Schema):
+ name = fields.String(required=True)
+ age = fields.Integer(required=True)
+
+ data, errors = UserSchema().load({'age': 42}, partial=True)
+ # OR UserSchema(partial=True).load({'age': 42})
+ data, errors # => ({'age': 42}, {})
+
Schema.validate
+++++++++++++++
diff --git a/marshmallow/marshalling.py b/marshmallow/marshalling.py
index 5caca583..6c315c03 100644
--- a/marshmallow/marshalling.py
+++ b/marshmallow/marshalling.py
@@ -208,7 +208,7 @@ class Unmarshaller(ErrorStore):
data=output
)
- def deserialize(self, data, fields_dict, many=False,
+ def deserialize(self, data, fields_dict, many=False, partial=False,
dict_class=dict, index_errors=True, index=None):
"""Deserialize ``data`` based on the schema defined by ``fields_dict``.
@@ -216,6 +216,7 @@ class Unmarshaller(ErrorStore):
:param dict fields_dict: Mapping of field names to :class:`Field` objects.
:param bool many: Set to `True` if ``data`` should be deserialized as
a collection.
+ :param bool partial: If `True`, ignore missing fields.
:param type dict_class: Dictionary class used to construct the output.
:param bool index_errors: Whether to store the index of invalid items in
``self.errors`` when ``many=True``.
@@ -229,7 +230,7 @@ class Unmarshaller(ErrorStore):
if many and data is not None:
self._pending = True
ret = [self.deserialize(d, fields_dict, many=False,
- dict_class=dict_class,
+ partial=partial, dict_class=dict_class,
index=idx, index_errors=index_errors)
for idx, d in enumerate(data)]
@@ -265,6 +266,8 @@ class Unmarshaller(ErrorStore):
field_name = field_obj.load_from
raw_value = data.get(field_obj.load_from, missing)
if raw_value is missing:
+ if partial:
+ continue
_miss = field_obj.missing
raw_value = _miss() if callable(_miss) else _miss
if raw_value is missing and not field_obj.required:
diff --git a/marshmallow/schema.py b/marshmallow/schema.py
index 6275bd0a..6b38c984 100644
--- a/marshmallow/schema.py
+++ b/marshmallow/schema.py
@@ -12,7 +12,7 @@ import types
import uuid
import warnings
from collections import namedtuple
-from functools import partial
+import functools
from marshmallow import base, fields, utils, class_registry, marshalling
from marshmallow.compat import (with_metaclass, iteritems, text_type,
@@ -251,6 +251,7 @@ class BaseSchema(base.SchemaABC):
:param tuple load_only: A list or tuple of fields to skip during serialization
:param tuple dump_only: A list or tuple of fields to skip during
deserialization, read-only fields
+ :param bool partial: If `True`, ignore missing fields when deserializing.
.. versionchanged:: 2.0.0
`__validators__`, `__preprocessors__`, and `__data_handlers__` are removed in favor of
@@ -320,7 +321,8 @@ class BaseSchema(base.SchemaABC):
pass
def __init__(self, extra=None, only=(), exclude=(), prefix='', strict=False,
- many=False, context=None, load_only=(), dump_only=()):
+ many=False, context=None, load_only=(), dump_only=(),
+ partial=False):
# copy declared fields from metaclass
self.declared_fields = copy.deepcopy(self._declared_fields)
self.many = many
@@ -331,6 +333,7 @@ class BaseSchema(base.SchemaABC):
self.ordered = self.opts.ordered
self.load_only = set(load_only) or set(self.opts.load_only)
self.dump_only = set(dump_only) or set(self.opts.dump_only)
+ self.partial = partial
#: Dictionary mapping field_names -> :class:`Field` objects
self.fields = self.dict_class()
#: Callable marshalling object
@@ -519,19 +522,21 @@ class BaseSchema(base.SchemaABC):
ret = self.opts.json_module.dumps(deserialized, *args, **kwargs)
return MarshalResult(ret, errors)
- def load(self, data, many=None):
+ def load(self, data, many=None, partial=None):
"""Deserialize a data structure to an object defined by this Schema's
fields and :meth:`make_object`.
:param dict data: The data to deserialize.
:param bool many: Whether to deserialize `data` as a collection. If `None`, the
value for `self.many` is used.
+ :param bool partial: Whether to ignore missing fields. If `None`, the
+ value for `self.partial` is used.
:return: A tuple of the form (``data``, ``errors``)
:rtype: `UnmarshalResult`, a `collections.namedtuple`
.. versionadded:: 1.0.0
"""
- result, errors = self._do_load(data, many, postprocess=True)
+ result, errors = self._do_load(data, many, partial, postprocess=True)
return UnmarshalResult(data=result, errors=errors)
def loads(self, json_data, many=None, *args, **kwargs):
@@ -540,13 +545,20 @@ class BaseSchema(base.SchemaABC):
:param str json_data: A JSON string of the data to deserialize.
:param bool many: Whether to deserialize `obj` as a collection. If `None`, the
value for `self.many` is used.
+ :param bool partial: Whether to ignore missing fields. If `None`, the
+ value for `self.partial` is used.
:return: A tuple of the form (``data``, ``errors``)
:rtype: `UnmarshalResult`, a `collections.namedtuple`
.. versionadded:: 1.0.0
"""
+ # TODO: This avoids breaking backward compatibility if people were
+ # passing in positional args after `many` for use by `json.loads`, but
+ # ideally we shouldn't have to do this.
+ partial = kwargs.pop('partial', None)
+
data = self.opts.json_module.loads(json_data, *args, **kwargs)
- return self.load(data, many=many)
+ return self.load(data, many=many, partial=partial)
def validate(self, data, many=None):
"""Validate `data` against the schema, returning a dictionary of
@@ -565,17 +577,20 @@ class BaseSchema(base.SchemaABC):
##### Private Helpers #####
- def _do_load(self, data, many=None, postprocess=True):
+ def _do_load(self, data, many=None, partial=None, postprocess=True):
"""Deserialize `data`, returning the deserialized result and a dictonary of
validation errors.
:param data: The data to deserialize.
:param bool many: Whether to deserialize `data` as a collection. If `None`, the
value for `self.many` is used.
+ :param bool partial: Whether to ignore missing fields. If `None`, the
+ value for `self.partial` is used.
:param bool postprocess: Whether to run post_load methods..
:return: A tuple of the form (`data`, `errors`)
"""
many = self.many if many is None else bool(many)
+ partial = self.partial if partial is None else bool(partial)
processed_data = self._invoke_load_processors(PRE_LOAD, data, many, original_data=data)
@@ -584,6 +599,7 @@ class BaseSchema(base.SchemaABC):
processed_data,
self.fields,
many=many,
+ partial=partial,
dict_class=self.dict_class,
index_errors=self.opts.index_errors,
)
@@ -780,7 +796,7 @@ class BaseSchema(base.SchemaABC):
validator_kwargs = validator.__marshmallow_kwargs__[(VALIDATES_SCHEMA, pass_many)]
pass_original = validator_kwargs.get('pass_original', False)
if pass_many:
- validator = partial(validator, many=many)
+ validator = functools.partial(validator, many=many)
if many:
for idx, item in enumerate(data):
try:
| "Partial" deserialization support
For implementing `PATCH` handlers on REST endpoints, it would be useful to have a concept of partial deserialization.
This would mean ignoring missing required fields and default values for missing fields.
I know this sounds a bit weird, but it matches a standard CRUD endpoint fairly well - `POST` or `PUT` to that endpoint should use the full validation w/r/t required fields or defaults, but `PATCH` is intended to apply a partial update and only modify what was actually changed.
I can handle this in userspace by catching `ValidationError`s for missing fields, but I don't think I can do the same for ignoring default field values.
Here's the equivalent API in DRF: http://www.django-rest-framework.org/api-guide/serializers/#partial-updates. From my POV I think any `partial` arg (if you think it makes sense) would best be positioned as a named argument on `load`, though. | marshmallow-code/marshmallow | diff --git a/tests/test_deserialization.py b/tests/test_deserialization.py
index 3b26dc5c..f886f5e6 100644
--- a/tests/test_deserialization.py
+++ b/tests/test_deserialization.py
@@ -1089,6 +1089,28 @@ class TestSchemaDeserialization:
assert len(errors['foo']) == 1
assert 'Missing data for required field.' in errors['foo']
+ @pytest.mark.parametrize('partial_schema',
+ [
+ True,
+ False
+ ])
+ def test_partial_deserialization(self, partial_schema):
+ class MySchema(Schema):
+ foo = fields.Field(required=True)
+ bar = fields.Field(required=True)
+
+ schema_args = {}
+ load_args = {}
+ if partial_schema:
+ schema_args['partial'] = True
+ else:
+ load_args['partial'] = True
+ data, errors = MySchema(**schema_args).load({'foo': 3}, **load_args)
+
+ assert data['foo'] == 3
+ assert 'bar' not in data
+ assert not errors
+
validators_gen = (func for func in [lambda x: x <= 24, lambda x: 18 <= x])
validators_gen_float = (func for func in
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_hyperlinks",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 2,
"issue_text_score": 0,
"test_score": 2
},
"num_modified_files": 3
} | 2.1 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[dev]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest",
"pytest-cov",
"pytest-xdist",
"pytest-mock",
"pytest-asyncio"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.9",
"reqs_path": [
"dev-requirements.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | backports.tarfile==1.2.0
cachetools==5.5.2
certifi==2025.1.31
cffi==1.17.1
chardet==5.2.0
charset-normalizer==3.4.1
colorama==0.4.6
coverage==7.8.0
cryptography==44.0.2
distlib==0.3.9
docutils==0.21.2
exceptiongroup==1.2.2
execnet==2.1.1
filelock==3.18.0
flake8==2.4.1
id==1.5.0
idna==3.10
importlib_metadata==8.6.1
iniconfig==2.1.0
invoke==2.2.0
jaraco.classes==3.4.0
jaraco.context==6.0.1
jaraco.functools==4.1.0
jeepney==0.9.0
keyring==25.6.0
markdown-it-py==3.0.0
-e git+https://github.com/marshmallow-code/marshmallow.git@39bed8d628e2d08da5026df2df5ec6b9e9bbadf3#egg=marshmallow
mccabe==0.3.1
mdurl==0.1.2
more-itertools==10.6.0
nh3==0.2.21
packaging==24.2
pep8==1.7.1
platformdirs==4.3.7
pluggy==1.5.0
py==1.11.0
pycparser==2.22
pyflakes==0.8.1
Pygments==2.19.1
pyproject-api==1.9.0
pytest==8.3.5
pytest-asyncio==0.26.0
pytest-cov==6.0.0
pytest-mock==3.14.0
pytest-xdist==3.6.1
python-dateutil==2.9.0.post0
pytz==2025.2
readme_renderer==44.0
requests==2.32.3
requests-toolbelt==1.0.0
rfc3986==2.0.0
rich==14.0.0
SecretStorage==3.3.3
simplejson==3.20.1
six==1.17.0
tomli==2.2.1
tox==4.25.0
twine==6.1.0
typing_extensions==4.13.0
urllib3==2.3.0
virtualenv==20.29.3
zipp==3.21.0
| name: marshmallow
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=3.0.16=h5eee18b_0
- pip=25.0=py39h06a4308_0
- python=3.9.21=he870216_1
- readline=8.2=h5eee18b_0
- setuptools=75.8.0=py39h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- tzdata=2025a=h04d1e81_0
- wheel=0.45.1=py39h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- backports-tarfile==1.2.0
- cachetools==5.5.2
- certifi==2025.1.31
- cffi==1.17.1
- chardet==5.2.0
- charset-normalizer==3.4.1
- colorama==0.4.6
- coverage==7.8.0
- cryptography==44.0.2
- distlib==0.3.9
- docutils==0.21.2
- exceptiongroup==1.2.2
- execnet==2.1.1
- filelock==3.18.0
- flake8==2.4.1
- id==1.5.0
- idna==3.10
- importlib-metadata==8.6.1
- iniconfig==2.1.0
- invoke==2.2.0
- jaraco-classes==3.4.0
- jaraco-context==6.0.1
- jaraco-functools==4.1.0
- jeepney==0.9.0
- keyring==25.6.0
- markdown-it-py==3.0.0
- mccabe==0.3.1
- mdurl==0.1.2
- more-itertools==10.6.0
- nh3==0.2.21
- packaging==24.2
- pep8==1.7.1
- platformdirs==4.3.7
- pluggy==1.5.0
- py==1.11.0
- pycparser==2.22
- pyflakes==0.8.1
- pygments==2.19.1
- pyproject-api==1.9.0
- pytest==8.3.5
- pytest-asyncio==0.26.0
- pytest-cov==6.0.0
- pytest-mock==3.14.0
- pytest-xdist==3.6.1
- python-dateutil==2.9.0.post0
- pytz==2025.2
- readme-renderer==44.0
- requests==2.32.3
- requests-toolbelt==1.0.0
- rfc3986==2.0.0
- rich==14.0.0
- secretstorage==3.3.3
- simplejson==3.20.1
- six==1.17.0
- tomli==2.2.1
- tox==4.25.0
- twine==6.1.0
- typing-extensions==4.13.0
- urllib3==2.3.0
- virtualenv==20.29.3
- zipp==3.21.0
prefix: /opt/conda/envs/marshmallow
| [
"tests/test_deserialization.py::TestSchemaDeserialization::test_partial_deserialization[True]",
"tests/test_deserialization.py::TestSchemaDeserialization::test_partial_deserialization[False]"
] | [] | [
"tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[String]",
"tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Integer]",
"tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Boolean]",
"tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Float]",
"tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Number]",
"tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[DateTime]",
"tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[LocalDateTime]",
"tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Time]",
"tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Date]",
"tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[TimeDelta]",
"tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Dict]",
"tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Url]",
"tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Email]",
"tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[FormattedString]",
"tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[UUID]",
"tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Decimal]",
"tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[String]",
"tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Integer]",
"tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Boolean]",
"tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Float]",
"tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Number]",
"tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[DateTime]",
"tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[LocalDateTime]",
"tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Time]",
"tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Date]",
"tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[TimeDelta]",
"tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Dict]",
"tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Url]",
"tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Email]",
"tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[FormattedString]",
"tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[UUID]",
"tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Decimal]",
"tests/test_deserialization.py::TestDeserializingNone::test_allow_none_is_true_if_missing_is_true",
"tests/test_deserialization.py::TestDeserializingNone::test_list_field_deserialize_none_to_empty_list",
"tests/test_deserialization.py::TestFieldDeserialization::test_float_field_deserialization",
"tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[bad]",
"tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[]",
"tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[in_val2]",
"tests/test_deserialization.py::TestFieldDeserialization::test_integer_field_deserialization",
"tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_deserialization",
"tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_with_places",
"tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_with_places_and_rounding",
"tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_deserialization_string",
"tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_special_values",
"tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_special_values_not_permitted",
"tests/test_deserialization.py::TestFieldDeserialization::test_string_field_deserialization",
"tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization",
"tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values",
"tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values_invalid[notvalid]",
"tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values_invalid[123]",
"tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[not-a-datetime]",
"tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[42]",
"tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[]",
"tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[in_value3]",
"tests/test_deserialization.py::TestFieldDeserialization::test_custom_date_format_datetime_field_deserialization",
"tests/test_deserialization.py::TestFieldDeserialization::test_rfc_datetime_field_deserialization[rfc]",
"tests/test_deserialization.py::TestFieldDeserialization::test_rfc_datetime_field_deserialization[rfc822]",
"tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[iso]",
"tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[iso8601]",
"tests/test_deserialization.py::TestFieldDeserialization::test_localdatetime_field_deserialization",
"tests/test_deserialization.py::TestFieldDeserialization::test_time_field_deserialization",
"tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[badvalue]",
"tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[]",
"tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[in_data2]",
"tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[42]",
"tests/test_deserialization.py::TestFieldDeserialization::test_timedelta_field_deserialization",
"tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[]",
"tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[badvalue]",
"tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[in_value2]",
"tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[9999999999]",
"tests/test_deserialization.py::TestFieldDeserialization::test_date_field_deserialization",
"tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[]",
"tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[123]",
"tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[in_value2]",
"tests/test_deserialization.py::TestFieldDeserialization::test_dict_field_deserialization",
"tests/test_deserialization.py::TestFieldDeserialization::test_url_field_deserialization",
"tests/test_deserialization.py::TestFieldDeserialization::test_relative_url_field_deserialization",
"tests/test_deserialization.py::TestFieldDeserialization::test_email_field_deserialization",
"tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_is_noop_by_default",
"tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_with_callable",
"tests/test_deserialization.py::TestFieldDeserialization::test_uuid_field_deserialization",
"tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[malformed]",
"tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[123]",
"tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[in_value2]",
"tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_function_must_be_callable",
"tests/test_deserialization.py::TestFieldDeserialization::test_method_field_deserialization_is_noop_by_default",
"tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_method",
"tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_method_must_be_a_method",
"tests/test_deserialization.py::TestFieldDeserialization::test_query_select_field_func_key_deserialization",
"tests/test_deserialization.py::TestFieldDeserialization::test_query_select_field_string_key_deserialization",
"tests/test_deserialization.py::TestFieldDeserialization::test_query_select_list_field_func_key_deserialization",
"tests/test_deserialization.py::TestFieldDeserialization::test_query_select_list_field_string_key_deserialization",
"tests/test_deserialization.py::TestFieldDeserialization::test_datetime_list_field_deserialization",
"tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_invalid_item",
"tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[notalist]",
"tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[42]",
"tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[value2]",
"tests/test_deserialization.py::TestFieldDeserialization::test_constant_field_deserialization",
"tests/test_deserialization.py::TestFieldDeserialization::test_constant_is_always_included_in_deserialized_data",
"tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_function",
"tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_class_that_returns_bool",
"tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_that_raises_error_with_list",
"tests/test_deserialization.py::TestFieldDeserialization::test_validator_must_return_false_to_raise_error",
"tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_validator_with_nonascii_input",
"tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validators",
"tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_custom_error_message",
"tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_to_dict",
"tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_values",
"tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_many",
"tests/test_deserialization.py::TestSchemaDeserialization::test_exclude",
"tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_deserialization_to_dict",
"tests/test_deserialization.py::TestSchemaDeserialization::test_nested_list_deserialization_to_dict",
"tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_none_not_allowed",
"tests/test_deserialization.py::TestSchemaDeserialization::test_nested_many_non_not_allowed",
"tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_required_missing",
"tests/test_deserialization.py::TestSchemaDeserialization::test_nested_many_required_missing",
"tests/test_deserialization.py::TestSchemaDeserialization::test_none_deserialization",
"tests/test_deserialization.py::TestSchemaDeserialization::test_nested_none_deserialization",
"tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param",
"tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_error_returns_field_name_not_attribute_name",
"tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_error_returns_load_from_not_attribute_name",
"tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_load_from_param",
"tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_dump_only_param",
"tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_value",
"tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_callable",
"tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_none",
"tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_returns_errors",
"tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_returns_errors_with_multiple_validators",
"tests/test_deserialization.py::TestSchemaDeserialization::test_strict_mode_deserialization",
"tests/test_deserialization.py::TestSchemaDeserialization::test_strict_mode_many",
"tests/test_deserialization.py::TestSchemaDeserialization::test_strict_mode_deserialization_with_multiple_validators",
"tests/test_deserialization.py::TestSchemaDeserialization::test_uncaught_validation_errors_are_stored",
"tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_a_field",
"tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_an_email_field",
"tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_a_url_field",
"tests/test_deserialization.py::TestSchemaDeserialization::test_required_value_only_passed_to_validators_if_provided",
"tests/test_deserialization.py::TestValidation::test_integer_with_validator",
"tests/test_deserialization.py::TestValidation::test_integer_with_validators[field0]",
"tests/test_deserialization.py::TestValidation::test_integer_with_validators[field1]",
"tests/test_deserialization.py::TestValidation::test_integer_with_validators[field2]",
"tests/test_deserialization.py::TestValidation::test_float_with_validators[field0]",
"tests/test_deserialization.py::TestValidation::test_float_with_validators[field1]",
"tests/test_deserialization.py::TestValidation::test_float_with_validators[field2]",
"tests/test_deserialization.py::TestValidation::test_string_validator",
"tests/test_deserialization.py::TestValidation::test_function_validator",
"tests/test_deserialization.py::TestValidation::test_function_validators[field0]",
"tests/test_deserialization.py::TestValidation::test_function_validators[field1]",
"tests/test_deserialization.py::TestValidation::test_function_validators[field2]",
"tests/test_deserialization.py::TestValidation::test_method_validator",
"tests/test_deserialization.py::TestValidation::test_nested_data_is_stored_when_validation_fails",
"tests/test_deserialization.py::test_required_field_failure[String]",
"tests/test_deserialization.py::test_required_field_failure[Integer]",
"tests/test_deserialization.py::test_required_field_failure[Boolean]",
"tests/test_deserialization.py::test_required_field_failure[Float]",
"tests/test_deserialization.py::test_required_field_failure[Number]",
"tests/test_deserialization.py::test_required_field_failure[DateTime]",
"tests/test_deserialization.py::test_required_field_failure[LocalDateTime]",
"tests/test_deserialization.py::test_required_field_failure[Time]",
"tests/test_deserialization.py::test_required_field_failure[Date]",
"tests/test_deserialization.py::test_required_field_failure[TimeDelta]",
"tests/test_deserialization.py::test_required_field_failure[Dict]",
"tests/test_deserialization.py::test_required_field_failure[Url]",
"tests/test_deserialization.py::test_required_field_failure[Email]",
"tests/test_deserialization.py::test_required_field_failure[UUID]",
"tests/test_deserialization.py::test_required_field_failure[Decimal]",
"tests/test_deserialization.py::test_required_message_can_be_changed[My",
"tests/test_deserialization.py::test_required_message_can_be_changed[message1]",
"tests/test_deserialization.py::test_required_message_can_be_changed[message2]",
"tests/test_deserialization.py::test_deserialize_doesnt_raise_exception_if_strict_is_false_and_input_type_is_incorrect",
"tests/test_deserialization.py::test_deserialize_raises_exception_if_strict_is_true_and_input_type_is_incorrect"
] | [] | MIT License | 263 |
|
docker__docker-py-806 | f479720d517a7db7f886916190b3032d29d18f10 | 2015-10-09 19:03:05 | f479720d517a7db7f886916190b3032d29d18f10 | dnephin: some CI failures, otherwise looks good | diff --git a/docker/auth/auth.py b/docker/auth/auth.py
index 366bc67e..1ee9f812 100644
--- a/docker/auth/auth.py
+++ b/docker/auth/auth.py
@@ -102,7 +102,7 @@ def decode_auth(auth):
def encode_header(auth):
auth_json = json.dumps(auth).encode('ascii')
- return base64.b64encode(auth_json)
+ return base64.urlsafe_b64encode(auth_json)
def parse_auth(entries):
| Auth fails with long passwords
See https://github.com/docker/docker/issues/16840
docker-py is encoding `X-Registry-Auth` with regular base64 and not the url safe version of base64 that jwt tokens use. | docker/docker-py | diff --git a/tests/utils_test.py b/tests/utils_test.py
index b1adde26..04183f9f 100644
--- a/tests/utils_test.py
+++ b/tests/utils_test.py
@@ -19,7 +19,9 @@ from docker.utils import (
exclude_paths, convert_volume_binds, decode_json_header
)
from docker.utils.ports import build_port_bindings, split_port
-from docker.auth import resolve_repository_name, resolve_authconfig
+from docker.auth import (
+ resolve_repository_name, resolve_authconfig, encode_header
+)
from . import base
from .helpers import make_tree
@@ -376,12 +378,21 @@ class UtilsTest(base.BaseTestCase):
obj = {'a': 'b', 'c': 1}
data = None
if six.PY3:
- data = base64.b64encode(bytes(json.dumps(obj), 'utf-8'))
+ data = base64.urlsafe_b64encode(bytes(json.dumps(obj), 'utf-8'))
else:
- data = base64.b64encode(json.dumps(obj))
+ data = base64.urlsafe_b64encode(json.dumps(obj))
decoded_data = decode_json_header(data)
self.assertEqual(obj, decoded_data)
+ def test_803_urlsafe_encode(self):
+ auth_data = {
+ 'username': 'root',
+ 'password': 'GR?XGR?XGR?XGR?X'
+ }
+ encoded = encode_header(auth_data)
+ assert b'/' not in encoded
+ assert b'_' in encoded
+
def test_resolve_repository_name(self):
# docker hub library image
self.assertEqual(
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_short_problem_statement",
"has_hyperlinks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 1,
"issue_text_score": 0,
"test_score": 2
},
"num_modified_files": 1
} | 1.4 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[dev]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest pytest-cov",
"pytest"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.7",
"reqs_path": [
"requirements.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | certifi @ file:///croot/certifi_1671487769961/work/certifi
coverage==7.2.7
-e git+https://github.com/docker/docker-py.git@f479720d517a7db7f886916190b3032d29d18f10#egg=docker_py
exceptiongroup==1.2.2
importlib-metadata==6.7.0
iniconfig==2.0.0
packaging==24.0
pluggy==1.2.0
pytest==7.4.4
pytest-cov==4.1.0
requests==2.5.3
six==1.17.0
tomli==2.0.1
typing_extensions==4.7.1
websocket-client==0.32.0
zipp==3.15.0
| name: docker-py
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2022.12.7=py37h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- pip=22.3.1=py37h06a4308_0
- python=3.7.16=h7a1cb2a_0
- readline=8.2=h5eee18b_0
- setuptools=65.6.3=py37h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- wheel=0.38.4=py37h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- coverage==7.2.7
- exceptiongroup==1.2.2
- importlib-metadata==6.7.0
- iniconfig==2.0.0
- packaging==24.0
- pluggy==1.2.0
- pytest==7.4.4
- pytest-cov==4.1.0
- requests==2.5.3
- six==1.17.0
- tomli==2.0.1
- typing-extensions==4.7.1
- websocket-client==0.32.0
- zipp==3.15.0
prefix: /opt/conda/envs/docker-py
| [
"tests/utils_test.py::UtilsTest::test_803_urlsafe_encode"
] | [] | [
"tests/utils_test.py::HostConfigTest::test_create_host_config_invalid_cpu_cfs_types",
"tests/utils_test.py::HostConfigTest::test_create_host_config_no_options",
"tests/utils_test.py::HostConfigTest::test_create_host_config_no_options_newer_api_version",
"tests/utils_test.py::HostConfigTest::test_create_host_config_with_cpu_period",
"tests/utils_test.py::HostConfigTest::test_create_host_config_with_cpu_quota",
"tests/utils_test.py::UlimitTest::test_create_host_config_dict_ulimit",
"tests/utils_test.py::UlimitTest::test_create_host_config_dict_ulimit_capitals",
"tests/utils_test.py::UlimitTest::test_create_host_config_obj_ulimit",
"tests/utils_test.py::UlimitTest::test_ulimit_invalid_type",
"tests/utils_test.py::LogConfigTest::test_create_host_config_dict_logconfig",
"tests/utils_test.py::LogConfigTest::test_create_host_config_obj_logconfig",
"tests/utils_test.py::LogConfigTest::test_logconfig_invalid_config_type",
"tests/utils_test.py::KwargsFromEnvTest::test_kwargs_from_env_empty",
"tests/utils_test.py::KwargsFromEnvTest::test_kwargs_from_env_no_cert_path",
"tests/utils_test.py::KwargsFromEnvTest::test_kwargs_from_env_tls",
"tests/utils_test.py::UtilsTest::test_convert_filters",
"tests/utils_test.py::UtilsTest::test_convert_volume_binds_compact",
"tests/utils_test.py::UtilsTest::test_convert_volume_binds_complete",
"tests/utils_test.py::UtilsTest::test_convert_volume_binds_empty",
"tests/utils_test.py::UtilsTest::test_convert_volume_binds_list",
"tests/utils_test.py::UtilsTest::test_convert_volume_binds_no_mode",
"tests/utils_test.py::UtilsTest::test_convert_volume_binds_unicode_bytes_input",
"tests/utils_test.py::UtilsTest::test_convert_volume_binds_unicode_unicode_input",
"tests/utils_test.py::UtilsTest::test_decode_json_header",
"tests/utils_test.py::UtilsTest::test_parse_bytes",
"tests/utils_test.py::UtilsTest::test_parse_env_file_commented_line",
"tests/utils_test.py::UtilsTest::test_parse_env_file_invalid_line",
"tests/utils_test.py::UtilsTest::test_parse_env_file_proper",
"tests/utils_test.py::UtilsTest::test_parse_host",
"tests/utils_test.py::UtilsTest::test_parse_host_empty_value",
"tests/utils_test.py::UtilsTest::test_parse_repository_tag",
"tests/utils_test.py::UtilsTest::test_resolve_authconfig",
"tests/utils_test.py::UtilsTest::test_resolve_registry_and_auth",
"tests/utils_test.py::UtilsTest::test_resolve_repository_name",
"tests/utils_test.py::PortsTest::test_build_port_bindings_with_matching_internal_port_ranges",
"tests/utils_test.py::PortsTest::test_build_port_bindings_with_matching_internal_ports",
"tests/utils_test.py::PortsTest::test_build_port_bindings_with_nonmatching_internal_port_ranges",
"tests/utils_test.py::PortsTest::test_build_port_bindings_with_nonmatching_internal_ports",
"tests/utils_test.py::PortsTest::test_build_port_bindings_with_one_port",
"tests/utils_test.py::PortsTest::test_build_port_bindings_with_port_range",
"tests/utils_test.py::PortsTest::test_host_only_with_colon",
"tests/utils_test.py::PortsTest::test_non_matching_length_port_ranges",
"tests/utils_test.py::PortsTest::test_port_and_range_invalid",
"tests/utils_test.py::PortsTest::test_port_only_with_colon",
"tests/utils_test.py::PortsTest::test_split_port_invalid",
"tests/utils_test.py::PortsTest::test_split_port_no_host_port",
"tests/utils_test.py::PortsTest::test_split_port_range_no_host_port",
"tests/utils_test.py::PortsTest::test_split_port_range_with_host_ip_no_port",
"tests/utils_test.py::PortsTest::test_split_port_range_with_host_port",
"tests/utils_test.py::PortsTest::test_split_port_range_with_protocol",
"tests/utils_test.py::PortsTest::test_split_port_with_host_ip",
"tests/utils_test.py::PortsTest::test_split_port_with_host_ip_no_port",
"tests/utils_test.py::PortsTest::test_split_port_with_host_port",
"tests/utils_test.py::PortsTest::test_split_port_with_protocol",
"tests/utils_test.py::ExcludePathsTest::test_directory",
"tests/utils_test.py::ExcludePathsTest::test_directory_with_single_exception",
"tests/utils_test.py::ExcludePathsTest::test_directory_with_subdir_exception",
"tests/utils_test.py::ExcludePathsTest::test_directory_with_trailing_slash",
"tests/utils_test.py::ExcludePathsTest::test_directory_with_wildcard_exception",
"tests/utils_test.py::ExcludePathsTest::test_exclude_custom_dockerfile",
"tests/utils_test.py::ExcludePathsTest::test_exclude_dockerfile_dockerignore",
"tests/utils_test.py::ExcludePathsTest::test_no_dupes",
"tests/utils_test.py::ExcludePathsTest::test_no_excludes",
"tests/utils_test.py::ExcludePathsTest::test_question_mark",
"tests/utils_test.py::ExcludePathsTest::test_single_filename",
"tests/utils_test.py::ExcludePathsTest::test_single_filename_trailing_slash",
"tests/utils_test.py::ExcludePathsTest::test_single_subdir_single_filename",
"tests/utils_test.py::ExcludePathsTest::test_single_subdir_wildcard_filename",
"tests/utils_test.py::ExcludePathsTest::test_subdirectory",
"tests/utils_test.py::ExcludePathsTest::test_wildcard_exclude",
"tests/utils_test.py::ExcludePathsTest::test_wildcard_filename_end",
"tests/utils_test.py::ExcludePathsTest::test_wildcard_filename_start",
"tests/utils_test.py::ExcludePathsTest::test_wildcard_subdir_single_filename",
"tests/utils_test.py::ExcludePathsTest::test_wildcard_subdir_wildcard_filename",
"tests/utils_test.py::ExcludePathsTest::test_wildcard_with_exception",
"tests/utils_test.py::ExcludePathsTest::test_wildcard_with_wildcard_exception"
] | [] | Apache License 2.0 | 264 |
vortec__versionbump-6 | 1b62d24471870d220f1f05ee1421a688f51d4923 | 2015-10-10 14:43:31 | 1b62d24471870d220f1f05ee1421a688f51d4923 | diff --git a/.travis.yml b/.travis.yml
index 2ab01b1..b7ed065 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -3,13 +3,9 @@ python:
- 2.7
- 3.4
- pypy
-before_install:
- - pip install codecov
install:
- pip install .
- pip install behave dont-fudge-up
script:
- py.test -v tests
- behave tests/features
-after_success:
- - codecov
diff --git a/versionbump/filebump.py b/versionbump/filebump.py
index 65713cb..98d29f9 100644
--- a/versionbump/filebump.py
+++ b/versionbump/filebump.py
@@ -32,6 +32,7 @@ class FileBump(object):
def write_cache_to_file(self):
self.fo.seek(0)
self.fo.write(self.file_cache)
+ self.fo.truncate()
def replace_version_in_cache(self, old_version, new_version):
self.file_cache = self.file_cache.replace(old_version, new_version)
| FileBump does not correctly adjust the target file size
When adjusting the version in a file, the file size is not correctly adjusted.
For example:
File contents before bump:
```
0.1.22222
```
Command used:
```
versionbump -c 0.1.22222 minor version.txt
```
File contents after bump:
```
0.2.0
222
```
Ideally the file contents would be:
```
0.2.0
``` | vortec/versionbump | diff --git a/tests/unit/test_filebump.py b/tests/unit/test_filebump.py
index 7bddb5f..12bc26f 100644
--- a/tests/unit/test_filebump.py
+++ b/tests/unit/test_filebump.py
@@ -51,3 +51,12 @@ def test_it_doesnt_find_the_version():
empty_fo = StringIO('')
with pytest.raises(ValueError):
FileBump(empty_fo, '1.2.3')
+
+
+def test_it_truncates_the_file():
+ version = '0.0.111'
+ fo = StringIO(version)
+ fb = FileBump(fo, version)
+ fb.bump('minor')
+ fo.seek(0)
+ assert fo.read() == '0.1.0'
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 0,
"issue_text_score": 1,
"test_score": 1
},
"num_modified_files": 2
} | unknown | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "pytest",
"pip_packages": [
"behave",
"pytest",
"codecov"
],
"pre_install": null,
"python": "3.4",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | attrs @ file:///opt/conda/conda-bld/attrs_1642510447205/work
behave==1.2.6
certifi==2021.5.30
charset-normalizer==2.0.12
codecov==2.1.13
coverage==6.2
idna==3.10
importlib-metadata @ file:///tmp/build/80754af9/importlib-metadata_1631916693255/work
iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work
more-itertools @ file:///tmp/build/80754af9/more-itertools_1637733554872/work
packaging @ file:///tmp/build/80754af9/packaging_1637314298585/work
parse==1.20.2
parse_type==0.6.4
pluggy @ file:///tmp/build/80754af9/pluggy_1615976315926/work
py @ file:///opt/conda/conda-bld/py_1644396412707/work
pyparsing @ file:///tmp/build/80754af9/pyparsing_1635766073266/work
pytest==6.2.4
requests==2.27.1
six==1.17.0
toml @ file:///tmp/build/80754af9/toml_1616166611790/work
typing_extensions @ file:///opt/conda/conda-bld/typing_extensions_1647553014482/work
urllib3==1.26.20
-e git+https://github.com/vortec/versionbump.git@1b62d24471870d220f1f05ee1421a688f51d4923#egg=versionbump
zipp @ file:///tmp/build/80754af9/zipp_1633618647012/work
| name: versionbump
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- attrs=21.4.0=pyhd3eb1b0_0
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2021.5.30=py36h06a4308_0
- importlib-metadata=4.8.1=py36h06a4308_0
- importlib_metadata=4.8.1=hd3eb1b0_0
- iniconfig=1.1.1=pyhd3eb1b0_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.3=he6710b0_2
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- more-itertools=8.12.0=pyhd3eb1b0_0
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- packaging=21.3=pyhd3eb1b0_0
- pip=21.2.2=py36h06a4308_0
- pluggy=0.13.1=py36h06a4308_0
- py=1.11.0=pyhd3eb1b0_0
- pyparsing=3.0.4=pyhd3eb1b0_0
- pytest=6.2.4=py36h06a4308_2
- python=3.6.13=h12debd9_1
- readline=8.2=h5eee18b_0
- setuptools=58.0.4=py36h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- toml=0.10.2=pyhd3eb1b0_0
- typing_extensions=4.1.1=pyh06a4308_0
- wheel=0.37.1=pyhd3eb1b0_0
- xz=5.6.4=h5eee18b_1
- zipp=3.6.0=pyhd3eb1b0_0
- zlib=1.2.13=h5eee18b_1
- pip:
- behave==1.2.6
- charset-normalizer==2.0.12
- codecov==2.1.13
- coverage==6.2
- idna==3.10
- parse==1.20.2
- parse-type==0.6.4
- requests==2.27.1
- six==1.17.0
- urllib3==1.26.20
prefix: /opt/conda/envs/versionbump
| [
"tests/unit/test_filebump.py::test_it_truncates_the_file"
] | [] | [
"tests/unit/test_filebump.py::test_file_gets_parsed_correctly",
"tests/unit/test_filebump.py::test_file_cache",
"tests/unit/test_filebump.py::test_bump",
"tests/unit/test_filebump.py::test_cache_write_to_file",
"tests/unit/test_filebump.py::test_print_output",
"tests/unit/test_filebump.py::test_it_doesnt_find_the_version"
] | [] | MIT License | 265 |
|
marshmallow-code__marshmallow-299 | 1dbcae9c439d1a268717feb089351fc3c5180ac3 | 2015-10-14 03:40:58 | 1dbcae9c439d1a268717feb089351fc3c5180ac3 | nelfin: Not really sure what's happened, all the Travis builds on Python 3.x failed with:
```pytb
Traceback (most recent call last):
File "setup.py", line 81, in <module>
cmdclass={'test': PyTest},
File "/opt/python/3.3.5/lib/python3.3/distutils/core.py", line 148, in setup
dist.run_commands()
File "/opt/python/3.3.5/lib/python3.3/distutils/dist.py", line 930, in run_commands
self.run_command(cmd)
File "/opt/python/3.3.5/lib/python3.3/distutils/dist.py", line 948, in run_command
cmd_obj.ensure_finalized()
File "/opt/python/3.3.5/lib/python3.3/distutils/cmd.py", line 107, in ensure_finalized
self.finalize_options()
File "setup.py", line 15, in finalize_options
self.test_args = ['--verbose', 'tests/']
AttributeError: can't set attribute
```
but `tox -e py34` works fine for me. :confused:
nelfin: Looks like this is being bitten by https://bitbucket.org/pypa/setuptools/commits/cf565b66b855dd4df189b679206f9fb113681737:
```diff
diff --git a/setuptools/command/test.py b/setuptools/command/test.py
--- a/setuptools/command/test.py
+++ b/setuptools/command/test.py
@@ -72,10 +72,6 @@
"You may specify a module or a suite, but not both"
)
- self.test_args = [self.test_suite]
-
- if self.verbose:
- self.test_args.insert(0, '--verbose')
if self.test_loader is None:
self.test_loader = getattr(self.distribution, 'test_loader', None)
if self.test_loader is None:
@@ -83,6 +79,11 @@
if self.test_runner is None:
self.test_runner = getattr(self.distribution, 'test_runner', None)
+ @property
+ def test_args(self):
+ verbose = ['--verbose'] if self.verbose else []
+ return verbose + [self.test_suite]
+
def with_project_on_sys_path(self, func):
with_2to3 = PY3 and getattr(self.distribution, 'use_2to3', False)
```
nelfin: Depends on #301
sloria: Thanks for this patch. I will looks into this more closely tomorrow.
Updating to the latest 2.1-line branch should fix the builds. | diff --git a/marshmallow/marshalling.py b/marshmallow/marshalling.py
index 5caca583..7961f087 100644
--- a/marshmallow/marshalling.py
+++ b/marshmallow/marshalling.py
@@ -21,6 +21,8 @@ __all__ = [
'Unmarshaller',
]
+# Key used for field-level validation errors on nested fields
+FIELD = '_field'
class ErrorStore(object):
@@ -68,6 +70,8 @@ class ErrorStore(object):
# Warning: Mutation!
if isinstance(err.messages, dict):
errors[field_name] = err.messages
+ elif isinstance(errors.get(field_name), dict):
+ errors[field_name].setdefault(FIELD, []).extend(err.messages)
else:
errors.setdefault(field_name, []).extend(err.messages)
# When a Nested field fails validation, the marshalled data is stored
| Field-level validation errors cannot be saved on a nested field with many=True
When validating a field, all of its error messages are saved and appended to the list of messages for that field name in `call_and_store`, but for `fields.Nested` with `many=True` the error messages for child elements of the collection are saved and stored in a dictionary keyed by the element index. This causes the following exception on this minimal test case:
```python
class Inner(Schema):
req = fields.Field(required=True)
class Outer(Schema):
inner = fields.Nested(Inner, many=True)
@validates('inner')
def validates_inner(self, data):
raise ValidationError('not a chance')
outer = Outer()
_, errors = outer.load({'inner': [{}]})
```
```pytb
Traceback (most recent call last):
File "/home/andrew/misc/marshmallow/tests/test_schema.py", line 1238, in test_all_errors_on_many_nested_field_with_validates_decorator
_, errors = outer.load({'inner': [{}]})
File "/home/andrew/misc/marshmallow/marshmallow/schema.py", line 539, in load
result, errors = self._do_load(data, many, partial=partial, postprocess=True)
File "/home/andrew/misc/marshmallow/marshmallow/schema.py", line 610, in _do_load
self._invoke_field_validators(data=result, many=many)
File "/home/andrew/misc/marshmallow/marshmallow/schema.py", line 789, in _invoke_field_validators
field_obj=field_obj
File "/home/andrew/misc/marshmallow/marshmallow/marshalling.py", line 74, in call_and_store
errors.setdefault(field_name, []).extend(err.messages)
AttributeError: 'dict' object has no attribute 'extend'
``` | marshmallow-code/marshmallow | diff --git a/tests/test_schema.py b/tests/test_schema.py
index 81d5d0fb..a18c7787 100644
--- a/tests/test_schema.py
+++ b/tests/test_schema.py
@@ -1222,6 +1222,23 @@ class TestNestedSchema:
_, errors = schema.load({'inner': 1})
assert errors['inner']['_schema'] == ['Invalid input type.']
+ # regression test for https://github.com/marshmallow-code/marshmallow/issues/298
+ def test_all_errors_on_many_nested_field_with_validates_decorator(self):
+ class Inner(Schema):
+ req = fields.Field(required=True)
+
+ class Outer(Schema):
+ inner = fields.Nested(Inner, many=True)
+
+ @validates('inner')
+ def validates_inner(self, data):
+ raise ValidationError('not a chance')
+
+ outer = Outer()
+ _, errors = outer.load({'inner': [{}]})
+ assert 'inner' in errors
+ assert '_field' in errors['inner']
+
def test_missing_required_nested_field(self):
class Inner(Schema):
inner_req = fields.Field(required=True, error_messages={'required': 'Oops'})
| {
"commit_name": "head_commit",
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true,
"llm_score": {
"difficulty_score": 0,
"issue_text_score": 1,
"test_score": 1
},
"num_modified_files": 1
} | 2.1 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[dev]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest",
"pytest-cov",
"pytest-xdist",
"pytest-mock",
"pytest-asyncio"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.9",
"reqs_path": [
"dev-requirements.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | backports.tarfile==1.2.0
cachetools==5.5.2
certifi==2025.1.31
cffi==1.17.1
chardet==5.2.0
charset-normalizer==3.4.1
colorama==0.4.6
coverage==7.8.0
cryptography==44.0.2
distlib==0.3.9
docutils==0.21.2
exceptiongroup==1.2.2
execnet==2.1.1
filelock==3.18.0
flake8==2.4.1
id==1.5.0
idna==3.10
importlib_metadata==8.6.1
iniconfig==2.1.0
invoke==2.2.0
jaraco.classes==3.4.0
jaraco.context==6.0.1
jaraco.functools==4.1.0
jeepney==0.9.0
keyring==25.6.0
markdown-it-py==3.0.0
-e git+https://github.com/marshmallow-code/marshmallow.git@1dbcae9c439d1a268717feb089351fc3c5180ac3#egg=marshmallow
mccabe==0.3.1
mdurl==0.1.2
more-itertools==10.6.0
nh3==0.2.21
packaging==24.2
pep8==1.7.1
platformdirs==4.3.7
pluggy==1.5.0
py==1.11.0
pycparser==2.22
pyflakes==0.8.1
Pygments==2.19.1
pyproject-api==1.9.0
pytest==8.3.5
pytest-asyncio==0.26.0
pytest-cov==6.0.0
pytest-mock==3.14.0
pytest-xdist==3.6.1
python-dateutil==2.9.0.post0
pytz==2025.2
readme_renderer==44.0
requests==2.32.3
requests-toolbelt==1.0.0
rfc3986==2.0.0
rich==14.0.0
SecretStorage==3.3.3
simplejson==3.20.1
six==1.17.0
tomli==2.2.1
tox==4.25.0
twine==6.1.0
typing_extensions==4.13.0
urllib3==2.3.0
virtualenv==20.29.3
zipp==3.21.0
| name: marshmallow
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=3.0.16=h5eee18b_0
- pip=25.0=py39h06a4308_0
- python=3.9.21=he870216_1
- readline=8.2=h5eee18b_0
- setuptools=75.8.0=py39h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- tzdata=2025a=h04d1e81_0
- wheel=0.45.1=py39h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- backports-tarfile==1.2.0
- cachetools==5.5.2
- certifi==2025.1.31
- cffi==1.17.1
- chardet==5.2.0
- charset-normalizer==3.4.1
- colorama==0.4.6
- coverage==7.8.0
- cryptography==44.0.2
- distlib==0.3.9
- docutils==0.21.2
- exceptiongroup==1.2.2
- execnet==2.1.1
- filelock==3.18.0
- flake8==2.4.1
- id==1.5.0
- idna==3.10
- importlib-metadata==8.6.1
- iniconfig==2.1.0
- invoke==2.2.0
- jaraco-classes==3.4.0
- jaraco-context==6.0.1
- jaraco-functools==4.1.0
- jeepney==0.9.0
- keyring==25.6.0
- markdown-it-py==3.0.0
- mccabe==0.3.1
- mdurl==0.1.2
- more-itertools==10.6.0
- nh3==0.2.21
- packaging==24.2
- pep8==1.7.1
- platformdirs==4.3.7
- pluggy==1.5.0
- py==1.11.0
- pycparser==2.22
- pyflakes==0.8.1
- pygments==2.19.1
- pyproject-api==1.9.0
- pytest==8.3.5
- pytest-asyncio==0.26.0
- pytest-cov==6.0.0
- pytest-mock==3.14.0
- pytest-xdist==3.6.1
- python-dateutil==2.9.0.post0
- pytz==2025.2
- readme-renderer==44.0
- requests==2.32.3
- requests-toolbelt==1.0.0
- rfc3986==2.0.0
- rich==14.0.0
- secretstorage==3.3.3
- simplejson==3.20.1
- six==1.17.0
- tomli==2.2.1
- tox==4.25.0
- twine==6.1.0
- typing-extensions==4.13.0
- urllib3==2.3.0
- virtualenv==20.29.3
- zipp==3.21.0
prefix: /opt/conda/envs/marshmallow
| [
"tests/test_schema.py::TestNestedSchema::test_all_errors_on_many_nested_field_with_validates_decorator"
] | [] | [
"tests/test_schema.py::test_serializing_basic_object[UserSchema]",
"tests/test_schema.py::test_serializing_basic_object[UserMetaSchema]",
"tests/test_schema.py::test_serializer_dump",
"tests/test_schema.py::test_dump_returns_dict_of_errors",
"tests/test_schema.py::test_dump_with_strict_mode_raises_error[UserSchema]",
"tests/test_schema.py::test_dump_with_strict_mode_raises_error[UserMetaSchema]",
"tests/test_schema.py::test_dump_resets_errors",
"tests/test_schema.py::test_load_resets_errors",
"tests/test_schema.py::test_dump_resets_error_fields",
"tests/test_schema.py::test_load_resets_error_fields",
"tests/test_schema.py::test_errored_fields_do_not_appear_in_output",
"tests/test_schema.py::test_load_many_stores_error_indices",
"tests/test_schema.py::test_dump_many",
"tests/test_schema.py::test_multiple_errors_can_be_stored_for_a_given_index",
"tests/test_schema.py::test_dump_many_stores_error_indices",
"tests/test_schema.py::test_dump_many_doesnt_stores_error_indices_when_index_errors_is_false",
"tests/test_schema.py::test_dump_returns_a_marshalresult",
"tests/test_schema.py::test_dumps_returns_a_marshalresult",
"tests/test_schema.py::test_dumping_single_object_with_collection_schema",
"tests/test_schema.py::test_loading_single_object_with_collection_schema",
"tests/test_schema.py::test_dumps_many",
"tests/test_schema.py::test_load_returns_an_unmarshalresult",
"tests/test_schema.py::test_load_many",
"tests/test_schema.py::test_loads_returns_an_unmarshalresult",
"tests/test_schema.py::test_loads_many",
"tests/test_schema.py::test_loads_deserializes_from_json",
"tests/test_schema.py::test_serializing_none",
"tests/test_schema.py::test_default_many_symmetry",
"tests/test_schema.py::test_on_bind_field_hook",
"tests/test_schema.py::TestValidate::test_validate_returns_errors_dict",
"tests/test_schema.py::TestValidate::test_validate_many",
"tests/test_schema.py::TestValidate::test_validate_many_doesnt_store_index_if_index_errors_option_is_false",
"tests/test_schema.py::TestValidate::test_validate_strict",
"tests/test_schema.py::TestValidate::test_validate_required",
"tests/test_schema.py::test_fields_are_not_copies[UserSchema]",
"tests/test_schema.py::test_fields_are_not_copies[UserMetaSchema]",
"tests/test_schema.py::test_dumps_returns_json",
"tests/test_schema.py::test_naive_datetime_field",
"tests/test_schema.py::test_datetime_formatted_field",
"tests/test_schema.py::test_datetime_iso_field",
"tests/test_schema.py::test_tz_datetime_field",
"tests/test_schema.py::test_local_datetime_field",
"tests/test_schema.py::test_class_variable",
"tests/test_schema.py::test_serialize_many[UserSchema]",
"tests/test_schema.py::test_serialize_many[UserMetaSchema]",
"tests/test_schema.py::test_inheriting_schema",
"tests/test_schema.py::test_custom_field",
"tests/test_schema.py::test_url_field",
"tests/test_schema.py::test_relative_url_field",
"tests/test_schema.py::test_stores_invalid_url_error[UserSchema]",
"tests/test_schema.py::test_stores_invalid_url_error[UserMetaSchema]",
"tests/test_schema.py::test_email_field[UserSchema]",
"tests/test_schema.py::test_email_field[UserMetaSchema]",
"tests/test_schema.py::test_stored_invalid_email",
"tests/test_schema.py::test_integer_field",
"tests/test_schema.py::test_as_string",
"tests/test_schema.py::test_extra",
"tests/test_schema.py::test_extra_many",
"tests/test_schema.py::test_method_field[UserSchema]",
"tests/test_schema.py::test_method_field[UserMetaSchema]",
"tests/test_schema.py::test_function_field",
"tests/test_schema.py::test_prefix[UserSchema]",
"tests/test_schema.py::test_prefix[UserMetaSchema]",
"tests/test_schema.py::test_fields_must_be_declared_as_instances",
"tests/test_schema.py::test_serializing_generator[UserSchema]",
"tests/test_schema.py::test_serializing_generator[UserMetaSchema]",
"tests/test_schema.py::test_serializing_empty_list_returns_empty_list",
"tests/test_schema.py::test_serializing_dict",
"tests/test_schema.py::test_serializing_dict_with_meta_fields",
"tests/test_schema.py::test_exclude_in_init[UserSchema]",
"tests/test_schema.py::test_exclude_in_init[UserMetaSchema]",
"tests/test_schema.py::test_only_in_init[UserSchema]",
"tests/test_schema.py::test_only_in_init[UserMetaSchema]",
"tests/test_schema.py::test_invalid_only_param",
"tests/test_schema.py::test_can_serialize_uuid",
"tests/test_schema.py::test_can_serialize_time",
"tests/test_schema.py::test_invalid_time",
"tests/test_schema.py::test_invalid_date",
"tests/test_schema.py::test_invalid_email",
"tests/test_schema.py::test_invalid_url",
"tests/test_schema.py::test_invalid_dict_but_okay",
"tests/test_schema.py::test_custom_json",
"tests/test_schema.py::test_custom_error_message",
"tests/test_schema.py::test_load_errors_with_many",
"tests/test_schema.py::test_error_raised_if_fields_option_is_not_list",
"tests/test_schema.py::test_error_raised_if_additional_option_is_not_list",
"tests/test_schema.py::test_only_and_exclude",
"tests/test_schema.py::test_exclude_invalid_attribute",
"tests/test_schema.py::test_only_with_invalid_attribute",
"tests/test_schema.py::test_only_bounded_by_fields",
"tests/test_schema.py::test_nested_only_and_exclude",
"tests/test_schema.py::test_nested_with_sets",
"tests/test_schema.py::test_meta_serializer_fields",
"tests/test_schema.py::test_meta_fields_mapping",
"tests/test_schema.py::test_meta_field_not_on_obj_raises_attribute_error",
"tests/test_schema.py::test_exclude_fields",
"tests/test_schema.py::test_fields_option_must_be_list_or_tuple",
"tests/test_schema.py::test_exclude_option_must_be_list_or_tuple",
"tests/test_schema.py::test_dateformat_option",
"tests/test_schema.py::test_default_dateformat",
"tests/test_schema.py::test_inherit_meta",
"tests/test_schema.py::test_inherit_meta_override",
"tests/test_schema.py::test_additional",
"tests/test_schema.py::test_cant_set_both_additional_and_fields",
"tests/test_schema.py::test_serializing_none_meta",
"tests/test_schema.py::TestErrorHandler::test_error_handler_decorator_is_deprecated",
"tests/test_schema.py::TestErrorHandler::test_dump_with_custom_error_handler",
"tests/test_schema.py::TestErrorHandler::test_load_with_custom_error_handler",
"tests/test_schema.py::TestErrorHandler::test_load_with_custom_error_handler_and_partially_valid_data",
"tests/test_schema.py::TestErrorHandler::test_custom_error_handler_with_validates_decorator",
"tests/test_schema.py::TestErrorHandler::test_custom_error_handler_with_validates_schema_decorator",
"tests/test_schema.py::TestErrorHandler::test_validate_with_custom_error_handler",
"tests/test_schema.py::TestFieldValidation::test_errors_are_cleared_after_loading_collection",
"tests/test_schema.py::TestFieldValidation::test_raises_error_with_list",
"tests/test_schema.py::TestFieldValidation::test_raises_error_with_dict",
"tests/test_schema.py::test_schema_repr",
"tests/test_schema.py::TestNestedSchema::test_flat_nested",
"tests/test_schema.py::TestNestedSchema::test_nested_many_with_missing_attribute",
"tests/test_schema.py::TestNestedSchema::test_nested_with_attribute_none",
"tests/test_schema.py::TestNestedSchema::test_flat_nested2",
"tests/test_schema.py::TestNestedSchema::test_nested_field_does_not_validate_required",
"tests/test_schema.py::TestNestedSchema::test_nested_none",
"tests/test_schema.py::TestNestedSchema::test_nested",
"tests/test_schema.py::TestNestedSchema::test_nested_many_fields",
"tests/test_schema.py::TestNestedSchema::test_nested_meta_many",
"tests/test_schema.py::TestNestedSchema::test_nested_only",
"tests/test_schema.py::TestNestedSchema::test_exclude",
"tests/test_schema.py::TestNestedSchema::test_list_field",
"tests/test_schema.py::TestNestedSchema::test_nested_load_many",
"tests/test_schema.py::TestNestedSchema::test_nested_errors",
"tests/test_schema.py::TestNestedSchema::test_nested_strict",
"tests/test_schema.py::TestNestedSchema::test_nested_method_field",
"tests/test_schema.py::TestNestedSchema::test_nested_function_field",
"tests/test_schema.py::TestNestedSchema::test_nested_prefixed_field",
"tests/test_schema.py::TestNestedSchema::test_nested_prefixed_many_field",
"tests/test_schema.py::TestNestedSchema::test_invalid_float_field",
"tests/test_schema.py::TestNestedSchema::test_serializer_meta_with_nested_fields",
"tests/test_schema.py::TestNestedSchema::test_serializer_with_nested_meta_fields",
"tests/test_schema.py::TestNestedSchema::test_nested_fields_must_be_passed_a_serializer",
"tests/test_schema.py::TestNestedSchema::test_invalid_type_passed_to_nested_field",
"tests/test_schema.py::TestNestedSchema::test_missing_required_nested_field",
"tests/test_schema.py::TestSelfReference::test_nesting_schema_within_itself",
"tests/test_schema.py::TestSelfReference::test_nesting_schema_by_passing_class_name",
"tests/test_schema.py::TestSelfReference::test_nesting_within_itself_meta",
"tests/test_schema.py::TestSelfReference::test_recursive_missing_required_field",
"tests/test_schema.py::TestSelfReference::test_recursive_missing_required_field_one_level_in",
"tests/test_schema.py::TestSelfReference::test_nested_self_with_only_param",
"tests/test_schema.py::TestSelfReference::test_multiple_nested_self_fields",
"tests/test_schema.py::TestSelfReference::test_nested_many",
"tests/test_schema.py::test_serialization_with_required_field",
"tests/test_schema.py::test_deserialization_with_required_field",
"tests/test_schema.py::test_deserialization_with_required_field_and_custom_validator",
"tests/test_schema.py::TestContext::test_context_method",
"tests/test_schema.py::TestContext::test_context_method_function",
"tests/test_schema.py::TestContext::test_function_field_raises_error_when_context_not_available",
"tests/test_schema.py::TestContext::test_fields_context",
"tests/test_schema.py::TestContext::test_nested_fields_inherit_context",
"tests/test_schema.py::test_serializer_can_specify_nested_object_as_attribute",
"tests/test_schema.py::TestFieldInheritance::test_inherit_fields_from_schema_subclass",
"tests/test_schema.py::TestFieldInheritance::test_inherit_fields_from_non_schema_subclass",
"tests/test_schema.py::TestFieldInheritance::test_inheritance_follows_mro",
"tests/test_schema.py::TestAccessor::test_accessor_decorator_is_deprecated",
"tests/test_schema.py::TestAccessor::test_accessor_is_used",
"tests/test_schema.py::TestAccessor::test_accessor_with_many",
"tests/test_schema.py::TestRequiredFields::test_required_string_field_missing",
"tests/test_schema.py::TestRequiredFields::test_required_string_field_failure",
"tests/test_schema.py::TestRequiredFields::test_allow_none_param",
"tests/test_schema.py::TestRequiredFields::test_allow_none_custom_message",
"tests/test_schema.py::TestDefaults::test_missing_inputs_are_excluded_from_dump_output",
"tests/test_schema.py::TestDefaults::test_none_is_serialized_to_none",
"tests/test_schema.py::TestDefaults::test_default_and_value_missing",
"tests/test_schema.py::TestDefaults::test_loading_none",
"tests/test_schema.py::TestDefaults::test_missing_inputs_are_excluded_from_load_output",
"tests/test_schema.py::TestLoadOnly::test_load_only",
"tests/test_schema.py::TestLoadOnly::test_dump_only"
] | [] | MIT License | 266 |
sympy__sympy-10004 | b740702f753d17b88579ea3160c3e89780cd346b | 2015-10-19 13:52:59 | 0241b35cae5f2adc04dc37b25f7dc9c5f00bd746 | diff --git a/sympy/stats/crv.py b/sympy/stats/crv.py
index 292427da84..fe2fd5e221 100644
--- a/sympy/stats/crv.py
+++ b/sympy/stats/crv.py
@@ -300,6 +300,9 @@ def probability(self, condition, **kwargs):
rv = [rv for rv in self.values if rv.symbol == domain.symbol][0]
# Integrate out all other random variables
pdf = self.compute_density(rv, **kwargs)
+ # return S.Zero if `domain` is empty set
+ if domain.set is S.EmptySet:
+ return S.Zero
# Integrate out the last variable over the special domain
return Integral(pdf(z), (z, domain.set), **kwargs)
| P(X < -1) of ExponentialDistribution
```
>>> from sympy import *
>>> from sympy.stats import Exponential, Gamma, P, pspace, Normal, Uniform
>>> X = Exponential('X', 3)
>>> P(X < -1)
AttributeError Traceback (most recent call last)
<ipython-input-168-7d38f8bb52c5> in <module>()
----> 1 P(X < -1)
/home/gxyd/Public/sympy/sympy/stats/rv.py in probability(condition, given_condition, numsamples, evaluate, **kwargs)
621 result = pspace(condition).probability(condition, **kwargs)
622 if evaluate and hasattr(result, 'doit'):
--> 623 return result.doit()
624 else:
625 return result
/home/gxyd/Public/sympy/sympy/integrals/integrals.py in doit(self, **hints)
525 else:
526 try:
--> 527 function = antideriv._eval_interval(x, a, b)
528 except NotImplementedError:
529 # This can happen if _eval_interval depends in a
/home/gxyd/Public/sympy/sympy/core/expr.py in _eval_interval(self, x, a, b)
778 B = 0
779 else:
--> 780 B = self.subs(x, b)
781 if B.has(S.NaN, S.Infinity, S.NegativeInfinity, S.ComplexInfinity):
782 B = limit(self, x, b)
/home/gxyd/Public/sympy/sympy/core/basic.py in subs(self, *args, **kwargs)
893 rv = self
894 for old, new in sequence:
--> 895 rv = rv._subs(old, new, **kwargs)
896 if not isinstance(rv, Basic):
897 break
/home/gxyd/Public/sympy/sympy/core/cache.py in wrapper(*args, **kwargs)
91 def wrapper(*args, **kwargs):
92 try:
---> 93 retval = cfunc(*args, **kwargs)
94 except TypeError:
95 retval = func(*args, **kwargs)
/usr/lib/python3.4/functools.py in wrapper(*args, **kwds)
470 hits += 1
471 return result
--> 472 result = user_function(*args, **kwds)
473 with lock:
474 if key in cache:
/home/gxyd/Public/sympy/sympy/core/basic.py in _subs(self, old, new, **hints)
1007 rv = self._eval_subs(old, new)
1008 if rv is None:
-> 1009 rv = fallback(self, old, new)
1010 return rv
1011
/home/gxyd/Public/sympy/sympy/core/basic.py in fallback(self, old, new)
979 if not hasattr(arg, '_eval_subs'):
980 continue
--> 981 arg = arg._subs(old, new, **hints)
982 if not _aresame(arg, args[i]):
983 hit = True
/home/gxyd/Public/sympy/sympy/core/cache.py in wrapper(*args, **kwargs)
91 def wrapper(*args, **kwargs):
92 try:
---> 93 retval = cfunc(*args, **kwargs)
94 except TypeError:
95 retval = func(*args, **kwargs)
/usr/lib/python3.4/functools.py in wrapper(*args, **kwds)
470 hits += 1
471 return result
--> 472 result = user_function(*args, **kwds)
473 with lock:
474 if key in cache:
/home/gxyd/Public/sympy/sympy/core/basic.py in _subs(self, old, new, **hints)
1007 rv = self._eval_subs(old, new)
1008 if rv is None:
-> 1009 rv = fallback(self, old, new)
1010 return rv
1011
/home/gxyd/Public/sympy/sympy/core/basic.py in fallback(self, old, new)
979 if not hasattr(arg, '_eval_subs'):
980 continue
--> 981 arg = arg._subs(old, new, **hints)
982 if not _aresame(arg, args[i]):
983 hit = True
/home/gxyd/Public/sympy/sympy/core/cache.py in wrapper(*args, **kwargs)
91 def wrapper(*args, **kwargs):
92 try:
---> 93 retval = cfunc(*args, **kwargs)
94 except TypeError:
95 retval = func(*args, **kwargs)
/usr/lib/python3.4/functools.py in wrapper(*args, **kwds)
470 hits += 1
471 return result
--> 472 result = user_function(*args, **kwds)
473 with lock:
474 if key in cache:
/home/gxyd/Public/sympy/sympy/core/basic.py in _subs(self, old, new, **hints)
1007 rv = self._eval_subs(old, new)
1008 if rv is None:
-> 1009 rv = fallback(self, old, new)
1010 return rv
1011
/home/gxyd/Public/sympy/sympy/core/basic.py in fallback(self, old, new)
984 args[i] = arg
985 if hit:
--> 986 rv = self.func(*args)
987 hack2 = hints.get('hack2', False)
988 if hack2 and self.is_Mul and not rv.is_Mul: # 2-arg hack
/home/gxyd/Public/sympy/sympy/core/cache.py in wrapper(*args, **kwargs)
91 def wrapper(*args, **kwargs):
92 try:
---> 93 retval = cfunc(*args, **kwargs)
94 except TypeError:
95 retval = func(*args, **kwargs)
/usr/lib/python3.4/functools.py in wrapper(*args, **kwds)
470 hits += 1
471 return result
--> 472 result = user_function(*args, **kwds)
473 with lock:
474 if key in cache:
/home/gxyd/Public/sympy/sympy/core/operations.py in __new__(cls, *args, **options)
39 return args[0]
40
---> 41 c_part, nc_part, order_symbols = cls.flatten(args)
42 is_commutative = not nc_part
43 obj = cls._from_args(c_part + nc_part, is_commutative)
/home/gxyd/Public/sympy/sympy/core/mul.py in flatten(cls, seq)
179 assert not a is S.One
180 if not a.is_zero and a.is_Rational:
--> 181 r, b = b.as_coeff_Mul()
182 if b.is_Add:
183 if r is not S.One: # 2-arg hack
AttributeError: 'EmptySet' object has no attribute 'as_coeff_Mul'
```
I guess this should return `S.Zero`, instead of an `AttributeError`. | sympy/sympy | diff --git a/sympy/stats/tests/test_continuous_rv.py b/sympy/stats/tests/test_continuous_rv.py
index 2ee455c1c1..05f5400293 100644
--- a/sympy/stats/tests/test_continuous_rv.py
+++ b/sympy/stats/tests/test_continuous_rv.py
@@ -633,3 +633,10 @@ def test_difficult_univariate():
assert density(x**3)
assert density(exp(x**2))
assert density(log(x))
+
+
+def test_issue_10003():
+ X = Exponential('x', 3)
+ G = Gamma('g', 1, 2)
+ assert P(X < -1) == S.Zero
+ assert P(G < -1) == S.Zero
| {
"commit_name": "head_commit",
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true,
"llm_score": {
"difficulty_score": 0,
"issue_text_score": 0,
"test_score": 1
},
"num_modified_files": 1
} | 0.7 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[dev]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"mpmath>=0.19",
"pytest",
"pytest-cov",
"pytest-xdist",
"pytest-mock",
"pytest-asyncio"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.7",
"reqs_path": [
"requirements/base.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | certifi @ file:///croot/certifi_1671487769961/work/certifi
coverage==7.2.7
exceptiongroup==1.2.2
execnet==2.0.2
importlib-metadata==6.7.0
iniconfig==2.0.0
mpmath==1.3.0
packaging==24.0
pluggy==1.2.0
pytest==7.4.4
pytest-asyncio==0.21.2
pytest-cov==4.1.0
pytest-mock==3.11.1
pytest-xdist==3.5.0
-e git+https://github.com/sympy/sympy.git@b740702f753d17b88579ea3160c3e89780cd346b#egg=sympy
tomli==2.0.1
typing_extensions==4.7.1
zipp==3.15.0
| name: sympy
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2022.12.7=py37h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- pip=22.3.1=py37h06a4308_0
- python=3.7.16=h7a1cb2a_0
- readline=8.2=h5eee18b_0
- setuptools=65.6.3=py37h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- wheel=0.38.4=py37h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- coverage==7.2.7
- exceptiongroup==1.2.2
- execnet==2.0.2
- importlib-metadata==6.7.0
- iniconfig==2.0.0
- mpmath==1.3.0
- packaging==24.0
- pluggy==1.2.0
- pytest==7.4.4
- pytest-asyncio==0.21.2
- pytest-cov==4.1.0
- pytest-mock==3.11.1
- pytest-xdist==3.5.0
- tomli==2.0.1
- typing-extensions==4.7.1
- zipp==3.15.0
prefix: /opt/conda/envs/sympy
| [
"sympy/stats/tests/test_continuous_rv.py::test_issue_10003"
] | [
"sympy/stats/tests/test_continuous_rv.py::test_conditional_1d",
"sympy/stats/tests/test_continuous_rv.py::test_triangular",
"sympy/stats/tests/test_continuous_rv.py::test_uniformsum",
"sympy/stats/tests/test_continuous_rv.py::test_unevaluated"
] | [
"sympy/stats/tests/test_continuous_rv.py::test_single_normal",
"sympy/stats/tests/test_continuous_rv.py::test_ContinuousDomain",
"sympy/stats/tests/test_continuous_rv.py::test_multiple_normal",
"sympy/stats/tests/test_continuous_rv.py::test_symbolic",
"sympy/stats/tests/test_continuous_rv.py::test_cdf",
"sympy/stats/tests/test_continuous_rv.py::test_sample",
"sympy/stats/tests/test_continuous_rv.py::test_ContinuousRV",
"sympy/stats/tests/test_continuous_rv.py::test_arcsin",
"sympy/stats/tests/test_continuous_rv.py::test_benini",
"sympy/stats/tests/test_continuous_rv.py::test_beta",
"sympy/stats/tests/test_continuous_rv.py::test_betaprime",
"sympy/stats/tests/test_continuous_rv.py::test_cauchy",
"sympy/stats/tests/test_continuous_rv.py::test_chi",
"sympy/stats/tests/test_continuous_rv.py::test_chi_noncentral",
"sympy/stats/tests/test_continuous_rv.py::test_chi_squared",
"sympy/stats/tests/test_continuous_rv.py::test_dagum",
"sympy/stats/tests/test_continuous_rv.py::test_erlang",
"sympy/stats/tests/test_continuous_rv.py::test_exponential",
"sympy/stats/tests/test_continuous_rv.py::test_f_distribution",
"sympy/stats/tests/test_continuous_rv.py::test_fisher_z",
"sympy/stats/tests/test_continuous_rv.py::test_frechet",
"sympy/stats/tests/test_continuous_rv.py::test_gamma",
"sympy/stats/tests/test_continuous_rv.py::test_gamma_inverse",
"sympy/stats/tests/test_continuous_rv.py::test_kumaraswamy",
"sympy/stats/tests/test_continuous_rv.py::test_laplace",
"sympy/stats/tests/test_continuous_rv.py::test_logistic",
"sympy/stats/tests/test_continuous_rv.py::test_lognormal",
"sympy/stats/tests/test_continuous_rv.py::test_maxwell",
"sympy/stats/tests/test_continuous_rv.py::test_nakagami",
"sympy/stats/tests/test_continuous_rv.py::test_pareto",
"sympy/stats/tests/test_continuous_rv.py::test_pareto_numeric",
"sympy/stats/tests/test_continuous_rv.py::test_raised_cosine",
"sympy/stats/tests/test_continuous_rv.py::test_rayleigh",
"sympy/stats/tests/test_continuous_rv.py::test_studentt",
"sympy/stats/tests/test_continuous_rv.py::test_quadratic_u",
"sympy/stats/tests/test_continuous_rv.py::test_uniform",
"sympy/stats/tests/test_continuous_rv.py::test_uniform_P",
"sympy/stats/tests/test_continuous_rv.py::test_von_mises",
"sympy/stats/tests/test_continuous_rv.py::test_weibull",
"sympy/stats/tests/test_continuous_rv.py::test_weibull_numeric",
"sympy/stats/tests/test_continuous_rv.py::test_wignersemicircle",
"sympy/stats/tests/test_continuous_rv.py::test_prefab_sampling",
"sympy/stats/tests/test_continuous_rv.py::test_input_value_assertions",
"sympy/stats/tests/test_continuous_rv.py::test_probability_unevaluated",
"sympy/stats/tests/test_continuous_rv.py::test_density_unevaluated",
"sympy/stats/tests/test_continuous_rv.py::test_NormalDistribution",
"sympy/stats/tests/test_continuous_rv.py::test_random_parameters",
"sympy/stats/tests/test_continuous_rv.py::test_random_parameters_given",
"sympy/stats/tests/test_continuous_rv.py::test_conjugate_priors",
"sympy/stats/tests/test_continuous_rv.py::test_difficult_univariate"
] | [] | BSD | 267 |
|
sympy__sympy-10009 | aab1ba97bd3fa1c411f77ee7f652edcaca24327e | 2015-10-20 09:54:10 | 0241b35cae5f2adc04dc37b25f7dc9c5f00bd746 | asmeurer: Does this fix the original issue in #9567 as well?
asmeurer: I don't understand what solve_linear does, but if it fixes the issue then +1.
smichr: I showed on the issue page that the reported issue returns correctly.
As for solve_linear, it is trying to solve for a linear variable and also report (early in the solve process) if there is no solution possible (like when a variable appears in an expression but actually cancels after simplification).
I can't believe we didn't see this error earlier.
asmeurer: I guess what I don't understand is why it sometimes returns a solution and sometimes returns the numerator and denominator.
smichr: > why it sometimes returns a solution and sometimes returns the numerator and denominator
it should probably have been a private function of solve; I think the original idea was to not throw away the extracted numerator which is needed for the more extended work of solve. Since the function was returning 2 values when it found a solution it made sense to return the denominator with the numerator, too, so 2 values would be returned when there wasn't a linear solution. | diff --git a/sympy/core/mod.py b/sympy/core/mod.py
index f31e75d4f8..4d58ebde75 100644
--- a/sympy/core/mod.py
+++ b/sympy/core/mod.py
@@ -36,7 +36,7 @@ def doit(p, q):
to be less than or equal q.
"""
- if p.is_infinite or q.is_infinite or p is nan or q is nan:
+ if p.is_infinite or q.is_infinite:
return nan
if (p == q or p == -q or
p.is_Pow and p.exp.is_Integer and p.base == q or
diff --git a/sympy/geometry/polygon.py b/sympy/geometry/polygon.py
index fbc93fbaf0..24a4e90960 100644
--- a/sympy/geometry/polygon.py
+++ b/sympy/geometry/polygon.py
@@ -516,7 +516,7 @@ def encloses_point(self, p):
References
==========
- [1] http://paulbourke.net/geometry/polygonmesh/#insidepoly
+ [1] http://www.ariel.com.au/a/python-point-int-poly.html
"""
p = Point(p)
@@ -559,8 +559,8 @@ def encloses_point(self, p):
if 0 <= max(p1x, p2x):
if p1y != p2y:
xinters = (-p1y)*(p2x - p1x)/(p2y - p1y) + p1x
- if p1x == p2x or 0 <= xinters:
- hit_odd = not hit_odd
+ if p1x == p2x or 0 <= xinters:
+ hit_odd = not hit_odd
p1x, p1y = p2x, p2y
return hit_odd
diff --git a/sympy/solvers/solvers.py b/sympy/solvers/solvers.py
index f9283083ed..f2c3fd2446 100644
--- a/sympy/solvers/solvers.py
+++ b/sympy/solvers/solvers.py
@@ -1271,17 +1271,18 @@ def _solve(f, *symbols, **flags):
got_s = set([])
result = []
for s in symbols:
- n, d = solve_linear(f, symbols=[s])
- if n.is_Symbol:
+ xi, v = solve_linear(f, symbols=[s])
+ if xi == s:
# no need to check but we should simplify if desired
if flags.get('simplify', True):
- d = simplify(d)
- if got_s and any([ss in d.free_symbols for ss in got_s]):
+ v = simplify(v)
+ vfree = v.free_symbols
+ if got_s and any([ss in vfree for ss in got_s]):
# sol depends on previously solved symbols: discard it
continue
- got_s.add(n)
- result.append({n: d})
- elif n and d: # otherwise there was no solution for s
+ got_s.add(xi)
+ result.append({xi: v})
+ elif xi: # there might be a non-linear solution if xi is not 0
failed.append(s)
if not failed:
return result
@@ -1329,7 +1330,7 @@ def _solve(f, *symbols, **flags):
elif f.is_Piecewise:
result = set()
for n, (expr, cond) in enumerate(f.args):
- candidates = _solve(expr, *symbols, **flags)
+ candidates = _solve(expr, symbol, **flags)
for candidate in candidates:
if candidate in result:
continue
@@ -1363,9 +1364,9 @@ def _solve(f, *symbols, **flags):
check = False
else:
# first see if it really depends on symbol and whether there
- # is a linear solution
+ # is only a linear solution
f_num, sol = solve_linear(f, symbols=symbols)
- if not symbol in f_num.free_symbols:
+ if f_num is S.Zero:
return []
elif f_num.is_Symbol:
# no need to check but simplify if desired
@@ -1821,36 +1822,52 @@ def _ok_syms(e, sort=False):
def solve_linear(lhs, rhs=0, symbols=[], exclude=[]):
- r""" Return a tuple derived from f = lhs - rhs that is either:
+ r""" Return a tuple derived from f = lhs - rhs that is one of
+ the following:
+
+ (0, 1) meaning that ``f`` is independent of the symbols in
+ ``symbols`` that aren't in ``exclude``, e.g::
+
+ >>> from sympy.solvers.solvers import solve_linear
+ >>> from sympy.abc import x, y, z
+ >>> from sympy import cos, sin
+ >>> eq = y*cos(x)**2 + y*sin(x)**2 - y # = y*(1 - 1) = 0
+ >>> solve_linear(eq)
+ (0, 1)
+ >>> eq = cos(x)**2 + sin(x)**2 # = 1
+ >>> solve_linear(eq)
+ (0, 1)
+ >>> solve_linear(x, exclude=[x])
+ (0, 1)
+
+ (0, 0) meaning that there is no solution to the equation
+ amongst the symbols given.
+
+ (If the first element of the tuple is not zero then
+ the function is guaranteed to be dependent on a symbol
+ in ``symbols``.)
+
+ (symbol, solution) where symbol appears linearly in the
+ numerator of ``f``, is in ``symbols`` (if given) and is
+ not in ``exclude`` (if given). No simplification is done
+ to ``f`` other than a ``mul=True`` expansion, so the
+ solution will correspond strictly to a unique solution.
+
+ ``(n, d)`` where ``n`` and ``d`` are the numerator and
+ denominator of ``f`` when the numerator was not linear
+ in any symbol of interest; ``n`` will never be a symbol
+ unless a solution for that symbol was found (in which case
+ the second element is the solution, not the denominator).
- (numerator, denominator) of ``f``
- If this comes back as (0, 1) it means
- that ``f`` is independent of the symbols in ``symbols``, e.g::
-
- y*cos(x)**2 + y*sin(x)**2 - y = y*(0) = 0
- cos(x)**2 + sin(x)**2 = 1
-
- If it comes back as (0, 0) there is no solution to the equation
- amongst the symbols given.
-
- If the numerator is not zero then the function is guaranteed
- to be dependent on a symbol in ``symbols``.
-
- or
-
- (symbol, solution) where symbol appears linearly in the numerator of
- ``f``, is in ``symbols`` (if given) and is not in ``exclude`` (if given).
-
- No simplification is done to ``f`` other than and mul=True expansion,
- so the solution will correspond strictly to a unique solution.
Examples
========
- >>> from sympy.solvers.solvers import solve_linear
- >>> from sympy.abc import x, y, z
+ >>> from sympy.core.power import Pow
+ >>> from sympy.polys.polytools import cancel
- These are linear in x and 1/x:
+ The variable ``x`` appears as a linear variable in each of the
+ following:
>>> solve_linear(x + y**2)
(x, -y**2)
@@ -1862,34 +1879,53 @@ def solve_linear(lhs, rhs=0, symbols=[], exclude=[]):
>>> solve_linear(x**2/y**2 - 3)
(x**2 - 3*y**2, y**2)
- If the numerator is a symbol then (0, 0) is returned if the solution for
- that symbol would have set any denominator to 0:
+ If the numerator of the expression is a symbol then (0, 0) is
+ returned if the solution for that symbol would have set any
+ denominator to 0:
- >>> solve_linear(1/(1/x - 2))
+ >>> eq = 1/(1/x - 2)
+ >>> eq.as_numer_denom()
+ (x, -2*x + 1)
+ >>> solve_linear(eq)
(0, 0)
- >>> 1/(1/x) # to SymPy, this looks like x ...
+
+ But automatic rewriting may cause a symbol in the denominator to
+ appear in the numerator so a solution will be returned:
+
+ >>> (1/x)**-1
x
- >>> solve_linear(1/(1/x)) # so a solution is given
+ >>> solve_linear((1/x)**-1)
(x, 0)
- If x is allowed to cancel, then this appears linear, but this sort of
- cancellation is not done so the solution will always satisfy the original
- expression without causing a division by zero error.
+ Use an unevaluated expression to avoid this:
- >>> solve_linear(x**2*(1/x - z**2/x))
+ >>> solve_linear(Pow(1/x, -1, evaluate=False))
+ (0, 0)
+
+ If ``x`` is allowed to cancel in the following expression, then it
+ appears to be linear in ``x``, but this sort of cancellation is not
+ done by ``solve_linear`` so the solution will always satisfy the
+ original expression without causing a division by zero error.
+
+ >>> eq = x**2*(1/x - z**2/x)
+ >>> solve_linear(cancel(eq))
+ (x, 0)
+ >>> solve_linear(eq)
(x**2*(-z**2 + 1), x)
- You can give a list of what you prefer for x candidates:
+ A list of symbols for which a solution is desired may be given:
>>> solve_linear(x + y + z, symbols=[y])
(y, -x - z)
- You can also indicate what variables you don't want to consider:
+ A list of symbols to ignore may also be given:
- >>> solve_linear(x + y + z, exclude=[x, z])
+ >>> solve_linear(x + y + z, exclude=[x])
(y, -x - z)
- If only x was excluded then a solution for y or z might be obtained.
+ (A solution for ``y`` is obtained because it is the first variable
+ from the canonically sorted list of symbols that had a linear
+ solution.)
"""
if isinstance(lhs, Equality):
@@ -1922,48 +1958,50 @@ def solve_linear(lhs, rhs=0, symbols=[], exclude=[]):
''' % (bad, eg)))
symbols = free.intersection(symbols)
symbols = symbols.difference(exclude)
+ if not symbols:
+ return S.Zero, S.One
dfree = d.free_symbols
- # derivatives are easy to do but tricky to analyze to see if they are going
- # to disallow a linear solution, so for simplicity we just evaluate the
- # ones that have the symbols of interest
+ # derivatives are easy to do but tricky to analyze to see if they
+ # are going to disallow a linear solution, so for simplicity we
+ # just evaluate the ones that have the symbols of interest
derivs = defaultdict(list)
for der in n.atoms(Derivative):
csym = der.free_symbols & symbols
for c in csym:
derivs[c].append(der)
- if symbols:
- all_zero = True
- for xi in symbols:
- # if there are derivatives in this var, calculate them now
- if type(derivs[xi]) is list:
- derivs[xi] = dict([(der, der.doit()) for der in derivs[xi]])
- nn = n.subs(derivs[xi])
- dn = nn.diff(xi)
- if dn:
- all_zero = False
- if dn is S.NaN:
- break
- if not xi in dn.free_symbols:
- vi = -(nn.subs(xi, 0))/dn
- if dens is None:
- dens = _simple_dens(eq, symbols)
- if not any(checksol(di, {xi: vi}, minimal=True) is True
- for di in dens):
- # simplify any trivial integral
- irep = [(i, i.doit()) for i in vi.atoms(Integral) if
- i.function.is_number]
- # do a slight bit of simplification
- vi = expand_mul(vi.subs(irep))
- if not d.has(xi) or not (d/xi).has(xi):
- return xi, vi
-
- if all_zero:
- return S.Zero, S.One
- if n.is_Symbol: # there was no valid solution
- n = d = S.Zero
- return n, d # should we cancel now?
+ all_zero = True
+ for xi in sorted(symbols, key=default_sort_key): # canonical order
+ # if there are derivatives in this var, calculate them now
+ if type(derivs[xi]) is list:
+ derivs[xi] = dict([(der, der.doit()) for der in derivs[xi]])
+ newn = n.subs(derivs[xi])
+ dnewn_dxi = newn.diff(xi)
+ # dnewn_dxi can be nonzero if it survives differentation by any
+ # of its free symbols
+ free = dnewn_dxi.free_symbols
+ if dnewn_dxi and (not free or any(dnewn_dxi.diff(s) for s in free)):
+ all_zero = False
+ if dnewn_dxi is S.NaN:
+ break
+ if xi not in dnewn_dxi.free_symbols:
+ vi = -(newn.subs(xi, 0))/dnewn_dxi
+ if dens is None:
+ dens = _simple_dens(eq, symbols)
+ if not any(checksol(di, {xi: vi}, minimal=True) is True
+ for di in dens):
+ # simplify any trivial integral
+ irep = [(i, i.doit()) for i in vi.atoms(Integral) if
+ i.function.is_number]
+ # do a slight bit of simplification
+ vi = expand_mul(vi.subs(irep))
+ return xi, vi
+ if all_zero:
+ return S.Zero, S.One
+ if n.is_Symbol: # no solution for this symbol was found
+ return S.Zero, S.Zero
+ return n, d
def minsolve_linear_system(system, *symbols, **flags):
@@ -1971,9 +2009,8 @@ def minsolve_linear_system(system, *symbols, **flags):
Find a particular solution to a linear system.
In particular, try to find a solution with the minimal possible number
- of non-zero variables. This is a very computationally hard prolem.
- If ``quick=True``, a heuristic is used. Otherwise a naive algorithm with
- exponential complexity is used.
+ of non-zero variables using a naive algorithm with exponential complexity.
+ If ``quick=True``, a heuristic is used.
"""
quick = flags.get('quick', False)
# Check if there are any non-zero solutions at all
| solve_univariate_inequality gives wrong solution to the rational inequality abs(1/(x-1)) > 1
In current SymPy (commit c2ffd9), I see
```python
In [1]: x = symbols('x', real=True)
In [2]: from sympy.solvers.solveset import solveset
In [3]: solveset(abs(1/(x-1)) > 1)
Out[3]: (1, 2)
```
while the result should be ```(0, 1) ∪ (1, 2)```.
The following similar case works:
```python
In [4]: solveset(abs(1/x) > 1)
Out[4]: (-1, 0) ∪ (0, 1)
```
@aktech - can you please take a look? | sympy/sympy | diff --git a/sympy/core/tests/test_arit.py b/sympy/core/tests/test_arit.py
index 8c8625ce62..cbc6f77ebd 100644
--- a/sympy/core/tests/test_arit.py
+++ b/sympy/core/tests/test_arit.py
@@ -1502,9 +1502,6 @@ def test_Mod():
assert x % 5 == Mod(x, 5)
assert x % y == Mod(x, y)
assert (x % y).subs({x: 5, y: 3}) == 2
- assert Mod(nan, 1) == nan
- assert Mod(1, nan) == nan
- assert Mod(nan, nan) == nan
# Float handling
point3 = Float(3.3) % 1
diff --git a/sympy/solvers/tests/test_solvers.py b/sympy/solvers/tests/test_solvers.py
index cfd5ca0c74..9aee8f389e 100644
--- a/sympy/solvers/tests/test_solvers.py
+++ b/sympy/solvers/tests/test_solvers.py
@@ -501,6 +501,8 @@ def test_issue_3870():
def test_solve_linear():
w = Wild('w')
assert solve_linear(x, x) == (0, 1)
+ assert solve_linear(x, exclude=[x]) == (0, 1)
+ assert solve_linear(x, symbols=[w]) == (0, 1)
assert solve_linear(x, y - 2*x) in [(x, y/3), (y, 3*x)]
assert solve_linear(x, y - 2*x, exclude=[x]) == (y, 3*x)
assert solve_linear(3*x - y, 0) in [(x, y/3), (y, 3*x)]
@@ -513,10 +515,15 @@ def test_solve_linear():
assert solve_linear(cos(x)**2 + sin(x)**2 + 2 + y, symbols=[x]) == (0, 1)
assert solve_linear(Eq(x, 3)) == (x, 3)
assert solve_linear(1/(1/x - 2)) == (0, 0)
- assert solve_linear((x + 1)*exp(-x), symbols=[x]) == (x + 1, exp(x))
+ assert solve_linear((x + 1)*exp(-x), symbols=[x]) == (x, -1)
assert solve_linear((x + 1)*exp(x), symbols=[x]) == ((x + 1)*exp(x), 1)
- assert solve_linear(x*exp(-x**2), symbols=[x]) == (0, 0)
+ assert solve_linear(x*exp(-x**2), symbols=[x]) == (x, 0)
assert solve_linear(0**x - 1) == (0**x - 1, 1)
+ assert solve_linear(1 + 1/(x - 1)) == (x, 0)
+ eq = y*cos(x)**2 + y*sin(x)**2 - y # = y*(1 - 1) = 0
+ assert solve_linear(eq) == (0, 1)
+ eq = cos(x)**2 + sin(x)**2 # = 1
+ assert solve_linear(eq) == (0, 1)
raises(ValueError, lambda: solve_linear(Eq(x, 3), 3))
@@ -1771,3 +1778,7 @@ def test_issue_2840_8155():
assert solve(2*sin(x) - 2*sin(2*x)) == [
0, -pi, pi, -2*I*log(-sqrt(3)/2 - I/2), -2*I*log(-sqrt(3)/2 + I/2),
-2*I*log(sqrt(3)/2 - I/2), -2*I*log(sqrt(3)/2 + I/2)]
+
+
+def test_issue_9567():
+ assert solve(1 + 1/(x - 1)) == [0]
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 1,
"issue_text_score": 0,
"test_score": 3
},
"num_modified_files": 3
} | 0.7 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "pytest",
"pip_packages": [
"pytest"
],
"pre_install": null,
"python": "3.7",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | attrs @ file:///croot/attrs_1668696182826/work
certifi @ file:///croot/certifi_1671487769961/work/certifi
flit_core @ file:///opt/conda/conda-bld/flit-core_1644941570762/work/source/flit_core
importlib-metadata @ file:///tmp/build/80754af9/importlib-metadata_1648562407465/work
iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work
mpmath==1.3.0
packaging @ file:///croot/packaging_1671697413597/work
pluggy @ file:///tmp/build/80754af9/pluggy_1648042572264/work
py @ file:///opt/conda/conda-bld/py_1644396412707/work
pytest==7.1.2
-e git+https://github.com/sympy/sympy.git@aab1ba97bd3fa1c411f77ee7f652edcaca24327e#egg=sympy
tomli @ file:///opt/conda/conda-bld/tomli_1657175507142/work
typing_extensions @ file:///croot/typing_extensions_1669924550328/work
zipp @ file:///croot/zipp_1672387121353/work
| name: sympy
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- attrs=22.1.0=py37h06a4308_0
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2022.12.7=py37h06a4308_0
- flit-core=3.6.0=pyhd3eb1b0_0
- importlib-metadata=4.11.3=py37h06a4308_0
- importlib_metadata=4.11.3=hd3eb1b0_0
- iniconfig=1.1.1=pyhd3eb1b0_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- packaging=22.0=py37h06a4308_0
- pip=22.3.1=py37h06a4308_0
- pluggy=1.0.0=py37h06a4308_1
- py=1.11.0=pyhd3eb1b0_0
- pytest=7.1.2=py37h06a4308_0
- python=3.7.16=h7a1cb2a_0
- readline=8.2=h5eee18b_0
- setuptools=65.6.3=py37h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- tomli=2.0.1=py37h06a4308_0
- typing_extensions=4.4.0=py37h06a4308_0
- wheel=0.38.4=py37h06a4308_0
- xz=5.6.4=h5eee18b_1
- zipp=3.11.0=py37h06a4308_0
- zlib=1.2.13=h5eee18b_1
- pip:
- mpmath==1.3.0
prefix: /opt/conda/envs/sympy
| [
"sympy/solvers/tests/test_solvers.py::test_solve_linear",
"sympy/solvers/tests/test_solvers.py::test_issue_9567"
] | [] | [
"sympy/core/tests/test_arit.py::test_bug1",
"sympy/core/tests/test_arit.py::test_Symbol",
"sympy/core/tests/test_arit.py::test_arit0",
"sympy/core/tests/test_arit.py::test_div",
"sympy/core/tests/test_arit.py::test_pow",
"sympy/core/tests/test_arit.py::test_pow2",
"sympy/core/tests/test_arit.py::test_pow3",
"sympy/core/tests/test_arit.py::test_pow_E",
"sympy/core/tests/test_arit.py::test_pow_issue_3516",
"sympy/core/tests/test_arit.py::test_pow_im",
"sympy/core/tests/test_arit.py::test_real_mul",
"sympy/core/tests/test_arit.py::test_ncmul",
"sympy/core/tests/test_arit.py::test_ncpow",
"sympy/core/tests/test_arit.py::test_powerbug",
"sympy/core/tests/test_arit.py::test_Mul_doesnt_expand_exp",
"sympy/core/tests/test_arit.py::test_Add_Mul_is_integer",
"sympy/core/tests/test_arit.py::test_Add_Mul_is_finite",
"sympy/core/tests/test_arit.py::test_Mul_is_even_odd",
"sympy/core/tests/test_arit.py::test_evenness_in_ternary_integer_product_with_even",
"sympy/core/tests/test_arit.py::test_oddness_in_ternary_integer_product_with_even",
"sympy/core/tests/test_arit.py::test_Mul_is_rational",
"sympy/core/tests/test_arit.py::test_Add_is_rational",
"sympy/core/tests/test_arit.py::test_Add_is_even_odd",
"sympy/core/tests/test_arit.py::test_Mul_is_negative_positive",
"sympy/core/tests/test_arit.py::test_Mul_is_negative_positive_2",
"sympy/core/tests/test_arit.py::test_Mul_is_nonpositive_nonnegative",
"sympy/core/tests/test_arit.py::test_Add_is_negative_positive",
"sympy/core/tests/test_arit.py::test_Add_is_nonpositive_nonnegative",
"sympy/core/tests/test_arit.py::test_Pow_is_integer",
"sympy/core/tests/test_arit.py::test_Pow_is_real",
"sympy/core/tests/test_arit.py::test_real_Pow",
"sympy/core/tests/test_arit.py::test_Pow_is_finite",
"sympy/core/tests/test_arit.py::test_Pow_is_even_odd",
"sympy/core/tests/test_arit.py::test_Pow_is_negative_positive",
"sympy/core/tests/test_arit.py::test_Pow_is_zero",
"sympy/core/tests/test_arit.py::test_Pow_is_nonpositive_nonnegative",
"sympy/core/tests/test_arit.py::test_Mul_is_imaginary_real",
"sympy/core/tests/test_arit.py::test_Mul_hermitian_antihermitian",
"sympy/core/tests/test_arit.py::test_Add_is_comparable",
"sympy/core/tests/test_arit.py::test_Mul_is_comparable",
"sympy/core/tests/test_arit.py::test_Pow_is_comparable",
"sympy/core/tests/test_arit.py::test_Add_is_positive_2",
"sympy/core/tests/test_arit.py::test_Add_is_irrational",
"sympy/core/tests/test_arit.py::test_issue_3531b",
"sympy/core/tests/test_arit.py::test_bug3",
"sympy/core/tests/test_arit.py::test_suppressed_evaluation",
"sympy/core/tests/test_arit.py::test_Add_as_coeff_mul",
"sympy/core/tests/test_arit.py::test_Pow_as_coeff_mul_doesnt_expand",
"sympy/core/tests/test_arit.py::test_issue_3514",
"sympy/core/tests/test_arit.py::test_make_args",
"sympy/core/tests/test_arit.py::test_issue_5126",
"sympy/core/tests/test_arit.py::test_Rational_as_content_primitive",
"sympy/core/tests/test_arit.py::test_Add_as_content_primitive",
"sympy/core/tests/test_arit.py::test_Mul_as_content_primitive",
"sympy/core/tests/test_arit.py::test_Pow_as_content_primitive",
"sympy/core/tests/test_arit.py::test_issue_5460",
"sympy/core/tests/test_arit.py::test_product_irrational",
"sympy/core/tests/test_arit.py::test_issue_5919",
"sympy/core/tests/test_arit.py::test_Mod",
"sympy/core/tests/test_arit.py::test_Mod_is_integer",
"sympy/core/tests/test_arit.py::test_Mod_is_nonposneg",
"sympy/core/tests/test_arit.py::test_issue_6001",
"sympy/core/tests/test_arit.py::test_polar",
"sympy/core/tests/test_arit.py::test_issue_6040",
"sympy/core/tests/test_arit.py::test_issue_6082",
"sympy/core/tests/test_arit.py::test_issue_6077",
"sympy/core/tests/test_arit.py::test_mul_flatten_oo",
"sympy/core/tests/test_arit.py::test_add_flatten",
"sympy/core/tests/test_arit.py::test_issue_5160_6087_6089_6090",
"sympy/core/tests/test_arit.py::test_float_int",
"sympy/core/tests/test_arit.py::test_issue_6611a",
"sympy/core/tests/test_arit.py::test_denest_add_mul",
"sympy/core/tests/test_arit.py::test_mul_coeff",
"sympy/core/tests/test_arit.py::test_mul_zero_detection",
"sympy/core/tests/test_arit.py::test_Mul_with_zero_infinite",
"sympy/core/tests/test_arit.py::test_issue_8247_8354",
"sympy/solvers/tests/test_solvers.py::test_swap_back",
"sympy/solvers/tests/test_solvers.py::test_guess_poly",
"sympy/solvers/tests/test_solvers.py::test_guess_poly_cv",
"sympy/solvers/tests/test_solvers.py::test_guess_rational_cv",
"sympy/solvers/tests/test_solvers.py::test_guess_transcendental",
"sympy/solvers/tests/test_solvers.py::test_solve_args",
"sympy/solvers/tests/test_solvers.py::test_solve_polynomial1",
"sympy/solvers/tests/test_solvers.py::test_solve_polynomial2",
"sympy/solvers/tests/test_solvers.py::test_solve_polynomial_cv_1a",
"sympy/solvers/tests/test_solvers.py::test_solve_polynomial_cv_1b",
"sympy/solvers/tests/test_solvers.py::test_solve_polynomial_cv_2",
"sympy/solvers/tests/test_solvers.py::test_quintics_1",
"sympy/solvers/tests/test_solvers.py::test_highorder_poly",
"sympy/solvers/tests/test_solvers.py::test_quintics_2",
"sympy/solvers/tests/test_solvers.py::test_solve_rational",
"sympy/solvers/tests/test_solvers.py::test_solve_nonlinear",
"sympy/solvers/tests/test_solvers.py::test_issue_8666",
"sympy/solvers/tests/test_solvers.py::test_issue_7228",
"sympy/solvers/tests/test_solvers.py::test_issue_7190",
"sympy/solvers/tests/test_solvers.py::test_linear_system",
"sympy/solvers/tests/test_solvers.py::test_linear_system_function",
"sympy/solvers/tests/test_solvers.py::test_linear_systemLU",
"sympy/solvers/tests/test_solvers.py::test_solve_transcendental",
"sympy/solvers/tests/test_solvers.py::test_solve_for_functions_derivatives",
"sympy/solvers/tests/test_solvers.py::test_issue_3725",
"sympy/solvers/tests/test_solvers.py::test_issue_3870",
"sympy/solvers/tests/test_solvers.py::test_solve_undetermined_coeffs",
"sympy/solvers/tests/test_solvers.py::test_solve_inequalities",
"sympy/solvers/tests/test_solvers.py::test_issue_4793",
"sympy/solvers/tests/test_solvers.py::test_PR1964",
"sympy/solvers/tests/test_solvers.py::test_issue_5197",
"sympy/solvers/tests/test_solvers.py::test_checking",
"sympy/solvers/tests/test_solvers.py::test_issue_4671_4463_4467",
"sympy/solvers/tests/test_solvers.py::test_issue_5132",
"sympy/solvers/tests/test_solvers.py::test_issue_5335",
"sympy/solvers/tests/test_solvers.py::test_issue_5767",
"sympy/solvers/tests/test_solvers.py::test_polysys",
"sympy/solvers/tests/test_solvers.py::test_unrad1",
"sympy/solvers/tests/test_solvers.py::test_unrad_slow",
"sympy/solvers/tests/test_solvers.py::test__invert",
"sympy/solvers/tests/test_solvers.py::test_issue_4463",
"sympy/solvers/tests/test_solvers.py::test_issue_5114",
"sympy/solvers/tests/test_solvers.py::test_issue_5849",
"sympy/solvers/tests/test_solvers.py::test_issue_5849_matrix",
"sympy/solvers/tests/test_solvers.py::test_issue_5901",
"sympy/solvers/tests/test_solvers.py::test_issue_5912",
"sympy/solvers/tests/test_solvers.py::test_float_handling",
"sympy/solvers/tests/test_solvers.py::test_check_assumptions",
"sympy/solvers/tests/test_solvers.py::test_issue_6056",
"sympy/solvers/tests/test_solvers.py::test_issue_6060",
"sympy/solvers/tests/test_solvers.py::test_issue_5673",
"sympy/solvers/tests/test_solvers.py::test_exclude",
"sympy/solvers/tests/test_solvers.py::test_high_order_roots",
"sympy/solvers/tests/test_solvers.py::test_minsolve_linear_system",
"sympy/solvers/tests/test_solvers.py::test_real_roots",
"sympy/solvers/tests/test_solvers.py::test_issue_6528",
"sympy/solvers/tests/test_solvers.py::test_overdetermined",
"sympy/solvers/tests/test_solvers.py::test_issue_6605",
"sympy/solvers/tests/test_solvers.py::test__ispow",
"sympy/solvers/tests/test_solvers.py::test_issue_6644",
"sympy/solvers/tests/test_solvers.py::test_issue_6752",
"sympy/solvers/tests/test_solvers.py::test_issue_6792",
"sympy/solvers/tests/test_solvers.py::test_issues_6819_6820_6821_6248_8692",
"sympy/solvers/tests/test_solvers.py::test_issue_6989",
"sympy/solvers/tests/test_solvers.py::test_lambert_multivariate",
"sympy/solvers/tests/test_solvers.py::test_rewrite_trig",
"sympy/solvers/tests/test_solvers.py::test_uselogcombine",
"sympy/solvers/tests/test_solvers.py::test_atan2",
"sympy/solvers/tests/test_solvers.py::test_errorinverses",
"sympy/solvers/tests/test_solvers.py::test_issue_2725",
"sympy/solvers/tests/test_solvers.py::test_issue_5114_6611",
"sympy/solvers/tests/test_solvers.py::test_det_quick",
"sympy/solvers/tests/test_solvers.py::test_piecewise",
"sympy/solvers/tests/test_solvers.py::test_real_imag_splitting",
"sympy/solvers/tests/test_solvers.py::test_issue_7110",
"sympy/solvers/tests/test_solvers.py::test_units",
"sympy/solvers/tests/test_solvers.py::test_issue_7547",
"sympy/solvers/tests/test_solvers.py::test_issue_7895",
"sympy/solvers/tests/test_solvers.py::test_issue_2777",
"sympy/solvers/tests/test_solvers.py::test_issue_7322",
"sympy/solvers/tests/test_solvers.py::test_nsolve",
"sympy/solvers/tests/test_solvers.py::test_issue_8587",
"sympy/solvers/tests/test_solvers.py::test_high_order_multivariate",
"sympy/solvers/tests/test_solvers.py::test_base_0_exp_0",
"sympy/solvers/tests/test_solvers.py::test__simple_dens",
"sympy/solvers/tests/test_solvers.py::test_issue_8755",
"sympy/solvers/tests/test_solvers.py::test_issue_8828",
"sympy/solvers/tests/test_solvers.py::test_issue_2840_8155"
] | [] | BSD | 268 |
sympy__sympy-10014 | f511df8e8f7f2ee8079981671500201e3c32dc3f | 2015-10-20 20:33:12 | 8bb5814067cfa0348fb8b708848f35dba2b55ff4 | diff --git a/sympy/core/function.py b/sympy/core/function.py
index 94eb5128ff..e1ae71929a 100644
--- a/sympy/core/function.py
+++ b/sympy/core/function.py
@@ -57,7 +57,7 @@
import mpmath.libmp as mlib
import inspect
-
+import collections
def _coeff_isneg(a):
"""Return True if the leading Number is negative.
@@ -1330,31 +1330,18 @@ def _eval_subs(self, old, new):
# equivalent to self or if old is a subderivative of self.
if old.is_Derivative and old.expr == self.args[0]:
# Check if canonnical order of variables is equal.
- old_vars = Derivative._sort_variables(old.variables)
- self_vars = Derivative._sort_variables(self.args[1:])
+ old_vars = collections.Counter(old.variables)
+ self_vars = collections.Counter(self.variables)
if old_vars == self_vars:
return new
- # Check if olf is a subderivative of self.
- if len(old_vars) < len(self_vars):
- self_vars_front = []
- match = True
- while old_vars and self_vars and match:
- if old_vars[0] == self_vars[0]:
- old_vars.pop(0)
- self_vars.pop(0)
- else:
- # If self_v does not match old_v, we need to check if
- # the types are the same (symbol vs non-symbol). If
- # they are, we can continue checking self_vars for a
- # match.
- if old_vars[0].is_Symbol != self_vars[0].is_Symbol:
- match = False
- else:
- self_vars_front.append(self_vars.pop(0))
- if match:
- variables = self_vars_front + self_vars
- return Derivative(new, *variables)
+ # collections.Counter doesn't have __le__
+ def _subset(a, b):
+ return all(a[i] <= b[i] for i in a)
+
+ if _subset(old_vars, self_vars):
+ return Derivative(new, *(self_vars - old_vars).elements())
+
return Derivative(*(x._subs(old, new) for x in self.args))
def _eval_lseries(self, x, logx):
| Incorrect subsitution of partial derivatives by .subs()
With sympy 0.7.6, the subs() method does a wrong substitution:
from sympy import *
init_printing()
x,y,z=symbols('x,y,z')
f=Function('f')
expr = diff(f(x,y),x,x,y)
pprint(expr)
e2 = expr.subs(diff(f(x,y),y,2), z)
pprint(e2)
The call to subs() method incorrectly substitutes a `df/dy` with `z`, while we asked to substitute `d2f/dy2` instead !
| sympy/sympy | diff --git a/sympy/core/tests/test_subs.py b/sympy/core/tests/test_subs.py
index c50890e0a3..f2133a36c3 100644
--- a/sympy/core/tests/test_subs.py
+++ b/sympy/core/tests/test_subs.py
@@ -431,17 +431,27 @@ def test_derivative_subs():
def test_derivative_subs2():
x, y, z = symbols('x y z')
- f, g = symbols('f g', cls=Function)
+ f_func, g_func = symbols('f g', cls=Function)
+ f, g = f_func(x, y, z), g_func(x, y, z)
assert Derivative(f, x, y).subs(Derivative(f, x, y), g) == g
assert Derivative(f, y, x).subs(Derivative(f, x, y), g) == g
assert Derivative(f, x, y).subs(Derivative(f, x), g) == Derivative(g, y)
assert Derivative(f, x, y).subs(Derivative(f, y), g) == Derivative(g, x)
- assert (Derivative(f(x, y, z), x, y, z).subs(
- Derivative(f(x, y, z), x, z), g) == Derivative(g, y))
- assert (Derivative(f(x, y, z), x, y, z).subs(
- Derivative(f(x, y, z), z, y), g) == Derivative(g, x))
- assert (Derivative(f(x, y, z), x, y, z).subs(
- Derivative(f(x, y, z), z, y, x), g) == g)
+ assert (Derivative(f, x, y, z).subs(
+ Derivative(f, x, z), g) == Derivative(g, y))
+ assert (Derivative(f, x, y, z).subs(
+ Derivative(f, z, y), g) == Derivative(g, x))
+ assert (Derivative(f, x, y, z).subs(
+ Derivative(f, z, y, x), g) == g)
+
+ # Issue 9135
+ assert (Derivative(f, x, x, y).subs(
+ Derivative(f, y, y), g) == Derivative(f, x, x, y))
+ assert (Derivative(f, x, y, y, z).subs(
+ Derivative(f, x, y, y, y), g) == Derivative(f, x, y, y, z))
+
+ assert Derivative(f, x, y).subs(Derivative(f_func(x), x, y), g) == Derivative(f, x, y)
+
def test_derivative_subs3():
x = Symbol('x')
| {
"commit_name": "head_commit",
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true,
"llm_score": {
"difficulty_score": 1,
"issue_text_score": 0,
"test_score": 0
},
"num_modified_files": 1
} | 1.0 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"mpmath>=0.19",
"pytest",
"pytest-cov"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.5",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | attrs==22.2.0
certifi==2021.5.30
coverage==6.2
importlib-metadata==4.8.3
iniconfig==1.1.1
mpmath==1.3.0
packaging==21.3
pluggy==1.0.0
py==1.11.0
pyparsing==3.1.4
pytest==7.0.1
pytest-cov==4.0.0
-e git+https://github.com/sympy/sympy.git@f511df8e8f7f2ee8079981671500201e3c32dc3f#egg=sympy
tomli==1.2.3
typing_extensions==4.1.1
zipp==3.6.0
| name: sympy
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2021.5.30=py36h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.3=he6710b0_2
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- pip=21.2.2=py36h06a4308_0
- python=3.6.13=h12debd9_1
- readline=8.2=h5eee18b_0
- setuptools=58.0.4=py36h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- wheel=0.37.1=pyhd3eb1b0_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- attrs==22.2.0
- coverage==6.2
- importlib-metadata==4.8.3
- iniconfig==1.1.1
- mpmath==1.3.0
- packaging==21.3
- pluggy==1.0.0
- py==1.11.0
- pyparsing==3.1.4
- pytest==7.0.1
- pytest-cov==4.0.0
- tomli==1.2.3
- typing-extensions==4.1.1
- zipp==3.6.0
prefix: /opt/conda/envs/sympy
| [
"sympy/core/tests/test_subs.py::test_derivative_subs2"
] | [] | [
"sympy/core/tests/test_subs.py::test_subs",
"sympy/core/tests/test_subs.py::test_subs_AccumBounds",
"sympy/core/tests/test_subs.py::test_trigonometric",
"sympy/core/tests/test_subs.py::test_powers",
"sympy/core/tests/test_subs.py::test_logexppow",
"sympy/core/tests/test_subs.py::test_bug",
"sympy/core/tests/test_subs.py::test_subbug1",
"sympy/core/tests/test_subs.py::test_subbug2",
"sympy/core/tests/test_subs.py::test_dict_set",
"sympy/core/tests/test_subs.py::test_dict_ambigous",
"sympy/core/tests/test_subs.py::test_deriv_sub_bug3",
"sympy/core/tests/test_subs.py::test_equality_subs1",
"sympy/core/tests/test_subs.py::test_equality_subs2",
"sympy/core/tests/test_subs.py::test_issue_3742",
"sympy/core/tests/test_subs.py::test_subs_dict1",
"sympy/core/tests/test_subs.py::test_mul",
"sympy/core/tests/test_subs.py::test_subs_simple",
"sympy/core/tests/test_subs.py::test_subs_constants",
"sympy/core/tests/test_subs.py::test_subs_commutative",
"sympy/core/tests/test_subs.py::test_subs_noncommutative",
"sympy/core/tests/test_subs.py::test_subs_basic_funcs",
"sympy/core/tests/test_subs.py::test_subs_wild",
"sympy/core/tests/test_subs.py::test_subs_mixed",
"sympy/core/tests/test_subs.py::test_division",
"sympy/core/tests/test_subs.py::test_add",
"sympy/core/tests/test_subs.py::test_subs_issue_4009",
"sympy/core/tests/test_subs.py::test_functions_subs",
"sympy/core/tests/test_subs.py::test_derivative_subs",
"sympy/core/tests/test_subs.py::test_derivative_subs3",
"sympy/core/tests/test_subs.py::test_issue_5284",
"sympy/core/tests/test_subs.py::test_subs_iter",
"sympy/core/tests/test_subs.py::test_subs_dict",
"sympy/core/tests/test_subs.py::test_no_arith_subs_on_floats",
"sympy/core/tests/test_subs.py::test_issue_5651",
"sympy/core/tests/test_subs.py::test_issue_6075",
"sympy/core/tests/test_subs.py::test_issue_6079",
"sympy/core/tests/test_subs.py::test_issue_4680",
"sympy/core/tests/test_subs.py::test_issue_6158",
"sympy/core/tests/test_subs.py::test_Function_subs",
"sympy/core/tests/test_subs.py::test_simultaneous_subs",
"sympy/core/tests/test_subs.py::test_issue_6419_6421",
"sympy/core/tests/test_subs.py::test_issue_6559",
"sympy/core/tests/test_subs.py::test_issue_5261",
"sympy/core/tests/test_subs.py::test_issue_6923",
"sympy/core/tests/test_subs.py::test_2arg_hack",
"sympy/core/tests/test_subs.py::test_noncommutative_subs",
"sympy/core/tests/test_subs.py::test_issue_2877",
"sympy/core/tests/test_subs.py::test_issue_5910",
"sympy/core/tests/test_subs.py::test_issue_5217",
"sympy/core/tests/test_subs.py::test_issue_10829",
"sympy/core/tests/test_subs.py::test_pow_eval_subs_no_cache",
"sympy/core/tests/test_subs.py::test_RootOf_issue_10092",
"sympy/core/tests/test_subs.py::test_issue_8886"
] | [] | BSD | 269 |
|
docker__docker-py-822 | 4c8c761bc15160be5eaa76d81edda17b067aa641 | 2015-10-21 22:58:11 | 9050e1c6e05b5b6807357def0aafc59e3b3ae378 | dnephin: Might be worth thinking about any other breaking changes you'd like to make before doing a 2.0 release. Sounds reasonable to me.
bfirsh: LGTM | diff --git a/docker/api/container.py b/docker/api/container.py
index 72c5852d..953a5f52 100644
--- a/docker/api/container.py
+++ b/docker/api/container.py
@@ -997,19 +997,16 @@ class ContainerApiMixin(object):
self._raise_for_status(res)
@utils.check_resource
- def start(self, container, binds=None, port_bindings=None, lxc_conf=None,
- publish_all_ports=None, links=None, privileged=None,
- dns=None, dns_search=None, volumes_from=None, network_mode=None,
- restart_policy=None, cap_add=None, cap_drop=None, devices=None,
- extra_hosts=None, read_only=None, pid_mode=None, ipc_mode=None,
- security_opt=None, ulimits=None):
+ def start(self, container, *args, **kwargs):
"""
Start a container. Similar to the ``docker start`` command, but
doesn't support attach options.
- **Deprecation warning:** For API version > 1.15, it is highly
- recommended to provide host config options in the ``host_config``
- parameter of :py:meth:`~ContainerApiMixin.create_container`.
+ **Deprecation warning:** Passing configuration options in ``start`` is
+ no longer supported. Users are expected to provide host config options
+ in the ``host_config`` parameter of
+ :py:meth:`~ContainerApiMixin.create_container`.
+
Args:
container (str): The container to start
@@ -1017,6 +1014,8 @@ class ContainerApiMixin(object):
Raises:
:py:class:`docker.errors.APIError`
If the server returns an error.
+ :py:class:`docker.errors.DeprecatedMethod`
+ If any argument besides ``container`` are provided.
Example:
@@ -1025,64 +1024,14 @@ class ContainerApiMixin(object):
... command='/bin/sleep 30')
>>> cli.start(container=container.get('Id'))
"""
- if utils.compare_version('1.10', self._version) < 0:
- if dns is not None:
- raise errors.InvalidVersion(
- 'dns is only supported for API version >= 1.10'
- )
- if volumes_from is not None:
- raise errors.InvalidVersion(
- 'volumes_from is only supported for API version >= 1.10'
- )
-
- if utils.compare_version('1.15', self._version) < 0:
- if security_opt is not None:
- raise errors.InvalidVersion(
- 'security_opt is only supported for API version >= 1.15'
- )
- if ipc_mode:
- raise errors.InvalidVersion(
- 'ipc_mode is only supported for API version >= 1.15'
- )
-
- if utils.compare_version('1.17', self._version) < 0:
- if read_only is not None:
- raise errors.InvalidVersion(
- 'read_only is only supported for API version >= 1.17'
- )
- if pid_mode is not None:
- raise errors.InvalidVersion(
- 'pid_mode is only supported for API version >= 1.17'
- )
-
- if utils.compare_version('1.18', self._version) < 0:
- if ulimits is not None:
- raise errors.InvalidVersion(
- 'ulimits is only supported for API version >= 1.18'
- )
-
- start_config_kwargs = dict(
- binds=binds, port_bindings=port_bindings, lxc_conf=lxc_conf,
- publish_all_ports=publish_all_ports, links=links, dns=dns,
- privileged=privileged, dns_search=dns_search, cap_add=cap_add,
- cap_drop=cap_drop, volumes_from=volumes_from, devices=devices,
- network_mode=network_mode, restart_policy=restart_policy,
- extra_hosts=extra_hosts, read_only=read_only, pid_mode=pid_mode,
- ipc_mode=ipc_mode, security_opt=security_opt, ulimits=ulimits,
- )
- start_config = None
-
- if any(v is not None for v in start_config_kwargs.values()):
- if utils.compare_version('1.15', self._version) > 0:
- warnings.warn(
- 'Passing host config parameters in start() is deprecated. '
- 'Please use host_config in create_container instead!',
- DeprecationWarning
- )
- start_config = self.create_host_config(**start_config_kwargs)
-
+ if args or kwargs:
+ raise errors.DeprecatedMethod(
+ 'Providing configuration in the start() method is no longer '
+ 'supported. Use the host_config param in create_container '
+ 'instead.'
+ )
url = self._url("/containers/{0}/start", container)
- res = self._post_json(url, data=start_config)
+ res = self._post(url)
self._raise_for_status(res)
@utils.minimum_version('1.17')
| Passing host_config parameters in start() overrides the host_config that was passed in create()?
I had a `host_config` with `extra_hosts` defined. I used this `host_config` to create a container. When starting container, I passed extra volumes_from parameter. However, this lead to `extra_hosts` seemingly not doing their job.
After I moved `volumes_from` from `start()` to `create_host_config` everything started working OK.
I figured, I should report this, since I spent a couple of hours figuring this out. IMO, start() should override the necessary parts of host_config(and not the whole thing). Or raise an exception.
| docker/docker-py | diff --git a/tests/unit/api_container_test.py b/tests/unit/api_container_test.py
index 6c080641..abf36138 100644
--- a/tests/unit/api_container_test.py
+++ b/tests/unit/api_container_test.py
@@ -34,10 +34,7 @@ class StartContainerTest(BaseAPIClientTest):
args[0][1],
url_prefix + 'containers/3cc2351ab11b/start'
)
- self.assertEqual(json.loads(args[1]['data']), {})
- self.assertEqual(
- args[1]['headers'], {'Content-Type': 'application/json'}
- )
+ assert 'data' not in args[1]
self.assertEqual(
args[1]['timeout'], DEFAULT_TIMEOUT_SECONDS
)
@@ -63,25 +60,21 @@ class StartContainerTest(BaseAPIClientTest):
self.client.start(**{'container': fake_api.FAKE_CONTAINER_ID})
def test_start_container_with_lxc_conf(self):
- def call_start():
+ with pytest.raises(docker.errors.DeprecatedMethod):
self.client.start(
fake_api.FAKE_CONTAINER_ID,
lxc_conf={'lxc.conf.k': 'lxc.conf.value'}
)
- pytest.deprecated_call(call_start)
-
def test_start_container_with_lxc_conf_compat(self):
- def call_start():
+ with pytest.raises(docker.errors.DeprecatedMethod):
self.client.start(
fake_api.FAKE_CONTAINER_ID,
lxc_conf=[{'Key': 'lxc.conf.k', 'Value': 'lxc.conf.value'}]
)
- pytest.deprecated_call(call_start)
-
def test_start_container_with_binds_ro(self):
- def call_start():
+ with pytest.raises(docker.errors.DeprecatedMethod):
self.client.start(
fake_api.FAKE_CONTAINER_ID, binds={
'/tmp': {
@@ -91,22 +84,18 @@ class StartContainerTest(BaseAPIClientTest):
}
)
- pytest.deprecated_call(call_start)
-
def test_start_container_with_binds_rw(self):
- def call_start():
+ with pytest.raises(docker.errors.DeprecatedMethod):
self.client.start(
fake_api.FAKE_CONTAINER_ID, binds={
'/tmp': {"bind": '/mnt', "ro": False}
}
)
- pytest.deprecated_call(call_start)
-
def test_start_container_with_port_binds(self):
self.maxDiff = None
- def call_start():
+ with pytest.raises(docker.errors.DeprecatedMethod):
self.client.start(fake_api.FAKE_CONTAINER_ID, port_bindings={
1111: None,
2222: 2222,
@@ -116,18 +105,14 @@ class StartContainerTest(BaseAPIClientTest):
6666: [('127.0.0.1',), ('192.168.0.1',)]
})
- pytest.deprecated_call(call_start)
-
def test_start_container_with_links(self):
- def call_start():
+ with pytest.raises(docker.errors.DeprecatedMethod):
self.client.start(
fake_api.FAKE_CONTAINER_ID, links={'path': 'alias'}
)
- pytest.deprecated_call(call_start)
-
def test_start_container_with_multiple_links(self):
- def call_start():
+ with pytest.raises(docker.errors.DeprecatedMethod):
self.client.start(
fake_api.FAKE_CONTAINER_ID,
links={
@@ -136,21 +121,15 @@ class StartContainerTest(BaseAPIClientTest):
}
)
- pytest.deprecated_call(call_start)
-
def test_start_container_with_links_as_list_of_tuples(self):
- def call_start():
+ with pytest.raises(docker.errors.DeprecatedMethod):
self.client.start(fake_api.FAKE_CONTAINER_ID,
links=[('path', 'alias')])
- pytest.deprecated_call(call_start)
-
def test_start_container_privileged(self):
- def call_start():
+ with pytest.raises(docker.errors.DeprecatedMethod):
self.client.start(fake_api.FAKE_CONTAINER_ID, privileged=True)
- pytest.deprecated_call(call_start)
-
def test_start_container_with_dict_instead_of_id(self):
self.client.start({'Id': fake_api.FAKE_CONTAINER_ID})
@@ -159,10 +138,7 @@ class StartContainerTest(BaseAPIClientTest):
args[0][1],
url_prefix + 'containers/3cc2351ab11b/start'
)
- self.assertEqual(json.loads(args[1]['data']), {})
- self.assertEqual(
- args[1]['headers'], {'Content-Type': 'application/json'}
- )
+ assert 'data' not in args[1]
self.assertEqual(
args[1]['timeout'], DEFAULT_TIMEOUT_SECONDS
)
| {
"commit_name": "head_commit",
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true,
"llm_score": {
"difficulty_score": 0,
"issue_text_score": 0,
"test_score": 0
},
"num_modified_files": 1
} | 1.10 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[dev]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.5",
"reqs_path": [
"requirements.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | attrs==22.2.0
certifi==2021.5.30
-e git+https://github.com/docker/docker-py.git@4c8c761bc15160be5eaa76d81edda17b067aa641#egg=docker_py
docker-pycreds==0.2.1
importlib-metadata==4.8.3
iniconfig==1.1.1
packaging==21.3
pluggy==1.0.0
py==1.11.0
pyparsing==3.1.4
pytest==7.0.1
requests==2.11.1
six==1.17.0
tomli==1.2.3
typing_extensions==4.1.1
websocket-client==0.32.0
zipp==3.6.0
| name: docker-py
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2021.5.30=py36h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.3=he6710b0_2
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- pip=21.2.2=py36h06a4308_0
- python=3.6.13=h12debd9_1
- readline=8.2=h5eee18b_0
- setuptools=58.0.4=py36h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- wheel=0.37.1=pyhd3eb1b0_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- attrs==22.2.0
- docker-pycreds==0.2.1
- importlib-metadata==4.8.3
- iniconfig==1.1.1
- packaging==21.3
- pluggy==1.0.0
- py==1.11.0
- pyparsing==3.1.4
- pytest==7.0.1
- requests==2.11.1
- six==1.17.0
- tomli==1.2.3
- typing-extensions==4.1.1
- websocket-client==0.32.0
- zipp==3.6.0
prefix: /opt/conda/envs/docker-py
| [
"tests/unit/api_container_test.py::StartContainerTest::test_start_container",
"tests/unit/api_container_test.py::StartContainerTest::test_start_container_privileged",
"tests/unit/api_container_test.py::StartContainerTest::test_start_container_with_binds_ro",
"tests/unit/api_container_test.py::StartContainerTest::test_start_container_with_binds_rw",
"tests/unit/api_container_test.py::StartContainerTest::test_start_container_with_dict_instead_of_id",
"tests/unit/api_container_test.py::StartContainerTest::test_start_container_with_links",
"tests/unit/api_container_test.py::StartContainerTest::test_start_container_with_links_as_list_of_tuples",
"tests/unit/api_container_test.py::StartContainerTest::test_start_container_with_lxc_conf",
"tests/unit/api_container_test.py::StartContainerTest::test_start_container_with_lxc_conf_compat",
"tests/unit/api_container_test.py::StartContainerTest::test_start_container_with_multiple_links",
"tests/unit/api_container_test.py::StartContainerTest::test_start_container_with_port_binds"
] | [] | [
"tests/unit/api_container_test.py::StartContainerTest::test_start_container_none",
"tests/unit/api_container_test.py::StartContainerTest::test_start_container_regression_573",
"tests/unit/api_container_test.py::CreateContainerTest::test_create_container",
"tests/unit/api_container_test.py::CreateContainerTest::test_create_container_empty_volumes_from",
"tests/unit/api_container_test.py::CreateContainerTest::test_create_container_privileged",
"tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_added_capabilities",
"tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_aliases",
"tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_binds",
"tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_binds_list",
"tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_binds_mode",
"tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_binds_mode_and_ro_error",
"tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_binds_ro",
"tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_binds_rw",
"tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_cgroup_parent",
"tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_cpu_shares",
"tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_cpuset",
"tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_devices",
"tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_dropped_capabilities",
"tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_entrypoint",
"tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_host_config_cpu_shares",
"tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_host_config_cpuset",
"tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_labels_dict",
"tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_labels_list",
"tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_links",
"tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_links_as_list_of_tuples",
"tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_lxc_conf",
"tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_lxc_conf_compat",
"tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_mac_address",
"tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_mem_limit_as_int",
"tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_mem_limit_as_string",
"tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_mem_limit_as_string_with_g_unit",
"tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_mem_limit_as_string_with_k_unit",
"tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_mem_limit_as_string_with_m_unit",
"tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_mem_limit_as_string_with_wrong_value",
"tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_multiple_links",
"tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_named_volume",
"tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_port_binds",
"tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_ports",
"tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_restart_policy",
"tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_stdin_open",
"tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_stop_signal",
"tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_sysctl",
"tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_tmpfs_dict",
"tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_tmpfs_list",
"tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_unicode_envvars",
"tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_volume_string",
"tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_volumes_from",
"tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_working_dir",
"tests/unit/api_container_test.py::CreateContainerTest::test_create_named_container",
"tests/unit/api_container_test.py::ContainerTest::test_container_stats",
"tests/unit/api_container_test.py::ContainerTest::test_container_top",
"tests/unit/api_container_test.py::ContainerTest::test_container_top_with_psargs",
"tests/unit/api_container_test.py::ContainerTest::test_container_update",
"tests/unit/api_container_test.py::ContainerTest::test_diff",
"tests/unit/api_container_test.py::ContainerTest::test_diff_with_dict_instead_of_id",
"tests/unit/api_container_test.py::ContainerTest::test_export",
"tests/unit/api_container_test.py::ContainerTest::test_export_with_dict_instead_of_id",
"tests/unit/api_container_test.py::ContainerTest::test_inspect_container",
"tests/unit/api_container_test.py::ContainerTest::test_inspect_container_undefined_id",
"tests/unit/api_container_test.py::ContainerTest::test_kill_container",
"tests/unit/api_container_test.py::ContainerTest::test_kill_container_with_dict_instead_of_id",
"tests/unit/api_container_test.py::ContainerTest::test_kill_container_with_signal",
"tests/unit/api_container_test.py::ContainerTest::test_list_containers",
"tests/unit/api_container_test.py::ContainerTest::test_log_following",
"tests/unit/api_container_test.py::ContainerTest::test_log_following_backwards",
"tests/unit/api_container_test.py::ContainerTest::test_log_since",
"tests/unit/api_container_test.py::ContainerTest::test_log_since_with_datetime",
"tests/unit/api_container_test.py::ContainerTest::test_log_streaming",
"tests/unit/api_container_test.py::ContainerTest::test_log_streaming_and_following",
"tests/unit/api_container_test.py::ContainerTest::test_log_tail",
"tests/unit/api_container_test.py::ContainerTest::test_log_tty",
"tests/unit/api_container_test.py::ContainerTest::test_logs",
"tests/unit/api_container_test.py::ContainerTest::test_logs_with_dict_instead_of_id",
"tests/unit/api_container_test.py::ContainerTest::test_pause_container",
"tests/unit/api_container_test.py::ContainerTest::test_port",
"tests/unit/api_container_test.py::ContainerTest::test_remove_container",
"tests/unit/api_container_test.py::ContainerTest::test_remove_container_with_dict_instead_of_id",
"tests/unit/api_container_test.py::ContainerTest::test_rename_container",
"tests/unit/api_container_test.py::ContainerTest::test_resize_container",
"tests/unit/api_container_test.py::ContainerTest::test_restart_container",
"tests/unit/api_container_test.py::ContainerTest::test_restart_container_with_dict_instead_of_id",
"tests/unit/api_container_test.py::ContainerTest::test_stop_container",
"tests/unit/api_container_test.py::ContainerTest::test_stop_container_with_dict_instead_of_id",
"tests/unit/api_container_test.py::ContainerTest::test_unpause_container",
"tests/unit/api_container_test.py::ContainerTest::test_wait",
"tests/unit/api_container_test.py::ContainerTest::test_wait_with_dict_instead_of_id"
] | [] | Apache License 2.0 | 270 |
sympy__sympy-10029 | 41fc8f5a4dabd350f2f23a4aef53db728ca8ee0d | 2015-10-23 09:54:50 | 0241b35cae5f2adc04dc37b25f7dc9c5f00bd746 | jksuom: ``oo**e`` could probably be best thought of as the limit of ``x**e`` for real ``x`` tending to ``oo``. If ``e`` is ``I``, then the limit does not exists, and ``nan`` could be used to indicate that. However, there are other values for which the limit exists. If the real part of ``e`` is positive, then the limit of ``|x**e|`` is ``oo``; so the limit of ``x**e`` is ``zoo``. If the real part of ``e`` is negative, then the limit is 0.
gxyd: I was thinking in terms of consider examples:
if `re(e) > 0` (for ex. `e = 1 + I`) then `oo**(1 + I)` should be equal to `oo**1*oo**I` now `oo**I` is `nan` then `oo*nan` is `nan`. Similarly for the `re(e) < 0` (for ex. `e = -1 + I`), `oo**(-1 + I)` should be equal to `oo**(-1)*oo**I = nan/0` equals `nan`.
gxyd: Ok, may be in terms of what i thought would not apply here. Since it involves `oo`. Probably approach looks good.
gxyd: Sorry, i have just updated it with one-more commit. :)
leosartaj: No problem. :smile:
asmeurer: I'm not a fan of seeing even more assumptions in the core, but this does fix a bug.
gxyd: Is there any problem in the latest changes to the `docs` that i have made? Tests still seem to fail, only in `python2.7` perhaps.
asmeurer: The is_number looks good. Perhaps you should just go ahead and move this in the direction of https://github.com/sympy/sympy/pull/9731 (and similar PRs by @debugger22) and only do automatic simplification from assumptions on things with is_number or is_Symbol, and move the more general simplification to `_eval_refine`.
gxyd: Perhaps i am not very familiar with the assumptions in `SymPy`, so may be i will take a day, to understand what the code is doing. So i will get back in ASAP.
gxyd: @asmeurer I have added a `_eval_refine` function in `Infinity` class, probably the way you referred to in your comment. | diff --git a/sympy/core/numbers.py b/sympy/core/numbers.py
index f01d3c683e..627a03a5d3 100644
--- a/sympy/core/numbers.py
+++ b/sympy/core/numbers.py
@@ -2464,6 +2464,8 @@ def _eval_power(self, expt):
NegativeInfinity
"""
+ from sympy.functions import re
+
if expt.is_positive:
return S.Infinity
if expt.is_negative:
@@ -2472,8 +2474,15 @@ def _eval_power(self, expt):
return S.NaN
if expt is S.ComplexInfinity:
return S.NaN
+ if expt.is_real is False and expt.is_number:
+ expt_real = re(expt)
+ if expt_real.is_positive:
+ return S.ComplexInfinity
+ if expt_real.is_negative:
+ return S.Zero
+ if expt_real.is_zero:
+ return S.NaN
- if expt.is_number:
return self**expt.evalf()
def _as_mpf_val(self, prec):
@@ -2673,7 +2682,7 @@ def _eval_power(self, expt):
NaN
"""
- if isinstance(expt, Number):
+ if expt.is_number:
if expt is S.NaN or \
expt is S.Infinity or \
expt is S.NegativeInfinity:
diff --git a/sympy/core/power.py b/sympy/core/power.py
index 42f6fef6b1..358d7d467e 100644
--- a/sympy/core/power.py
+++ b/sympy/core/power.py
@@ -80,7 +80,7 @@ class Pow(Expr):
"""
Defines the expression x**y as "x raised to a power y"
- Singleton definitions involving (0, 1, -1, oo, -oo):
+ Singleton definitions involving (0, 1, -1, oo, -oo, I, -I):
+--------------+---------+-----------------------------------------------+
| expr | value | reason |
@@ -124,6 +124,18 @@ class Pow(Expr):
| (-oo)**oo | nan | |
| (-oo)**-oo | | |
+--------------+---------+-----------------------------------------------+
+ | oo**I | nan | oo**e could probably be best thought of as |
+ | (-oo)**I | | the limit of x**e for real x as x tends to |
+ | | | oo. If e is I, then the limit does not exist |
+ | | | and nan is used to indicate that. |
+ +--------------+---------+-----------------------------------------------+
+ | oo**(1+I) | zoo | If the real part of e is positive, then the |
+ | (-oo)**(1+I) | | limit of abs(x**e) is oo. So the limit value |
+ | | | is zoo. |
+ +--------------+---------+-----------------------------------------------+
+ | oo**(-1+I) | 0 | If the real part of e is negative, then the |
+ | -oo**(-1+I) | | limit is 0. |
+ +--------------+---------+-----------------------------------------------+
Because symbolic computations are more flexible that floating point
calculations and we prefer to never return an incorrect answer,
| oo**I raises RunTimeError
```
gxyd@swap:~/Public/sympy$ python3.4
Python 3.4.3 (default, Jul 28 2015, 18:20:59)
[GCC 4.8.4] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from sympy import *
>>> oo**I
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/gxyd/Public/sympy/sympy/core/decorators.py", line 77, in __sympifyit_wrapper
return func(a, b)
File "/home/gxyd/Public/sympy/sympy/core/decorators.py", line 118, in binary_op_wrapper
return func(self, other)
File "/home/gxyd/Public/sympy/sympy/core/expr.py", line 151, in __pow__
return Pow(self, other)
File "/home/gxyd/Public/sympy/sympy/core/cache.py", line 93, in wrapper
retval = cfunc(*args, **kwargs)
File "/usr/lib/python3.4/functools.py", line 472, in wrapper
result = user_function(*args, **kwds)
File "/home/gxyd/Public/sympy/sympy/core/power.py", line 192, in __new__
obj = b._eval_power(e)
File "/home/gxyd/Public/sympy/sympy/core/numbers.py", line 2474, in _eval_power
return self**expt.evalf()
File "/home/gxyd/Public/sympy/sympy/core/decorators.py", line 77, in __sympifyit_wrapper
return func(a, b)
File "/home/gxyd/Public/sympy/sympy/core/decorators.py", line 118, in binary_op_wrapper
return func(self, other)
File "/home/gxyd/Public/sympy/sympy/core/expr.py", line 151, in __pow__
return Pow(self, other)
File "/home/gxyd/Public/sympy/sympy/core/cache.py", line 93, in wrapper
retval = cfunc(*args, **kwargs)
File "/usr/lib/python3.4/functools.py", line 472, in wrapper
result = user_function(*args, **kwds)
File "/home/gxyd/Public/sympy/sympy/core/power.py", line 192, in __new__
obj = b._eval_power(e)
File "/home/gxyd/Public/sympy/sympy/core/numbers.py", line 2474, in _eval_power
return self**expt.evalf()
File "/home/gxyd/Public/sympy/sympy/core/decorators.py", line 77, in __sympifyit_wrapper
return func(a, b)
File "/home/gxyd/Public/sympy/sympy/core/decorators.py", line 118, in binary_op_wrapper
return func(self, other)
File "/home/gxyd/Public/sympy/sympy/core/expr.py", line 151, in __pow__
return Pow(self, other)
File "/home/gxyd/Public/sympy/sympy/core/cache.py", line 93, in wrapper
retval = cfunc(*args, **kwargs)
File "/usr/lib/python3.4/functools.py", line 472, in wrapper
result = user_function(*args, **kwds)
File "/home/gxyd/Public/sympy/sympy/core/power.py", line 192, in __new__
obj = b._eval_power(e)
File "/home/gxyd/Public/sympy/sympy/core/numbers.py", line 2474, in _eval_power
return self**expt.evalf()
File "/home/gxyd/Public/sympy/sympy/core/decorators.py", line 77, in __sympifyit_wrapper
return func(a, b)
File "/home/gxyd/Public/sympy/sympy/core/decorators.py", line 118, in binary_op_wrapper
return func(self, other)
File "/home/gxyd/Public/sympy/sympy/core/expr.py", line 151, in __pow__
return Pow(self, other)
File "/home/gxyd/Public/sympy/sympy/core/cache.py", line 93, in wrapper
retval = cfunc(*args, **kwargs)
File "/usr/lib/python3.4/functools.py", line 472, in wrapper
result = user_function(*args, **kwds)
File "/home/gxyd/Public/sympy/sympy/core/power.py", line 192, in __new__
obj = b._eval_power(e)
File "/home/gxyd/Public/sympy/sympy/core/numbers.py", line 2474, in _eval_power
return self**expt.evalf()
File "/home/gxyd/Public/sympy/sympy/core/decorators.py", line 77, in __sympifyit_wrapper
return func(a, b)
File "/home/gxyd/Public/sympy/sympy/core/decorators.py", line 118, in binary_op_wrapper
return func(self, other)
File "/home/gxyd/Public/sympy/sympy/core/expr.py", line 151, in __pow__
return Pow(self, other)
File "/home/gxyd/Public/sympy/sympy/core/cache.py", line 93, in wrapper
retval = cfunc(*args, **kwargs)
File "/usr/lib/python3.4/functools.py", line 472, in wrapper
result = user_function(*args, **kwds)
File "/home/gxyd/Public/sympy/sympy/core/power.py", line 192, in __new__
obj = b._eval_power(e)
File "/home/gxyd/Public/sympy/sympy/core/numbers.py", line 2474, in _eval_power
return self**expt.evalf()
File "/home/gxyd/Public/sympy/sympy/core/decorators.py", line 77, in __sympifyit_wrapper
return func(a, b)
File "/home/gxyd/Public/sympy/sympy/core/decorators.py", line 118, in binary_op_wrapper
return func(self, other)
File "/home/gxyd/Public/sympy/sympy/core/expr.py", line 151, in __pow__
return Pow(self, other)
File "/home/gxyd/Public/sympy/sympy/core/cache.py", line 93, in wrapper
retval = cfunc(*args, **kwargs)
File "/usr/lib/python3.4/functools.py", line 472, in wrapper
result = user_function(*args, **kwds)
File "/home/gxyd/Public/sympy/sympy/core/power.py", line 192, in __new__
obj = b._eval_power(e)
File "/home/gxyd/Public/sympy/sympy/core/numbers.py", line 2474, in _eval_power
return self**expt.evalf()
File "/home/gxyd/Public/sympy/sympy/core/decorators.py", line 77, in __sympifyit_wrapper
return func(a, b)
File "/home/gxyd/Public/sympy/sympy/core/decorators.py", line 118, in binary_op_wrapper
return func(self, other)
File "/home/gxyd/Public/sympy/sympy/core/expr.py", line 151, in __pow__
return Pow(self, other)
File "/home/gxyd/Public/sympy/sympy/core/cache.py", line 93, in wrapper
retval = cfunc(*args, **kwargs)
File "/usr/lib/python3.4/functools.py", line 472, in wrapper
result = user_function(*args, **kwds)
File "/home/gxyd/Public/sympy/sympy/core/power.py", line 192, in __new__
obj = b._eval_power(e)
File "/home/gxyd/Public/sympy/sympy/core/numbers.py", line 2474, in _eval_power
return self**expt.evalf()
File "/home/gxyd/Public/sympy/sympy/core/decorators.py", line 77, in __sympifyit_wrapper
return func(a, b)
File "/home/gxyd/Public/sympy/sympy/core/decorators.py", line 118, in binary_op_wrapper
return func(self, other)
File "/home/gxyd/Public/sympy/sympy/core/expr.py", line 151, in __pow__
return Pow(self, other)
File "/home/gxyd/Public/sympy/sympy/core/cache.py", line 93, in wrapper
retval = cfunc(*args, **kwargs)
File "/usr/lib/python3.4/functools.py", line 472, in wrapper
result = user_function(*args, **kwds)
File "/home/gxyd/Public/sympy/sympy/core/power.py", line 192, in __new__
obj = b._eval_power(e)
File "/home/gxyd/Public/sympy/sympy/core/numbers.py", line 2474, in _eval_power
return self**expt.evalf()
File "/home/gxyd/Public/sympy/sympy/core/decorators.py", line 77, in __sympifyit_wrapper
return func(a, b)
File "/home/gxyd/Public/sympy/sympy/core/decorators.py", line 118, in binary_op_wrapper
return func(self, other)
File "/home/gxyd/Public/sympy/sympy/core/expr.py", line 151, in __pow__
return Pow(self, other)
File "/home/gxyd/Public/sympy/sympy/core/cache.py", line 93, in wrapper
retval = cfunc(*args, **kwargs)
File "/usr/lib/python3.4/functools.py", line 472, in wrapper
result = user_function(*args, **kwds)
File "/home/gxyd/Public/sympy/sympy/core/power.py", line 192, in __new__
obj = b._eval_power(e)
File "/home/gxyd/Public/sympy/sympy/core/numbers.py", line 2474, in _eval_power
return self**expt.evalf()
File "/home/gxyd/Public/sympy/sympy/core/decorators.py", line 77, in __sympifyit_wrapper
return func(a, b)
File "/home/gxyd/Public/sympy/sympy/core/decorators.py", line 118, in binary_op_wrapper
return func(self, other)
File "/home/gxyd/Public/sympy/sympy/core/expr.py", line 151, in __pow__
return Pow(self, other)
File "/home/gxyd/Public/sympy/sympy/core/cache.py", line 93, in wrapper
retval = cfunc(*args, **kwargs)
File "/usr/lib/python3.4/functools.py", line 472, in wrapper
result = user_function(*args, **kwds)
File "/home/gxyd/Public/sympy/sympy/core/power.py", line 192, in __new__
obj = b._eval_power(e)
File "/home/gxyd/Public/sympy/sympy/core/numbers.py", line 2474, in _eval_power
return self**expt.evalf()
File "/home/gxyd/Public/sympy/sympy/core/decorators.py", line 77, in __sympifyit_wrapper
return func(a, b)
File "/home/gxyd/Public/sympy/sympy/core/decorators.py", line 118, in binary_op_wrapper
return func(self, other)
File "/home/gxyd/Public/sympy/sympy/core/expr.py", line 151, in __pow__
return Pow(self, other)
File "/home/gxyd/Public/sympy/sympy/core/cache.py", line 93, in wrapper
retval = cfunc(*args, **kwargs)
File "/usr/lib/python3.4/functools.py", line 472, in wrapper
result = user_function(*args, **kwds)
File "/home/gxyd/Public/sympy/sympy/core/power.py", line 192, in __new__
obj = b._eval_power(e)
File "/home/gxyd/Public/sympy/sympy/core/numbers.py", line 2474, in _eval_power
return self**expt.evalf()
File "/home/gxyd/Public/sympy/sympy/core/decorators.py", line 77, in __sympifyit_wrapper
return func(a, b)
File "/home/gxyd/Public/sympy/sympy/core/decorators.py", line 118, in binary_op_wrapper
return func(self, other)
File "/home/gxyd/Public/sympy/sympy/core/expr.py", line 151, in __pow__
return Pow(self, other)
File "/home/gxyd/Public/sympy/sympy/core/cache.py", line 93, in wrapper
retval = cfunc(*args, **kwargs)
File "/usr/lib/python3.4/functools.py", line 472, in wrapper
result = user_function(*args, **kwds)
File "/home/gxyd/Public/sympy/sympy/core/power.py", line 192, in __new__
obj = b._eval_power(e)
File "/home/gxyd/Public/sympy/sympy/core/numbers.py", line 2474, in _eval_power
return self**expt.evalf()
File "/home/gxyd/Public/sympy/sympy/core/decorators.py", line 77, in __sympifyit_wrapper
return func(a, b)
File "/home/gxyd/Public/sympy/sympy/core/decorators.py", line 118, in binary_op_wrapper
return func(self, other)
File "/home/gxyd/Public/sympy/sympy/core/expr.py", line 151, in __pow__
return Pow(self, other)
File "/home/gxyd/Public/sympy/sympy/core/cache.py", line 93, in wrapper
retval = cfunc(*args, **kwargs)
File "/usr/lib/python3.4/functools.py", line 472, in wrapper
result = user_function(*args, **kwds)
File "/home/gxyd/Public/sympy/sympy/core/power.py", line 192, in __new__
obj = b._eval_power(e)
File "/home/gxyd/Public/sympy/sympy/core/numbers.py", line 2474, in _eval_power
return self**expt.evalf()
File "/home/gxyd/Public/sympy/sympy/core/decorators.py", line 77, in __sympifyit_wrapper
return func(a, b)
File "/home/gxyd/Public/sympy/sympy/core/decorators.py", line 118, in binary_op_wrapper
return func(self, other)
File "/home/gxyd/Public/sympy/sympy/core/expr.py", line 151, in __pow__
return Pow(self, other)
File "/home/gxyd/Public/sympy/sympy/core/cache.py", line 93, in wrapper
retval = cfunc(*args, **kwargs)
File "/usr/lib/python3.4/functools.py", line 472, in wrapper
result = user_function(*args, **kwds)
File "/home/gxyd/Public/sympy/sympy/core/power.py", line 192, in __new__
obj = b._eval_power(e)
File "/home/gxyd/Public/sympy/sympy/core/numbers.py", line 2474, in _eval_power
return self**expt.evalf()
File "/home/gxyd/Public/sympy/sympy/core/decorators.py", line 77, in __sympifyit_wrapper
return func(a, b)
File "/home/gxyd/Public/sympy/sympy/core/decorators.py", line 118, in binary_op_wrapper
return func(self, other)
File "/home/gxyd/Public/sympy/sympy/core/expr.py", line 151, in __pow__
return Pow(self, other)
File "/home/gxyd/Public/sympy/sympy/core/cache.py", line 93, in wrapper
retval = cfunc(*args, **kwargs)
File "/usr/lib/python3.4/functools.py", line 472, in wrapper
result = user_function(*args, **kwds)
File "/home/gxyd/Public/sympy/sympy/core/power.py", line 192, in __new__
obj = b._eval_power(e)
File "/home/gxyd/Public/sympy/sympy/core/numbers.py", line 2474, in _eval_power
return self**expt.evalf()
File "/home/gxyd/Public/sympy/sympy/core/decorators.py", line 77, in __sympifyit_wrapper
return func(a, b)
File "/home/gxyd/Public/sympy/sympy/core/decorators.py", line 118, in binary_op_wrapper
return func(self, other)
File "/home/gxyd/Public/sympy/sympy/core/expr.py", line 151, in __pow__
return Pow(self, other)
File "/home/gxyd/Public/sympy/sympy/core/cache.py", line 93, in wrapper
retval = cfunc(*args, **kwargs)
File "/usr/lib/python3.4/functools.py", line 472, in wrapper
result = user_function(*args, **kwds)
File "/home/gxyd/Public/sympy/sympy/core/power.py", line 192, in __new__
obj = b._eval_power(e)
File "/home/gxyd/Public/sympy/sympy/core/numbers.py", line 2474, in _eval_power
return self**expt.evalf()
File "/home/gxyd/Public/sympy/sympy/core/decorators.py", line 77, in __sympifyit_wrapper
return func(a, b)
File "/home/gxyd/Public/sympy/sympy/core/decorators.py", line 118, in binary_op_wrapper
return func(self, other)
File "/home/gxyd/Public/sympy/sympy/core/expr.py", line 151, in __pow__
return Pow(self, other)
File "/home/gxyd/Public/sympy/sympy/core/cache.py", line 93, in wrapper
retval = cfunc(*args, **kwargs)
File "/usr/lib/python3.4/functools.py", line 472, in wrapper
result = user_function(*args, **kwds)
File "/home/gxyd/Public/sympy/sympy/core/power.py", line 192, in __new__
obj = b._eval_power(e)
File "/home/gxyd/Public/sympy/sympy/core/numbers.py", line 2474, in _eval_power
return self**expt.evalf()
File "/home/gxyd/Public/sympy/sympy/core/decorators.py", line 77, in __sympifyit_wrapper
return func(a, b)
File "/home/gxyd/Public/sympy/sympy/core/decorators.py", line 118, in binary_op_wrapper
return func(self, other)
File "/home/gxyd/Public/sympy/sympy/core/expr.py", line 151, in __pow__
return Pow(self, other)
File "/home/gxyd/Public/sympy/sympy/core/cache.py", line 93, in wrapper
retval = cfunc(*args, **kwargs)
File "/usr/lib/python3.4/functools.py", line 472, in wrapper
result = user_function(*args, **kwds)
File "/home/gxyd/Public/sympy/sympy/core/power.py", line 192, in __new__
obj = b._eval_power(e)
File "/home/gxyd/Public/sympy/sympy/core/numbers.py", line 2474, in _eval_power
return self**expt.evalf()
File "/home/gxyd/Public/sympy/sympy/core/decorators.py", line 77, in __sympifyit_wrapper
return func(a, b)
RuntimeError: maximum recursion depth exceeded while calling a Python object
```
Some part of traceback has been removed to keep it short | sympy/sympy | diff --git a/sympy/core/tests/test_numbers.py b/sympy/core/tests/test_numbers.py
index 2dd3da28ef..3179711555 100644
--- a/sympy/core/tests/test_numbers.py
+++ b/sympy/core/tests/test_numbers.py
@@ -12,6 +12,7 @@
from sympy.utilities.pytest import XFAIL, raises
import mpmath
+t = Symbol('t', real=False)
def same_and_same_prec(a, b):
# stricter matching for Floats
@@ -1503,3 +1504,13 @@ def test_issue_9491():
def test_issue_10063():
assert 2**Float(3) == Float(8)
+
+
+def test_issue_10020():
+ assert oo**I is S.NaN
+ assert oo**(1 + I) is S.ComplexInfinity
+ assert oo**(-1 + I) is S.Zero
+ assert (-oo)**I is S.NaN
+ assert (-oo)**(-1 + I) is S.Zero
+ assert oo**t == Pow(oo, t, evaluate=False)
+ assert (-oo)**t == Pow(-oo, t, evaluate=False)
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 2,
"issue_text_score": 0,
"test_score": 3
},
"num_modified_files": 2
} | 0.7 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "pytest",
"pip_packages": [
"pytest"
],
"pre_install": null,
"python": "3.7",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | attrs @ file:///croot/attrs_1668696182826/work
certifi @ file:///croot/certifi_1671487769961/work/certifi
flit_core @ file:///opt/conda/conda-bld/flit-core_1644941570762/work/source/flit_core
importlib-metadata @ file:///tmp/build/80754af9/importlib-metadata_1648562407465/work
iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work
mpmath==1.3.0
packaging @ file:///croot/packaging_1671697413597/work
pluggy @ file:///tmp/build/80754af9/pluggy_1648042572264/work
py @ file:///opt/conda/conda-bld/py_1644396412707/work
pytest==7.1.2
-e git+https://github.com/sympy/sympy.git@41fc8f5a4dabd350f2f23a4aef53db728ca8ee0d#egg=sympy
tomli @ file:///opt/conda/conda-bld/tomli_1657175507142/work
typing_extensions @ file:///croot/typing_extensions_1669924550328/work
zipp @ file:///croot/zipp_1672387121353/work
| name: sympy
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- attrs=22.1.0=py37h06a4308_0
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2022.12.7=py37h06a4308_0
- flit-core=3.6.0=pyhd3eb1b0_0
- importlib-metadata=4.11.3=py37h06a4308_0
- importlib_metadata=4.11.3=hd3eb1b0_0
- iniconfig=1.1.1=pyhd3eb1b0_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- packaging=22.0=py37h06a4308_0
- pip=22.3.1=py37h06a4308_0
- pluggy=1.0.0=py37h06a4308_1
- py=1.11.0=pyhd3eb1b0_0
- pytest=7.1.2=py37h06a4308_0
- python=3.7.16=h7a1cb2a_0
- readline=8.2=h5eee18b_0
- setuptools=65.6.3=py37h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- tomli=2.0.1=py37h06a4308_0
- typing_extensions=4.4.0=py37h06a4308_0
- wheel=0.38.4=py37h06a4308_0
- xz=5.6.4=h5eee18b_1
- zipp=3.11.0=py37h06a4308_0
- zlib=1.2.13=h5eee18b_1
- pip:
- mpmath==1.3.0
prefix: /opt/conda/envs/sympy
| [
"sympy/core/tests/test_numbers.py::test_issue_10020"
] | [] | [
"sympy/core/tests/test_numbers.py::test_integers_cache",
"sympy/core/tests/test_numbers.py::test_seterr",
"sympy/core/tests/test_numbers.py::test_mod",
"sympy/core/tests/test_numbers.py::test_divmod",
"sympy/core/tests/test_numbers.py::test_igcd",
"sympy/core/tests/test_numbers.py::test_ilcm",
"sympy/core/tests/test_numbers.py::test_igcdex",
"sympy/core/tests/test_numbers.py::test_Integer_new",
"sympy/core/tests/test_numbers.py::test_Rational_new",
"sympy/core/tests/test_numbers.py::test_Number_new",
"sympy/core/tests/test_numbers.py::test_Rational_cmp",
"sympy/core/tests/test_numbers.py::test_Float",
"sympy/core/tests/test_numbers.py::test_Float_default_to_highprec_from_str",
"sympy/core/tests/test_numbers.py::test_Float_eval",
"sympy/core/tests/test_numbers.py::test_Float_issue_2107",
"sympy/core/tests/test_numbers.py::test_Infinity",
"sympy/core/tests/test_numbers.py::test_Infinity_2",
"sympy/core/tests/test_numbers.py::test_Mul_Infinity_Zero",
"sympy/core/tests/test_numbers.py::test_Div_By_Zero",
"sympy/core/tests/test_numbers.py::test_Infinity_inequations",
"sympy/core/tests/test_numbers.py::test_NaN",
"sympy/core/tests/test_numbers.py::test_special_numbers",
"sympy/core/tests/test_numbers.py::test_powers",
"sympy/core/tests/test_numbers.py::test_integer_nthroot_overflow",
"sympy/core/tests/test_numbers.py::test_powers_Integer",
"sympy/core/tests/test_numbers.py::test_powers_Rational",
"sympy/core/tests/test_numbers.py::test_powers_Float",
"sympy/core/tests/test_numbers.py::test_abs1",
"sympy/core/tests/test_numbers.py::test_accept_int",
"sympy/core/tests/test_numbers.py::test_dont_accept_str",
"sympy/core/tests/test_numbers.py::test_int",
"sympy/core/tests/test_numbers.py::test_long",
"sympy/core/tests/test_numbers.py::test_real_bug",
"sympy/core/tests/test_numbers.py::test_bug_sqrt",
"sympy/core/tests/test_numbers.py::test_pi_Pi",
"sympy/core/tests/test_numbers.py::test_no_len",
"sympy/core/tests/test_numbers.py::test_issue_3321",
"sympy/core/tests/test_numbers.py::test_issue_3692",
"sympy/core/tests/test_numbers.py::test_issue_3423",
"sympy/core/tests/test_numbers.py::test_issue_3449",
"sympy/core/tests/test_numbers.py::test_Integer_factors",
"sympy/core/tests/test_numbers.py::test_Rational_factors",
"sympy/core/tests/test_numbers.py::test_issue_4107",
"sympy/core/tests/test_numbers.py::test_IntegerInteger",
"sympy/core/tests/test_numbers.py::test_Rational_gcd_lcm_cofactors",
"sympy/core/tests/test_numbers.py::test_Float_gcd_lcm_cofactors",
"sympy/core/tests/test_numbers.py::test_issue_4611",
"sympy/core/tests/test_numbers.py::test_conversion_to_mpmath",
"sympy/core/tests/test_numbers.py::test_relational",
"sympy/core/tests/test_numbers.py::test_Integer_as_index",
"sympy/core/tests/test_numbers.py::test_Rational_int",
"sympy/core/tests/test_numbers.py::test_zoo",
"sympy/core/tests/test_numbers.py::test_issue_4122",
"sympy/core/tests/test_numbers.py::test_GoldenRatio_expand",
"sympy/core/tests/test_numbers.py::test_as_content_primitive",
"sympy/core/tests/test_numbers.py::test_hashing_sympy_integers",
"sympy/core/tests/test_numbers.py::test_issue_4172",
"sympy/core/tests/test_numbers.py::test_Catalan_EulerGamma_prec",
"sympy/core/tests/test_numbers.py::test_Float_eq",
"sympy/core/tests/test_numbers.py::test_int_NumberSymbols",
"sympy/core/tests/test_numbers.py::test_issue_6640",
"sympy/core/tests/test_numbers.py::test_issue_6349",
"sympy/core/tests/test_numbers.py::test_mpf_norm",
"sympy/core/tests/test_numbers.py::test_latex",
"sympy/core/tests/test_numbers.py::test_issue_7742",
"sympy/core/tests/test_numbers.py::test_simplify_AlgebraicNumber",
"sympy/core/tests/test_numbers.py::test_Float_idempotence",
"sympy/core/tests/test_numbers.py::test_comp",
"sympy/core/tests/test_numbers.py::test_issue_9491",
"sympy/core/tests/test_numbers.py::test_issue_10063"
] | [] | BSD | 271 |
sympy__sympy-10032 | 4f3f9d0ef5d9552c1f34ac056728708571e567b0 | 2015-10-23 22:12:05 | 0241b35cae5f2adc04dc37b25f7dc9c5f00bd746 | diff --git a/sympy/solvers/inequalities.py b/sympy/solvers/inequalities.py
index 2013ed0fb9..ac58e9af99 100644
--- a/sympy/solvers/inequalities.py
+++ b/sympy/solvers/inequalities.py
@@ -406,65 +406,71 @@ def solve_univariate_inequality(expr, gen, relational=True):
_gen = gen
gen = d
- e = expr.lhs - expr.rhs
- parts = n, d = e.as_numer_denom()
- if all(i.is_polynomial(gen) for i in parts):
- solns = solve(n, gen, check=False)
- singularities = solve(d, gen, check=False)
+ if expr is S.true:
+ rv = S.Reals
+ elif expr is S.false:
+ rv = S.EmptySet
else:
- solns = solve(e, gen, check=False)
- singularities = []
- for d in denoms(e):
- singularities.extend(solve(d, gen))
+ e = expr.lhs - expr.rhs
+ parts = n, d = e.as_numer_denom()
+ if all(i.is_polynomial(gen) for i in parts):
+ solns = solve(n, gen, check=False)
+ singularities = solve(d, gen, check=False)
+ else:
+ solns = solve(e, gen, check=False)
+ singularities = []
+ for d in denoms(e):
+ singularities.extend(solve(d, gen))
+
+ include_x = expr.func(0, 0)
- include_x = expr.func(0, 0)
+ def valid(x):
+ v = e.subs(gen, x)
+ try:
+ r = expr.func(v, 0)
+ except TypeError:
+ r = S.false
+ if r in (S.true, S.false):
+ return r
+ if v.is_real is False:
+ return S.false
+ else:
+ v = v.n(2)
+ if v.is_comparable:
+ return expr.func(v, 0)
+ return S.false
- def valid(x):
- v = e.subs(gen, x)
+ start = S.NegativeInfinity
+ sol_sets = [S.EmptySet]
try:
- r = expr.func(v, 0)
- except TypeError:
- r = S.false
- if r in (S.true, S.false):
- return r
- if v.is_real is False:
- return S.false
- else:
- v = v.n(2)
- if v.is_comparable:
- return expr.func(v, 0)
- return S.false
+ reals = _nsort(set(solns + singularities), separated=True)[0]
+ except NotImplementedError:
+ raise NotImplementedError('sorting of these roots is not supported')
+ for x in reals:
+ end = x
- start = S.NegativeInfinity
- sol_sets = [S.EmptySet]
- try:
- reals = _nsort(set(solns + singularities), separated=True)[0]
- except NotImplementedError:
- raise NotImplementedError('sorting of these roots is not supported')
- for x in reals:
- end = x
-
- if end in [S.NegativeInfinity, S.Infinity]:
- if valid(S(0)):
- sol_sets.append(Interval(start, S.Infinity, True, True))
- break
+ if end in [S.NegativeInfinity, S.Infinity]:
+ if valid(S(0)):
+ sol_sets.append(Interval(start, S.Infinity, True, True))
+ break
- if valid((start + end)/2 if start != S.NegativeInfinity else end - 1):
- sol_sets.append(Interval(start, end, True, True))
+ if valid((start + end)/2 if start != S.NegativeInfinity else end - 1):
+ sol_sets.append(Interval(start, end, True, True))
+
+ if x in singularities:
+ singularities.remove(x)
+ elif include_x:
+ sol_sets.append(FiniteSet(x))
- if x in singularities:
- singularities.remove(x)
- elif include_x:
- sol_sets.append(FiniteSet(x))
+ start = end
- start = end
+ end = S.Infinity
- end = S.Infinity
+ if valid(start + 1):
+ sol_sets.append(Interval(start, end, True, True))
- if valid(start + 1):
- sol_sets.append(Interval(start, end, True, True))
+ rv = Union(*sol_sets).subs(gen, _gen)
- rv = Union(*sol_sets).subs(gen, _gen)
return rv if not relational else rv.as_relational(_gen)
| solve_univariate_inequality(x**2 >= 0, x) raises AttributeError
```
>>> x = Symbol('x')
>>> solve_univariate_inequality(x**2 >= 0, x)
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-5-d005c642db25> in <module>()
----> 1 solve_univariate_inequality(x**2 >= 0, x)
/home/gxyd/Public/sympy/sympy/solvers/inequalities.py in solve_univariate_inequality(expr, gen, relational)
407 gen = d
408
--> 409 e = expr.lhs - expr.rhs
410 parts = n, d = e.as_numer_denom()
411 if all(i.is_polynomial(gen) for i in parts):
AttributeError: 'BooleanTrue' object has no attribute 'lhs'
```
Using `git-bisect` reveals [this](https://github.com/shivamvats/sympy/commit/b4596e3e2fe339062d27a0a1104fea298e25dfdf) commit by @shivamvats
```
gxyd@swap:~/Public/sympy$ git bisect good
Bisecting: 263 revisions left to test after this (roughly 8 steps)
[3517ef5e50bf0510c74c0434aff14766e160343c] Merge pull request #9803 from leosartaj/diffDelta
gxyd@swap:~/Public/sympy$ git bisect bad
Bisecting: 137 revisions left to test after this (roughly 7 steps)
[f4ad439372f377e4041b2a94e582815292616c3c] Fix test and docstring
gxyd@swap:~/Public/sympy$ git bisect bad
Bisecting: 64 revisions left to test after this (roughly 6 steps)
[0a850aaff35c353370400185a39cc958ae7b1e38] Merge pull request #9716 from aktech/sets-replace-solve
gxyd@swap:~/Public/sympy$ git bisect good
Bisecting: 32 revisions left to test after this (roughly 5 steps)
[49e2de008e4b8d0a666fd659510f49c24296971a] Merge pull request #9735 from gxyd/sphx_docs
gxyd@swap:~/Public/sympy$ git bisect good
Bisecting: 20 revisions left to test after this (roughly 4 steps)
[12c5f496815e58de8dd56ba9a8ef2518f401ecc4] `solveset_real` used instead of `singularities`
gxyd@swap:~/Public/sympy$ git bisect good
Bisecting: 10 revisions left to test after this (roughly 3 steps)
[7c696fcfdfcb0ed5c0b959163f64b21dfc1d61e2] Merge pull request #9719 from gxyd/Range_Function
gxyd@swap:~/Public/sympy$ git bisect good
Bisecting: 5 revisions left to test after this (roughly 3 steps)
[d2baf540c8341541c1a2197f7d7e76028f751242] Replace use of assumption with domain as argument to solveset
gxyd@swap:~/Public/sympy$ git bisect good
Bisecting: 2 revisions left to test after this (roughly 2 steps)
[5d1bf976f6b6eddd42463cdd4d1044d3a3ba68c9] Fix failing tests and use assumption with solve_univariate_inequality
gxyd@swap:~/Public/sympy$ git bisect good
Bisecting: 0 revisions left to test after this (roughly 1 step)
[f986e5950607118cb216488871a4d7a3e49851a3] Update docstring
gxyd@swap:~/Public/sympy$ git bisect bad
Bisecting: 0 revisions left to test after this (roughly 0 steps)
[b4596e3e2fe339062d27a0a1104fea298e25dfdf] Fix doc and use dummy variable in solve_univariate_inequality
gxyd@swap:~/Public/sympy$ git bisect bad
b4596e3e2fe339062d27a0a1104fea298e25dfdf is the first bad commit
commit b4596e3e2fe339062d27a0a1104fea298e25dfdf
Author: Shivam Vats <[email protected]>
Date: Sun Aug 2 08:44:22 2015 +0530
Fix doc and use dummy variable in solve_univariate_inequality
:040000 040000 79e7b8b24aeee0d1700295b7e7b1f3d863d73f3c e5fc32bc649a14e349f935b3963b125c1d2af690 M sympy
``` | sympy/sympy | diff --git a/sympy/solvers/tests/test_inequalities.py b/sympy/solvers/tests/test_inequalities.py
index d0b6346062..13569bc9bc 100644
--- a/sympy/solvers/tests/test_inequalities.py
+++ b/sympy/solvers/tests/test_inequalities.py
@@ -284,6 +284,13 @@ def test_solve_univariate_inequality():
Or(And(-oo < x, x < 1), And(S(1) < x, x < 2))
+def test_issue_9954():
+ assert isolve(x**2 >= 0, x, relational=False) == S.Reals
+ assert isolve(x**2 >= 0, x, relational=True) == S.Reals.as_relational(x)
+ assert isolve(x**2 < 0, x, relational=False) == S.EmptySet
+ assert isolve(x**2 < 0, x, relational=True) == S.EmptySet.as_relational(x)
+
+
@slow
def test_slow_general_univariate():
r = RootOf(x**5 - x**2 + 1, 0)
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_hyperlinks",
"has_git_commit_hash"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 1,
"issue_text_score": 1,
"test_score": 3
},
"num_modified_files": 1
} | 0.7 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "pytest",
"pip_packages": [
"mpmath>=0.19",
"pytest"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.7",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | attrs @ file:///croot/attrs_1668696182826/work
certifi @ file:///croot/certifi_1671487769961/work/certifi
flit_core @ file:///opt/conda/conda-bld/flit-core_1644941570762/work/source/flit_core
importlib-metadata @ file:///tmp/build/80754af9/importlib-metadata_1648562407465/work
iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work
mpmath==1.3.0
packaging @ file:///croot/packaging_1671697413597/work
pluggy @ file:///tmp/build/80754af9/pluggy_1648042572264/work
py @ file:///opt/conda/conda-bld/py_1644396412707/work
pytest==7.1.2
-e git+https://github.com/sympy/sympy.git@4f3f9d0ef5d9552c1f34ac056728708571e567b0#egg=sympy
tomli @ file:///opt/conda/conda-bld/tomli_1657175507142/work
typing_extensions @ file:///croot/typing_extensions_1669924550328/work
zipp @ file:///croot/zipp_1672387121353/work
| name: sympy
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- attrs=22.1.0=py37h06a4308_0
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2022.12.7=py37h06a4308_0
- flit-core=3.6.0=pyhd3eb1b0_0
- importlib-metadata=4.11.3=py37h06a4308_0
- importlib_metadata=4.11.3=hd3eb1b0_0
- iniconfig=1.1.1=pyhd3eb1b0_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- packaging=22.0=py37h06a4308_0
- pip=22.3.1=py37h06a4308_0
- pluggy=1.0.0=py37h06a4308_1
- py=1.11.0=pyhd3eb1b0_0
- pytest=7.1.2=py37h06a4308_0
- python=3.7.16=h7a1cb2a_0
- readline=8.2=h5eee18b_0
- setuptools=65.6.3=py37h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- tomli=2.0.1=py37h06a4308_0
- typing_extensions=4.4.0=py37h06a4308_0
- wheel=0.38.4=py37h06a4308_0
- xz=5.6.4=h5eee18b_1
- zipp=3.11.0=py37h06a4308_0
- zlib=1.2.13=h5eee18b_1
- pip:
- mpmath==1.3.0
prefix: /opt/conda/envs/sympy
| [
"sympy/solvers/tests/test_inequalities.py::test_issue_9954"
] | [] | [
"sympy/solvers/tests/test_inequalities.py::test_solve_poly_inequality",
"sympy/solvers/tests/test_inequalities.py::test_reduce_poly_inequalities_real_interval",
"sympy/solvers/tests/test_inequalities.py::test_reduce_poly_inequalities_complex_relational",
"sympy/solvers/tests/test_inequalities.py::test_reduce_rational_inequalities_real_relational",
"sympy/solvers/tests/test_inequalities.py::test_reduce_abs_inequalities",
"sympy/solvers/tests/test_inequalities.py::test_reduce_inequalities_general",
"sympy/solvers/tests/test_inequalities.py::test_reduce_inequalities_boolean",
"sympy/solvers/tests/test_inequalities.py::test_reduce_inequalities_multivariate",
"sympy/solvers/tests/test_inequalities.py::test_reduce_inequalities_errors",
"sympy/solvers/tests/test_inequalities.py::test_hacky_inequalities",
"sympy/solvers/tests/test_inequalities.py::test_issue_6343",
"sympy/solvers/tests/test_inequalities.py::test_issue_8235",
"sympy/solvers/tests/test_inequalities.py::test_issue_5526",
"sympy/solvers/tests/test_inequalities.py::test_solve_univariate_inequality",
"sympy/solvers/tests/test_inequalities.py::test_slow_general_univariate",
"sympy/solvers/tests/test_inequalities.py::test_issue_8545",
"sympy/solvers/tests/test_inequalities.py::test_issue_8974"
] | [] | BSD | 272 |
|
mogproject__mog-commons-python-8 | 71a072abdbeff70c14543ef9b307fae3277dc24a | 2015-10-24 16:43:22 | 0a6ffc13e621b0c2cbe35d20a6b938de570c0626 | diff --git a/src/mog_commons/__init__.py b/src/mog_commons/__init__.py
index 8ce9b36..7525d19 100644
--- a/src/mog_commons/__init__.py
+++ b/src/mog_commons/__init__.py
@@ -1,1 +1,1 @@
-__version__ = '0.1.3'
+__version__ = '0.1.4'
diff --git a/src/mog_commons/collection.py b/src/mog_commons/collection.py
index 21a8f62..621e572 100644
--- a/src/mog_commons/collection.py
+++ b/src/mog_commons/collection.py
@@ -2,6 +2,8 @@ from __future__ import division, print_function, absolute_import, unicode_litera
import six
+__all__ = ['get_single_item', 'get_single_key', 'get_single_value', 'distinct']
+
def get_single_item(d):
"""Get an item from a dict which contains just one item."""
@@ -19,3 +21,10 @@ def get_single_value(d):
"""Get a value from a dict which contains just one item."""
assert len(d) == 1, 'Single-item dict must have just one item, not %d.' % len(d)
return next(six.itervalues(d))
+
+
+def distinct(xs):
+ """Get the list of distinct values with preserving order."""
+ # don't use collections.OrderedDict because we do support Python 2.6
+ seen = set()
+ return [x for x in xs if x not in seen and not seen.add(x)]
diff --git a/src/mog_commons/string.py b/src/mog_commons/string.py
index 0e6c894..321c6a2 100644
--- a/src/mog_commons/string.py
+++ b/src/mog_commons/string.py
@@ -3,6 +3,21 @@ from __future__ import division, print_function, absolute_import, unicode_litera
from unicodedata import east_asian_width
import six
+from mog_commons.collection import distinct
+
+__all__ = [
+ 'is_unicode',
+ 'is_strlike',
+ 'unicode_width',
+ 'to_unicode',
+ 'to_str',
+ 'to_bytes',
+ 'edge_just',
+ 'unicode_right',
+ 'unicode_left',
+ 'unicode_decode',
+]
+
__unicode_width_mapping = {'F': 2, 'H': 1, 'W': 2, 'Na': 1, 'A': 2, 'N': 1}
@@ -104,3 +119,22 @@ def unicode_right(s, width):
break
i -= 1
return s[i:]
+
+
+def unicode_decode(data, encoding_list):
+ """
+ Decode string data with one or more encodings, trying sequentially
+ :param data: bytes: encoded string data
+ :param encoding_list: list[string] or string: encoding names
+ :return: string: decoded string
+ """
+ assert encoding_list, 'encodings must not be empty.'
+
+ xs = distinct(encoding_list if isinstance(encoding_list, list) else [encoding_list])
+ init, last = xs[:-1], xs[-1]
+ for encoding in init:
+ try:
+ return data.decode(encoding)
+ except UnicodeDecodeError:
+ pass
+ return data.decode(last)
| Decode string with multiple encodings | mogproject/mog-commons-python | diff --git a/src/mog_commons/unittest.py b/src/mog_commons/unittest.py
index 27445ba..06bc135 100644
--- a/src/mog_commons/unittest.py
+++ b/src/mog_commons/unittest.py
@@ -19,6 +19,7 @@ class StringBuffer(object):
We don't use StringIO because there are many differences between PY2 and PY3.
"""
+
def __init__(self, init_buffer=None):
self._buffer = init_buffer or b''
@@ -37,9 +38,17 @@ class StringBuffer(object):
class TestCase(base_unittest.TestCase):
def assertRaisesRegexp(self, expected_exception, expected_regexp, callable_obj=None, *args, **kwargs):
- """Accept difference of the function name between PY2 and PY3."""
- f = base_unittest.TestCase.assertRaisesRegex if six.PY3 else base_unittest.TestCase.assertRaisesRegexp
- f(self, expected_exception, expected_regexp, callable_obj, *args, **kwargs)
+ """
+ Accept difference of the function name between PY2 and PY3.
+
+ We don't use built-in assertRaisesRegexp because it is unicode-unsafe.
+ """
+ with self.assertRaises(expected_exception) as cm:
+ callable_obj(*args, **kwargs)
+ if six.PY2:
+ self.assertRegexpMatches(str(cm.exception), expected_regexp)
+ else:
+ self.assertRegex(str(cm.exception), expected_regexp)
def assertOutput(self, expected_stdout, expected_stderr, function, encoding='utf-8'):
with self.withOutput() as (out, err):
diff --git a/tests/mog_commons/test_collection.py b/tests/mog_commons/test_collection.py
index 2bd136e..da6fda2 100644
--- a/tests/mog_commons/test_collection.py
+++ b/tests/mog_commons/test_collection.py
@@ -1,6 +1,6 @@
from __future__ import division, print_function, absolute_import, unicode_literals
-from mog_commons.collection import get_single_item, get_single_key, get_single_value
+from mog_commons.collection import *
from mog_commons import unittest
@@ -31,3 +31,12 @@ class TestCollection(unittest.TestCase):
{})
self.assertRaisesRegexp(AssertionError, 'Single-item dict must have just one item, not 2.', get_single_value,
{'x': 123, 'y': 45})
+
+ def test_distinct(self):
+ self.assertEqual(distinct([]), [])
+ self.assertEqual(distinct([1]), [1])
+ self.assertEqual(distinct([1] * 100), [1])
+ self.assertEqual(distinct([1, 2, 3, 4, 5]), [1, 2, 3, 4, 5])
+ self.assertEqual(distinct([1, 2, 1, 2, 1]), [1, 2])
+ self.assertEqual(distinct([2, 1, 2, 1, 1]), [2, 1])
+ self.assertEqual(distinct('mog-commons-python'), ['m', 'o', 'g', '-', 'c', 'n', 's', 'p', 'y', 't', 'h'])
diff --git a/tests/mog_commons/test_string.py b/tests/mog_commons/test_string.py
index 2f00173..399abc8 100644
--- a/tests/mog_commons/test_string.py
+++ b/tests/mog_commons/test_string.py
@@ -92,3 +92,19 @@ class TestString(unittest.TestCase):
self.assertEqual(string.unicode_right('あいうえお', 11), 'あいうえお')
self.assertEqual(string.unicode_right('あxいxうxえxお', 4), 'xお')
self.assertEqual(string.unicode_right('あxいxうxえxお', 5), 'えxお')
+
+ def test_unicode_decode(self):
+ self.assertRaisesRegexp(AssertionError, 'encodings must not be empty.', string.unicode_decode, 'abc', [])
+ self.assertEqual(string.unicode_decode(b'abc', 'ascii'), 'abc')
+ self.assertEqual(string.unicode_decode(b'abc', ['ascii']), 'abc')
+ self.assertRaisesRegexp(
+ UnicodeDecodeError, "'ascii' codec can't decode",
+ string.unicode_decode, 'あいうえお'.encode('utf-8'), 'ascii')
+ self.assertEqual(string.unicode_decode('あいうえお'.encode('utf-8'), ['ascii', 'sjis', 'utf-8']), 'あいうえお')
+ self.assertEqual(string.unicode_decode('あいうえお'.encode('utf-8'), ['ascii', 'utf-8', 'sjis']), 'あいうえお')
+ self.assertEqual(string.unicode_decode('あいうえお'.encode('utf-8'), ['utf-8', 'ascii', 'sjis']), 'あいうえお')
+ self.assertEqual(string.unicode_decode('あいうえお'.encode('utf-8'), ['utf-8', 'utf-8', 'utf-8']), 'あいうえお')
+ self.assertEqual(string.unicode_decode('あいうえお'.encode('sjis'), ['ascii', 'utf-8', 'sjis']), 'あいうえお')
+ self.assertRaisesRegexp(
+ UnicodeDecodeError, "'shift_jis' codec can't decode",
+ string.unicode_decode, 'あいうえお'.encode('utf-8'), ['ascii', 'sjis'])
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files",
"has_many_hunks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 2,
"issue_text_score": 3,
"test_score": 3
},
"num_modified_files": 3
} | 0.1 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "pytest",
"pip_packages": [
"coverage",
"coveralls",
"pytest"
],
"pre_install": null,
"python": "3.4",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | attrs @ file:///opt/conda/conda-bld/attrs_1642510447205/work
certifi==2021.5.30
charset-normalizer==2.0.12
coverage==6.2
coveralls==3.3.1
docopt==0.6.2
idna==3.10
importlib-metadata @ file:///tmp/build/80754af9/importlib-metadata_1631916693255/work
iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work
linecache2==1.0.0
-e git+https://github.com/mogproject/mog-commons-python.git@71a072abdbeff70c14543ef9b307fae3277dc24a#egg=mog_commons
more-itertools @ file:///tmp/build/80754af9/more-itertools_1637733554872/work
packaging @ file:///tmp/build/80754af9/packaging_1637314298585/work
pluggy @ file:///tmp/build/80754af9/pluggy_1615976315926/work
py @ file:///opt/conda/conda-bld/py_1644396412707/work
pyparsing @ file:///tmp/build/80754af9/pyparsing_1635766073266/work
pytest==6.2.4
requests==2.27.1
six==1.17.0
toml @ file:///tmp/build/80754af9/toml_1616166611790/work
traceback2==1.4.0
typing_extensions @ file:///opt/conda/conda-bld/typing_extensions_1647553014482/work
unittest2==1.1.0
urllib3==1.26.20
zipp @ file:///tmp/build/80754af9/zipp_1633618647012/work
| name: mog-commons-python
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- attrs=21.4.0=pyhd3eb1b0_0
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2021.5.30=py36h06a4308_0
- importlib-metadata=4.8.1=py36h06a4308_0
- importlib_metadata=4.8.1=hd3eb1b0_0
- iniconfig=1.1.1=pyhd3eb1b0_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.3=he6710b0_2
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- more-itertools=8.12.0=pyhd3eb1b0_0
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- packaging=21.3=pyhd3eb1b0_0
- pip=21.2.2=py36h06a4308_0
- pluggy=0.13.1=py36h06a4308_0
- py=1.11.0=pyhd3eb1b0_0
- pyparsing=3.0.4=pyhd3eb1b0_0
- pytest=6.2.4=py36h06a4308_2
- python=3.6.13=h12debd9_1
- readline=8.2=h5eee18b_0
- setuptools=58.0.4=py36h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- toml=0.10.2=pyhd3eb1b0_0
- typing_extensions=4.1.1=pyh06a4308_0
- wheel=0.37.1=pyhd3eb1b0_0
- xz=5.6.4=h5eee18b_1
- zipp=3.6.0=pyhd3eb1b0_0
- zlib=1.2.13=h5eee18b_1
- pip:
- argparse==1.4.0
- charset-normalizer==2.0.12
- coverage==6.2
- coveralls==3.3.1
- docopt==0.6.2
- idna==3.10
- linecache2==1.0.0
- requests==2.27.1
- six==1.17.0
- traceback2==1.4.0
- unittest2==1.1.0
- urllib3==1.26.20
prefix: /opt/conda/envs/mog-commons-python
| [
"tests/mog_commons/test_collection.py::TestCollection::test_distinct",
"tests/mog_commons/test_string.py::TestString::test_unicode_decode"
] | [] | [
"tests/mog_commons/test_collection.py::TestCollection::test_get_single_item",
"tests/mog_commons/test_collection.py::TestCollection::test_get_single_item_error",
"tests/mog_commons/test_collection.py::TestCollection::test_get_single_key",
"tests/mog_commons/test_collection.py::TestCollection::test_get_single_key_error",
"tests/mog_commons/test_collection.py::TestCollection::test_get_single_value",
"tests/mog_commons/test_collection.py::TestCollection::test_get_single_value_error",
"tests/mog_commons/test_string.py::TestString::test_edge_just",
"tests/mog_commons/test_string.py::TestString::test_edge_just_unicode",
"tests/mog_commons/test_string.py::TestString::test_to_bytes",
"tests/mog_commons/test_string.py::TestString::test_to_str",
"tests/mog_commons/test_string.py::TestString::test_to_str_py3",
"tests/mog_commons/test_string.py::TestString::test_to_unicode",
"tests/mog_commons/test_string.py::TestString::test_unicode_left",
"tests/mog_commons/test_string.py::TestString::test_unicode_right",
"tests/mog_commons/test_string.py::TestString::test_unicode_width"
] | [] | Apache License 2.0 | 273 |
|
davidhalter__jedi-641 | e0753da6f1ed83185b84c0f9ab65eed67c80dcb4 | 2015-10-24 23:35:37 | 2ba78ab725f1e02dfef8bc50b0204cf656e8ee23 | diff --git a/AUTHORS.txt b/AUTHORS.txt
index 64aae316..bc258d6b 100644
--- a/AUTHORS.txt
+++ b/AUTHORS.txt
@@ -33,5 +33,6 @@ Savor d'Isavano (@KenetJervet) <[email protected]>
Phillip Berndt (@phillipberndt) <[email protected]>
Ian Lee (@IanLee1521) <[email protected]>
Farkhad Khatamov (@hatamov) <[email protected]>
+Kevin Kelley (@kelleyk) <[email protected]>
Note: (@user) means a github user name.
diff --git a/jedi/api/classes.py b/jedi/api/classes.py
index a1d42bd0..75275dd2 100644
--- a/jedi/api/classes.py
+++ b/jedi/api/classes.py
@@ -336,7 +336,7 @@ class BaseDefinition(object):
raise AttributeError()
followed = followed[0] # only check the first one.
- if followed.type == 'funcdef':
+ if followed.type in ('funcdef', 'lambda'):
if isinstance(followed, er.InstanceElement):
params = followed.params[1:]
else:
diff --git a/jedi/parser/tree.py b/jedi/parser/tree.py
index 619067e1..899d5f1c 100644
--- a/jedi/parser/tree.py
+++ b/jedi/parser/tree.py
@@ -748,6 +748,15 @@ def _create_params(parent, argslist_list):
class Function(ClassOrFunc):
"""
Used to store the parsed contents of a python function.
+
+ Children:
+ 0) <Keyword: def>
+ 1) <Name>
+ 2) parameter list (including open-paren and close-paren <Operator>s)
+ 3) <Operator: :>
+ 4) Node() representing function body
+ 5) ??
+ 6) annotation (if present)
"""
__slots__ = ('listeners',)
type = 'funcdef'
@@ -760,6 +769,7 @@ class Function(ClassOrFunc):
@property
def params(self):
+ # Contents of parameter lit minus the leading <Operator: (> and the trailing <Operator: )>.
return self.children[2].children[1:-1]
@property
@@ -791,10 +801,13 @@ class Function(ClassOrFunc):
:rtype: str
"""
- func_name = func_name or self.children[1]
- code = unicode(func_name) + self.children[2].get_code()
+ func_name = func_name or self.name
+ code = unicode(func_name) + self._get_paramlist_code()
return '\n'.join(textwrap.wrap(code, width))
+ def _get_paramlist_code(self):
+ return self.children[2].get_code()
+
@property
def doc(self):
""" Return a document string including call signature. """
@@ -805,6 +818,12 @@ class Function(ClassOrFunc):
class Lambda(Function):
"""
Lambdas are basically trimmed functions, so give it the same interface.
+
+ Children:
+ 0) <Keyword: lambda>
+ *) <Param x> for each argument x
+ -2) <Operator: :>
+ -1) Node() representing body
"""
type = 'lambda'
__slots__ = ()
@@ -813,9 +832,17 @@ class Lambda(Function):
# We don't want to call the Function constructor, call its parent.
super(Function, self).__init__(children)
self.listeners = set() # not used here, but in evaluation.
- lst = self.children[1:-2] # After `def foo`
+ lst = self.children[1:-2] # Everything between `lambda` and the `:` operator is a parameter.
self.children[1:-2] = _create_params(self, lst)
+ @property
+ def name(self):
+ # Borrow the position of the <Keyword: lambda> AST node.
+ return Name(self.children[0].position_modifier, '<lambda>', self.children[0].start_pos)
+
+ def _get_paramlist_code(self):
+ return '(' + ''.join(param.get_code() for param in self.params).strip() + ')'
+
@property
def params(self):
return self.children[1:-2]
@@ -823,6 +850,7 @@ class Lambda(Function):
def is_generator(self):
return False
+ @property
def yields(self):
return []
| 'Lambda' object has no attribute 'get_subscope_by_name'
Jedi 0.9.0, Python 2.7.3
Reproduction:
```Python
import jedi
script = """\
my_lambda = lambda x: x+1
my_lambda(1)
"""
sigs = jedi.Script(script, line=2, column=11).call_signatures()
print sigs[0].index
```
Traceback:
```
Traceback (most recent call last):
File "/home/forcer/Projects/elpy/elpy/rpc.py", line 100, in handle_request
result = method(*params)
File "/home/forcer/Projects/elpy/elpy/server.py", line 87, in rpc_get_calltip
get_source(source), offset)
File "/home/forcer/Projects/elpy/elpy/server.py", line 49, in _call_backend
return meth(*args, **kwargs)
File "/home/forcer/Projects/elpy/elpy/jedibackend.py", line 129, in rpc_get_calltip
"index": call.index,
File "/home/forcer/.virtualenvs/elpy/local/lib/python2.7/site-packages/jedi/api/classes.py", line 653, in index
if self._index >= len(self.params):
File "/home/forcer/.virtualenvs/elpy/local/lib/python2.7/site-packages/jedi/evaluate/cache.py", line 41, in wrapper
rv = function(obj, *args, **kwargs)
File "/home/forcer/.virtualenvs/elpy/local/lib/python2.7/site-packages/jedi/api/classes.py", line 348, in params
sub = followed.get_subscope_by_name('__init__')
File "/home/forcer/.virtualenvs/elpy/local/lib/python2.7/site-packages/jedi/evaluate/representation.py", line 563, in __getattr__
return getattr(self.base_func, name)
AttributeError: 'Lambda' object has no attribute 'get_subscope_by_name'
``` | davidhalter/jedi | diff --git a/test/test_parser/test_parser_tree.py b/test/test_parser/test_parser_tree.py
new file mode 100644
index 00000000..480230ba
--- /dev/null
+++ b/test/test_parser/test_parser_tree.py
@@ -0,0 +1,64 @@
+# -*- coding: utf-8 # This file contains Unicode characters.
+
+from textwrap import dedent
+
+import pytest
+
+from jedi._compatibility import u, unicode
+from jedi.parser import Parser, load_grammar
+from jedi.parser import tree as pt
+
+
+class TestsFunctionAndLambdaParsing(object):
+
+ FIXTURES = [
+ ('def my_function(x, y, z):\n return x + y * z\n', {
+ 'name': 'my_function',
+ 'call_sig': 'my_function(x, y, z)',
+ 'params': ['x', 'y', 'z'],
+ }),
+ ('lambda x, y, z: x + y * z\n', {
+ 'name': '<lambda>',
+ 'call_sig': '<lambda>(x, y, z)',
+ 'params': ['x', 'y', 'z'],
+ }),
+ ]
+
+ @pytest.fixture(params=FIXTURES)
+ def node(self, request):
+ parsed = Parser(load_grammar(), dedent(u(request.param[0])))
+ request.keywords['expected'] = request.param[1]
+ return parsed.module.subscopes[0]
+
+ @pytest.fixture()
+ def expected(self, request, node):
+ return request.keywords['expected']
+
+ def test_name(self, node, expected):
+ assert isinstance(node.name, pt.Name)
+ assert unicode(node.name) == u(expected['name'])
+
+ def test_params(self, node, expected):
+ assert isinstance(node.params, list)
+ assert all(isinstance(x, pt.Param) for x in node.params)
+ assert [unicode(x.name) for x in node.params] == [u(x) for x in expected['params']]
+
+ def test_is_generator(self, node, expected):
+ assert node.is_generator() is expected.get('is_generator', False)
+
+ def test_yields(self, node, expected):
+ # TODO: There's a comment in the code noting that the current implementation is incorrect. This returns an
+ # empty list at the moment (not e.g. False).
+ if expected.get('yields', False):
+ assert node.yields
+ else:
+ assert not node.yields
+
+ def test_annotation(self, node, expected):
+ assert node.annotation() is expected.get('annotation', None)
+
+ def test_get_call_signature(self, node, expected):
+ assert node.get_call_signature() == expected['call_sig']
+
+ def test_doc(self, node, expected):
+ assert node.doc == expected.get('doc') or (expected['call_sig'] + '\n\n')
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 2,
"issue_text_score": 0,
"test_score": 2
},
"num_modified_files": 3
} | 0.9 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest",
"pytest-cache",
"docopt",
"colorama"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.9",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | colorama==0.4.6
docopt==0.6.2
exceptiongroup==1.2.2
execnet==2.1.1
iniconfig==2.1.0
-e git+https://github.com/davidhalter/jedi.git@e0753da6f1ed83185b84c0f9ab65eed67c80dcb4#egg=jedi
packaging==24.2
pluggy==1.5.0
pytest==8.3.5
pytest-cache==1.0
tomli==2.2.1
| name: jedi
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=3.0.16=h5eee18b_0
- pip=25.0=py39h06a4308_0
- python=3.9.21=he870216_1
- readline=8.2=h5eee18b_0
- setuptools=75.8.0=py39h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- tzdata=2025a=h04d1e81_0
- wheel=0.45.1=py39h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- colorama==0.4.6
- docopt==0.6.2
- exceptiongroup==1.2.2
- execnet==2.1.1
- iniconfig==2.1.0
- packaging==24.2
- pluggy==1.5.0
- pytest==8.3.5
- pytest-cache==1.0
- tomli==2.2.1
prefix: /opt/conda/envs/jedi
| [
"test/test_parser/test_parser_tree.py::TestsFunctionAndLambdaParsing::test_name[node1]",
"test/test_parser/test_parser_tree.py::TestsFunctionAndLambdaParsing::test_yields[node1]",
"test/test_parser/test_parser_tree.py::TestsFunctionAndLambdaParsing::test_get_call_signature[node1]"
] | [] | [
"test/test_parser/test_parser_tree.py::TestsFunctionAndLambdaParsing::test_name[node0]",
"test/test_parser/test_parser_tree.py::TestsFunctionAndLambdaParsing::test_params[node0]",
"test/test_parser/test_parser_tree.py::TestsFunctionAndLambdaParsing::test_params[node1]",
"test/test_parser/test_parser_tree.py::TestsFunctionAndLambdaParsing::test_is_generator[node0]",
"test/test_parser/test_parser_tree.py::TestsFunctionAndLambdaParsing::test_is_generator[node1]",
"test/test_parser/test_parser_tree.py::TestsFunctionAndLambdaParsing::test_yields[node0]",
"test/test_parser/test_parser_tree.py::TestsFunctionAndLambdaParsing::test_annotation[node0]",
"test/test_parser/test_parser_tree.py::TestsFunctionAndLambdaParsing::test_annotation[node1]",
"test/test_parser/test_parser_tree.py::TestsFunctionAndLambdaParsing::test_get_call_signature[node0]",
"test/test_parser/test_parser_tree.py::TestsFunctionAndLambdaParsing::test_doc[node0]",
"test/test_parser/test_parser_tree.py::TestsFunctionAndLambdaParsing::test_doc[node1]"
] | [] | MIT License | 274 |
|
sphinx-gallery__sphinx-gallery-66 | 44a1460ae32ac278597cf5f56905fbe519fa025b | 2015-10-27 13:19:02 | c1dbb14a7cc7ab8460a55999cffb5a1d90e9ab14 | diff --git a/README.rst b/README.rst
index 327e8cd..f6e3d05 100644
--- a/README.rst
+++ b/README.rst
@@ -49,10 +49,10 @@ After installing you need to include in your Sphinx ``conf.py`` file:
.. code-block:: python
- import sphinxgallery
+ import sphinx_gallery
extensions = [
...
- 'sphinxgallery.gen_gallery',
+ 'sphinx_gallery.gen_gallery',
]
diff --git a/doc/advanced_configuration.rst b/doc/advanced_configuration.rst
index e697a9c..269d567 100644
--- a/doc/advanced_configuration.rst
+++ b/doc/advanced_configuration.rst
@@ -12,7 +12,7 @@ Within your Sphinx ``conf.py`` file you need to add a configuration dictionary:
.. code-block:: python
- sphinxgallery_conf = {
+ sphinx_gallery_conf = {
'examples_dirs' : '../examples', # path to your examples scripts
'gallery_dirs' : 'auto_examples'} # path where to save gallery generated examples
@@ -30,7 +30,7 @@ the sphinx configuration dictionary:
.. code-block:: python
- sphinxgallery_conf = {
+ sphinx_gallery_conf = {
'examples_dirs' : ['../examples', '../tutorials'],
'gallery_dirs' : ['auto_examples', 'tutorials'],
}
@@ -60,10 +60,10 @@ dictionary within your Sphinx ``conf.py`` file :
.. code-block:: python
- sphinxgallery_conf = {
+ sphinx_gallery_conf = {
'reference_url': {
# The module you locally document uses a None
- 'sphinxgallery': None,
+ 'sphinx_gallery': None,
# External python modules use their documentation websites
'matplotlib': 'http://matplotlib.org',
@@ -84,12 +84,12 @@ configuration dictionary:
.. code-block:: python
- sphinxgallery_conf = {
+ sphinx_gallery_conf = {
# path where to store your example linker templates
'mod_example_dir' : 'modules/generated',
# Your documented modules. You can use a string or a list of strings
- 'doc_module' : ('sphinxgallery', 'numpy')}
+ 'doc_module' : ('sphinx_gallery', 'numpy')}
The path you specified will get populated with the links to examples using your
module and their methods. Then within your sphinx documentation files you
@@ -122,5 +122,5 @@ file. You need to add to the configuration dictionary a key called
.. code-block:: python
- sphinxgallery_conf = {
+ sphinx_gallery_conf = {
'default_thumb_file' : 'path/to/thumb/file.png'}}
diff --git a/doc/conf.py b/doc/conf.py
index 9b2b7a2..daf448c 100644
--- a/doc/conf.py
+++ b/doc/conf.py
@@ -15,7 +15,7 @@
import sys
import os
from datetime import date
-import sphinxgallery
+import sphinx_gallery
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
@@ -37,7 +37,7 @@ extensions = [
'sphinx.ext.todo',
'sphinx.ext.coverage',
'sphinx.ext.mathjax',
- 'sphinxgallery.gen_gallery',
+ 'sphinx_gallery.gen_gallery',
]
# Add any paths that contain templates here, relative to this directory.
@@ -61,9 +61,9 @@ copyright = u'2014-%s, Óscar Nájera' % date.today().year
# built documents.
#
# The short X.Y version.
-version = sphinxgallery.__version__
+version = sphinx_gallery.__version__
# The full version, including alpha/beta/rc tags.
-release = sphinxgallery.__version__ + '-git'
+release = sphinx_gallery.__version__ + '-git'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
@@ -291,10 +291,10 @@ except ImportError:
find_mayavi_figures = False
-sphinxgallery_conf = {
- 'doc_module': ('sphinxgallery', 'numpy'),
+sphinx_gallery_conf = {
+ 'doc_module': ('sphinx_gallery', 'numpy'),
'reference_url': {
- 'sphinxgallery': None,
+ 'sphinx_gallery': None,
'matplotlib': 'http://matplotlib.org',
'numpy': 'http://docs.scipy.org/doc/numpy-1.9.1'},
'examples_dirs': examples_dirs,
diff --git a/doc/reference.rst b/doc/reference.rst
index 7d6c7e8..1df81a5 100644
--- a/doc/reference.rst
+++ b/doc/reference.rst
@@ -3,25 +3,25 @@ Sphinx-Gallery Reference
========================
-.. automodule:: sphinxgallery
+.. automodule:: sphinx_gallery
:members:
-.. autodata:: sphinxgallery.__version__
+.. autodata:: sphinx_gallery.__version__
:annotation: Sphinx Gallery current version
-.. include:: modules/generated/sphinxgallery.__version__.examples
+.. include:: modules/generated/sphinx_gallery.__version__.examples
.. raw:: html
<div style='clear:both'></div>
-.. automodule:: sphinxgallery.gen_gallery
+.. automodule:: sphinx_gallery.gen_gallery
:members:
-.. automodule:: sphinxgallery.backreferences
+.. automodule:: sphinx_gallery.backreferences
:members:
-.. automodule:: sphinxgallery.gen_rst
+.. automodule:: sphinx_gallery.gen_rst
:members:
-.. automodule:: sphinxgallery.docs_resolv
+.. automodule:: sphinx_gallery.docs_resolv
:members:
diff --git a/examples/plot_gallery_version.py b/examples/plot_gallery_version.py
index 7755616..bcd0cd8 100644
--- a/examples/plot_gallery_version.py
+++ b/examples/plot_gallery_version.py
@@ -13,7 +13,7 @@ version.
import numpy as np
import matplotlib.pyplot as plt
-import sphinxgallery
+import sphinx_gallery
np.random.seed(32)
@@ -43,7 +43,7 @@ for mixture in d.T:
mixture[[0, -1]] = 0.
plt.fill(x, mixture, alpha=0.9)
-plt.annotate('Introducing Sphinx-Gallery ' + sphinxgallery.__version__,
+plt.annotate('Introducing Sphinx-Gallery ' + sphinx_gallery.__version__,
xy=(12, 4), arrowprops=dict(arrowstyle='->'), xytext=(22, 6))
plt.xticks([])
diff --git a/setup.cfg b/setup.cfg
index 4e2423b..4e43f4c 100644
--- a/setup.cfg
+++ b/setup.cfg
@@ -2,7 +2,7 @@
verbosity=1
detailed-errors=1
with-coverage=1
-cover-package=sphinxgallery
+cover-package=sphinx_gallery
with-doctest=1
doctest-extension=rst
diff --git a/setup.py b/setup.py
index d2808aa..a24015b 100644
--- a/setup.py
+++ b/setup.py
@@ -6,7 +6,7 @@ Installer Sphinx extension for gallery generator
"""
from setuptools import setup, find_packages
-import sphinxgallery
+import sphinx_gallery
with open('README.rst') as f:
long_description = f.read()
@@ -16,9 +16,9 @@ setup(
name="sphinx-gallery",
description="Sphinx extension to automatically generate an examples gallery",
long_description=long_description,
- version=sphinxgallery.__version__,
+ version=sphinx_gallery.__version__,
packages=find_packages(),
- package_data={'sphinxgallery': ['_static/gallery.css', '_static/no_image.png']},
+ package_data={'sphinx_gallery': ['_static/gallery.css', '_static/no_image.png']},
url="https://github.com/sphinx-gallery/sphinx-gallery",
author="Óscar Nájera",
author_email='[email protected]',
diff --git a/sphinxgallery/__init__.py b/sphinx_gallery/__init__.py
similarity index 100%
rename from sphinxgallery/__init__.py
rename to sphinx_gallery/__init__.py
diff --git a/sphinxgallery/_static/gallery.css b/sphinx_gallery/_static/gallery.css
similarity index 100%
rename from sphinxgallery/_static/gallery.css
rename to sphinx_gallery/_static/gallery.css
diff --git a/sphinxgallery/_static/gallery.scss b/sphinx_gallery/_static/gallery.scss
similarity index 100%
rename from sphinxgallery/_static/gallery.scss
rename to sphinx_gallery/_static/gallery.scss
diff --git a/sphinxgallery/_static/no_image.png b/sphinx_gallery/_static/no_image.png
similarity index 100%
rename from sphinxgallery/_static/no_image.png
rename to sphinx_gallery/_static/no_image.png
diff --git a/sphinxgallery/backreferences.py b/sphinx_gallery/backreferences.py
similarity index 100%
rename from sphinxgallery/backreferences.py
rename to sphinx_gallery/backreferences.py
diff --git a/sphinxgallery/docs_resolv.py b/sphinx_gallery/docs_resolv.py
similarity index 99%
rename from sphinxgallery/docs_resolv.py
rename to sphinx_gallery/docs_resolv.py
index 7a04f4b..fb596fd 100644
--- a/sphinxgallery/docs_resolv.py
+++ b/sphinx_gallery/docs_resolv.py
@@ -426,7 +426,7 @@ def embed_code_links(app, exception):
print('Embedding documentation hyperlinks in examples..')
- gallery_conf = app.config.sphinxgallery_conf
+ gallery_conf = app.config.sphinx_gallery_conf
gallery_dirs = gallery_conf['gallery_dirs']
if not isinstance(gallery_dirs, list):
diff --git a/sphinxgallery/gen_gallery.py b/sphinx_gallery/gen_gallery.py
similarity index 96%
rename from sphinxgallery/gen_gallery.py
rename to sphinx_gallery/gen_gallery.py
index 39eb931..22ae562 100644
--- a/sphinxgallery/gen_gallery.py
+++ b/sphinx_gallery/gen_gallery.py
@@ -43,10 +43,10 @@ def generate_gallery_rst(app):
except TypeError:
plot_gallery = bool(app.builder.config.plot_gallery)
- gallery_conf.update(app.config.sphinxgallery_conf)
+ gallery_conf.update(app.config.sphinx_gallery_conf)
# this assures I can call the config in other places
- app.config.sphinxgallery_conf = gallery_conf
+ app.config.sphinx_gallery_conf = gallery_conf
app.config.html_static_path.append(glr_path_static())
if not plot_gallery:
@@ -104,7 +104,7 @@ gallery_conf = {
def setup(app):
"""Setup sphinx-gallery sphinx extension"""
app.add_config_value('plot_gallery', True, 'html')
- app.add_config_value('sphinxgallery_conf', gallery_conf, 'html')
+ app.add_config_value('sphinx_gallery_conf', gallery_conf, 'html')
app.add_stylesheet('gallery.css')
app.connect('builder-inited', generate_gallery_rst)
| Rename package to sphinx_gallery rather than sphinxgallery?
A very minor annoyance, but I thought I would vent it out and ask for opinions, it seems to me that sphinx_gallery for the package name is more in line with sphinx-gallery as the project name.
Basically if people agree it would be wise to fix that sooner rather than later, to reduce the impact on potential users. | sphinx-gallery/sphinx-gallery | diff --git a/sphinxgallery/gen_rst.py b/sphinx_gallery/gen_rst.py
similarity index 100%
rename from sphinxgallery/gen_rst.py
rename to sphinx_gallery/gen_rst.py
diff --git a/sphinxgallery/tests/reference_parse.txt b/sphinx_gallery/tests/reference_parse.txt
similarity index 100%
rename from sphinxgallery/tests/reference_parse.txt
rename to sphinx_gallery/tests/reference_parse.txt
diff --git a/sphinxgallery/tests/test_backreferences.py b/sphinx_gallery/tests/test_backreferences.py
similarity index 96%
rename from sphinxgallery/tests/test_backreferences.py
rename to sphinx_gallery/tests/test_backreferences.py
index d11deb3..ca1542b 100644
--- a/sphinxgallery/tests/test_backreferences.py
+++ b/sphinx_gallery/tests/test_backreferences.py
@@ -5,7 +5,7 @@
Testing the rst files generator
"""
from __future__ import division, absolute_import, print_function
-import sphinxgallery.backreferences as sg
+import sphinx_gallery.backreferences as sg
from nose.tools import assert_equal
diff --git a/sphinxgallery/tests/test_docs_resolv.py b/sphinx_gallery/tests/test_docs_resolv.py
similarity index 96%
rename from sphinxgallery/tests/test_docs_resolv.py
rename to sphinx_gallery/tests/test_docs_resolv.py
index a858834..7162910 100644
--- a/sphinxgallery/tests/test_docs_resolv.py
+++ b/sphinx_gallery/tests/test_docs_resolv.py
@@ -5,7 +5,7 @@
Testing the rst files generator
"""
from __future__ import division, absolute_import, print_function
-import sphinxgallery.docs_resolv as sg
+import sphinx_gallery.docs_resolv as sg
import tempfile
import sys
from nose.tools import assert_equal
diff --git a/sphinxgallery/tests/test_gen_rst.py b/sphinx_gallery/tests/test_gen_rst.py
similarity index 96%
rename from sphinxgallery/tests/test_gen_rst.py
rename to sphinx_gallery/tests/test_gen_rst.py
index 8914ab6..4fb7854 100644
--- a/sphinxgallery/tests/test_gen_rst.py
+++ b/sphinx_gallery/tests/test_gen_rst.py
@@ -7,7 +7,7 @@ Testing the rst files generator
from __future__ import division, absolute_import, print_function
import tempfile
-import sphinxgallery.gen_rst as sg
+import sphinx_gallery.gen_rst as sg
from nose.tools import assert_equal, assert_false
import ast
@@ -25,7 +25,7 @@ def test_bug_cases_of_notebook_syntax():
"""Test over the known requirements of supported syntax in the
notebook styled comments"""
- with open('sphinxgallery/tests/reference_parse.txt') as reference:
+ with open('sphinx_gallery/tests/reference_parse.txt') as reference:
ref_blocks = ast.literal_eval(reference.read())
blocks = sg.split_code_and_text_blocks('tutorials/plot_parse.py')
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 0,
"issue_text_score": 0,
"test_score": 3
},
"num_modified_files": 9
} | 0.0 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.9",
"reqs_path": [
"requirements.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | alabaster==0.7.16
babel==2.17.0
certifi==2025.1.31
charset-normalizer==3.4.1
contourpy==1.3.0
cycler==0.12.1
docutils==0.21.2
exceptiongroup==1.2.2
fonttools==4.56.0
idna==3.10
imagesize==1.4.1
importlib_metadata==8.6.1
importlib_resources==6.5.2
iniconfig==2.1.0
Jinja2==3.1.6
kiwisolver==1.4.7
MarkupSafe==3.0.2
matplotlib==3.9.4
nose==1.3.7
numpy==2.0.2
packaging==24.2
pillow==11.1.0
pluggy==1.5.0
Pygments==2.19.1
pyparsing==3.2.3
pytest==8.3.5
python-dateutil==2.9.0.post0
requests==2.32.3
six==1.17.0
snowballstemmer==2.2.0
Sphinx==7.4.7
-e git+https://github.com/sphinx-gallery/sphinx-gallery.git@44a1460ae32ac278597cf5f56905fbe519fa025b#egg=sphinx_gallery
sphinxcontrib-applehelp==2.0.0
sphinxcontrib-devhelp==2.0.0
sphinxcontrib-htmlhelp==2.1.0
sphinxcontrib-jsmath==1.0.1
sphinxcontrib-qthelp==2.0.0
sphinxcontrib-serializinghtml==2.0.0
tomli==2.2.1
urllib3==2.3.0
zipp==3.21.0
| name: sphinx-gallery
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=3.0.16=h5eee18b_0
- pip=25.0=py39h06a4308_0
- python=3.9.21=he870216_1
- readline=8.2=h5eee18b_0
- setuptools=75.8.0=py39h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- tzdata=2025a=h04d1e81_0
- wheel=0.45.1=py39h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- alabaster==0.7.16
- babel==2.17.0
- certifi==2025.1.31
- charset-normalizer==3.4.1
- contourpy==1.3.0
- cycler==0.12.1
- docutils==0.21.2
- exceptiongroup==1.2.2
- fonttools==4.56.0
- idna==3.10
- imagesize==1.4.1
- importlib-metadata==8.6.1
- importlib-resources==6.5.2
- iniconfig==2.1.0
- jinja2==3.1.6
- kiwisolver==1.4.7
- markupsafe==3.0.2
- matplotlib==3.9.4
- nose==1.3.7
- numpy==2.0.2
- packaging==24.2
- pillow==11.1.0
- pluggy==1.5.0
- pygments==2.19.1
- pyparsing==3.2.3
- pytest==8.3.5
- python-dateutil==2.9.0.post0
- requests==2.32.3
- six==1.17.0
- snowballstemmer==2.2.0
- sphinx==7.4.7
- sphinxcontrib-applehelp==2.0.0
- sphinxcontrib-devhelp==2.0.0
- sphinxcontrib-htmlhelp==2.1.0
- sphinxcontrib-jsmath==1.0.1
- sphinxcontrib-qthelp==2.0.0
- sphinxcontrib-serializinghtml==2.0.0
- tomli==2.2.1
- urllib3==2.3.0
- zipp==3.21.0
prefix: /opt/conda/envs/sphinx-gallery
| [
"sphinx_gallery/tests/test_backreferences.py::test_thumbnail_div",
"sphinx_gallery/tests/test_backreferences.py::test_backref_thumbnail_div",
"sphinx_gallery/tests/test_docs_resolv.py::test_shelve",
"sphinx_gallery/tests/test_gen_rst.py::test_split_code_and_text_blocks",
"sphinx_gallery/tests/test_gen_rst.py::test_direct_comment_after_docstring",
"sphinx_gallery/tests/test_gen_rst.py::test_codestr2rst",
"sphinx_gallery/tests/test_gen_rst.py::test_extract_intro"
] | [
"sphinx_gallery/tests/test_gen_rst.py::test_bug_cases_of_notebook_syntax"
] | [] | [] | BSD 3-Clause "New" or "Revised" License | 275 |
|
pystorm__pystorm-14 | 111356b63c7a44261fb4d0c827745e793ca8717e | 2015-10-27 16:46:13 | eaa0bf28f57e43950379dfaabac7174ad5db4740 | diff --git a/pystorm/component.py b/pystorm/component.py
index 23d82e8..80c5abf 100644
--- a/pystorm/component.py
+++ b/pystorm/component.py
@@ -3,14 +3,17 @@ from __future__ import absolute_import, print_function, unicode_literals
import logging
import os
+import re
import signal
import sys
-from collections import deque, namedtuple
+from collections import defaultdict, deque, namedtuple
from logging.handlers import RotatingFileHandler
from os.path import join
from threading import RLock
from traceback import format_exc
+from six import iteritems
+
from .exceptions import StormWentAwayError
from .serializers.msgpack_serializer import MsgpackSerializer
from .serializers.json_serializer import JSONSerializer
@@ -36,6 +39,9 @@ _PYTHON_LOG_LEVELS = {'critical': logging.CRITICAL,
'debug': logging.DEBUG,
'trace': logging.DEBUG}
_SERIALIZERS = {"json": JSONSerializer, "msgpack": MsgpackSerializer}
+# Convert names to valid Python identifiers by replacing non-word characters
+# whitespace and leading digits with underscores.
+_IDENTIFIER_RE = re.compile(r'\W|^(?=\d)')
log = logging.getLogger(__name__)
@@ -121,7 +127,7 @@ Tuple = namedtuple('Tuple', 'id component stream task values')
:ivar task: the task the Tuple was generated from.
:type task: int
:ivar values: the payload of the Tuple where data is stored.
-:type values: list
+:type values: tuple (or namedtuple for Storm 0.10.0+)
"""
@@ -177,6 +183,7 @@ class Component(object):
self.context = None
self.pid = os.getpid()
self.logger = None
+ self._source_tuple_types = defaultdict(dict)
# pending commands/Tuples we read while trying to read task IDs
self._pending_commands = deque()
# pending task IDs we read while trying to read commands/Tuples
@@ -207,6 +214,15 @@ class Component(object):
self.topology_name = storm_conf.get('topology.name', '')
self.task_id = context.get('taskid', '')
self.component_name = context.get('componentid')
+ # source->stream->fields requires Storm 0.10.0 or later
+ source_stream_fields = context.get('source->stream->fields', {})
+ for source, stream_fields in iteritems(source_stream_fields):
+ for stream, fields in iteritems(stream_fields):
+ type_name = (_IDENTIFIER_RE.sub('_', source.title()) +
+ _IDENTIFIER_RE.sub('_', stream.title()) +
+ 'Tuple')
+ self._source_tuple_types[source][stream] = namedtuple(type_name,
+ fields)
# If using Storm before 0.10.0 componentid is not available
if self.component_name is None:
self.component_name = context.get('task->component', {})\
@@ -280,8 +296,12 @@ class Component(object):
def read_tuple(self):
cmd = self.read_command()
- return Tuple(cmd['id'], cmd['comp'], cmd['stream'], cmd['task'],
- cmd['tuple'])
+ source = cmd['comp']
+ stream = cmd['stream']
+ values = cmd['tuple']
+ val_type = self._source_tuple_types[source].get(stream)
+ return Tuple(cmd['id'], source, stream, cmd['task'],
+ tuple(values) if val_type is None else val_type(*values))
def read_handshake(self):
"""Read and process an initial handshake message from Storm."""
| Have Tuple.values be a namedtuple so fields can be accessed by name
_From @dan-blanchard on April 15, 2015 13:57_
This was brought up as part of our discussion of the rejected #120. What we want to do is:
- [x] Submit a PR to Storm that serializes [`TopologyContext.componentToStreamToFields`](https://github.com/apache/storm/blob/master/storm-core/src/jvm/backtype/storm/task/TopologyContext.java#L61) and sends that along as part of Multi-Lang handshake.
- [x] Add a `_stream_fields` dictionary attribute to the `Component` class that maps from streams to `namedtuple` types representing the names of fields/values in the tuple. This should get created at handshake time based on the contents of `componentToStreamToFields`.
- [x] Modify `Component.read_tuple()` to set `Tuple.values` to be a `namedtuple` of the appropriate type for the current stream (by looking it up in `Component._stream_fields`.
This will allow users to get values out of their tuples by accessing values directly by name (`word = tup.values.word`), or by unpacking (`word, count = tup.values`).
_Copied from original issue: Parsely/streamparse#127_ | pystorm/pystorm | diff --git a/test/pystorm/test_bolt.py b/test/pystorm/test_bolt.py
index f9586c3..80cf5c8 100644
--- a/test/pystorm/test_bolt.py
+++ b/test/pystorm/test_bolt.py
@@ -34,7 +34,7 @@ class BoltTests(unittest.TestCase):
tup_json = "{}\nend\n".format(json.dumps(self.tup_dict)).encode('utf-8')
self.tup = Tuple(self.tup_dict['id'], self.tup_dict['comp'],
self.tup_dict['stream'], self.tup_dict['task'],
- self.tup_dict['tuple'],)
+ tuple(self.tup_dict['tuple']),)
self.bolt = Bolt(input_stream=BytesIO(tup_json),
output_stream=BytesIO())
self.bolt.initialize({}, {})
@@ -190,7 +190,7 @@ class BoltTests(unittest.TestCase):
def test_heartbeat_response(self, send_message_mock, read_tuple_mock):
# Make sure we send sync for heartbeats
read_tuple_mock.return_value = Tuple(id='foo', task=-1,
- stream='__heartbeat', values=[],
+ stream='__heartbeat', values=(),
component='__system')
self.bolt._run()
send_message_mock.assert_called_with(self.bolt, {'command': 'sync'})
@@ -201,7 +201,7 @@ class BoltTests(unittest.TestCase):
# Make sure we send sync for heartbeats
read_tuple_mock.return_value = Tuple(id=None, task=-1,
component='__system',
- stream='__tick', values=[50])
+ stream='__tick', values=(50,))
self.bolt._run()
process_tick_mock.assert_called_with(self.bolt,
read_tuple_mock.return_value)
@@ -239,8 +239,8 @@ class BatchingBoltTests(unittest.TestCase):
tups_json = '\nend\n'.join([json.dumps(tup_dict) for tup_dict in
self.tup_dicts] + [''])
self.tups = [Tuple(tup_dict['id'], tup_dict['comp'], tup_dict['stream'],
- tup_dict['task'], tup_dict['tuple']) for tup_dict in
- self.tup_dicts]
+ tup_dict['task'], tuple(tup_dict['tuple']))
+ for tup_dict in self.tup_dicts]
self.nontick_tups = [tup for tup in self.tups if tup.stream != '__tick']
self.bolt = BatchingBolt(input_stream=BytesIO(tups_json.encode('utf-8')),
output_stream=BytesIO())
@@ -364,7 +364,7 @@ class BatchingBoltTests(unittest.TestCase):
def test_heartbeat_response(self, send_message_mock, read_tuple_mock):
# Make sure we send sync for heartbeats
read_tuple_mock.return_value = Tuple(id='foo', task=-1,
- stream='__heartbeat', values=[],
+ stream='__heartbeat', values=(),
component='__system')
self.bolt._run()
send_message_mock.assert_called_with(self.bolt, {'command': 'sync'})
@@ -375,7 +375,7 @@ class BatchingBoltTests(unittest.TestCase):
# Make sure we send sync for heartbeats
read_tuple_mock.return_value = Tuple(id=None, task=-1,
component='__system',
- stream='__tick', values=[50])
+ stream='__tick', values=(50,))
self.bolt._run()
process_tick_mock.assert_called_with(self.bolt,
read_tuple_mock.return_value)
diff --git a/test/pystorm/test_component.py b/test/pystorm/test_component.py
index f7228f4..c508ae1 100644
--- a/test/pystorm/test_component.py
+++ b/test/pystorm/test_component.py
@@ -7,6 +7,7 @@ from __future__ import absolute_import, print_function, unicode_literals
import logging
import os
import unittest
+from collections import namedtuple
from io import BytesIO
import simplejson as json
@@ -24,49 +25,48 @@ log = logging.getLogger(__name__)
class ComponentTests(unittest.TestCase):
-
- def test_read_handshake(self):
- handshake_dict = {
- "conf": {
- "topology.message.timeout.secs": 3,
- "topology.tick.tuple.freq.secs": 1,
- "topology.debug": True
- },
- "pidDir": ".",
- "context": {
- "task->component": {
- "1": "example-spout",
- "2": "__acker",
- "3": "example-bolt1",
- "4": "example-bolt2"
- },
- "taskid": 3,
- # Everything below this line is only available in Storm 0.10.0+
- "componentid": "example-bolt1",
- "stream->target->grouping": {
- "default": {
- "example-bolt2": {
- "type": "SHUFFLE"
- }
- }
- },
- "streams": ["default"],
- "stream->outputfields": {"default": ["word"]},
- "source->stream->grouping": {
- "example-spout": {
- "default": {
- "type": "FIELDS",
- "fields": ["word"]
- }
- }
- },
- "source->stream->fields": {
- "example-spout": {
- "default": ["word"]
- }
+ conf = {"topology.message.timeout.secs": 3,
+ "topology.tick.tuple.freq.secs": 1,
+ "topology.debug": True,
+ "topology.name": "foo"}
+ context = {
+ "task->component": {
+ "1": "example-spout",
+ "2": "__acker",
+ "3": "example-bolt1",
+ "4": "example-bolt2"
+ },
+ "taskid": 3,
+ # Everything below this line is only available in Storm 0.11.0+
+ "componentid": "example-bolt1",
+ "stream->target->grouping": {
+ "default": {
+ "example-bolt2": {
+ "type": "SHUFFLE"
+ }
+ }
+ },
+ "streams": ["default"],
+ "stream->outputfields": {"default": ["word"]},
+ "source->stream->grouping": {
+ "example-spout": {
+ "default": {
+ "type": "FIELDS",
+ "fields": ["word"]
}
}
+ },
+ "source->stream->fields": {
+ "example-spout": {
+ "default": ["sentence", "word", "number"]
+ }
}
+ }
+
+ def test_read_handshake(self):
+ handshake_dict = {"conf": self.conf,
+ "pidDir": ".",
+ "context": self.context}
pid_dir = handshake_dict['pidDir']
expected_conf = handshake_dict['conf']
expected_context = handshake_dict['context']
@@ -84,52 +84,18 @@ class ComponentTests(unittest.TestCase):
component.serializer.output_stream.buffer.getvalue())
def test_setup_component(self):
- conf = {"topology.message.timeout.secs": 3,
- "topology.tick.tuple.freq.secs": 1,
- "topology.debug": True,
- "topology.name": "foo"}
- context = {
- "task->component": {
- "1": "example-spout",
- "2": "__acker",
- "3": "example-bolt1",
- "4": "example-bolt2"
- },
- "taskid": 3,
- # Everything below this line is only available in Storm 0.11.0+
- "componentid": "example-bolt1",
- "stream->target->grouping": {
- "default": {
- "example-bolt2": {
- "type": "SHUFFLE"
- }
- }
- },
- "streams": ["default"],
- "stream->outputfields": {"default": ["word"]},
- "source->stream->grouping": {
- "example-spout": {
- "default": {
- "type": "FIELDS",
- "fields": ["word"]
- }
- }
- },
- "source->stream->fields": {
- "example-spout": {
- "default": ["word"]
- }
- }
- }
+ conf = self.conf
component = Component(input_stream=BytesIO(),
output_stream=BytesIO())
- component._setup_component(conf, context)
+ component._setup_component(conf, self.context)
+ self.assertEqual(component._source_tuple_types['example-spout']['default'].__name__,
+ 'Example_SpoutDefaultTuple')
self.assertEqual(component.topology_name, conf['topology.name'])
- self.assertEqual(component.task_id, context['taskid'])
+ self.assertEqual(component.task_id, self.context['taskid'])
self.assertEqual(component.component_name,
- context['task->component'][str(context['taskid'])])
+ self.context['task->component'][str(self.context['taskid'])])
self.assertEqual(component.storm_conf, conf)
- self.assertEqual(component.context, context)
+ self.assertEqual(component.context, self.context)
def test_read_message(self):
inputs = [# Task IDs
@@ -259,7 +225,7 @@ class ComponentTests(unittest.TestCase):
for msg in inputs[::2]:
output = json.loads(msg)
output['component'] = output['comp']
- output['values'] = output['tuple']
+ output['values'] = tuple(output['tuple'])
del output['comp']
del output['tuple']
outputs.append(Tuple(**output))
@@ -272,6 +238,38 @@ class ComponentTests(unittest.TestCase):
tup = component.read_tuple()
self.assertEqual(output, tup)
+ def test_read_tuple_named_fields(self):
+ # This is only valid for bolts, so we only need to test with task IDs
+ # and Tuples
+ inputs = [('{ "id": "-6955786537413359385", "comp": "example-spout", '
+ '"stream": "default", "task": 9, "tuple": ["snow white and '
+ 'the seven dwarfs", "field2", 3]}\n'), 'end\n']
+
+ component = Component(input_stream=BytesIO(''.join(inputs).encode('utf-8')),
+ output_stream=BytesIO())
+ component._setup_component(self.conf, self.context)
+
+ Example_SpoutDefaultTuple = namedtuple('Example_SpoutDefaultTuple',
+ field_names=['sentence', 'word',
+ 'number'])
+
+ outputs = []
+ for msg in inputs[::2]:
+ output = json.loads(msg)
+ output['component'] = output['comp']
+ output['values'] = Example_SpoutDefaultTuple(*output['tuple'])
+ del output['comp']
+ del output['tuple']
+ outputs.append(Tuple(**output))
+
+ for output in outputs:
+ log.info('Checking Tuple for %r', output)
+ tup = component.read_tuple()
+ self.assertEqual(output.values.sentence, tup.values.sentence)
+ self.assertEqual(output.values.word, tup.values.word)
+ self.assertEqual(output.values.number, tup.values.number)
+ self.assertEqual(output, tup)
+
def test_send_message(self):
component = Component(input_stream=BytesIO(), output_stream=BytesIO())
inputs = [{"command": "emit", "id": 4, "stream": "", "task": 9,
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_hyperlinks",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 1,
"issue_text_score": 0,
"test_score": 0
},
"num_modified_files": 1
} | 1.0 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[all]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest",
"mock"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.5",
"reqs_path": [
"requirements.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | attrs==22.2.0
certifi==2021.5.30
importlib-metadata==4.8.3
iniconfig==1.1.1
mock==5.2.0
msgpack-python==0.5.6
packaging==21.3
pluggy==1.0.0
py==1.11.0
pyparsing==3.1.4
-e git+https://github.com/pystorm/pystorm.git@111356b63c7a44261fb4d0c827745e793ca8717e#egg=pystorm
pytest==7.0.1
simplejson==3.20.1
six==1.17.0
tomli==1.2.3
typing_extensions==4.1.1
zipp==3.6.0
| name: pystorm
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2021.5.30=py36h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.3=he6710b0_2
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- pip=21.2.2=py36h06a4308_0
- python=3.6.13=h12debd9_1
- readline=8.2=h5eee18b_0
- setuptools=58.0.4=py36h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- wheel=0.37.1=pyhd3eb1b0_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- attrs==22.2.0
- importlib-metadata==4.8.3
- iniconfig==1.1.1
- mock==5.2.0
- msgpack-python==0.5.6
- packaging==21.3
- pluggy==1.0.0
- py==1.11.0
- pyparsing==3.1.4
- pytest==7.0.1
- simplejson==3.20.1
- six==1.17.0
- tomli==1.2.3
- typing-extensions==4.1.1
- zipp==3.6.0
prefix: /opt/conda/envs/pystorm
| [
"test/pystorm/test_bolt.py::BoltTests::test_auto_ack_on",
"test/pystorm/test_bolt.py::BoltTests::test_run",
"test/pystorm/test_bolt.py::BatchingBoltTests::test_auto_ack_off",
"test/pystorm/test_bolt.py::BatchingBoltTests::test_auto_ack_on",
"test/pystorm/test_bolt.py::BatchingBoltTests::test_auto_fail_on",
"test/pystorm/test_bolt.py::BatchingBoltTests::test_batching",
"test/pystorm/test_bolt.py::BatchingBoltTests::test_group_key",
"test/pystorm/test_component.py::ComponentTests::test_read_tuple",
"test/pystorm/test_component.py::ComponentTests::test_read_tuple_named_fields",
"test/pystorm/test_component.py::ComponentTests::test_setup_component"
] | [] | [
"test/pystorm/test_bolt.py::BoltTests::test_ack_id",
"test/pystorm/test_bolt.py::BoltTests::test_ack_tuple",
"test/pystorm/test_bolt.py::BoltTests::test_auto_ack_off",
"test/pystorm/test_bolt.py::BoltTests::test_auto_anchor_off",
"test/pystorm/test_bolt.py::BoltTests::test_auto_anchor_on",
"test/pystorm/test_bolt.py::BoltTests::test_auto_anchor_override",
"test/pystorm/test_bolt.py::BoltTests::test_auto_fail_off",
"test/pystorm/test_bolt.py::BoltTests::test_auto_fail_on",
"test/pystorm/test_bolt.py::BoltTests::test_emit_basic",
"test/pystorm/test_bolt.py::BoltTests::test_emit_direct",
"test/pystorm/test_bolt.py::BoltTests::test_emit_stream_anchors",
"test/pystorm/test_bolt.py::BoltTests::test_fail_id",
"test/pystorm/test_bolt.py::BoltTests::test_fail_tuple",
"test/pystorm/test_bolt.py::BoltTests::test_heartbeat_response",
"test/pystorm/test_bolt.py::BoltTests::test_process_tick",
"test/pystorm/test_bolt.py::BatchingBoltTests::test_auto_fail_off",
"test/pystorm/test_bolt.py::BatchingBoltTests::test_auto_fail_partial",
"test/pystorm/test_bolt.py::BatchingBoltTests::test_heartbeat_response",
"test/pystorm/test_bolt.py::BatchingBoltTests::test_process_tick",
"test/pystorm/test_component.py::ComponentTests::test_log",
"test/pystorm/test_component.py::ComponentTests::test_read_command",
"test/pystorm/test_component.py::ComponentTests::test_read_handshake",
"test/pystorm/test_component.py::ComponentTests::test_read_message",
"test/pystorm/test_component.py::ComponentTests::test_read_message_unicode",
"test/pystorm/test_component.py::ComponentTests::test_read_split_message",
"test/pystorm/test_component.py::ComponentTests::test_read_task_ids",
"test/pystorm/test_component.py::ComponentTests::test_send_message",
"test/pystorm/test_component.py::ComponentTests::test_send_message_unicode"
] | [] | Apache License 2.0 | 276 |
|
sympy__sympy-10053 | 4349739ef2685623b379ed338a67b9cff093b54b | 2015-10-27 17:47:23 | 0241b35cae5f2adc04dc37b25f7dc9c5f00bd746 | jksuom: This looks good.
There are other (nonsensical) cases where ``pspace(condition)`` returns ``None`` and ``AttributeError`` results, for example ``P(1)``. Perhaps these should also be caught and something more informative be returned (maybe ``nan``).
```
gxyd: > Perhaps these should also be caught and something more informative be returned (maybe nan).
Yes, i have added `ValueError`, but since `condition` is expected to be a `Relational`, so i think returning `ValueError` looks better to me instead of `nan`.
jksuom: It is a good idea to catch any ``condition`` that is not a ``Relational``.
In addition, I think it would be advisable to make sure that ``pspace(condition)`` does not return ``None``. That can happen even when ``condition`` is a ``Relational`` if it does not contain random variables. For example, ``P(x < 1)`` for an ordinary symbol ``x``.
gxyd: > It is a good idea to catch any condition that is not a Relational.
It can even take non-relationals like: `And(X + Y < 3, Y < 2) `. That's why
the current tests fail. I think i should use some, `.has(Relational)`
property for that may be.
On Wed, Oct 28, 2015 at 12:41 PM, Kalevi Suominen <[email protected]>
wrote:
> It is a good idea to catch any condition that is not a Relational.
> In addition, I think it would be advisable to make sure that
> pspace(condition) does not return None. That can happen even when
> condition is a Relational if it does not contain random variables. For
> example, P(x < 1) for an ordinary symbol x.
>
> —
> Reply to this email directly or view it on GitHub
> <https://github.com/sympy/sympy/pull/10053#issuecomment-151749233>.
>
gxyd: Ex. P(And(X + Y < 2, X > 1)) where `X` and `Y` are both `RandomSymbol`.
On Wed, Oct 28, 2015 at 12:46 PM, Gaurav Dhingra <[email protected]> wrote:
> > It is a good idea to catch any condition that is not a Relational.
>
> It can even take non-relationals like: `And(X + Y < 3, Y < 2) `. That's
> why the current tests fail. I think i should use some, `.has(Relational)`
> property for that may be.
>
> On Wed, Oct 28, 2015 at 12:41 PM, Kalevi Suominen <
> [email protected]> wrote:
>
>> It is a good idea to catch any condition that is not a Relational.
>> In addition, I think it would be advisable to make sure that
>> pspace(condition) does not return None. That can happen even when
>> condition is a Relational if it does not contain random variables. For
>> example, P(x < 1) for an ordinary symbol x.
>>
>> —
>> Reply to this email directly or view it on GitHub
>> <https://github.com/sympy/sympy/pull/10053#issuecomment-151749233>.
>>
>
>
jksuom: Yes, there are ``BooleanFunction``s like ``And`` that should be accepted. Perhaps everything that derives from ``Boolean`` should be allowed. That would simplify the test.
gxyd: I too think it is better for `given(condition)` to raise an Error instead of returning `None`. It is now ready for review. | diff --git a/sympy/stats/rv.py b/sympy/stats/rv.py
index ff9060cf6e..b3686a1fab 100644
--- a/sympy/stats/rv.py
+++ b/sympy/stats/rv.py
@@ -15,7 +15,9 @@
from __future__ import print_function, division
from sympy import (Basic, S, Expr, Symbol, Tuple, And, Add, Eq, lambdify,
- Equality, Lambda, DiracDelta)
+ Equality, Lambda, DiracDelta, sympify)
+from sympy.core.relational import Relational
+from sympy.logic.boolalg import Boolean
from sympy.solvers.solveset import solveset
from sympy.sets.sets import FiniteSet, ProductSet, Intersection
from sympy.abc import x
@@ -121,7 +123,7 @@ class PSpace(Basic):
A Probability Space
Probability Spaces encode processes that equal different values
- probabalistically. These underly Random Symbols which occur in SymPy
+ probabilistically. These underly Random Symbols which occur in SymPy
expressions and contain the mechanics to evaluate statistical statements.
See Also
@@ -422,9 +424,10 @@ def pspace(expr):
True
"""
+ expr = sympify(expr)
rvs = random_symbols(expr)
if not rvs:
- return None
+ raise ValueError("Expression containing Random Variable expected, not %s" % (expr))
# If only one space present
if all(rv.pspace == rvs[0].pspace for rv in rvs):
return rvs[0].pspace
@@ -469,7 +472,7 @@ def given(expr, condition=None, **kwargs):
>>> from sympy.stats import given, density, Die
>>> X = Die('X', 6)
- >>> Y = given(X, X>3)
+ >>> Y = given(X, X > 3)
>>> density(Y).dict
{4: 1/3, 5: 1/3, 6: 1/3}
@@ -550,7 +553,7 @@ def expectation(expr, condition=None, numsamples=None, evaluate=True, **kwargs):
>>> E(2*X + 1)
8
- >>> E(X, X>3) # Expectation of X given that it is above 3
+ >>> E(X, X > 3) # Expectation of X given that it is above 3
5
"""
@@ -585,10 +588,11 @@ def probability(condition, given_condition=None, numsamples=None,
Parameters
==========
- condition : Relational containing RandomSymbols
+ condition : Combination of Relationals containing RandomSymbols
The condition of which you want to compute the probability
- given_condition : Relational containing RandomSymbols
- A conditional expression. P(X>1, X>0) is expectation of X>1 given X>0
+ given_condition : Combination of Relationals containing RandomSymbols
+ A conditional expression. P(X > 1, X > 0) is expectation of X > 1
+ given X > 0
numsamples : int
Enables sampling and approximates the probability with this many samples
evaluate : Bool (defaults to True)
@@ -608,6 +612,23 @@ def probability(condition, given_condition=None, numsamples=None,
5/12
"""
+ condition = sympify(condition)
+ given_condition = sympify(given_condition)
+
+ if given_condition is not None and \
+ not isinstance(given_condition, (Relational, Boolean)):
+ raise ValueError("%s is not a relational or combination of relationals"
+ % (given_condition))
+ if given_condition == False:
+ return S.Zero
+ if not isinstance(condition, (Relational, Boolean)):
+ raise ValueError("%s is not a relational or combination of relationals"
+ % (condition))
+ if condition is S.true:
+ return S.One
+ if condition is S.false:
+ return S.Zero
+
if numsamples:
return sampling_P(condition, given_condition, numsamples=numsamples,
**kwargs)
@@ -667,7 +688,8 @@ def density(expr, condition=None, evaluate=True, numsamples=None, **kwargs):
expr : Expr containing RandomSymbols
The expression of which you want to compute the density value
condition : Relational containing RandomSymbols
- A conditional expression. density(X>1, X>0) is density of X>1 given X>0
+ A conditional expression. density(X > 1, X > 0) is density of X > 1
+ given X > 0
numsamples : int
Enables sampling and approximates the density with this many samples
@@ -720,7 +742,7 @@ def cdf(expr, condition=None, evaluate=True, **kwargs):
{1: 1/6, 2: 1/6, 3: 1/6, 4: 1/6, 5: 1/6, 6: 1/6}
>>> cdf(D)
{1: 1/6, 2: 1/3, 3: 1/2, 4: 2/3, 5: 5/6, 6: 1}
- >>> cdf(3*D, D>2)
+ >>> cdf(3*D, D > 2)
{9: 1/4, 12: 1/2, 15: 3/4, 18: 1}
>>> cdf(X)
| P(X < oo ) for any Continuous Distribution raises AttributeError
```
>>> from sympy import *
>>> from sympy.stats import P, Exponential
>>> X = Exponential('X', 3)
>>> P(X < oo)
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-5-c320871e22f8> in <module>()
----> 1 P(X < oo)
/home/gxyd/Public/sympy/sympy/stats/rv.py in probability(condition, given_condition, numsamples, evaluate, **kwargs)
617
618 # Otherwise pass work off to the ProbabilitySpace
--> 619 result = pspace(condition).probability(condition, **kwargs)
620 if evaluate and hasattr(result, 'doit'):
621 return result.doit()
AttributeError: 'NoneType' object has no attribute 'probability'
``` | sympy/sympy | diff --git a/sympy/stats/tests/test_rv.py b/sympy/stats/tests/test_rv.py
index 69115c2771..52ef81f9f1 100644
--- a/sympy/stats/tests/test_rv.py
+++ b/sympy/stats/tests/test_rv.py
@@ -7,6 +7,7 @@
from sympy.stats.rv import ProductPSpace, rs_swap, Density, NamedArgsMixin
from sympy.utilities.pytest import raises, XFAIL
from sympy.core.compatibility import range
+from sympy.abc import x
def test_where():
@@ -45,7 +46,8 @@ def test_random_symbols():
def test_pspace():
X, Y = Normal('X', 0, 1), Normal('Y', 0, 1)
- assert not pspace(5 + 3)
+ raises(ValueError, lambda: pspace(5 + 3))
+ raises(ValueError, lambda: pspace(x < 1))
assert pspace(X) == X.pspace
assert pspace(2*X + 1) == X.pspace
assert pspace(2*X + Y) == ProductPSpace(Y.pspace, X.pspace)
@@ -195,3 +197,15 @@ def test_density_constant():
def test_real():
x = Normal('x', 0, 1)
assert x.is_real
+
+
+def test_issue_10052():
+ X = Exponential('X', 3)
+ assert P(X < oo) == 1
+ assert P(X > oo) == 0
+ assert P(X < 2, X > oo) == 0
+ assert P(X < oo, X > oo) == 0
+ assert P(X < oo, X > 2) == 1
+ assert P(X < 3, X == 2) == 0
+ raises(ValueError, lambda: P(1))
+ raises(ValueError, lambda: P(X < 1, 2))
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 2,
"issue_text_score": 0,
"test_score": 2
},
"num_modified_files": 1
} | 0.7 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "pytest",
"pip_packages": [
"mpmath>=0.19",
"pytest",
"pytest-cov",
"pytest-xdist",
"pytest-mock",
"pytest-asyncio"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.6",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | attrs @ file:///opt/conda/conda-bld/attrs_1642510447205/work
certifi==2021.5.30
coverage==6.2
execnet==1.9.0
importlib-metadata @ file:///tmp/build/80754af9/importlib-metadata_1631916693255/work
iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work
more-itertools @ file:///tmp/build/80754af9/more-itertools_1637733554872/work
mpmath==1.3.0
packaging @ file:///tmp/build/80754af9/packaging_1637314298585/work
pluggy @ file:///tmp/build/80754af9/pluggy_1615976315926/work
py @ file:///opt/conda/conda-bld/py_1644396412707/work
pyparsing @ file:///tmp/build/80754af9/pyparsing_1635766073266/work
pytest==6.2.4
pytest-asyncio==0.16.0
pytest-cov==4.0.0
pytest-mock==3.6.1
pytest-xdist==3.0.2
-e git+https://github.com/sympy/sympy.git@4349739ef2685623b379ed338a67b9cff093b54b#egg=sympy
toml @ file:///tmp/build/80754af9/toml_1616166611790/work
tomli==1.2.3
typing_extensions @ file:///opt/conda/conda-bld/typing_extensions_1647553014482/work
zipp @ file:///tmp/build/80754af9/zipp_1633618647012/work
| name: sympy
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- attrs=21.4.0=pyhd3eb1b0_0
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2021.5.30=py36h06a4308_0
- importlib-metadata=4.8.1=py36h06a4308_0
- importlib_metadata=4.8.1=hd3eb1b0_0
- iniconfig=1.1.1=pyhd3eb1b0_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.3=he6710b0_2
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- more-itertools=8.12.0=pyhd3eb1b0_0
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- packaging=21.3=pyhd3eb1b0_0
- pip=21.2.2=py36h06a4308_0
- pluggy=0.13.1=py36h06a4308_0
- py=1.11.0=pyhd3eb1b0_0
- pyparsing=3.0.4=pyhd3eb1b0_0
- pytest=6.2.4=py36h06a4308_2
- python=3.6.13=h12debd9_1
- readline=8.2=h5eee18b_0
- setuptools=58.0.4=py36h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- toml=0.10.2=pyhd3eb1b0_0
- typing_extensions=4.1.1=pyh06a4308_0
- wheel=0.37.1=pyhd3eb1b0_0
- xz=5.6.4=h5eee18b_1
- zipp=3.6.0=pyhd3eb1b0_0
- zlib=1.2.13=h5eee18b_1
- pip:
- coverage==6.2
- execnet==1.9.0
- mpmath==1.3.0
- pytest-asyncio==0.16.0
- pytest-cov==4.0.0
- pytest-mock==3.6.1
- pytest-xdist==3.0.2
- tomli==1.2.3
prefix: /opt/conda/envs/sympy
| [
"sympy/stats/tests/test_rv.py::test_pspace",
"sympy/stats/tests/test_rv.py::test_issue_10052"
] | [] | [
"sympy/stats/tests/test_rv.py::test_where",
"sympy/stats/tests/test_rv.py::test_random_symbols",
"sympy/stats/tests/test_rv.py::test_rs_swap",
"sympy/stats/tests/test_rv.py::test_RandomSymbol",
"sympy/stats/tests/test_rv.py::test_RandomSymbol_diff",
"sympy/stats/tests/test_rv.py::test_overlap",
"sympy/stats/tests/test_rv.py::test_ProductPSpace",
"sympy/stats/tests/test_rv.py::test_E",
"sympy/stats/tests/test_rv.py::test_Sample",
"sympy/stats/tests/test_rv.py::test_given",
"sympy/stats/tests/test_rv.py::test_dependence",
"sympy/stats/tests/test_rv.py::test_normality",
"sympy/stats/tests/test_rv.py::test_Density",
"sympy/stats/tests/test_rv.py::test_NamedArgsMixin",
"sympy/stats/tests/test_rv.py::test_density_constant",
"sympy/stats/tests/test_rv.py::test_real"
] | [] | BSD | 277 |
sympy__sympy-10064 | 4349739ef2685623b379ed338a67b9cff093b54b | 2015-10-29 04:34:03 | 0241b35cae5f2adc04dc37b25f7dc9c5f00bd746 | diff --git a/sympy/core/numbers.py b/sympy/core/numbers.py
index cd046fceae..f01d3c683e 100644
--- a/sympy/core/numbers.py
+++ b/sympy/core/numbers.py
@@ -1867,6 +1867,9 @@ def _eval_power(self, expt):
# (-2)**k --> 2**k
if self.is_negative and expt.is_even:
return (-self)**expt
+ if isinstance(expt, Float):
+ # Rational knows how to exponentiate by a Float
+ return super(Integer, self)._eval_power(expt)
if not isinstance(expt, Rational):
return
if expt is S.Half and self.is_negative:
| Integer raised to Float power does not evaluate
Rational raised to Float power does the right thing, but Integer raised to Float does not:
````
In [5]: 2**Float(3)
Out[5]: 2**3.0
In [6]: Rational(2, 3)**Float(3)
Out[6]: 0.296296296296296
````
I think the first result should do the same as
````
In [7]: Float(2)**Float(3)
Out[7]: 8.00000000000000
````
| sympy/sympy | diff --git a/sympy/core/tests/test_numbers.py b/sympy/core/tests/test_numbers.py
index dfbb67eb56..2dd3da28ef 100644
--- a/sympy/core/tests/test_numbers.py
+++ b/sympy/core/tests/test_numbers.py
@@ -1499,3 +1499,7 @@ def test_comp():
def test_issue_9491():
assert oo**zoo == nan
+
+
+def test_issue_10063():
+ assert 2**Float(3) == Float(8)
diff --git a/sympy/printing/pretty/tests/test_pretty.py b/sympy/printing/pretty/tests/test_pretty.py
index 48fad91708..3664011a2b 100644
--- a/sympy/printing/pretty/tests/test_pretty.py
+++ b/sympy/printing/pretty/tests/test_pretty.py
@@ -396,7 +396,7 @@ def test_pretty_basic():
assert upretty(expr) == ucode_str
# see issue #2860
- expr = S(2)**-1.0
+ expr = Pow(S(2), -1.0, evaluate=False)
ascii_str = \
"""\
-1.0\n\
diff --git a/sympy/printing/tests/test_str.py b/sympy/printing/tests/test_str.py
index ec2942ecf2..0f2bf4eaaf 100644
--- a/sympy/printing/tests/test_str.py
+++ b/sympy/printing/tests/test_str.py
@@ -2,7 +2,7 @@
from sympy import (Abs, Catalan, cos, Derivative, E, EulerGamma, exp,
factorial, factorial2, Function, GoldenRatio, I, Integer, Integral,
- Interval, Lambda, Limit, Matrix, nan, O, oo, pi, Rational, Float, Rel,
+ Interval, Lambda, Limit, Matrix, nan, O, oo, pi, Pow, Rational, Float, Rel,
S, sin, SparseMatrix, sqrt, summation, Sum, Symbol, symbols, Wild,
WildFunction, zeta, zoo, Dummy, Dict, Tuple, FiniteSet, factor,
subfactorial, true, false, Equivalent, Xor, Complement, SymmetricDifference)
@@ -409,7 +409,7 @@ def test_Pow():
# not the same as x**-1
assert str(x**-1.0) == 'x**(-1.0)'
# see issue #2860
- assert str(S(2)**-1.0) == '2**(-1.0)'
+ assert str(Pow(S(2), -1.0, evaluate=False)) == '2**(-1.0)'
def test_sqrt():
| {
"commit_name": "head_commit",
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true,
"llm_score": {
"difficulty_score": 0,
"issue_text_score": 1,
"test_score": 0
},
"num_modified_files": 1
} | 0.7 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "pytest",
"pip_packages": [
"pytest"
],
"pre_install": null,
"python": "3.7",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | attrs @ file:///croot/attrs_1668696182826/work
certifi @ file:///croot/certifi_1671487769961/work/certifi
flit_core @ file:///opt/conda/conda-bld/flit-core_1644941570762/work/source/flit_core
importlib-metadata @ file:///tmp/build/80754af9/importlib-metadata_1648562407465/work
iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work
mpmath==1.3.0
packaging @ file:///croot/packaging_1671697413597/work
pluggy @ file:///tmp/build/80754af9/pluggy_1648042572264/work
py @ file:///opt/conda/conda-bld/py_1644396412707/work
pytest==7.1.2
-e git+https://github.com/sympy/sympy.git@4349739ef2685623b379ed338a67b9cff093b54b#egg=sympy
tomli @ file:///opt/conda/conda-bld/tomli_1657175507142/work
typing_extensions @ file:///croot/typing_extensions_1669924550328/work
zipp @ file:///croot/zipp_1672387121353/work
| name: sympy
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- attrs=22.1.0=py37h06a4308_0
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2022.12.7=py37h06a4308_0
- flit-core=3.6.0=pyhd3eb1b0_0
- importlib-metadata=4.11.3=py37h06a4308_0
- importlib_metadata=4.11.3=hd3eb1b0_0
- iniconfig=1.1.1=pyhd3eb1b0_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- packaging=22.0=py37h06a4308_0
- pip=22.3.1=py37h06a4308_0
- pluggy=1.0.0=py37h06a4308_1
- py=1.11.0=pyhd3eb1b0_0
- pytest=7.1.2=py37h06a4308_0
- python=3.7.16=h7a1cb2a_0
- readline=8.2=h5eee18b_0
- setuptools=65.6.3=py37h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- tomli=2.0.1=py37h06a4308_0
- typing_extensions=4.4.0=py37h06a4308_0
- wheel=0.38.4=py37h06a4308_0
- xz=5.6.4=h5eee18b_1
- zipp=3.11.0=py37h06a4308_0
- zlib=1.2.13=h5eee18b_1
- pip:
- mpmath==1.3.0
prefix: /opt/conda/envs/sympy
| [
"sympy/core/tests/test_numbers.py::test_issue_10063"
] | [] | [
"sympy/core/tests/test_numbers.py::test_integers_cache",
"sympy/core/tests/test_numbers.py::test_seterr",
"sympy/core/tests/test_numbers.py::test_mod",
"sympy/core/tests/test_numbers.py::test_divmod",
"sympy/core/tests/test_numbers.py::test_igcd",
"sympy/core/tests/test_numbers.py::test_ilcm",
"sympy/core/tests/test_numbers.py::test_igcdex",
"sympy/core/tests/test_numbers.py::test_Integer_new",
"sympy/core/tests/test_numbers.py::test_Rational_new",
"sympy/core/tests/test_numbers.py::test_Number_new",
"sympy/core/tests/test_numbers.py::test_Rational_cmp",
"sympy/core/tests/test_numbers.py::test_Float",
"sympy/core/tests/test_numbers.py::test_Float_default_to_highprec_from_str",
"sympy/core/tests/test_numbers.py::test_Float_eval",
"sympy/core/tests/test_numbers.py::test_Float_issue_2107",
"sympy/core/tests/test_numbers.py::test_Infinity",
"sympy/core/tests/test_numbers.py::test_Infinity_2",
"sympy/core/tests/test_numbers.py::test_Mul_Infinity_Zero",
"sympy/core/tests/test_numbers.py::test_Div_By_Zero",
"sympy/core/tests/test_numbers.py::test_Infinity_inequations",
"sympy/core/tests/test_numbers.py::test_NaN",
"sympy/core/tests/test_numbers.py::test_special_numbers",
"sympy/core/tests/test_numbers.py::test_powers",
"sympy/core/tests/test_numbers.py::test_integer_nthroot_overflow",
"sympy/core/tests/test_numbers.py::test_powers_Integer",
"sympy/core/tests/test_numbers.py::test_powers_Rational",
"sympy/core/tests/test_numbers.py::test_powers_Float",
"sympy/core/tests/test_numbers.py::test_abs1",
"sympy/core/tests/test_numbers.py::test_accept_int",
"sympy/core/tests/test_numbers.py::test_dont_accept_str",
"sympy/core/tests/test_numbers.py::test_int",
"sympy/core/tests/test_numbers.py::test_long",
"sympy/core/tests/test_numbers.py::test_real_bug",
"sympy/core/tests/test_numbers.py::test_bug_sqrt",
"sympy/core/tests/test_numbers.py::test_pi_Pi",
"sympy/core/tests/test_numbers.py::test_no_len",
"sympy/core/tests/test_numbers.py::test_issue_3321",
"sympy/core/tests/test_numbers.py::test_issue_3692",
"sympy/core/tests/test_numbers.py::test_issue_3423",
"sympy/core/tests/test_numbers.py::test_issue_3449",
"sympy/core/tests/test_numbers.py::test_Integer_factors",
"sympy/core/tests/test_numbers.py::test_Rational_factors",
"sympy/core/tests/test_numbers.py::test_issue_4107",
"sympy/core/tests/test_numbers.py::test_IntegerInteger",
"sympy/core/tests/test_numbers.py::test_Rational_gcd_lcm_cofactors",
"sympy/core/tests/test_numbers.py::test_Float_gcd_lcm_cofactors",
"sympy/core/tests/test_numbers.py::test_issue_4611",
"sympy/core/tests/test_numbers.py::test_conversion_to_mpmath",
"sympy/core/tests/test_numbers.py::test_relational",
"sympy/core/tests/test_numbers.py::test_Integer_as_index",
"sympy/core/tests/test_numbers.py::test_Rational_int",
"sympy/core/tests/test_numbers.py::test_zoo",
"sympy/core/tests/test_numbers.py::test_issue_4122",
"sympy/core/tests/test_numbers.py::test_GoldenRatio_expand",
"sympy/core/tests/test_numbers.py::test_as_content_primitive",
"sympy/core/tests/test_numbers.py::test_hashing_sympy_integers",
"sympy/core/tests/test_numbers.py::test_issue_4172",
"sympy/core/tests/test_numbers.py::test_Catalan_EulerGamma_prec",
"sympy/core/tests/test_numbers.py::test_Float_eq",
"sympy/core/tests/test_numbers.py::test_int_NumberSymbols",
"sympy/core/tests/test_numbers.py::test_issue_6640",
"sympy/core/tests/test_numbers.py::test_issue_6349",
"sympy/core/tests/test_numbers.py::test_mpf_norm",
"sympy/core/tests/test_numbers.py::test_latex",
"sympy/core/tests/test_numbers.py::test_issue_7742",
"sympy/core/tests/test_numbers.py::test_simplify_AlgebraicNumber",
"sympy/core/tests/test_numbers.py::test_Float_idempotence",
"sympy/core/tests/test_numbers.py::test_comp",
"sympy/core/tests/test_numbers.py::test_issue_9491",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_ascii_str",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_unicode_str",
"sympy/printing/pretty/tests/test_pretty.py::test_upretty_greek",
"sympy/printing/pretty/tests/test_pretty.py::test_upretty_multiindex",
"sympy/printing/pretty/tests/test_pretty.py::test_upretty_sub_super",
"sympy/printing/pretty/tests/test_pretty.py::test_upretty_subs_missing_in_24",
"sympy/printing/pretty/tests/test_pretty.py::test_upretty_modifiers",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_basic",
"sympy/printing/pretty/tests/test_pretty.py::test_negative_fractions",
"sympy/printing/pretty/tests/test_pretty.py::test_issue_5524",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_ordering",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_relational",
"sympy/printing/pretty/tests/test_pretty.py::test_issue_7117",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_rational",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_functions",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_sqrt",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_sqrt_char_knob",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_sqrt_longsymbol_no_sqrt_char",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_KroneckerDelta",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_product",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_lambda",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_order",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_derivatives",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_integrals",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_matrix",
"sympy/printing/pretty/tests/test_pretty.py::test_Adjoint",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_piecewise",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_seq",
"sympy/printing/pretty/tests/test_pretty.py::test_any_object_in_sequence",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_sets",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_ConditionSet",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_ComplexRegion",
"sympy/printing/pretty/tests/test_pretty.py::test_ProductSet_paranthesis",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_sequences",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_FourierSeries",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_FormalPowerSeries",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_limits",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_RootOf",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_RootSum",
"sympy/printing/pretty/tests/test_pretty.py::test_GroebnerBasis",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_Boolean",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_Domain",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_prec",
"sympy/printing/pretty/tests/test_pretty.py::test_pprint",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_class",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_no_wrap_line",
"sympy/printing/pretty/tests/test_pretty.py::test_settings",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_sum",
"sympy/printing/pretty/tests/test_pretty.py::test_units",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_Subs",
"sympy/printing/pretty/tests/test_pretty.py::test_gammas",
"sympy/printing/pretty/tests/test_pretty.py::test_hyper",
"sympy/printing/pretty/tests/test_pretty.py::test_meijerg",
"sympy/printing/pretty/tests/test_pretty.py::test_noncommutative",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_special_functions",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_geometry",
"sympy/printing/pretty/tests/test_pretty.py::test_expint",
"sympy/printing/pretty/tests/test_pretty.py::test_elliptic_functions",
"sympy/printing/pretty/tests/test_pretty.py::test_RandomDomain",
"sympy/printing/pretty/tests/test_pretty.py::test_PrettyPoly",
"sympy/printing/pretty/tests/test_pretty.py::test_issue_6285",
"sympy/printing/pretty/tests/test_pretty.py::test_issue_6359",
"sympy/printing/pretty/tests/test_pretty.py::test_issue_6739",
"sympy/printing/pretty/tests/test_pretty.py::test_complicated_symbol_unchanged",
"sympy/printing/pretty/tests/test_pretty.py::test_categories",
"sympy/printing/pretty/tests/test_pretty.py::test_PrettyModules",
"sympy/printing/pretty/tests/test_pretty.py::test_QuotientRing",
"sympy/printing/pretty/tests/test_pretty.py::test_Homomorphism",
"sympy/printing/pretty/tests/test_pretty.py::test_Tr",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_Add",
"sympy/printing/pretty/tests/test_pretty.py::test_issue_7179",
"sympy/printing/pretty/tests/test_pretty.py::test_issue_7180",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_Complement",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_SymmetricDifference",
"sympy/printing/pretty/tests/test_pretty.py::test_pretty_Contains",
"sympy/printing/pretty/tests/test_pretty.py::test_issue_8292",
"sympy/printing/pretty/tests/test_pretty.py::test_issue_4335",
"sympy/printing/pretty/tests/test_pretty.py::test_issue_8344",
"sympy/printing/pretty/tests/test_pretty.py::test_issue_6324",
"sympy/printing/pretty/tests/test_pretty.py::test_issue_7927",
"sympy/printing/pretty/tests/test_pretty.py::test_issue_6134",
"sympy/printing/tests/test_str.py::test_printmethod",
"sympy/printing/tests/test_str.py::test_Abs",
"sympy/printing/tests/test_str.py::test_Add",
"sympy/printing/tests/test_str.py::test_Catalan",
"sympy/printing/tests/test_str.py::test_ComplexInfinity",
"sympy/printing/tests/test_str.py::test_Derivative",
"sympy/printing/tests/test_str.py::test_dict",
"sympy/printing/tests/test_str.py::test_Dict",
"sympy/printing/tests/test_str.py::test_Dummy",
"sympy/printing/tests/test_str.py::test_EulerGamma",
"sympy/printing/tests/test_str.py::test_Exp",
"sympy/printing/tests/test_str.py::test_factorial",
"sympy/printing/tests/test_str.py::test_Function",
"sympy/printing/tests/test_str.py::test_Geometry",
"sympy/printing/tests/test_str.py::test_GoldenRatio",
"sympy/printing/tests/test_str.py::test_ImaginaryUnit",
"sympy/printing/tests/test_str.py::test_Infinity",
"sympy/printing/tests/test_str.py::test_Integer",
"sympy/printing/tests/test_str.py::test_Integral",
"sympy/printing/tests/test_str.py::test_Interval",
"sympy/printing/tests/test_str.py::test_Lambda",
"sympy/printing/tests/test_str.py::test_Limit",
"sympy/printing/tests/test_str.py::test_list",
"sympy/printing/tests/test_str.py::test_Matrix_str",
"sympy/printing/tests/test_str.py::test_Mul",
"sympy/printing/tests/test_str.py::test_NaN",
"sympy/printing/tests/test_str.py::test_NegativeInfinity",
"sympy/printing/tests/test_str.py::test_Order",
"sympy/printing/tests/test_str.py::test_Permutation_Cycle",
"sympy/printing/tests/test_str.py::test_Pi",
"sympy/printing/tests/test_str.py::test_Poly",
"sympy/printing/tests/test_str.py::test_PolyRing",
"sympy/printing/tests/test_str.py::test_FracField",
"sympy/printing/tests/test_str.py::test_PolyElement",
"sympy/printing/tests/test_str.py::test_FracElement",
"sympy/printing/tests/test_str.py::test_Pow",
"sympy/printing/tests/test_str.py::test_sqrt",
"sympy/printing/tests/test_str.py::test_Rational",
"sympy/printing/tests/test_str.py::test_Float",
"sympy/printing/tests/test_str.py::test_Relational",
"sympy/printing/tests/test_str.py::test_RootOf",
"sympy/printing/tests/test_str.py::test_RootSum",
"sympy/printing/tests/test_str.py::test_GroebnerBasis",
"sympy/printing/tests/test_str.py::test_set",
"sympy/printing/tests/test_str.py::test_SparseMatrix",
"sympy/printing/tests/test_str.py::test_Sum",
"sympy/printing/tests/test_str.py::test_Symbol",
"sympy/printing/tests/test_str.py::test_tuple",
"sympy/printing/tests/test_str.py::test_Unit",
"sympy/printing/tests/test_str.py::test_wild_str",
"sympy/printing/tests/test_str.py::test_zeta",
"sympy/printing/tests/test_str.py::test_issue_3101",
"sympy/printing/tests/test_str.py::test_issue_3103",
"sympy/printing/tests/test_str.py::test_issue_4021",
"sympy/printing/tests/test_str.py::test_sstrrepr",
"sympy/printing/tests/test_str.py::test_infinity",
"sympy/printing/tests/test_str.py::test_full_prec",
"sympy/printing/tests/test_str.py::test_noncommutative",
"sympy/printing/tests/test_str.py::test_empty_printer",
"sympy/printing/tests/test_str.py::test_settings",
"sympy/printing/tests/test_str.py::test_RandomDomain",
"sympy/printing/tests/test_str.py::test_FiniteSet",
"sympy/printing/tests/test_str.py::test_PrettyPoly",
"sympy/printing/tests/test_str.py::test_categories",
"sympy/printing/tests/test_str.py::test_Tr",
"sympy/printing/tests/test_str.py::test_issue_6387",
"sympy/printing/tests/test_str.py::test_MatMul_MatAdd",
"sympy/printing/tests/test_str.py::test_MatrixSlice",
"sympy/printing/tests/test_str.py::test_true_false",
"sympy/printing/tests/test_str.py::test_Equivalent",
"sympy/printing/tests/test_str.py::test_Xor",
"sympy/printing/tests/test_str.py::test_Complement",
"sympy/printing/tests/test_str.py::test_SymmetricDifference"
] | [] | BSD | 278 |
|
scrapy__scrapy-1563 | dd9f777ba725d7a7dbb192302cc52a120005ad64 | 2015-10-29 06:21:42 | 6aa85aee2a274393307ac3e777180fcbdbdc9848 | diff --git a/scrapy/http/request/form.py b/scrapy/http/request/form.py
index a12a2fd07..4a9bd732e 100644
--- a/scrapy/http/request/form.py
+++ b/scrapy/http/request/form.py
@@ -11,6 +11,7 @@ from parsel.selector import create_root_node
import six
from scrapy.http.request import Request
from scrapy.utils.python import to_bytes, is_listlike
+from scrapy.utils.response import get_base_url
class FormRequest(Request):
@@ -44,7 +45,7 @@ class FormRequest(Request):
def _get_form_url(form, url):
if url is None:
- return form.action or form.base_url
+ return urljoin(form.base_url, form.action)
return urljoin(form.base_url, url)
@@ -58,7 +59,7 @@ def _urlencode(seq, enc):
def _get_form(response, formname, formid, formnumber, formxpath):
"""Find the form element """
text = response.body_as_unicode()
- root = create_root_node(text, lxml.html.HTMLParser, base_url=response.url)
+ root = create_root_node(text, lxml.html.HTMLParser, base_url=get_base_url(response))
forms = root.xpath('//form')
if not forms:
raise ValueError("No <form> element found in %s" % response)
| [Bug] Incorrectly picked URL in `scrapy.http.FormRequest.from_response` when there is a `<base>` tag
## Issue Description
Incorrectly picked URL in `scrapy.http.FormRequest.from_response` when there is a `<base>` tag.
## How to Reproduce the Issue & Version Used
```
[pengyu@GLaDOS tmp]$ python2
Python 2.7.10 (default, Sep 7 2015, 13:51:49)
[GCC 5.2.0] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import scrapy
>>> scrapy.__version__
u'1.0.3'
>>> html_body = '''
... <html>
... <head>
... <base href="http://b.com/">
... </head>
... <body>
... <form action="test_form">
... </form>
... </body>
... </html>
... '''
>>> response = scrapy.http.TextResponse(url='http://a.com/', body=html_body)
>>> request = scrapy.http.FormRequest.from_response(response)
>>> request.url
'http://a.com/test_form'
```
## Expected Result
`request.url` shall be `'http://b.com/test_form'`
## Suggested Fix
The issue can be fixed by fixing a few lines in `scrapy/http/request/form.py` | scrapy/scrapy | diff --git a/tests/test_http_request.py b/tests/test_http_request.py
index ff0941961..60fd855dd 100644
--- a/tests/test_http_request.py
+++ b/tests/test_http_request.py
@@ -801,6 +801,25 @@ class FormRequestTest(RequestTest):
self.assertEqual(fs[b'test2'], [b'val2'])
self.assertEqual(fs[b'button1'], [b''])
+ def test_html_base_form_action(self):
+ response = _buildresponse(
+ """
+ <html>
+ <head>
+ <base href="http://b.com/">
+ </head>
+ <body>
+ <form action="test_form">
+ </form>
+ </body>
+ </html>
+ """,
+ url='http://a.com/'
+ )
+ req = self.request_class.from_response(response)
+ self.assertEqual(req.url, 'http://b.com/test_form')
+
+
def _buildresponse(body, **kwargs):
kwargs.setdefault('body', body)
kwargs.setdefault('url', 'http://example.com')
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_hyperlinks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 1,
"issue_text_score": 0,
"test_score": 0
},
"num_modified_files": 1
} | 1.0 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest pytest-cov pytest-xdist pytest-mock pytest-asyncio"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc libxml2-dev libxslt1-dev zlib1g-dev libffi-dev libssl-dev"
],
"python": "3.9",
"reqs_path": [
"requirements.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | attrs==25.3.0
Automat==24.8.1
cffi==1.17.1
constantly==23.10.4
coverage==7.8.0
cryptography==44.0.2
cssselect==1.3.0
exceptiongroup==1.2.2
execnet==2.1.1
hyperlink==21.0.0
idna==3.10
incremental==24.7.2
iniconfig==2.1.0
jmespath==1.0.1
lxml==5.3.1
packaging==24.2
parsel==1.10.0
pluggy==1.5.0
pyasn1==0.6.1
pyasn1_modules==0.4.2
pycparser==2.22
PyDispatcher==2.0.7
pyOpenSSL==25.0.0
pytest==8.3.5
pytest-asyncio==0.26.0
pytest-cov==6.0.0
pytest-mock==3.14.0
pytest-xdist==3.6.1
queuelib==1.7.0
-e git+https://github.com/scrapy/scrapy.git@dd9f777ba725d7a7dbb192302cc52a120005ad64#egg=Scrapy
service-identity==24.2.0
six==1.17.0
tomli==2.2.1
Twisted==24.11.0
typing_extensions==4.13.0
w3lib==2.3.1
zope.interface==7.2
| name: scrapy
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=3.0.16=h5eee18b_0
- pip=25.0=py39h06a4308_0
- python=3.9.21=he870216_1
- readline=8.2=h5eee18b_0
- setuptools=75.8.0=py39h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- tzdata=2025a=h04d1e81_0
- wheel=0.45.1=py39h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- attrs==25.3.0
- automat==24.8.1
- cffi==1.17.1
- constantly==23.10.4
- coverage==7.8.0
- cryptography==44.0.2
- cssselect==1.3.0
- exceptiongroup==1.2.2
- execnet==2.1.1
- hyperlink==21.0.0
- idna==3.10
- incremental==24.7.2
- iniconfig==2.1.0
- jmespath==1.0.1
- lxml==5.3.1
- packaging==24.2
- parsel==1.10.0
- pluggy==1.5.0
- pyasn1==0.6.1
- pyasn1-modules==0.4.2
- pycparser==2.22
- pydispatcher==2.0.7
- pyopenssl==25.0.0
- pytest==8.3.5
- pytest-asyncio==0.26.0
- pytest-cov==6.0.0
- pytest-mock==3.14.0
- pytest-xdist==3.6.1
- queuelib==1.7.0
- service-identity==24.2.0
- six==1.17.0
- tomli==2.2.1
- twisted==24.11.0
- typing-extensions==4.13.0
- w3lib==2.3.1
- zope-interface==7.2
prefix: /opt/conda/envs/scrapy
| [
"tests/test_http_request.py::FormRequestTest::test_html_base_form_action"
] | [
"tests/test_http_request.py::FormRequestTest::test_from_response_button_notype",
"tests/test_http_request.py::FormRequestTest::test_from_response_button_novalue",
"tests/test_http_request.py::FormRequestTest::test_from_response_button_submit",
"tests/test_http_request.py::FormRequestTest::test_from_response_checkbox",
"tests/test_http_request.py::FormRequestTest::test_from_response_descendants",
"tests/test_http_request.py::FormRequestTest::test_from_response_dont_click",
"tests/test_http_request.py::FormRequestTest::test_from_response_dont_submit_image_as_input",
"tests/test_http_request.py::FormRequestTest::test_from_response_dont_submit_reset_as_input",
"tests/test_http_request.py::FormRequestTest::test_from_response_formid_exists",
"tests/test_http_request.py::FormRequestTest::test_from_response_formid_notexist",
"tests/test_http_request.py::FormRequestTest::test_from_response_formname_exists",
"tests/test_http_request.py::FormRequestTest::test_from_response_formname_notexist",
"tests/test_http_request.py::FormRequestTest::test_from_response_formname_notexists_fallback_formid",
"tests/test_http_request.py::FormRequestTest::test_from_response_get",
"tests/test_http_request.py::FormRequestTest::test_from_response_input_hidden",
"tests/test_http_request.py::FormRequestTest::test_from_response_input_text",
"tests/test_http_request.py::FormRequestTest::test_from_response_input_textarea",
"tests/test_http_request.py::FormRequestTest::test_from_response_invalid_html5",
"tests/test_http_request.py::FormRequestTest::test_from_response_multiple_clickdata",
"tests/test_http_request.py::FormRequestTest::test_from_response_multiple_forms_clickdata",
"tests/test_http_request.py::FormRequestTest::test_from_response_noformname",
"tests/test_http_request.py::FormRequestTest::test_from_response_nr_index_clickdata",
"tests/test_http_request.py::FormRequestTest::test_from_response_override_clickable",
"tests/test_http_request.py::FormRequestTest::test_from_response_override_params",
"tests/test_http_request.py::FormRequestTest::test_from_response_post",
"tests/test_http_request.py::FormRequestTest::test_from_response_radio",
"tests/test_http_request.py::FormRequestTest::test_from_response_select",
"tests/test_http_request.py::FormRequestTest::test_from_response_submit_first_clickable",
"tests/test_http_request.py::FormRequestTest::test_from_response_submit_not_first_clickable",
"tests/test_http_request.py::FormRequestTest::test_from_response_submit_novalue",
"tests/test_http_request.py::FormRequestTest::test_from_response_unicode_clickdata",
"tests/test_http_request.py::FormRequestTest::test_from_response_xpath"
] | [
"tests/test_http_request.py::RequestTest::test_ajax_url",
"tests/test_http_request.py::RequestTest::test_body",
"tests/test_http_request.py::RequestTest::test_copy",
"tests/test_http_request.py::RequestTest::test_copy_inherited_classes",
"tests/test_http_request.py::RequestTest::test_eq",
"tests/test_http_request.py::RequestTest::test_headers",
"tests/test_http_request.py::RequestTest::test_immutable_attributes",
"tests/test_http_request.py::RequestTest::test_init",
"tests/test_http_request.py::RequestTest::test_method_always_str",
"tests/test_http_request.py::RequestTest::test_replace",
"tests/test_http_request.py::RequestTest::test_url",
"tests/test_http_request.py::RequestTest::test_url_no_scheme",
"tests/test_http_request.py::RequestTest::test_url_quoting",
"tests/test_http_request.py::FormRequestTest::test_ajax_url",
"tests/test_http_request.py::FormRequestTest::test_body",
"tests/test_http_request.py::FormRequestTest::test_copy",
"tests/test_http_request.py::FormRequestTest::test_copy_inherited_classes",
"tests/test_http_request.py::FormRequestTest::test_custom_encoding",
"tests/test_http_request.py::FormRequestTest::test_empty_formdata",
"tests/test_http_request.py::FormRequestTest::test_eq",
"tests/test_http_request.py::FormRequestTest::test_from_response_ambiguous_clickdata",
"tests/test_http_request.py::FormRequestTest::test_from_response_errors_formnumber",
"tests/test_http_request.py::FormRequestTest::test_from_response_errors_noform",
"tests/test_http_request.py::FormRequestTest::test_from_response_extra_headers",
"tests/test_http_request.py::FormRequestTest::test_from_response_formid_errors_formnumber",
"tests/test_http_request.py::FormRequestTest::test_from_response_formname_errors_formnumber",
"tests/test_http_request.py::FormRequestTest::test_from_response_invalid_nr_index_clickdata",
"tests/test_http_request.py::FormRequestTest::test_from_response_non_matching_clickdata",
"tests/test_http_request.py::FormRequestTest::test_from_response_override_method",
"tests/test_http_request.py::FormRequestTest::test_from_response_override_url",
"tests/test_http_request.py::FormRequestTest::test_headers",
"tests/test_http_request.py::FormRequestTest::test_immutable_attributes",
"tests/test_http_request.py::FormRequestTest::test_init",
"tests/test_http_request.py::FormRequestTest::test_method_always_str",
"tests/test_http_request.py::FormRequestTest::test_multi_key_values",
"tests/test_http_request.py::FormRequestTest::test_replace",
"tests/test_http_request.py::FormRequestTest::test_url",
"tests/test_http_request.py::FormRequestTest::test_url_no_scheme",
"tests/test_http_request.py::FormRequestTest::test_url_quoting",
"tests/test_http_request.py::XmlRpcRequestTest::test_ajax_url",
"tests/test_http_request.py::XmlRpcRequestTest::test_body",
"tests/test_http_request.py::XmlRpcRequestTest::test_copy",
"tests/test_http_request.py::XmlRpcRequestTest::test_copy_inherited_classes",
"tests/test_http_request.py::XmlRpcRequestTest::test_eq",
"tests/test_http_request.py::XmlRpcRequestTest::test_headers",
"tests/test_http_request.py::XmlRpcRequestTest::test_immutable_attributes",
"tests/test_http_request.py::XmlRpcRequestTest::test_init",
"tests/test_http_request.py::XmlRpcRequestTest::test_method_always_str",
"tests/test_http_request.py::XmlRpcRequestTest::test_replace",
"tests/test_http_request.py::XmlRpcRequestTest::test_url",
"tests/test_http_request.py::XmlRpcRequestTest::test_url_no_scheme",
"tests/test_http_request.py::XmlRpcRequestTest::test_url_quoting",
"tests/test_http_request.py::XmlRpcRequestTest::test_xmlrpc_dumps"
] | [] | BSD 3-Clause "New" or "Revised" License | 279 |
|
joblib__joblib-262 | aeb018af545e025654176ffe9ae876bda1bddb89 | 2015-10-29 12:40:19 | 40341615cc2600675ce7457d9128fb030f6f89fa | lesteve: > Maybe I'm wrong, but why not adding here a condition "not obj.dtype.hasobject" and keep the previous behavior (using the except) ?
We could do that I am just slightly worried that this try except is not a very clean way of hiding failures. A few weird behaviours we recently saw:
* for Python 2.6 and @aabadie's PR with `with gzip.GZipFile as f`, you get a failure when you exit the context manager, meaning that you actually write a valid .z auxiliary file but then still pickle the array inside the master file because you encountered an error. This auxiliary file is never deleted.
* for Python 3, when trying to dump an array with dtype object, you encountered an error quite early on but you still write an invalid .z auxiliary file with just the header. This auxiliary file is never deleted.
* for Python 2.7, when trying to dump an array with dtype object, you don't even encounter an error and you end up writing str(array). You only see the problem at load time.
@aabadie as an aside, just a gentle reminder: always better to comment in the "Files changed" tab rather than in individual commits.
| diff --git a/joblib/numpy_pickle.py b/joblib/numpy_pickle.py
index 6d727d6..f2d43eb 100644
--- a/joblib/numpy_pickle.py
+++ b/joblib/numpy_pickle.py
@@ -215,7 +215,7 @@ class NumpyPickler(Pickler):
else:
self.file = BytesIO()
# Count the number of npy files that we have created:
- self._npy_counter = 0
+ self._npy_counter = 1
# By default we want a pickle protocol that only changes with
# the major python version and not the minor one
if protocol is None:
@@ -257,8 +257,8 @@ class NumpyPickler(Pickler):
files, rather than pickling them. Of course, this is a
total abuse of the Pickler class.
"""
- if self.np is not None and type(obj) in (self.np.ndarray,
- self.np.matrix, self.np.memmap):
+ if (self.np is not None and type(obj) in
+ (self.np.ndarray, self.np.matrix, self.np.memmap)):
size = obj.size * obj.itemsize
if self.compress and size < self.cache_size * _MEGA:
# When compressing, as we are not writing directly to the
@@ -267,19 +267,21 @@ class NumpyPickler(Pickler):
# Pickling doesn't work with memmaped arrays
obj = self.np.asarray(obj)
return Pickler.save(self, obj)
- self._npy_counter += 1
- try:
- filename = '%s_%02i.npy' % (self._filename,
- self._npy_counter)
- # This converts the array in a container
- obj, filename = self._write_array(obj, filename)
- self._filenames.append(filename)
- except:
- self._npy_counter -= 1
- # XXX: We should have a logging mechanism
- print('Failed to save %s to .npy file:\n%s' % (
+
+ if not obj.dtype.hasobject:
+ try:
+ filename = '%s_%02i.npy' % (self._filename,
+ self._npy_counter)
+ # This converts the array in a container
+ obj, filename = self._write_array(obj, filename)
+ self._filenames.append(filename)
+ self._npy_counter += 1
+ except Exception:
+ # XXX: We should have a logging mechanism
+ print('Failed to save %s to .npy file:\n%s' % (
type(obj),
traceback.format_exc()))
+
return Pickler.save(self, obj)
def close(self):
| joblib.dump bug with too large object-type arrays
issue from
https://github.com/scikit-learn/scikit-learn/issues/4889
The code
```python
import joblib
import os
import numpy as np
from gzip import GzipFile
from io import BytesIO
from urllib2 import urlopen
from os.path import join
from sklearn.datasets import get_data_home
URL10 = ('http://archive.ics.uci.edu/ml/'
'machine-learning-databases/kddcup99-mld/kddcup.data_10_percent.gz')
data_home = get_data_home()
kddcup_dir = join(data_home, "test")
samples_path = join(kddcup_dir, "samples")
os.makedirs(kddcup_dir)
f = BytesIO(urlopen(URL10).read())
file = GzipFile(fileobj=f, mode='r')
X = []
for line in file.readlines():
X.append(line.replace('\n', '').split(','))
file.close()
X = np.asarray(X, dtype=object)
joblib.dump(X, samples_path, compress=9)
X = joblib.load(samples_path)
```
More precisely, it works if X has less than 300000 lines or if X is not of dtype `object`:
```python
Y = X[:300000,:] ### works
joblib.dump(Y, samples_path, compress=9)
Y = joblib.load(samples_path)
###
Y = X[:400000,:].astype(str) ### works
joblib.dump(Y, samples_path, compress=9)
Y = joblib.load(samples_path)
###
Y = X[:400000,:] ### doesnt work
joblib.dump(Y, samples_path, compress=9)
Y = joblib.load(samples_path)
```
The error raised by joblib.load is
```
---------------------------------------------------------------------------
AssertionError Traceback (most recent call last)
<ipython-input-32-25fe17420f08> in <module>()
----> 1 Y = joblib.load(samples_path)
/usr/lib/python2.7/dist-packages/joblib/numpy_pickle.pyc in load(filename, mmap_mode)
422
423 try:
--> 424 obj = unpickler.load()
425 finally:
426 if hasattr(unpickler, 'file_handle'):
/usr/lib/python2.7/pickle.pyc in load(self)
856 while 1:
857 key = read(1)
--> 858 dispatch[key](self)
859 except _Stop, stopinst:
860 return stopinst.value
/usr/lib/python2.7/dist-packages/joblib/numpy_pickle.pyc in load_build(self)
288 "but numpy didn't import correctly")
289 nd_array_wrapper = self.stack.pop()
--> 290 array = nd_array_wrapper.read(self)
291 self.stack.append(array)
292
/usr/lib/python2.7/dist-packages/joblib/numpy_pickle.pyc in read(self, unpickler)
158 array = unpickler.np.core.multiarray._reconstruct(*self.init_args)
159 with open(filename, 'rb') as f:
--> 160 data = read_zfile(f)
161 state = self.state + (data,)
162 array.__setstate__(state)
/usr/lib/python2.7/dist-packages/joblib/numpy_pickle.pyc in read_zfile(file_handle)
69 assert len(data) == length, (
70 "Incorrect data length while decompressing %s."
---> 71 "The file could be corrupted." % file_handle)
72 return data
73
AssertionError: Incorrect data length while decompressing <open file '/home/nicolas/scikit_learn_data/test/samples_01.npy.z', mode 'rb' at 0x7efcea714db0>.The file could be corrupted.
```
@lesteve what do you think? | joblib/joblib | diff --git a/joblib/test/test_numpy_pickle.py b/joblib/test/test_numpy_pickle.py
index ab80354..c6b8960 100644
--- a/joblib/test/test_numpy_pickle.py
+++ b/joblib/test/test_numpy_pickle.py
@@ -260,6 +260,7 @@ def test_z_file():
def test_compressed_pickle_dump_and_load():
expected_list = [np.arange(5, dtype=np.int64),
np.arange(5, dtype=np.float64),
+ np.array([1, 'abc', {'a': 1, 'b': 2}]),
# .tostring actually returns bytes and is a
# compatibility alias for .tobytes which was
# added in 1.9.0
@@ -269,17 +270,23 @@ def test_compressed_pickle_dump_and_load():
with tempfile.NamedTemporaryFile(suffix='.gz', dir=env['dir']) as f:
fname = f.name
- try:
- numpy_pickle.dump(expected_list, fname, compress=1)
- result_list = numpy_pickle.load(fname)
- for result, expected in zip(result_list, expected_list):
- if isinstance(expected, np.ndarray):
- nose.tools.assert_equal(result.dtype, expected.dtype)
- np.testing.assert_equal(result, expected)
- else:
- nose.tools.assert_equal(result, expected)
- finally:
- os.remove(fname)
+ # Need to test both code branches (whether array size is greater
+ # or smaller than cache_size)
+ for cache_size in [0, 1e9]:
+ try:
+ dumped_filenames = numpy_pickle.dump(
+ expected_list, fname, compress=1,
+ cache_size=cache_size)
+ result_list = numpy_pickle.load(fname)
+ for result, expected in zip(result_list, expected_list):
+ if isinstance(expected, np.ndarray):
+ nose.tools.assert_equal(result.dtype, expected.dtype)
+ np.testing.assert_equal(result, expected)
+ else:
+ nose.tools.assert_equal(result, expected)
+ finally:
+ for fn in dumped_filenames:
+ os.remove(fn)
def _check_pickle(filename, expected_list):
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_hyperlinks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 2,
"issue_text_score": 0,
"test_score": 3
},
"num_modified_files": 1
} | 0.9 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "",
"pip_packages": [
"nose",
"coverage",
"numpy>=1.6.1",
"pytest"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.5",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | attrs==22.2.0
certifi==2021.5.30
coverage==6.2
importlib-metadata==4.8.3
iniconfig==1.1.1
-e git+https://github.com/joblib/joblib.git@aeb018af545e025654176ffe9ae876bda1bddb89#egg=joblib
nose==1.3.7
numpy==1.19.5
packaging==21.3
pluggy==1.0.0
py==1.11.0
pyparsing==3.1.4
pytest==7.0.1
tomli==1.2.3
typing_extensions==4.1.1
zipp==3.6.0
| name: joblib
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2021.5.30=py36h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.3=he6710b0_2
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- pip=21.2.2=py36h06a4308_0
- python=3.6.13=h12debd9_1
- readline=8.2=h5eee18b_0
- setuptools=58.0.4=py36h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- wheel=0.37.1=pyhd3eb1b0_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- attrs==22.2.0
- coverage==6.2
- importlib-metadata==4.8.3
- iniconfig==1.1.1
- nose==1.3.7
- numpy==1.19.5
- packaging==21.3
- pluggy==1.0.0
- py==1.11.0
- pyparsing==3.1.4
- pytest==7.0.1
- tomli==1.2.3
- typing-extensions==4.1.1
- zipp==3.6.0
prefix: /opt/conda/envs/joblib
| [
"joblib/test/test_numpy_pickle.py::test_memmap_persistence_mixed_dtypes"
] | [
"joblib/test/test_numpy_pickle.py::test_joblib_pickle_across_python_versions"
] | [
"joblib/test/test_numpy_pickle.py::test_value_error",
"joblib/test/test_numpy_pickle.py::test_numpy_persistence",
"joblib/test/test_numpy_pickle.py::test_memmap_persistence",
"joblib/test/test_numpy_pickle.py::test_masked_array_persistence",
"joblib/test/test_numpy_pickle.py::test_z_file",
"joblib/test/test_numpy_pickle.py::test_compressed_pickle_dump_and_load",
"joblib/test/test_numpy_pickle.py::test_numpy_subclass"
] | [] | BSD 3-Clause "New" or "Revised" License | 280 |
docker__docker-py-832 | 47ab89ec2bd3bddf1221b856ffbaff333edeabb4 | 2015-10-29 15:17:54 | 1ca2bc58f0cf2e2cdda2734395bd3e7ad9b178bf | diff --git a/docker/auth/auth.py b/docker/auth/auth.py
index 2ed894ee..416dd7c4 100644
--- a/docker/auth/auth.py
+++ b/docker/auth/auth.py
@@ -96,7 +96,7 @@ def decode_auth(auth):
auth = auth.encode('ascii')
s = base64.b64decode(auth)
login, pwd = s.split(b':', 1)
- return login.decode('ascii'), pwd.decode('ascii')
+ return login.decode('utf8'), pwd.decode('utf8')
def encode_header(auth):
| decode_auth function does not handle utf-8 logins or password
HI
I have found that the function **decode_auth** (line 96, [file](https://github.com/docker/docker-py/blob/master/docker/auth/auth.py)) fails when decoding UTF-8 passwords from the .dockercfg file, and **load_config** returning an empty config.
I have checked and docker hub can handle UTF-8 passwords, this code proves that:
```python
# coding=utf-8
from docker import Client
cred = { 'username': <user>, 'password': <utf-8 password> }
c = Client(base_url='unix://var/run/docker.sock')
res = c.pull(repository='<private container>', tag='latest', auth_config=cred)
print(res)
```
Thank you | docker/docker-py | diff --git a/tests/unit/auth_test.py b/tests/unit/auth_test.py
index 9f4d439b..67830381 100644
--- a/tests/unit/auth_test.py
+++ b/tests/unit/auth_test.py
@@ -316,3 +316,33 @@ class LoadConfigTest(base.Cleanup, base.BaseTestCase):
self.assertEqual(cfg['password'], 'izayoi')
self.assertEqual(cfg['email'], '[email protected]')
self.assertEqual(cfg.get('auth'), None)
+
+ def test_load_config_custom_config_env_utf8(self):
+ folder = tempfile.mkdtemp()
+ self.addCleanup(shutil.rmtree, folder)
+
+ dockercfg_path = os.path.join(folder, 'config.json')
+ registry = 'https://your.private.registry.io'
+ auth_ = base64.b64encode(
+ b'sakuya\xc3\xa6:izayoi\xc3\xa6').decode('ascii')
+ config = {
+ 'auths': {
+ registry: {
+ 'auth': '{0}'.format(auth_),
+ 'email': '[email protected]'
+ }
+ }
+ }
+
+ with open(dockercfg_path, 'w') as f:
+ json.dump(config, f)
+
+ with mock.patch.dict(os.environ, {'DOCKER_CONFIG': folder}):
+ cfg = auth.load_config(None)
+ assert registry in cfg
+ self.assertNotEqual(cfg[registry], None)
+ cfg = cfg[registry]
+ self.assertEqual(cfg['username'], b'sakuya\xc3\xa6'.decode('utf8'))
+ self.assertEqual(cfg['password'], b'izayoi\xc3\xa6'.decode('utf8'))
+ self.assertEqual(cfg['email'], '[email protected]')
+ self.assertEqual(cfg.get('auth'), None)
| {
"commit_name": "head_commit",
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true,
"llm_score": {
"difficulty_score": 1,
"issue_text_score": 1,
"test_score": 0
},
"num_modified_files": 1
} | 1.5 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest",
"pytest-cov",
"pytest-xdist",
"pytest-mock"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.7",
"reqs_path": [
"requirements.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | certifi @ file:///croot/certifi_1671487769961/work/certifi
coverage==7.2.7
-e git+https://github.com/docker/docker-py.git@47ab89ec2bd3bddf1221b856ffbaff333edeabb4#egg=docker_py
exceptiongroup==1.2.2
execnet==2.0.2
importlib-metadata==6.7.0
iniconfig==2.0.0
packaging==24.0
pluggy==1.2.0
pytest==7.4.4
pytest-cov==4.1.0
pytest-mock==3.11.1
pytest-xdist==3.5.0
requests==2.5.3
six==1.17.0
tomli==2.0.1
typing_extensions==4.7.1
websocket-client==0.32.0
zipp==3.15.0
| name: docker-py
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2022.12.7=py37h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- pip=22.3.1=py37h06a4308_0
- python=3.7.16=h7a1cb2a_0
- readline=8.2=h5eee18b_0
- setuptools=65.6.3=py37h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- wheel=0.38.4=py37h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- coverage==7.2.7
- exceptiongroup==1.2.2
- execnet==2.0.2
- importlib-metadata==6.7.0
- iniconfig==2.0.0
- packaging==24.0
- pluggy==1.2.0
- pytest==7.4.4
- pytest-cov==4.1.0
- pytest-mock==3.11.1
- pytest-xdist==3.5.0
- requests==2.5.3
- six==1.17.0
- tomli==2.0.1
- typing-extensions==4.7.1
- websocket-client==0.32.0
- zipp==3.15.0
prefix: /opt/conda/envs/docker-py
| [
"tests/unit/auth_test.py::LoadConfigTest::test_load_config_custom_config_env_utf8"
] | [] | [
"tests/unit/auth_test.py::RegressionTest::test_803_urlsafe_encode",
"tests/unit/auth_test.py::ResolveAuthTest::test_resolve_authconfig_default_explicit_none",
"tests/unit/auth_test.py::ResolveAuthTest::test_resolve_authconfig_default_registry",
"tests/unit/auth_test.py::ResolveAuthTest::test_resolve_authconfig_fully_explicit",
"tests/unit/auth_test.py::ResolveAuthTest::test_resolve_authconfig_hostname_only",
"tests/unit/auth_test.py::ResolveAuthTest::test_resolve_authconfig_legacy_config",
"tests/unit/auth_test.py::ResolveAuthTest::test_resolve_authconfig_no_match",
"tests/unit/auth_test.py::ResolveAuthTest::test_resolve_authconfig_no_path",
"tests/unit/auth_test.py::ResolveAuthTest::test_resolve_authconfig_no_path_trailing_slash",
"tests/unit/auth_test.py::ResolveAuthTest::test_resolve_authconfig_no_path_wrong_insecure_proto",
"tests/unit/auth_test.py::ResolveAuthTest::test_resolve_authconfig_no_path_wrong_secure_proto",
"tests/unit/auth_test.py::ResolveAuthTest::test_resolve_authconfig_no_protocol",
"tests/unit/auth_test.py::ResolveAuthTest::test_resolve_authconfig_path_wrong_proto",
"tests/unit/auth_test.py::ResolveAuthTest::test_resolve_registry_and_auth_hub_image",
"tests/unit/auth_test.py::ResolveAuthTest::test_resolve_registry_and_auth_library_image",
"tests/unit/auth_test.py::ResolveAuthTest::test_resolve_registry_and_auth_private_registry",
"tests/unit/auth_test.py::ResolveAuthTest::test_resolve_registry_and_auth_unauthenticated_registry",
"tests/unit/auth_test.py::ResolveAuthTest::test_resolve_repository_name_hub_image",
"tests/unit/auth_test.py::ResolveAuthTest::test_resolve_repository_name_hub_library_image",
"tests/unit/auth_test.py::ResolveAuthTest::test_resolve_repository_name_localhost",
"tests/unit/auth_test.py::ResolveAuthTest::test_resolve_repository_name_localhost_with_username",
"tests/unit/auth_test.py::ResolveAuthTest::test_resolve_repository_name_no_dots_but_port",
"tests/unit/auth_test.py::ResolveAuthTest::test_resolve_repository_name_no_dots_but_port_and_username",
"tests/unit/auth_test.py::ResolveAuthTest::test_resolve_repository_name_private_registry",
"tests/unit/auth_test.py::ResolveAuthTest::test_resolve_repository_name_private_registry_with_port",
"tests/unit/auth_test.py::ResolveAuthTest::test_resolve_repository_name_private_registry_with_username",
"tests/unit/auth_test.py::LoadConfigTest::test_load_config",
"tests/unit/auth_test.py::LoadConfigTest::test_load_config_custom_config_env",
"tests/unit/auth_test.py::LoadConfigTest::test_load_config_custom_config_env_with_auths",
"tests/unit/auth_test.py::LoadConfigTest::test_load_config_no_file",
"tests/unit/auth_test.py::LoadConfigTest::test_load_config_with_random_name"
] | [] | Apache License 2.0 | 281 |
|
jonathanj__eliottree-40 | 4dae7890294edb4d845b00a8bb310bc08c555352 | 2015-10-30 07:46:22 | 26748c5e640b6d25d71eefad95920c41dab0f8db | diff --git a/eliottree/_cli.py b/eliottree/_cli.py
index 6b0d24e..c333d8c 100644
--- a/eliottree/_cli.py
+++ b/eliottree/_cli.py
@@ -2,36 +2,20 @@ import argparse
import codecs
import json
import sys
-from datetime import datetime
from itertools import chain
from six import PY3
from six.moves import map
-from toolz import compose
from eliottree import (
Tree, filter_by_jmespath, filter_by_uuid, render_task_nodes)
-def _convert_timestamp(task):
- """
- Convert a ``timestamp`` key to a ``datetime``.
- """
- task['timestamp'] = datetime.utcfromtimestamp(task['timestamp'])
- return task
-
-
-def build_task_nodes(files=None, select=None, task_uuid=None,
- human_readable=True):
+def build_task_nodes(files=None, select=None, task_uuid=None):
"""
Build the task nodes given some input data, query criteria and formatting
options.
"""
- def task_transformers():
- if human_readable:
- yield _convert_timestamp
- yield json.loads
-
def filter_funcs():
if select is not None:
for query in select:
@@ -47,8 +31,7 @@ def build_task_nodes(files=None, select=None, task_uuid=None,
files = [codecs.getreader('utf-8')(sys.stdin)]
tree = Tree()
- tasks = map(compose(*task_transformers()),
- chain.from_iterable(files))
+ tasks = map(json.loads, chain.from_iterable(files))
return tree.nodes(tree.merge_tasks(tasks, filter_funcs()))
@@ -65,13 +48,13 @@ def display_task_tree(args):
nodes = build_task_nodes(
files=args.files,
select=args.select,
- task_uuid=args.task_uuid,
- human_readable=args.human_readable)
+ task_uuid=args.task_uuid)
render_task_nodes(
write=write,
nodes=nodes,
ignored_task_keys=set(args.ignored_task_keys) or None,
- field_limit=args.field_limit)
+ field_limit=args.field_limit,
+ human_readable=args.human_readable)
def main():
diff --git a/eliottree/render.py b/eliottree/render.py
index 4876a3e..626683c 100644
--- a/eliottree/render.py
+++ b/eliottree/render.py
@@ -8,20 +8,42 @@ DEFAULT_IGNORED_KEYS = set([
u'message_type'])
-def _format_value(value):
+def _format_value_raw(value):
"""
- Format a value for a task tree.
+ Format a value.
"""
if isinstance(value, datetime):
if PY3:
return value.isoformat(' ')
else:
return value.isoformat(' ').decode('ascii')
- elif isinstance(value, text_type):
+ return None
+
+
+def _format_value_hint(value, hint):
+ """
+ Format a value given a rendering hint.
+ """
+ if hint == u'timestamp':
+ return _format_value_raw(datetime.utcfromtimestamp(value))
+ return None
+
+
+def _format_value(value, field_hint=None, human_readable=False):
+ """
+ Format a value for a task tree.
+ """
+ if isinstance(value, text_type):
return value
elif isinstance(value, binary_type):
# We guess bytes values are UTF-8.
return value.decode('utf-8', 'replace')
+ if human_readable:
+ formatted = _format_value_raw(value)
+ if formatted is None:
+ formatted = _format_value_hint(value, field_hint)
+ if formatted is not None:
+ return formatted
result = repr(value)
if isinstance(result, binary_type):
result = result.decode('utf-8', 'replace')
@@ -48,7 +70,7 @@ def _truncate_value(value, limit):
return value
-def _render_task(write, task, ignored_task_keys, field_limit):
+def _render_task(write, task, ignored_task_keys, field_limit, human_readable):
"""
Render a single ``_TaskNode`` as an ``ASCII`` tree.
@@ -64,6 +86,9 @@ def _render_task(write, task, ignored_task_keys, field_limit):
:type ignored_task_keys: ``set`` of ``text_type``
:param ignored_task_keys: Set of task key names to ignore.
+
+ :type human_readable: ``bool``
+ :param human_readable: Should this be rendered as human-readable?
"""
_write = _indented_write(write)
num_items = len(task)
@@ -78,9 +103,12 @@ def _render_task(write, task, ignored_task_keys, field_limit):
_render_task(write=_write,
task=value,
ignored_task_keys={},
- field_limit=field_limit)
+ field_limit=field_limit,
+ human_readable=human_readable)
else:
- _value = _format_value(value)
+ _value = _format_value(value,
+ field_hint=key,
+ human_readable=human_readable)
if field_limit:
first_line = _truncate_value(_value, field_limit)
else:
@@ -96,7 +124,8 @@ def _render_task(write, task, ignored_task_keys, field_limit):
_write(line + '\n')
-def _render_task_node(write, node, field_limit, ignored_task_keys):
+def _render_task_node(write, node, field_limit, ignored_task_keys,
+ human_readable):
"""
Render a single ``_TaskNode`` as an ``ASCII`` tree.
@@ -112,6 +141,9 @@ def _render_task_node(write, node, field_limit, ignored_task_keys):
:type ignored_task_keys: ``set`` of ``text_type``
:param ignored_task_keys: Set of task key names to ignore.
+
+ :type human_readable: ``bool``
+ :param human_readable: Should this be rendered as human-readable?
"""
_child_write = _indented_write(write)
write(
@@ -120,17 +152,20 @@ def _render_task_node(write, node, field_limit, ignored_task_keys):
write=_child_write,
task=node.task,
field_limit=field_limit,
- ignored_task_keys=ignored_task_keys)
+ ignored_task_keys=ignored_task_keys,
+ human_readable=human_readable)
for child in node.children():
_render_task_node(
write=_child_write,
node=child,
field_limit=field_limit,
- ignored_task_keys=ignored_task_keys)
+ ignored_task_keys=ignored_task_keys,
+ human_readable=human_readable)
-def render_task_nodes(write, nodes, field_limit, ignored_task_keys=None):
+def render_task_nodes(write, nodes, field_limit, ignored_task_keys=None,
+ human_readable=False):
"""
Render a tree of task nodes as an ``ASCII`` tree.
@@ -147,6 +182,9 @@ def render_task_nodes(write, nodes, field_limit, ignored_task_keys=None):
:type ignored_task_keys: ``set`` of ``text_type``
:param ignored_task_keys: Set of task key names to ignore.
+
+ :type human_readable: ``bool``
+ :param human_readable: Should this be rendered as human-readable?
"""
if ignored_task_keys is None:
ignored_task_keys = DEFAULT_IGNORED_KEYS
@@ -156,7 +194,8 @@ def render_task_nodes(write, nodes, field_limit, ignored_task_keys=None):
write=write,
node=node,
field_limit=field_limit,
- ignored_task_keys=ignored_task_keys)
+ ignored_task_keys=ignored_task_keys,
+ human_readable=human_readable)
write('\n')
diff --git a/setup.py b/setup.py
index e54a48d..9767156 100644
--- a/setup.py
+++ b/setup.py
@@ -29,7 +29,6 @@ setup(
install_requires=[
"six>=1.9.0",
"jmespath>=0.7.1",
- "toolz>=0.7.2",
],
extras_require={
"dev": ["pytest>=2.7.1", "testtools>=1.8.0"],
| Human-readable values should only be formatted when rendered instead of modifying the tree data
The problem with modifying the tree data is that it makes it very difficult to write queries against it if eliot-tree is changing it in undisclosed ways to suit it's renderer. | jonathanj/eliottree | diff --git a/eliottree/test/test_render.py b/eliottree/test/test_render.py
index 81d3128..81dea43 100644
--- a/eliottree/test/test_render.py
+++ b/eliottree/test/test_render.py
@@ -15,14 +15,14 @@ class FormatValueTests(TestCase):
"""
Tests for ``eliottree.render._format_value``.
"""
- def test_datetime(self):
+ def test_datetime_human_readable(self):
"""
Format ``datetime`` values as ISO8601.
"""
now = datetime(2015, 6, 6, 22, 57, 12)
self.assertThat(
- _format_value(now),
- Equals('2015-06-06 22:57:12'))
+ _format_value(now, human_readable=True),
+ Equals(u'2015-06-06 22:57:12'))
def test_unicode(self):
"""
@@ -59,6 +59,16 @@ class FormatValueTests(TestCase):
_format_value({'a': u('\N{SNOWMAN}')}),
Equals("{'a': u'\\u2603'}"))
+ def test_timestamp_hint(self):
+ """
+ Format "timestamp" hinted data as timestamps.
+ """
+ # datetime(2015, 6, 6, 22, 57, 12)
+ now = 1433631432
+ self.assertThat(
+ _format_value(now, field_hint='timestamp', human_readable=True),
+ Equals(u'2015-06-06 22:57:12'))
+
class RenderTaskNodesTests(TestCase):
"""
@@ -85,6 +95,28 @@ class RenderTaskNodesTests(TestCase):
' +-- app:action@2/succeeded\n'
' `-- timestamp: 1425356800\n\n'))
+ def test_tasks_human_readable(self):
+ """
+ Render two tasks of sequential levels, by default most standard Eliot
+ task keys are ignored, values are formatted to be human readable.
+ """
+ fd = StringIO()
+ tree = Tree()
+ tree.merge_tasks([action_task, action_task_end])
+ render_task_nodes(
+ write=fd.write,
+ nodes=tree.nodes(),
+ field_limit=0,
+ human_readable=True)
+ self.assertThat(
+ fd.getvalue(),
+ Equals(
+ 'f3a32bb3-ea6b-457c-aa99-08a3d0491ab4\n'
+ '+-- app:action@1/started\n'
+ ' `-- timestamp: 2015-03-03 04:26:40\n'
+ ' +-- app:action@2/succeeded\n'
+ ' `-- timestamp: 2015-03-03 04:26:40\n\n'))
+
def test_multiline_field(self):
"""
When no field limit is specified for task values, multiple lines are
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 1,
"issue_text_score": 2,
"test_score": 3
},
"num_modified_files": 3
} | 15.3 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[dev]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": null,
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.9",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | -e git+https://github.com/jonathanj/eliottree.git@4dae7890294edb4d845b00a8bb310bc08c555352#egg=eliot_tree
exceptiongroup==1.2.2
iniconfig==2.1.0
jmespath==1.0.1
packaging==24.2
pluggy==1.5.0
pytest==8.3.5
six==1.17.0
testtools==2.7.2
tomli==2.2.1
toolz==1.0.0
| name: eliottree
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=3.0.16=h5eee18b_0
- pip=25.0=py39h06a4308_0
- python=3.9.21=he870216_1
- readline=8.2=h5eee18b_0
- setuptools=75.8.0=py39h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- tzdata=2025a=h04d1e81_0
- wheel=0.45.1=py39h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- exceptiongroup==1.2.2
- iniconfig==2.1.0
- jmespath==1.0.1
- packaging==24.2
- pluggy==1.5.0
- pytest==8.3.5
- six==1.17.0
- testtools==2.7.2
- tomli==2.2.1
- toolz==1.0.0
prefix: /opt/conda/envs/eliottree
| [
"eliottree/test/test_render.py::FormatValueTests::test_datetime_human_readable",
"eliottree/test/test_render.py::FormatValueTests::test_timestamp_hint",
"eliottree/test/test_render.py::RenderTaskNodesTests::test_tasks_human_readable"
] | [] | [
"eliottree/test/test_render.py::FormatValueTests::test_other",
"eliottree/test/test_render.py::FormatValueTests::test_str",
"eliottree/test/test_render.py::FormatValueTests::test_unicode",
"eliottree/test/test_render.py::RenderTaskNodesTests::test_dict_data",
"eliottree/test/test_render.py::RenderTaskNodesTests::test_field_limit",
"eliottree/test/test_render.py::RenderTaskNodesTests::test_ignored_keys",
"eliottree/test/test_render.py::RenderTaskNodesTests::test_multiline_field",
"eliottree/test/test_render.py::RenderTaskNodesTests::test_multiline_field_limit",
"eliottree/test/test_render.py::RenderTaskNodesTests::test_nested",
"eliottree/test/test_render.py::RenderTaskNodesTests::test_task_data",
"eliottree/test/test_render.py::RenderTaskNodesTests::test_tasks"
] | [] | MIT License | 282 |
|
sympy__sympy-10083 | c67d601999dae4ebf16f055454954a6a556e6857 | 2015-10-30 15:53:56 | 0241b35cae5f2adc04dc37b25f7dc9c5f00bd746 | gxyd: I was hoping that something like
```
>>> x = Symbol('x')
>>> X = DieDistribution(6)
>>> X.pdf(x)
PDF(X, x) # some PDF be returned though i guess no such PDF class or function is there
```
I expected something similar to `Contains`
```
>>> A.contains(x)
Contains(A, x)
```
jksuom: I think it could be possible to return a sensible ``X.pdf(x)`` even for a symbol ``x``. For an ordinary die (with 6 faces) it would be ``AddWithLimits(KroneckerDelta(x, i)/6, (i, 1, 6))`` (though that looks a bit clumsy).
gxyd: It looks good to me. I did not know about the `KroneckerDelta` function till now though.
> AddWithLimits(KroneckerDelta(x, i)/6, (i, 1, 6)) (though that looks a bit clumsy).
I think i am ok, with that.
jksuom: I now think that we should have ``Sum`` instead of ``AddWithLimits``. I had forgotten its existence. It seems that ``X.pdf(x).subs(x, 1).doit()`` would compute correctly with ``Sum`` since it has its own version of ``doit``. There could be some tests for such substitutions. And maybe for some illegal substitution as well.
gxyd: I myself, even before seeing with `AddWithLimits` checked with `Sum.doit()` . But i could not though make that out how to do that. But Ok, let me try again. I may now be able to come to solution.
gxyd: I have made the changes. Perhaps previously i was also using `.doit()` itself in code. Now using ony `Sum` works fine.
jksuom: This looks good to me. The separation of arguments that do not belong to the probability space (i.e. integers between 1 and ``sides``) into two classes: numbers returning 0, and non-numbers returning an error, is somewhat arbitrary, but I cannot think of a better way now. | diff --git a/sympy/stats/frv_types.py b/sympy/stats/frv_types.py
index be522333c8..fa6688dd1e 100644
--- a/sympy/stats/frv_types.py
+++ b/sympy/stats/frv_types.py
@@ -17,8 +17,9 @@
from sympy.core.compatibility import as_int, range
from sympy.core.logic import fuzzy_not, fuzzy_and
from sympy.stats.frv import (SingleFinitePSpace, SingleFiniteDistribution)
+from sympy.concrete.summations import Sum
from sympy import (S, sympify, Rational, binomial, cacheit, Integer,
- Dict, Basic)
+ Dict, Basic, KroneckerDelta, Dummy)
__all__ = ['FiniteRV', 'DiscreteUniform', 'Die', 'Bernoulli', 'Coin',
'Binomial', 'Hypergeometric']
@@ -49,7 +50,7 @@ def FiniteRV(name, density):
>>> E(X)
2.00000000000000
- >>> P(X>=2)
+ >>> P(X >= 2)
0.700000000000000
"""
return rv(name, FiniteDistributionHandmade, density)
@@ -118,14 +119,19 @@ def dict(self):
@property
def set(self):
- return list(map(Integer, list(range(1, self.sides+1))))
+ return list(map(Integer, list(range(1, self.sides + 1))))
def pdf(self, x):
x = sympify(x)
- if x.is_Integer and x >= 1 and x <= self.sides:
- return Rational(1, self.sides)
- else:
- return 0
+ if x.is_number:
+ if x.is_Integer and x >= 1 and x <= self.sides:
+ return Rational(1, self.sides)
+ return S.Zero
+ if x.is_Symbol:
+ i = Dummy('i', integer=True, positive=True)
+ return Sum(KroneckerDelta(x, i)/self.sides, (i, 1, self.sides))
+ raise ValueError("'x' expected as an argument of type 'number' or 'symbol', "
+ "not %s" % (type(x)))
def Die(name, sides=6):
| X.pdf(x) for Symbol x returns 0
```
>>> x = Symbol('x')
>>> from sympy.stats.frv_types import DieDistribution
>>> X = DieDistribution(6)
>>> X.pdf(x)
0
```
Either this should raise a `ValueError` or unevaluated. Returning unevaluated seems more favourable. | sympy/sympy | diff --git a/sympy/stats/tests/test_finite_rv.py b/sympy/stats/tests/test_finite_rv.py
index 5f3663623f..e8e3a9c2bb 100644
--- a/sympy/stats/tests/test_finite_rv.py
+++ b/sympy/stats/tests/test_finite_rv.py
@@ -1,13 +1,16 @@
from sympy.core.compatibility import range
from sympy import (FiniteSet, S, Symbol, sqrt,
symbols, simplify, Eq, cos, And, Tuple, Or, Dict, sympify, binomial,
- cancel)
+ cancel, KroneckerDelta)
+from sympy.concrete.expr_with_limits import AddWithLimits
+from sympy.matrices import Matrix
from sympy.stats import (DiscreteUniform, Die, Bernoulli, Coin, Binomial,
Hypergeometric, Rademacher, P, E, variance, covariance, skewness, sample,
density, where, FiniteRV, pspace, cdf,
correlation, moment, cmoment, smoment)
+from sympy.stats.frv_types import DieDistribution
from sympy.utilities.pytest import raises, slow
-from sympy.abc import p
+from sympy.abc import p, x, i
oo = S.Infinity
@@ -259,3 +262,14 @@ def test_density_call():
assert 0 in d
assert 5 not in d
assert d(S(0)) == d[S(0)]
+
+
+def test_DieDistribution():
+ X = DieDistribution(6)
+ assert X.pdf(S(1)/2) == S.Zero
+ assert X.pdf(x).subs({x: 1}).doit() == S(1)/6
+ assert X.pdf(x).subs({x: 7}).doit() == 0
+ assert X.pdf(x).subs({x: -1}).doit() == 0
+ assert X.pdf(x).subs({x: S(1)/3}).doit() == 0
+ raises(TypeError, lambda: X.pdf(x).subs({x: Matrix([0, 0])}))
+ raises(ValueError, lambda: X.pdf(x**2 - 1))
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_short_problem_statement"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 0,
"issue_text_score": 0,
"test_score": 2
},
"num_modified_files": 1
} | 0.7 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[dev]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"mpmath>=0.19",
"pytest",
"pytest-cov",
"pytest-xdist",
"pytest-mock",
"pytest-asyncio"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.7",
"reqs_path": [
"requirements/base.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | certifi @ file:///croot/certifi_1671487769961/work/certifi
coverage==7.2.7
exceptiongroup==1.2.2
execnet==2.0.2
importlib-metadata==6.7.0
iniconfig==2.0.0
mpmath==1.3.0
packaging==24.0
pluggy==1.2.0
pytest==7.4.4
pytest-asyncio==0.21.2
pytest-cov==4.1.0
pytest-mock==3.11.1
pytest-xdist==3.5.0
-e git+https://github.com/sympy/sympy.git@c67d601999dae4ebf16f055454954a6a556e6857#egg=sympy
tomli==2.0.1
typing_extensions==4.7.1
zipp==3.15.0
| name: sympy
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2022.12.7=py37h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- pip=22.3.1=py37h06a4308_0
- python=3.7.16=h7a1cb2a_0
- readline=8.2=h5eee18b_0
- setuptools=65.6.3=py37h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- wheel=0.38.4=py37h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- coverage==7.2.7
- exceptiongroup==1.2.2
- execnet==2.0.2
- importlib-metadata==6.7.0
- iniconfig==2.0.0
- mpmath==1.3.0
- packaging==24.0
- pluggy==1.2.0
- pytest==7.4.4
- pytest-asyncio==0.21.2
- pytest-cov==4.1.0
- pytest-mock==3.11.1
- pytest-xdist==3.5.0
- tomli==2.0.1
- typing-extensions==4.7.1
- zipp==3.15.0
prefix: /opt/conda/envs/sympy
| [
"sympy/stats/tests/test_finite_rv.py::test_DieDistribution"
] | [] | [
"sympy/stats/tests/test_finite_rv.py::test_discreteuniform",
"sympy/stats/tests/test_finite_rv.py::test_dice",
"sympy/stats/tests/test_finite_rv.py::test_given",
"sympy/stats/tests/test_finite_rv.py::test_domains",
"sympy/stats/tests/test_finite_rv.py::test_dice_bayes",
"sympy/stats/tests/test_finite_rv.py::test_die_args",
"sympy/stats/tests/test_finite_rv.py::test_bernoulli",
"sympy/stats/tests/test_finite_rv.py::test_cdf",
"sympy/stats/tests/test_finite_rv.py::test_coins",
"sympy/stats/tests/test_finite_rv.py::test_binomial_verify_parameters",
"sympy/stats/tests/test_finite_rv.py::test_binomial_numeric",
"sympy/stats/tests/test_finite_rv.py::test_binomial_symbolic",
"sympy/stats/tests/test_finite_rv.py::test_hypergeometric_numeric",
"sympy/stats/tests/test_finite_rv.py::test_rademacher",
"sympy/stats/tests/test_finite_rv.py::test_FiniteRV",
"sympy/stats/tests/test_finite_rv.py::test_density_call"
] | [] | BSD | 283 |
sprymix__csscompressor-4 | 153ab1bb6cd925dc73a314af74db874a3314010f | 2015-11-01 06:16:44 | bec3e582cb5ab7182a0ca08ba381e491b94ed10c | diff --git a/csscompressor/__init__.py b/csscompressor/__init__.py
index 1b41119..1233cd3 100644
--- a/csscompressor/__init__.py
+++ b/csscompressor/__init__.py
@@ -56,9 +56,12 @@ _space_after_re = re.compile(r'([!{}:;>+\(\[,])\s+')
_semi_re = re.compile(r';+}')
_zero_fmt_spec_re = re.compile(r'''(\s|:|\(|,)(?:0?\.)?0
- (?:px|em|%|in|cm|mm|pc|pt|ex|deg|g?rad|m?s|k?hz)''',
+ (?:px|em|%|in|cm|mm|pc|pt|ex|deg|g?rad|k?hz)''',
re.I | re.X)
+_zero_req_unit_re = re.compile(r'''(\s|:|\(|,)(?:0?\.)?0
+ (m?s)''', re.I | re.X)
+
_bg_pos_re = re.compile(r'''(background-position|webkit-mask-position|transform-origin|
webkit-transform-origin|moz-transform-origin|o-transform-origin|
ms-transform-origin):0(;|})''', re.I | re.X)
@@ -377,6 +380,9 @@ def _compress(css, max_linelen=0):
# Replace 0(px,em,%) with 0.
css = _zero_fmt_spec_re.sub(lambda match: match.group(1) + '0', css)
+ # Replace 0.0(m,ms) or .0(m,ms) with 0(m,ms)
+ css = _zero_req_unit_re.sub(lambda match: match.group(1) + '0' + match.group(2), css)
+
# Replace 0 0 0 0; with 0.
css = _quad_0_re.sub(r':0\1', css)
css = _trip_0_re.sub(r':0\1', css)
| Omitting the unit on a time value is invalid
Input: `csscompressor.compress("transition: background-color 1s linear 0ms;")`
Expected output: `'transition:background-color 1s linear 0ms;'`
Actual output: `'transition:background-color 1s linear 0;'`
According to the [MDN page on \<time>](https://developer.mozilla.org/en-US/docs/Web/CSS/time), omitting the unit is only valid for \<length>, so when I use csscompressor, the declaration containing the 0ms or 0s is ignored by both Firefox and Chrome.
The same case is for `<frequency>`, and probably a few of the other ones, I think. Omitting the unit used to be valid in CSS2, but breaks in CSS3 unfortunately.
This is a fairly simple fix (removing the `m?s` from `_zero_fmt_spec_re`), and I'll create a PR and some tests. | sprymix/csscompressor | diff --git a/csscompressor/tests/test_yui.py b/csscompressor/tests/test_yui.py
index a0d6715..5d56d24 100644
--- a/csscompressor/tests/test_yui.py
+++ b/csscompressor/tests/test_yui.py
@@ -1458,7 +1458,7 @@ serve! */"""
"""
- output = """a{margin:0;_padding-top:0;background-position:0 0;padding:0;transition:opacity 0;transition-delay:0;transform:rotate3d(0,0,0);pitch:0;pitch:0}"""
+ output = """a{margin:0;_padding-top:0;background-position:0 0;padding:0;transition:opacity 0s;transition-delay:0ms;transform:rotate3d(0,0,0);pitch:0;pitch:0}"""
self._test(input, output)
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_hyperlinks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 1,
"issue_text_score": 2,
"test_score": 0
},
"num_modified_files": 1
} | 0.9 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "pytest",
"pip_packages": [
"pytest"
],
"pre_install": null,
"python": "3.9",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | -e git+https://github.com/sprymix/csscompressor.git@153ab1bb6cd925dc73a314af74db874a3314010f#egg=csscompressor
exceptiongroup @ file:///croot/exceptiongroup_1706031385326/work
iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work
packaging @ file:///croot/packaging_1734472117206/work
pluggy @ file:///croot/pluggy_1733169602837/work
pytest @ file:///croot/pytest_1738938843180/work
tomli @ file:///opt/conda/conda-bld/tomli_1657175507142/work
| name: csscompressor
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- exceptiongroup=1.2.0=py39h06a4308_0
- iniconfig=1.1.1=pyhd3eb1b0_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=3.0.16=h5eee18b_0
- packaging=24.2=py39h06a4308_0
- pip=25.0=py39h06a4308_0
- pluggy=1.5.0=py39h06a4308_0
- pytest=8.3.4=py39h06a4308_0
- python=3.9.21=he870216_1
- readline=8.2=h5eee18b_0
- setuptools=75.8.0=py39h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- tomli=2.0.1=py39h06a4308_0
- tzdata=2025a=h04d1e81_0
- wheel=0.45.1=py39h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
prefix: /opt/conda/envs/csscompressor
| [
"csscompressor/tests/test_yui.py::TestYUI::test_yui_zeros"
] | [] | [
"csscompressor/tests/test_yui.py::TestYUI::test_yui_background_position",
"csscompressor/tests/test_yui.py::TestYUI::test_yui_border_none",
"csscompressor/tests/test_yui.py::TestYUI::test_yui_box_model_hack",
"csscompressor/tests/test_yui.py::TestYUI::test_yui_bug2527974",
"csscompressor/tests/test_yui.py::TestYUI::test_yui_bug2527991",
"csscompressor/tests/test_yui.py::TestYUI::test_yui_bug2527998",
"csscompressor/tests/test_yui.py::TestYUI::test_yui_bug2528034",
"csscompressor/tests/test_yui.py::TestYUI::test_yui_charset_media",
"csscompressor/tests/test_yui.py::TestYUI::test_yui_color_keyword",
"csscompressor/tests/test_yui.py::TestYUI::test_yui_color_simple",
"csscompressor/tests/test_yui.py::TestYUI::test_yui_color",
"csscompressor/tests/test_yui.py::TestYUI::test_yui_comment",
"csscompressor/tests/test_yui.py::TestYUI::test_yui_concat_charset",
"csscompressor/tests/test_yui.py::TestYUI::test_yui_dataurl_base64_doublequotes",
"csscompressor/tests/test_yui.py::TestYUI::test_yui_dataurl_base64_eof",
"csscompressor/tests/test_yui.py::TestYUI::test_yui_dataurl_base64_linebreakindata",
"csscompressor/tests/test_yui.py::TestYUI::test_yui_dataurl_base64_noquotes",
"csscompressor/tests/test_yui.py::TestYUI::test_yui_dataurl_base64_singlequotes",
"csscompressor/tests/test_yui.py::TestYUI::test_yui_dataurl_base64_twourls",
"csscompressor/tests/test_yui.py::TestYUI::test_yui_dataurl_dbquote_font",
"csscompressor/tests/test_yui.py::TestYUI::test_yui_dataurl_nonbase64_doublequotes",
"csscompressor/tests/test_yui.py::TestYUI::test_yui_dataurl_nonbase64_noquotes",
"csscompressor/tests/test_yui.py::TestYUI::test_yui_dataurl_noquote_multiline_font",
"csscompressor/tests/test_yui.py::TestYUI::test_yui_dataurl_realdata_doublequotes",
"csscompressor/tests/test_yui.py::TestYUI::test_yui_dataurl_realdata_noquotes",
"csscompressor/tests/test_yui.py::TestYUI::test_yui_dataurl_realdata_singlequotes",
"csscompressor/tests/test_yui.py::TestYUI::test_yui_dataurl_realdata_yuiapp",
"csscompressor/tests/test_yui.py::TestYUI::test_yui_dataurl_singlequote_font",
"csscompressor/tests/test_yui.py::TestYUI::test_yui_decimals",
"csscompressor/tests/test_yui.py::TestYUI::test_yui_dollar_header",
"csscompressor/tests/test_yui.py::TestYUI::test_yui_font_face",
"csscompressor/tests/test_yui.py::TestYUI::test_yui_ie5mac",
"csscompressor/tests/test_yui.py::TestYUI::test_yui_lowercasing",
"csscompressor/tests/test_yui.py::TestYUI::test_yui_media_empty_class",
"csscompressor/tests/test_yui.py::TestYUI::test_yui_media_multi",
"csscompressor/tests/test_yui.py::TestYUI::test_yui_media_test",
"csscompressor/tests/test_yui.py::TestYUI::test_yui_old_ie_filter_matrix",
"csscompressor/tests/test_yui.py::TestYUI::test_yui_opacity_filter",
"csscompressor/tests/test_yui.py::TestYUI::test_yui_opera_pixel_ratio",
"csscompressor/tests/test_yui.py::TestYUI::test_yui_preserve_case",
"csscompressor/tests/test_yui.py::TestYUI::test_yui_preserve_important",
"csscompressor/tests/test_yui.py::TestYUI::test_yui_preserve_new_line",
"csscompressor/tests/test_yui.py::TestYUI::test_yui_preserve_strings",
"csscompressor/tests/test_yui.py::TestYUI::test_yui_pseudo_first",
"csscompressor/tests/test_yui.py::TestYUI::test_yui_pseudo",
"csscompressor/tests/test_yui.py::TestYUI::test_yui_special_comments",
"csscompressor/tests/test_yui.py::TestYUI::test_yui_star_underscore_hacks",
"csscompressor/tests/test_yui.py::TestYUI::test_yui_string_in_comment",
"csscompressor/tests/test_yui.py::TestYUI::test_yui_webkit_transform",
"csscompressor/tests/test_yui.py::TestYUI::test_yui_dataurl_nonbase64_singlequotes"
] | [] | BSD | 284 |
|
sympy__sympy-10097 | 41fc8f5a4dabd350f2f23a4aef53db728ca8ee0d | 2015-11-01 21:52:11 | 0241b35cae5f2adc04dc37b25f7dc9c5f00bd746 | diff --git a/README.rst b/README.rst
index 13e71d11fa..23342c4eac 100644
--- a/README.rst
+++ b/README.rst
@@ -184,7 +184,7 @@ from Google Summer of Code students.
In 2011, Ondřej Čertík stepped down as lead developer, with Aaron Meurer, who
also started as a Google Summer of Code student, taking his place. Ondřej
Čertík is still active in the community, but is too busy with work and family
-to play a lead development role.
+to play a lead development role
Since then, a lot more people have joined the development and some people have
also left. You can see the full list in doc/src/aboutus.rst, or online at:
diff --git a/doc/src/aboutus.rst b/doc/src/aboutus.rst
index 8b262bc5bb..ee954a9c14 100644
--- a/doc/src/aboutus.rst
+++ b/doc/src/aboutus.rst
@@ -236,7 +236,7 @@ want to be mentioned here, so see our repository history for a full list).
#. Marek Šuppa: Improvements to symbols, tests
#. Prasoon Shukla: Bug fixes
#. Stefen Yin: Fixes to the mechanics module
-#. Thomas Hisch: Spherical Hankel functions, Improvements to the printing module, Improvements to the doctesting system
+#. Thomas Hisch: Improvements to the printing module
#. Matthew Hoff: Addition to quantum module
#. Madeleine Ball: Bug fix
#. Case Van Horsen: Fixes to gmpy support
diff --git a/sympy/functions/__init__.py b/sympy/functions/__init__.py
index ce1a4e0c36..9c71f40365 100644
--- a/sympy/functions/__init__.py
+++ b/sympy/functions/__init__.py
@@ -34,7 +34,7 @@
from sympy.functions.special.delta_functions import DiracDelta, Heaviside
from sympy.functions.special.bsplines import bspline_basis, bspline_basis_set
from sympy.functions.special.bessel import (besselj, bessely, besseli, besselk,
- hankel1, hankel2, jn, yn, jn_zeros, hn1, hn2, airyai, airybi, airyaiprime, airybiprime)
+ hankel1, hankel2, jn, yn, jn_zeros, airyai, airybi, airyaiprime, airybiprime)
from sympy.functions.special.hyper import hyper, meijerg
from sympy.functions.special.polynomials import (legendre, assoc_legendre,
hermite, chebyshevt, chebyshevu, chebyshevu_root, chebyshevt_root,
diff --git a/sympy/functions/special/bessel.py b/sympy/functions/special/bessel.py
index f087730969..1789a6e84e 100644
--- a/sympy/functions/special/bessel.py
+++ b/sympy/functions/special/bessel.py
@@ -1,11 +1,8 @@
from __future__ import print_function, division
-from functools import wraps
-
from sympy import S, pi, I, Rational, Wild, cacheit, sympify
from sympy.core.function import Function, ArgumentIndexError
from sympy.core.power import Pow
-from sympy.core.compatibility import range
from sympy.functions.combinatorial.factorials import factorial
from sympy.functions.elementary.trigonometric import sin, cos, csc, cot
from sympy.functions.elementary.complexes import Abs
@@ -13,8 +10,7 @@
from sympy.functions.elementary.complexes import re, im
from sympy.functions.special.gamma_functions import gamma
from sympy.functions.special.hyper import hyper
-from sympy.polys.orthopolys import spherical_bessel_fn as fn
-
+from sympy.core.compatibility import range
# TODO
# o Scorer functions G1 and G2
@@ -559,13 +555,7 @@ def _eval_conjugate(self):
if (z.is_real and z.is_negative) is False:
return hankel1(self.order.conjugate(), z.conjugate())
-
-def assume_integer_order(fn):
- @wraps(fn)
- def g(self, nu, z):
- if nu.is_integer:
- return fn(self, nu, z)
- return g
+from sympy.polys.orthopolys import spherical_bessel_fn as fn
class SphericalBesselBase(BesselBase):
@@ -590,11 +580,11 @@ def _rewrite(self):
def _eval_expand_func(self, **hints):
if self.order.is_Integer:
return self._expand(**hints)
- return self
+ else:
+ return self
def _eval_evalf(self, prec):
- if self.order.is_Integer:
- return self._rewrite()._eval_evalf(prec)
+ return self._rewrite()._eval_evalf(prec)
def fdiff(self, argindex=2):
if argindex != 2:
@@ -603,15 +593,6 @@ def fdiff(self, argindex=2):
self * (self.order + 1)/self.argument
-def _jn(n, z):
- return fn(n, z)*sin(z) + (-1)**(n + 1)*fn(-n - 1, z)*cos(z)
-
-
-def _yn(n, z):
- # (-1)**(n + 1) * _jn(-n - 1, z)
- return (-1)**(n + 1) * fn(-n - 1, z)*sin(z) - fn(n, z)*cos(z)
-
-
class jn(SphericalBesselBase):
r"""
Spherical Bessel function of the first kind.
@@ -629,62 +610,43 @@ class jn(SphericalBesselBase):
where :math:`J_\nu(z)` is the Bessel function of the first kind.
- The spherical Bessel functions of integral order are
- calculated using the formula:
-
- .. math:: j_n(z) = f_n(z) \sin{z} + (-1)^{n+1} f_{-n-1}(z) \cos{z},
-
- where the coefficients :math:`f_n(z)` are available as
- :func:`polys.orthopolys.spherical_bessel_fn`.
-
Examples
========
- >>> from sympy import Symbol, jn, sin, cos, expand_func, besselj, bessely
- >>> from sympy import simplify
+ >>> from sympy import Symbol, jn, sin, cos, expand_func
>>> z = Symbol("z")
- >>> nu = Symbol("nu", integer=True)
- >>> print(expand_func(jn(0, z)))
+ >>> print(jn(0, z).expand(func=True))
sin(z)/z
- >>> expand_func(jn(1, z)) == sin(z)/z**2 - cos(z)/z
+ >>> jn(1, z).expand(func=True) == sin(z)/z**2 - cos(z)/z
True
>>> expand_func(jn(3, z))
(-6/z**2 + 15/z**4)*sin(z) + (1/z - 15/z**3)*cos(z)
- >>> jn(nu, z).rewrite(besselj)
- sqrt(2)*sqrt(pi)*sqrt(1/z)*besselj(nu + 1/2, z)/2
- >>> jn(nu, z).rewrite(bessely)
- (-1)**nu*sqrt(2)*sqrt(pi)*sqrt(1/z)*bessely(-nu - 1/2, z)/2
- >>> jn(2, 5.2+0.3j).evalf(20)
- 0.099419756723640344491 - 0.054525080242173562897*I
+
+ The spherical Bessel functions of integral order
+ are calculated using the formula:
+
+ .. math:: j_n(z) = f_n(z) \sin{z} + (-1)^{n+1} f_{-n-1}(z) \cos{z},
+
+ where the coefficients :math:`f_n(z)` are available as
+ :func:`polys.orthopolys.spherical_bessel_fn`.
See Also
========
besselj, bessely, besselk, yn
- References
- ==========
-
- .. [1] http://dlmf.nist.gov/10.47
-
"""
def _rewrite(self):
return self._eval_rewrite_as_besselj(self.order, self.argument)
- @assume_integer_order
def _eval_rewrite_as_besselj(self, nu, z):
- return sqrt(pi/(2*z)) * besselj(nu + S.Half, z)
-
- @assume_integer_order
- def _eval_rewrite_as_bessely(self, nu, z):
- return (-1)**nu * sqrt(pi/(2*z)) * bessely(-nu - S.Half, z)
-
- def _eval_rewrite_as_yn(self, nu, z):
- return (-1)**(nu) * yn(-nu - 1, z)
+ return sqrt(pi/(2*z)) * besselj(nu + S('1/2'), z)
def _expand(self, **hints):
- return _jn(self.order, self.argument)
+ n = self.order
+ z = self.argument
+ return fn(n, z) * sin(z) + (-1)**(n + 1) * fn(-n - 1, z) * cos(z)
class yn(SphericalBesselBase):
@@ -695,221 +657,42 @@ class yn(SphericalBesselBase):
linearly independent from :math:`j_n`. It can be defined as
.. math ::
- y_\nu(z) = \sqrt{\frac{\pi}{2z}} Y_{\nu + \frac{1}{2}}(z),
+ j_\nu(z) = \sqrt{\frac{\pi}{2z}} Y_{\nu + \frac{1}{2}}(z),
where :math:`Y_\nu(z)` is the Bessel function of the second kind.
- For integral orders :math:`n`, :math:`y_n` is calculated using the formula:
-
- .. math:: y_n(z) = (-1)^{n+1} j_{-n-1}(z)
-
Examples
========
- >>> from sympy import Symbol, yn, sin, cos, expand_func, besselj, bessely
+ >>> from sympy import Symbol, yn, sin, cos, expand_func
>>> z = Symbol("z")
- >>> nu = Symbol("nu", integer=True)
>>> print(expand_func(yn(0, z)))
-cos(z)/z
>>> expand_func(yn(1, z)) == -cos(z)/z**2-sin(z)/z
True
- >>> yn(nu, z).rewrite(besselj)
- (-1)**(nu + 1)*sqrt(2)*sqrt(pi)*sqrt(1/z)*besselj(-nu - 1/2, z)/2
- >>> yn(nu, z).rewrite(bessely)
- sqrt(2)*sqrt(pi)*sqrt(1/z)*bessely(nu + 1/2, z)/2
- >>> yn(2, 5.2+0.3j).evalf(20)
- 0.18525034196069722536 + 0.014895573969924817587*I
+
+ For integral orders :math:`n`, :math:`y_n` is calculated using the formula:
+
+ .. math:: y_n(z) = (-1)^{n+1} j_{-n-1}(z)
See Also
========
besselj, bessely, besselk, jn
- References
- ==========
-
- .. [1] http://dlmf.nist.gov/10.47
-
"""
def _rewrite(self):
return self._eval_rewrite_as_bessely(self.order, self.argument)
- @assume_integer_order
- def _eval_rewrite_as_besselj(self, nu, z):
- return (-1)**(nu+1) * sqrt(pi/(2*z)) * besselj(-nu - S.Half, z)
-
- @assume_integer_order
- def _eval_rewrite_as_bessely(self, nu, z):
- return sqrt(pi/(2*z)) * bessely(nu + S.Half, z)
-
- def _eval_rewrite_as_jn(self, nu, z):
- return (-1)**(nu + 1) * jn(-nu - 1, z)
-
- def _expand(self, **hints):
- return _yn(self.order, self.argument)
-
-
-class SphericalHankelBase(SphericalBesselBase):
-
- def _rewrite(self):
- return self._eval_rewrite_as_besselj(self.order, self.argument)
-
- @assume_integer_order
- def _eval_rewrite_as_besselj(self, nu, z):
- # jn +- I*yn
- # jn as beeselj: sqrt(pi/(2*z)) * besselj(nu + S.Half, z)
- # yn as besselj: (-1)**(nu+1) * sqrt(pi/(2*z)) * besselj(-nu - S.Half, z)
- hks = self._hankel_kind_sign
- return sqrt(pi/(2*z))*(besselj(nu + S.Half, z) +
- hks*I*(-1)**(nu+1)*besselj(-nu - S.Half, z))
-
- @assume_integer_order
def _eval_rewrite_as_bessely(self, nu, z):
- # jn +- I*yn
- # jn as bessely: (-1)**nu * sqrt(pi/(2*z)) * bessely(-nu - S.Half, z)
- # yn as bessely: sqrt(pi/(2*z)) * bessely(nu + S.Half, z)
- hks = self._hankel_kind_sign
- return sqrt(pi/(2*z))*((-1)**nu*bessely(-nu - S.Half, z) +
- hks*I*bessely(nu + S.Half, z))
-
- def _eval_rewrite_as_yn(self, nu, z):
- hks = self._hankel_kind_sign
- return jn(nu, z).rewrite(yn) + hks*I*yn(nu, z)
-
- def _eval_rewrite_as_jn(self, nu, z):
- hks = self._hankel_kind_sign
- return jn(nu, z) + hks*I*yn(nu, z).rewrite(jn)
-
- def _eval_expand_func(self, **hints):
- if self.order.is_Integer:
- return self._expand(**hints)
- else:
- nu = self.order
- z = self.argument
- hks = self._hankel_kind_sign
- return jn(nu, z) + hks*I*yn(nu, z)
+ return sqrt(pi/(2*z)) * bessely(nu + S('1/2'), z)
def _expand(self, **hints):
n = self.order
z = self.argument
- hks = self._hankel_kind_sign
-
- # fully expanded version
- # return ((fn(n, z) * sin(z) +
- # (-1)**(n + 1) * fn(-n - 1, z) * cos(z)) + # jn
- # (hks * I * (-1)**(n + 1) *
- # (fn(-n - 1, z) * hk * I * sin(z) +
- # (-1)**(-n) * fn(n, z) * I * cos(z))) # +-I*yn
- # )
-
- return (_jn(n, z) + hks*I*_yn(n, z)).expand()
-
-
-class hn1(SphericalHankelBase):
- r"""
- Spherical Hankel function of the first kind.
-
- This function is defined as
-
- .. math:: h_\nu^(1)(z) = j_\nu(z) + i y_\nu(z),
-
- where :math:`j_\nu(z)` and :math:`y_\nu(z)` are the spherical
- Bessel function of the first and second kinds.
-
- For integral orders :math:`n`, :math:`h_n^(1)` is calculated using the formula:
-
- .. math:: h_n^(1)(z) = j_{n}(z) + i (-1)^{n+1} j_{-n-1}(z)
-
- Examples
- ========
-
- >>> from sympy import Symbol, hn1, hankel1, expand_func, yn, jn
- >>> z = Symbol("z")
- >>> nu = Symbol("nu", integer=True)
- >>> print(expand_func(hn1(nu, z)))
- jn(nu, z) + I*yn(nu, z)
- >>> print(expand_func(hn1(0, z)))
- sin(z)/z - I*cos(z)/z
- >>> print(expand_func(hn1(1, z)))
- -I*sin(z)/z - cos(z)/z + sin(z)/z**2 - I*cos(z)/z**2
- >>> hn1(nu, z).rewrite(jn)
- (-1)**(nu + 1)*I*jn(-nu - 1, z) + jn(nu, z)
- >>> hn1(nu, z).rewrite(yn)
- (-1)**nu*yn(-nu - 1, z) + I*yn(nu, z)
- >>> hn1(nu, z).rewrite(hankel1)
- sqrt(2)*sqrt(pi)*sqrt(1/z)*hankel1(nu, z)/2
-
- See Also
- ========
-
- hn2, jn, yn, hankel1, hankel2
-
- References
- ==========
-
- .. [1] http://dlmf.nist.gov/10.47
-
- """
-
- _hankel_kind_sign = S.One
-
- @assume_integer_order
- def _eval_rewrite_as_hankel1(self, nu, z):
- return sqrt(pi/(2*z))*hankel1(nu, z)
-
-
-class hn2(SphericalHankelBase):
- r"""
- Spherical Hankel function of the second kind.
-
- This function is defined as
-
- .. math:: h_\nu^(2)(z) = j_\nu(z) - i y_\nu(z),
-
- where :math:`j_\nu(z)` and :math:`y_\nu(z)` are the spherical
- Bessel function of the first and second kinds.
-
- For integral orders :math:`n`, :math:`h_n^(2)` is calculated using the formula:
-
- .. math:: h_n^(2)(z) = j_{n} - i (-1)^{n+1} j_{-n-1}(z)
-
- Examples
- ========
-
- >>> from sympy import Symbol, hn2, hankel2, expand_func, jn, yn
- >>> z = Symbol("z")
- >>> nu = Symbol("nu", integer=True)
- >>> print(expand_func(hn2(nu, z)))
- jn(nu, z) - I*yn(nu, z)
- >>> print(expand_func(hn2(0, z)))
- sin(z)/z + I*cos(z)/z
- >>> print(expand_func(hn2(1, z)))
- I*sin(z)/z - cos(z)/z + sin(z)/z**2 + I*cos(z)/z**2
- >>> hn2(nu, z).rewrite(hankel2)
- sqrt(2)*sqrt(pi)*sqrt(1/z)*hankel2(nu, z)/2
- >>> hn2(nu, z).rewrite(jn)
- -(-1)**(nu + 1)*I*jn(-nu - 1, z) + jn(nu, z)
- >>> hn2(nu, z).rewrite(yn)
- (-1)**nu*yn(-nu - 1, z) - I*yn(nu, z)
-
- See Also
- ========
-
- hn1, jn, yn, hankel1, hankel2
-
- References
- ==========
-
- .. [1] http://dlmf.nist.gov/10.47
-
- """
-
- _hankel_kind_sign = -S.One
-
- @assume_integer_order
- def _eval_rewrite_as_hankel2(self, nu, z):
- return sqrt(pi/(2*z))*hankel2(nu, z)
+ return (-1)**(n + 1) * \
+ (fn(-n - 1, z) * sin(z) + (-1)**(-n) * fn(n, z) * cos(z))
def jn_zeros(n, k, method="sympy", dps=15):
diff --git a/sympy/geometry/point.py b/sympy/geometry/point.py
index b17f652a4f..0fe89dfea8 100644
--- a/sympy/geometry/point.py
+++ b/sympy/geometry/point.py
@@ -269,39 +269,6 @@ def distance(self, p):
p = Point(p)
return sqrt(sum([(a - b)**2 for a, b in zip(self.args, p.args)]))
- def taxicab_distance(self, p):
- """The Taxicab Distance from self to point p.
-
- Returns the sum of the horizontal and vertical distances to point p.
-
- Parameters
- ==========
-
- p : Point
-
- Returns
- =======
-
- taxicab_distance : The sum of the horizontal
- and vertical distances to point p.
-
- See Also
- ========
-
- sympy.geometry.Point.distance
-
- Examples
- ========
-
- >>> from sympy.geometry import Point
- >>> p1, p2 = Point(1, 1), Point(4, 5)
- >>> p1.taxicab_distance(p2)
- 7
-
- """
- p = Point(p)
- return sum(abs(a - b) for a, b in zip(self.args, p.args))
-
def midpoint(self, p):
"""The midpoint between self and point p.
diff --git a/sympy/polys/rootoftools.py b/sympy/polys/rootoftools.py
index 3a891d9d9b..6de12d9ec9 100644
--- a/sympy/polys/rootoftools.py
+++ b/sympy/polys/rootoftools.py
@@ -530,6 +530,10 @@ def _set_interval(self, interval):
reals_count = len(_reals_cache[self.poly])
_complexes_cache[self.poly][self.index - reals_count] = interval
+ def _eval_subs(self, old, new):
+ # don't allow subs to change anything
+ return self
+
def _eval_evalf(self, prec):
"""Evaluate this complex root to the given precision. """
with workprec(prec):
diff --git a/sympy/printing/latex.py b/sympy/printing/latex.py
index add4e9535a..0210a53e7f 100644
--- a/sympy/printing/latex.py
+++ b/sympy/printing/latex.py
@@ -1054,12 +1054,6 @@ def _print_hankel1(self, expr, exp=None):
def _print_hankel2(self, expr, exp=None):
return self._hprint_BesselBase(expr, exp, 'H^{(2)}')
- def _print_hn1(self, expr, exp=None):
- return self._hprint_BesselBase(expr, exp, 'h^{(1)}')
-
- def _print_hn2(self, expr, exp=None):
- return self._hprint_BesselBase(expr, exp, 'h^{(2)}')
-
def _hprint_airy(self, expr, exp=None, notation=""):
tex = r"\left(%s\right)" % self._print(expr.args[0])
diff --git a/sympy/sets/sets.py b/sympy/sets/sets.py
index 3b4a237995..424b63febe 100644
--- a/sympy/sets/sets.py
+++ b/sympy/sets/sets.py
@@ -280,6 +280,8 @@ def contains(self, other):
other = sympify(other, strict=True)
ret = sympify(self._contains(other))
if ret is None:
+ if all(Eq(i, other) == False for i in self):
+ return false
ret = Contains(other, self, evaluate=False)
return ret
diff --git a/sympy/simplify/simplify.py b/sympy/simplify/simplify.py
index 3de708981e..fe33bd8ed2 100644
--- a/sympy/simplify/simplify.py
+++ b/sympy/simplify/simplify.py
@@ -204,9 +204,8 @@ def _is_sum_surds(p):
def posify(eq):
- """Return eq (with generic symbols made positive) and a
- dictionary containing the mapping between the old and new
- symbols.
+ """Return eq (with generic symbols made positive) and a restore
+ dictionary.
Any symbol that has positive=None will be replaced with a positive dummy
symbol having the same name. This replacement will allow more symbolic
@@ -216,30 +215,21 @@ def posify(eq):
A dictionary that can be sent to subs to restore eq to its original
symbols is also returned.
- >>> from sympy import posify, Symbol, log, solve
+ >>> from sympy import posify, Symbol, log
>>> from sympy.abc import x
>>> posify(x + Symbol('p', positive=True) + Symbol('n', negative=True))
(_x + n + p, {_x: x})
- >>> eq = 1/x
- >>> log(eq).expand()
+ >> log(1/x).expand() # should be log(1/x) but it comes back as -log(x)
log(1/x)
- >>> log(posify(eq)[0]).expand()
+
+ >>> log(posify(1/x)[0]).expand() # take [0] and ignore replacements
-log(_x)
- >>> p, rep = posify(eq)
- >>> log(p).expand().subs(rep)
+ >>> eq, rep = posify(1/x)
+ >>> log(eq).expand().subs(rep)
-log(x)
-
- It is possible to apply the same transformations to an iterable
- of expressions:
-
- >>> eq = x**2 - 4
- >>> solve(eq, x)
- [-2, 2]
- >>> eq_x, reps = posify([eq, x]); eq_x
- [_x**2 - 4, _x]
- >>> solve(*eq_x)
- [2]
+ >>> posify([x, 1 + x])
+ ([_x, _x + 1], {_x: x})
"""
eq = sympify(eq)
if iterable(eq):
| subs into inequality involving RootOf raises GeneratorsNeeded
If x is real then the following generates and error
```python
>>> from sympy import *
>>> var('x', real=True)
x
>>> eq=RootOf(x**3 - 17*x**2 + 81*x - 118, 0)
>>> (x<eq).subs(x,eq)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "sympy\core\basic.py", line 895, in subs
rv = rv._subs(old, new, **kwargs)
File "sympy\core\cache.py", line 93, in wrapper
retval = cfunc(*args, **kwargs)
File "sympy\core\compatibility.py", line 880, in wrapper
result = user_function(*args, **kwds)
File "sympy\core\basic.py", line 1009, in _subs
rv = fallback(self, old, new)
File "sympy\core\basic.py", line 981, in fallback
arg = arg._subs(old, new, **hints)
File "sympy\core\cache.py", line 93, in wrapper
retval = cfunc(*args, **kwargs)
File "sympy\core\compatibility.py", line 880, in wrapper
result = user_function(*args, **kwds)
File "sympy\core\basic.py", line 1009, in _subs
rv = fallback(self, old, new)
File "sympy\core\basic.py", line 986, in fallback
rv = self.func(*args)
File "sympy\polys\rootoftools.py", line 68, in __new__
poly = PurePoly(f, x, greedy=False, expand=expand)
File "sympy\polys\polytools.py", line 89, in __new__
return cls._from_expr(rep, opt)
File "sympy\polys\polytools.py", line 199, in _from_expr
rep, opt = _dict_from_expr(rep, opt)
File "sympy\polys\polyutils.py", line 366, in _dict_from_expr
rep, gens = _dict_from_expr_no_gens(expr, opt)
File "sympy\polys\polyutils.py", line 311, in _dict_from_expr_no_gens
(poly,), gens = _parallel_dict_from_expr_no_gens((expr,), opt)
File "sympy\polys\polyutils.py", line 272, in _parallel_dict_from_expr_no_gens
raise GeneratorsNeeded("specify generators to give %s a meaning" % arg)
sympy.polys.polyerrors.GeneratorsNeeded: specify generators to give -17*RootOf(x
**3 - 17*x**2 + 81*x - 118, 0)**2 - 118 + RootOf(x**3 - 17*x**2 + 81*x - 118, 0)
**3 + 81*RootOf(x**3 - 17*x**2 + 81*x - 118, 0) a meaning
```
But a vanilla x does not raise:
```
>>> var('x')
x
>>> eq=RootOf(x**3 - 17*x**2 + 81*x - 118, 0)
>>> (x<eq).subs(x,eq)
False
``` | sympy/sympy | diff --git a/sympy/core/tests/test_args.py b/sympy/core/tests/test_args.py
index 7c733fc9a8..37ddc2923e 100644
--- a/sympy/core/tests/test_args.py
+++ b/sympy/core/tests/test_args.py
@@ -1351,11 +1351,6 @@ def test_sympy__functions__special__bessel__SphericalBesselBase():
pass
-@SKIP("abstract class")
-def test_sympy__functions__special__bessel__SphericalHankelBase():
- pass
-
-
def test_sympy__functions__special__bessel__besseli():
from sympy.functions.special.bessel import besseli
assert _test_args(besseli(x, 1))
@@ -1396,16 +1391,6 @@ def test_sympy__functions__special__bessel__yn():
assert _test_args(yn(0, x))
-def test_sympy__functions__special__bessel__hn1():
- from sympy.functions.special.bessel import hn1
- assert _test_args(hn1(0, x))
-
-
-def test_sympy__functions__special__bessel__hn2():
- from sympy.functions.special.bessel import hn2
- assert _test_args(hn2(0, x))
-
-
def test_sympy__functions__special__bessel__AiryBase():
pass
diff --git a/sympy/core/tests/test_subs.py b/sympy/core/tests/test_subs.py
index 5d3f987e1d..2972947e2e 100644
--- a/sympy/core/tests/test_subs.py
+++ b/sympy/core/tests/test_subs.py
@@ -2,7 +2,7 @@
from sympy import (Symbol, Wild, sin, cos, exp, sqrt, pi, Function, Derivative,
abc, Integer, Eq, symbols, Add, I, Float, log, Rational, Lambda, atan2,
cse, cot, tan, S, Tuple, Basic, Dict, Piecewise, oo, Mul,
- factor, nsimplify, zoo, Subs)
+ factor, nsimplify, zoo, Subs, RootOf)
from sympy.core.basic import _aresame
from sympy.utilities.pytest import XFAIL
from sympy.abc import x, y, z
@@ -657,3 +657,10 @@ def test_pow_eval_subs_no_cache():
# It incorrectly returned 1/sqrt(x**2) before this pull request.
result = s.subs(sqrt(x**2), y)
assert result == 1/y
+
+
+def test_RootOf_issue_10092():
+ x = Symbol('x', real=True)
+ eq = x**3 - 17*x**2 + 81*x - 118
+ r = RootOf(eq, 0)
+ assert (x < r).subs(x, r) is S.false
diff --git a/sympy/functions/special/tests/test_bessel.py b/sympy/functions/special/tests/test_bessel.py
index f4d7827b09..74402bc869 100644
--- a/sympy/functions/special/tests/test_bessel.py
+++ b/sympy/functions/special/tests/test_bessel.py
@@ -1,9 +1,7 @@
-from itertools import product
-
from sympy import (jn, yn, symbols, Symbol, sin, cos, pi, S, jn_zeros, besselj,
- bessely, besseli, besselk, hankel1, hankel2, hn1, hn2,
- expand_func, sqrt, sinh, cosh, diff, series, gamma, hyper,
- Abs, I, O, oo, conjugate)
+ bessely, besseli, besselk, hankel1, hankel2, expand_func,
+ sqrt, sinh, cosh, diff, series, gamma, hyper, Abs, I, O, oo,
+ conjugate)
from sympy.functions.special.bessel import fn
from sympy.functions.special.bessel import (airyai, airybi,
airyaiprime, airybiprime)
@@ -19,12 +17,9 @@
def test_bessel_rand():
- for f in [besselj, bessely, besseli, besselk, hankel1, hankel2]:
+ for f in [besselj, bessely, besseli, besselk, hankel1, hankel2, jn, yn]:
assert td(f(randcplx(), z), z)
- for f in [jn, yn, hn1, hn2]:
- assert td(f(randint(-10, 10), z), z)
-
def test_bessel_twoinputs():
for f in [besselj, bessely, besseli, besselk, hankel1, hankel2, jn, yn]:
@@ -66,40 +61,6 @@ def test_rewrite():
assert tn(besselk(nu, z), besselk(nu, z).rewrite(besseli), z)
assert tn(besselk(nu, z), besselk(nu, z).rewrite(bessely), z)
- # check that a rewrite was triggered, when the order is set to a generic
- # symbol 'nu'
- assert yn(nu, z) != yn(nu, z).rewrite(jn)
- assert hn1(nu, z) != hn1(nu, z).rewrite(jn)
- assert hn2(nu, z) != hn2(nu, z).rewrite(jn)
- assert jn(nu, z) != jn(nu, z).rewrite(yn)
- assert hn1(nu, z) != hn1(nu, z).rewrite(yn)
- assert hn2(nu, z) != hn2(nu, z).rewrite(yn)
-
- # rewriting spherical bessel functions (SBFs) w.r.t. besselj, bessely is
- # not allowed if a generic symbol 'nu' is used as the order of the SBFs
- # to avoid inconsistencies (the order of bessel[jy] is allowed to be
- # complex-valued, whereas SBFs are defined only for integer orders)
- order = nu
- for f in (besselj, bessely):
- assert yn(order, z) == yn(order, z).rewrite(f)
- assert jn(order, z) == jn(order, z).rewrite(f)
- assert hn1(order, z) == hn1(order, z).rewrite(f)
- assert hn2(order, z) == hn2(order, z).rewrite(f)
-
- # for integral orders rewriting SBFs w.r.t bessel[jy] is allowed
- N = Symbol('n', integer=True)
- ri = randint(-11, 10)
- for order in (ri, N):
- for f in (besselj, bessely):
- assert yn(order, z) != yn(order, z).rewrite(f)
- assert jn(order, z) != jn(order, z).rewrite(f)
- assert hn1(order, z) != hn1(order, z).rewrite(f)
- assert hn2(order, z) != hn2(order, z).rewrite(f)
-
- for func, refunc in product((yn, jn, hn1, hn2),
- (jn, yn, besselj, bessely)):
- assert tn(func(ri, z), func(ri, z).rewrite(refunc), z)
-
def test_expand():
from sympy import besselsimp, Symbol, exp, exp_polar, I
@@ -232,12 +193,6 @@ def test_jn():
assert expand_func(jn(n, z)) == jn(n, z)
- # SBFs not defined for complex-valued orders
- assert jn(2+3j, 5.2+0.3j).evalf() == jn(2+3j, 5.2+0.3j)
-
- assert eq([jn(2, 5.2+0.3j).evalf(10)],
- [0.09941975672 - 0.05452508024*I])
-
def test_yn():
z = symbols("z")
@@ -246,12 +201,6 @@ def test_yn():
assert myn(2, z) == -((3/z**3 - 1/z)*cos(z) + (3/z**2)*sin(z))
assert expand_func(yn(n, z)) == yn(n, z)
- # SBFs not defined for complex-valued orders
- assert yn(2+3j, 5.2+0.3j).evalf() == yn(2+3j, 5.2+0.3j)
-
- assert eq([yn(2, 5.2+0.3j).evalf(10)],
- [0.185250342 + 0.01489557397*I])
-
def test_sympify_yn():
assert S(15) in myn(3, pi).atoms()
@@ -340,14 +289,14 @@ def test_conjugate():
n, z, x = Symbol('n'), Symbol('z', real=False), Symbol('x', real=True)
y, t = Symbol('y', real=True, positive=True), Symbol('t', negative=True)
- for f in [besseli, besselj, besselk, bessely, hankel1, hankel2]:
+ for f in [besseli, besselj, besselk, bessely, jn, yn, hankel1, hankel2]:
assert f(n, -1).conjugate() != f(conjugate(n), -1)
assert f(n, x).conjugate() != f(conjugate(n), x)
assert f(n, t).conjugate() != f(conjugate(n), t)
rz = randcplx(b=0.5)
- for f in [besseli, besselj, besselk, bessely]:
+ for f in [besseli, besselj, besselk, bessely, jn, yn]:
assert f(n, 1 + I).conjugate() == f(conjugate(n), 1 - I)
assert f(n, 0).conjugate() == f(conjugate(n), 0)
assert f(n, 1).conjugate() == f(conjugate(n), 1)
diff --git a/sympy/geometry/tests/test_point.py b/sympy/geometry/tests/test_point.py
index 248613f827..caca591956 100644
--- a/sympy/geometry/tests/test_point.py
+++ b/sympy/geometry/tests/test_point.py
@@ -60,8 +60,6 @@ def test_point():
assert Point.distance(p1, p1) == 0
assert Point.distance(p3, p2) == sqrt(p2.x**2 + p2.y**2)
- assert Point.taxicab_distance(p4, p3) == 2
-
p1_1 = Point(x1, x1)
p1_2 = Point(y2, y2)
p1_3 = Point(x1 + 1, x1)
diff --git a/sympy/printing/tests/test_latex.py b/sympy/printing/tests/test_latex.py
index f50b103c5e..884b2ac699 100644
--- a/sympy/printing/tests/test_latex.py
+++ b/sympy/printing/tests/test_latex.py
@@ -127,7 +127,6 @@ def test_latex_builtins():
assert latex(true) == r"\mathrm{True}"
assert latex(false) == r'\mathrm{False}'
-
def test_latex_Float():
assert latex(Float(1.0e100)) == r"1.0 \cdot 10^{100}"
assert latex(Float(1.0e-100)) == r"1.0 \cdot 10^{-100}"
@@ -353,7 +352,6 @@ def test_latex_functions():
# even when it is referred to without an argument
assert latex(fjlkd) == r'\operatorname{fjlkd}'
-
def test_hyper_printing():
from sympy import pi
from sympy.abc import x, z
@@ -373,7 +371,7 @@ def test_hyper_printing():
def test_latex_bessel():
from sympy.functions.special.bessel import (besselj, bessely, besseli,
- besselk, hankel1, hankel2, jn, yn, hn1, hn2)
+ besselk, hankel1, hankel2, jn, yn)
from sympy.abc import z
assert latex(besselj(n, z**2)**k) == r'J^{k}_{n}\left(z^{2}\right)'
assert latex(bessely(n, z)) == r'Y_{n}\left(z\right)'
@@ -384,8 +382,6 @@ def test_latex_bessel():
assert latex(hankel2(n, z)) == r'H^{(2)}_{n}\left(z\right)'
assert latex(jn(n, z)) == r'j_{n}\left(z\right)'
assert latex(yn(n, z)) == r'y_{n}\left(z\right)'
- assert latex(hn1(n, z)) == r'h^{(1)}_{n}\left(z\right)'
- assert latex(hn2(n, z)) == r'h^{(2)}_{n}\left(z\right)'
def test_latex_fresnel():
diff --git a/sympy/simplify/tests/test_simplify.py b/sympy/simplify/tests/test_simplify.py
index 79bf14c9f0..251a5690e2 100644
--- a/sympy/simplify/tests/test_simplify.py
+++ b/sympy/simplify/tests/test_simplify.py
@@ -420,6 +420,9 @@ def test_posify():
Symbol('p', positive=True) +
Symbol('n', negative=True))) == '(_x + n + p, {_x: x})'
+ # log(1/x).expand() should be log(1/x) but it comes back as -log(x)
+ # when it is corrected, posify will allow the change to be made. The
+ # force=True option can do so as well when it is implemented.
eq, rep = posify(1/x)
assert log(eq).expand().subs(rep) == -log(x)
assert str(posify([x, 1 + x])) == '([_x, _x + 1], {_x: x})'
diff --git a/sympy/solvers/tests/test_inequalities.py b/sympy/solvers/tests/test_inequalities.py
index 13569bc9bc..2ec3865448 100644
--- a/sympy/solvers/tests/test_inequalities.py
+++ b/sympy/solvers/tests/test_inequalities.py
@@ -291,7 +291,6 @@ def test_issue_9954():
assert isolve(x**2 < 0, x, relational=True) == S.EmptySet.as_relational(x)
-@slow
def test_slow_general_univariate():
r = RootOf(x**5 - x**2 + 1, 0)
assert solve(sqrt(x) + 1/root(x, 3) > 1) == \
@@ -299,12 +298,11 @@ def test_slow_general_univariate():
def test_issue_8545():
- from sympy import refine
eq = 1 - x - abs(1 - x)
ans = And(Lt(1, x), Lt(x, oo))
assert reduce_abs_inequality(eq, '<', x) == ans
eq = 1 - x - sqrt((1 - x)**2)
- assert reduce_inequalities(refine(eq) < 0) == ans
+ assert reduce_inequalities(eq < 0) == ans
def test_issue_8974():
diff --git a/sympy/solvers/tests/test_solveset.py b/sympy/solvers/tests/test_solveset.py
index 2ccd876be9..db313f87ed 100644
--- a/sympy/solvers/tests/test_solveset.py
+++ b/sympy/solvers/tests/test_solveset.py
@@ -17,7 +17,7 @@
from sympy.sets import (FiniteSet, ConditionSet)
-from sympy.utilities.pytest import XFAIL, raises, skip
+from sympy.utilities.pytest import XFAIL, raises, skip, slow
from sympy.utilities.randtest import verify_numerically as tn
from sympy.physics.units import cm
@@ -421,6 +421,7 @@ def test_solve_sqrt_fail():
assert solveset_real(eq, x) == FiniteSet(S(1)/3)
+@slow
def test_solve_sqrt_3():
R = Symbol('R')
eq = sqrt(2)*R*sqrt(1/(R + 1)) + (R + 1)*(sqrt(2)*sqrt(1/(R + 1)) - 1)
@@ -439,7 +440,10 @@ def test_solve_sqrt_3():
eq = -sqrt((m - q)**2 + (-m/(2*q) + S(1)/2)**2) + sqrt((-m**2/2 - sqrt(
4*m**4 - 4*m**2 + 8*m + 1)/4 - S(1)/4)**2 + (m**2/2 - m - sqrt(
4*m**4 - 4*m**2 + 8*m + 1)/4 - S(1)/4)**2)
- unsolved_object = ConditionSet(q, Eq((-2*sqrt(4*q**2*(m - q)**2 + (-m + q)**2) + sqrt((-2*m**2 - sqrt(4*m**4 - 4*m**2 + 8*m + 1) - 1)**2 + (2*m**2 - 4*m - sqrt(4*m**4 - 4*m**2 + 8*m + 1) - 1)**2)*Abs(q))/Abs(q), 0), S.Reals)
+ unsolved_object = ConditionSet(q, Eq((-2*sqrt(4*q**2*(m - q)**2 +
+ (-m + q)**2) + sqrt((-2*m**2 - sqrt(4*m**4 - 4*m**2 + 8*m + 1) -
+ 1)**2 + (2*m**2 - 4*m - sqrt(4*m**4 - 4*m**2 + 8*m + 1) - 1)**2
+ )*Abs(q))/Abs(q), 0), S.Reals)
assert solveset_real(eq, q) == unsolved_object
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 3,
"issue_text_score": 0,
"test_score": 2
},
"num_modified_files": 9
} | 0.7 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "pytest",
"pip_packages": [
"pytest"
],
"pre_install": null,
"python": "3.6",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | attrs @ file:///opt/conda/conda-bld/attrs_1642510447205/work
certifi==2021.5.30
importlib-metadata @ file:///tmp/build/80754af9/importlib-metadata_1631916693255/work
iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work
more-itertools @ file:///tmp/build/80754af9/more-itertools_1637733554872/work
mpmath==1.3.0
packaging @ file:///tmp/build/80754af9/packaging_1637314298585/work
pluggy @ file:///tmp/build/80754af9/pluggy_1615976315926/work
py @ file:///opt/conda/conda-bld/py_1644396412707/work
pyparsing @ file:///tmp/build/80754af9/pyparsing_1635766073266/work
pytest==6.2.4
-e git+https://github.com/sympy/sympy.git@41fc8f5a4dabd350f2f23a4aef53db728ca8ee0d#egg=sympy
toml @ file:///tmp/build/80754af9/toml_1616166611790/work
typing_extensions @ file:///opt/conda/conda-bld/typing_extensions_1647553014482/work
zipp @ file:///tmp/build/80754af9/zipp_1633618647012/work
| name: sympy
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- attrs=21.4.0=pyhd3eb1b0_0
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2021.5.30=py36h06a4308_0
- importlib-metadata=4.8.1=py36h06a4308_0
- importlib_metadata=4.8.1=hd3eb1b0_0
- iniconfig=1.1.1=pyhd3eb1b0_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.3=he6710b0_2
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- more-itertools=8.12.0=pyhd3eb1b0_0
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- packaging=21.3=pyhd3eb1b0_0
- pip=21.2.2=py36h06a4308_0
- pluggy=0.13.1=py36h06a4308_0
- py=1.11.0=pyhd3eb1b0_0
- pyparsing=3.0.4=pyhd3eb1b0_0
- pytest=6.2.4=py36h06a4308_2
- python=3.6.13=h12debd9_1
- readline=8.2=h5eee18b_0
- setuptools=58.0.4=py36h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- toml=0.10.2=pyhd3eb1b0_0
- typing_extensions=4.1.1=pyh06a4308_0
- wheel=0.37.1=pyhd3eb1b0_0
- xz=5.6.4=h5eee18b_1
- zipp=3.6.0=pyhd3eb1b0_0
- zlib=1.2.13=h5eee18b_1
- pip:
- mpmath==1.3.0
prefix: /opt/conda/envs/sympy
| [
"sympy/core/tests/test_args.py::test_all_classes_are_tested",
"sympy/core/tests/test_subs.py::test_RootOf_issue_10092",
"sympy/functions/special/tests/test_bessel.py::test_bessel_rand",
"sympy/functions/special/tests/test_bessel.py::test_conjugate"
] | [] | [
"sympy/core/tests/test_args.py::test_sympy__assumptions__assume__AppliedPredicate",
"sympy/core/tests/test_args.py::test_sympy__assumptions__assume__Predicate",
"sympy/core/tests/test_args.py::test_sympy__assumptions__sathandlers__UnevaluatedOnFree",
"sympy/core/tests/test_args.py::test_sympy__assumptions__sathandlers__AllArgs",
"sympy/core/tests/test_args.py::test_sympy__assumptions__sathandlers__AnyArgs",
"sympy/core/tests/test_args.py::test_sympy__assumptions__sathandlers__ExactlyOneArg",
"sympy/core/tests/test_args.py::test_sympy__assumptions__sathandlers__CheckOldAssump",
"sympy/core/tests/test_args.py::test_sympy__assumptions__sathandlers__CheckIsPrime",
"sympy/core/tests/test_args.py::test_sympy__combinatorics__subsets__Subset",
"sympy/core/tests/test_args.py::test_sympy__combinatorics__perm_groups__PermutationGroup",
"sympy/core/tests/test_args.py::test_sympy__combinatorics__polyhedron__Polyhedron",
"sympy/core/tests/test_args.py::test_sympy__combinatorics__partitions__Partition",
"sympy/core/tests/test_args.py::test_sympy__concrete__products__Product",
"sympy/core/tests/test_args.py::test_sympy__concrete__summations__Sum",
"sympy/core/tests/test_args.py::test_sympy__core__add__Add",
"sympy/core/tests/test_args.py::test_sympy__core__basic__Atom",
"sympy/core/tests/test_args.py::test_sympy__core__basic__Basic",
"sympy/core/tests/test_args.py::test_sympy__core__containers__Dict",
"sympy/core/tests/test_args.py::test_sympy__core__containers__Tuple",
"sympy/core/tests/test_args.py::test_sympy__core__expr__AtomicExpr",
"sympy/core/tests/test_args.py::test_sympy__core__expr__Expr",
"sympy/core/tests/test_args.py::test_sympy__core__function__Application",
"sympy/core/tests/test_args.py::test_sympy__core__function__AppliedUndef",
"sympy/core/tests/test_args.py::test_sympy__core__function__Derivative",
"sympy/core/tests/test_args.py::test_sympy__core__function__Lambda",
"sympy/core/tests/test_args.py::test_sympy__core__function__Subs",
"sympy/core/tests/test_args.py::test_sympy__core__function__WildFunction",
"sympy/core/tests/test_args.py::test_sympy__core__mod__Mod",
"sympy/core/tests/test_args.py::test_sympy__core__mul__Mul",
"sympy/core/tests/test_args.py::test_sympy__core__numbers__Catalan",
"sympy/core/tests/test_args.py::test_sympy__core__numbers__ComplexInfinity",
"sympy/core/tests/test_args.py::test_sympy__core__numbers__EulerGamma",
"sympy/core/tests/test_args.py::test_sympy__core__numbers__Exp1",
"sympy/core/tests/test_args.py::test_sympy__core__numbers__Float",
"sympy/core/tests/test_args.py::test_sympy__core__numbers__GoldenRatio",
"sympy/core/tests/test_args.py::test_sympy__core__numbers__Half",
"sympy/core/tests/test_args.py::test_sympy__core__numbers__ImaginaryUnit",
"sympy/core/tests/test_args.py::test_sympy__core__numbers__Infinity",
"sympy/core/tests/test_args.py::test_sympy__core__numbers__Integer",
"sympy/core/tests/test_args.py::test_sympy__core__numbers__NaN",
"sympy/core/tests/test_args.py::test_sympy__core__numbers__NegativeInfinity",
"sympy/core/tests/test_args.py::test_sympy__core__numbers__NegativeOne",
"sympy/core/tests/test_args.py::test_sympy__core__numbers__Number",
"sympy/core/tests/test_args.py::test_sympy__core__numbers__NumberSymbol",
"sympy/core/tests/test_args.py::test_sympy__core__numbers__One",
"sympy/core/tests/test_args.py::test_sympy__core__numbers__Pi",
"sympy/core/tests/test_args.py::test_sympy__core__numbers__Rational",
"sympy/core/tests/test_args.py::test_sympy__core__numbers__Zero",
"sympy/core/tests/test_args.py::test_sympy__core__power__Pow",
"sympy/core/tests/test_args.py::test_sympy__core__relational__Equality",
"sympy/core/tests/test_args.py::test_sympy__core__relational__GreaterThan",
"sympy/core/tests/test_args.py::test_sympy__core__relational__LessThan",
"sympy/core/tests/test_args.py::test_sympy__core__relational__StrictGreaterThan",
"sympy/core/tests/test_args.py::test_sympy__core__relational__StrictLessThan",
"sympy/core/tests/test_args.py::test_sympy__core__relational__Unequality",
"sympy/core/tests/test_args.py::test_sympy__sets__sets__EmptySet",
"sympy/core/tests/test_args.py::test_sympy__sets__sets__UniversalSet",
"sympy/core/tests/test_args.py::test_sympy__sets__sets__FiniteSet",
"sympy/core/tests/test_args.py::test_sympy__sets__sets__Interval",
"sympy/core/tests/test_args.py::test_sympy__sets__sets__ProductSet",
"sympy/core/tests/test_args.py::test_sympy__sets__sets__Intersection",
"sympy/core/tests/test_args.py::test_sympy__sets__sets__Union",
"sympy/core/tests/test_args.py::test_sympy__sets__sets__Complement",
"sympy/core/tests/test_args.py::test_sympy__sets__sets__SymmetricDifference",
"sympy/core/tests/test_args.py::test_sympy__core__trace__Tr",
"sympy/core/tests/test_args.py::test_sympy__sets__fancysets__Naturals",
"sympy/core/tests/test_args.py::test_sympy__sets__fancysets__Naturals0",
"sympy/core/tests/test_args.py::test_sympy__sets__fancysets__Integers",
"sympy/core/tests/test_args.py::test_sympy__sets__fancysets__Reals",
"sympy/core/tests/test_args.py::test_sympy__sets__fancysets__Complexes",
"sympy/core/tests/test_args.py::test_sympy__sets__fancysets__ComplexRegion",
"sympy/core/tests/test_args.py::test_sympy__sets__fancysets__ImageSet",
"sympy/core/tests/test_args.py::test_sympy__sets__fancysets__Range",
"sympy/core/tests/test_args.py::test_sympy__sets__conditionset__ConditionSet",
"sympy/core/tests/test_args.py::test_sympy__sets__contains__Contains",
"sympy/core/tests/test_args.py::test_sympy__stats__crv__ContinuousDomain",
"sympy/core/tests/test_args.py::test_sympy__stats__crv__SingleContinuousDomain",
"sympy/core/tests/test_args.py::test_sympy__stats__crv__ProductContinuousDomain",
"sympy/core/tests/test_args.py::test_sympy__stats__crv__ConditionalContinuousDomain",
"sympy/core/tests/test_args.py::test_sympy__stats__crv__ContinuousPSpace",
"sympy/core/tests/test_args.py::test_sympy__stats__crv__SingleContinuousPSpace",
"sympy/core/tests/test_args.py::test_sympy__stats__crv__ProductContinuousPSpace",
"sympy/core/tests/test_args.py::test_sympy__stats__drv__SingleDiscreteDomain",
"sympy/core/tests/test_args.py::test_sympy__stats__drv__SingleDiscretePSpace",
"sympy/core/tests/test_args.py::test_sympy__stats__rv__RandomDomain",
"sympy/core/tests/test_args.py::test_sympy__stats__rv__SingleDomain",
"sympy/core/tests/test_args.py::test_sympy__stats__rv__ConditionalDomain",
"sympy/core/tests/test_args.py::test_sympy__stats__rv__PSpace",
"sympy/core/tests/test_args.py::test_sympy__stats__rv__RandomSymbol",
"sympy/core/tests/test_args.py::test_sympy__stats__rv__ProductPSpace",
"sympy/core/tests/test_args.py::test_sympy__stats__rv__ProductDomain",
"sympy/core/tests/test_args.py::test_sympy__stats__frv_types__DiscreteUniformDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__frv_types__DieDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__frv_types__BernoulliDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__frv_types__BinomialDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__frv_types__HypergeometricDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__frv_types__RademacherDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__frv__FiniteDomain",
"sympy/core/tests/test_args.py::test_sympy__stats__frv__SingleFiniteDomain",
"sympy/core/tests/test_args.py::test_sympy__stats__frv__ProductFiniteDomain",
"sympy/core/tests/test_args.py::test_sympy__stats__frv__ConditionalFiniteDomain",
"sympy/core/tests/test_args.py::test_sympy__stats__frv__FinitePSpace",
"sympy/core/tests/test_args.py::test_sympy__stats__frv__SingleFinitePSpace",
"sympy/core/tests/test_args.py::test_sympy__stats__frv__ProductFinitePSpace",
"sympy/core/tests/test_args.py::test_sympy__stats__frv_types__FiniteDistributionHandmade",
"sympy/core/tests/test_args.py::test_sympy__stats__crv__ContinuousDistributionHandmade",
"sympy/core/tests/test_args.py::test_sympy__stats__rv__Density",
"sympy/core/tests/test_args.py::test_sympy__stats__crv_types__ArcsinDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__crv_types__BeniniDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__crv_types__BetaDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__crv_types__BetaPrimeDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__crv_types__CauchyDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__crv_types__ChiDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__crv_types__ChiNoncentralDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__crv_types__ChiSquaredDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__crv_types__DagumDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__crv_types__ExponentialDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__crv_types__FDistributionDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__crv_types__FisherZDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__crv_types__FrechetDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__crv_types__GammaInverseDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__crv_types__GammaDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__crv_types__KumaraswamyDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__crv_types__LaplaceDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__crv_types__LogisticDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__crv_types__LogNormalDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__crv_types__MaxwellDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__crv_types__NakagamiDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__crv_types__NormalDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__crv_types__ParetoDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__crv_types__QuadraticUDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__crv_types__RaisedCosineDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__crv_types__RayleighDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__crv_types__StudentTDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__crv_types__TriangularDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__crv_types__UniformDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__crv_types__UniformSumDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__crv_types__VonMisesDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__crv_types__WeibullDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__crv_types__WignerSemicircleDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__drv_types__PoissonDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__drv_types__GeometricDistribution",
"sympy/core/tests/test_args.py::test_sympy__core__symbol__Dummy",
"sympy/core/tests/test_args.py::test_sympy__core__symbol__Symbol",
"sympy/core/tests/test_args.py::test_sympy__core__symbol__Wild",
"sympy/core/tests/test_args.py::test_sympy__functions__combinatorial__factorials__FallingFactorial",
"sympy/core/tests/test_args.py::test_sympy__functions__combinatorial__factorials__MultiFactorial",
"sympy/core/tests/test_args.py::test_sympy__functions__combinatorial__factorials__RisingFactorial",
"sympy/core/tests/test_args.py::test_sympy__functions__combinatorial__factorials__binomial",
"sympy/core/tests/test_args.py::test_sympy__functions__combinatorial__factorials__subfactorial",
"sympy/core/tests/test_args.py::test_sympy__functions__combinatorial__factorials__factorial",
"sympy/core/tests/test_args.py::test_sympy__functions__combinatorial__factorials__factorial2",
"sympy/core/tests/test_args.py::test_sympy__functions__combinatorial__numbers__bell",
"sympy/core/tests/test_args.py::test_sympy__functions__combinatorial__numbers__bernoulli",
"sympy/core/tests/test_args.py::test_sympy__functions__combinatorial__numbers__catalan",
"sympy/core/tests/test_args.py::test_sympy__functions__combinatorial__numbers__genocchi",
"sympy/core/tests/test_args.py::test_sympy__functions__combinatorial__numbers__euler",
"sympy/core/tests/test_args.py::test_sympy__functions__combinatorial__numbers__fibonacci",
"sympy/core/tests/test_args.py::test_sympy__functions__combinatorial__numbers__harmonic",
"sympy/core/tests/test_args.py::test_sympy__functions__combinatorial__numbers__lucas",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__complexes__Abs",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__complexes__adjoint",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__complexes__arg",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__complexes__conjugate",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__complexes__im",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__complexes__re",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__complexes__sign",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__complexes__polar_lift",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__complexes__periodic_argument",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__complexes__principal_branch",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__complexes__transpose",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__exponential__LambertW",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__exponential__exp",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__exponential__exp_polar",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__exponential__log",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__hyperbolic__acosh",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__hyperbolic__acoth",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__hyperbolic__asinh",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__hyperbolic__atanh",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__hyperbolic__asech",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__hyperbolic__cosh",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__hyperbolic__coth",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__hyperbolic__csch",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__hyperbolic__sech",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__hyperbolic__sinh",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__hyperbolic__tanh",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__integers__ceiling",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__integers__floor",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__integers__frac",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__miscellaneous__IdentityFunction",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__miscellaneous__Max",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__miscellaneous__Min",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__piecewise__ExprCondPair",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__piecewise__Piecewise",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__trigonometric__acos",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__trigonometric__acot",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__trigonometric__asin",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__trigonometric__asec",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__trigonometric__acsc",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__trigonometric__atan",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__trigonometric__atan2",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__trigonometric__cos",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__trigonometric__csc",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__trigonometric__cot",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__trigonometric__sin",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__trigonometric__sinc",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__trigonometric__sec",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__trigonometric__tan",
"sympy/core/tests/test_args.py::test_sympy__functions__special__bessel__besseli",
"sympy/core/tests/test_args.py::test_sympy__functions__special__bessel__besselj",
"sympy/core/tests/test_args.py::test_sympy__functions__special__bessel__besselk",
"sympy/core/tests/test_args.py::test_sympy__functions__special__bessel__bessely",
"sympy/core/tests/test_args.py::test_sympy__functions__special__bessel__hankel1",
"sympy/core/tests/test_args.py::test_sympy__functions__special__bessel__hankel2",
"sympy/core/tests/test_args.py::test_sympy__functions__special__bessel__jn",
"sympy/core/tests/test_args.py::test_sympy__functions__special__bessel__yn",
"sympy/core/tests/test_args.py::test_sympy__functions__special__bessel__AiryBase",
"sympy/core/tests/test_args.py::test_sympy__functions__special__bessel__airyai",
"sympy/core/tests/test_args.py::test_sympy__functions__special__bessel__airybi",
"sympy/core/tests/test_args.py::test_sympy__functions__special__bessel__airyaiprime",
"sympy/core/tests/test_args.py::test_sympy__functions__special__bessel__airybiprime",
"sympy/core/tests/test_args.py::test_sympy__functions__special__elliptic_integrals__elliptic_k",
"sympy/core/tests/test_args.py::test_sympy__functions__special__elliptic_integrals__elliptic_f",
"sympy/core/tests/test_args.py::test_sympy__functions__special__elliptic_integrals__elliptic_e",
"sympy/core/tests/test_args.py::test_sympy__functions__special__elliptic_integrals__elliptic_pi",
"sympy/core/tests/test_args.py::test_sympy__functions__special__delta_functions__DiracDelta",
"sympy/core/tests/test_args.py::test_sympy__functions__special__delta_functions__Heaviside",
"sympy/core/tests/test_args.py::test_sympy__functions__special__error_functions__erf",
"sympy/core/tests/test_args.py::test_sympy__functions__special__error_functions__erfc",
"sympy/core/tests/test_args.py::test_sympy__functions__special__error_functions__erfi",
"sympy/core/tests/test_args.py::test_sympy__functions__special__error_functions__erf2",
"sympy/core/tests/test_args.py::test_sympy__functions__special__error_functions__erfinv",
"sympy/core/tests/test_args.py::test_sympy__functions__special__error_functions__erfcinv",
"sympy/core/tests/test_args.py::test_sympy__functions__special__error_functions__erf2inv",
"sympy/core/tests/test_args.py::test_sympy__functions__special__error_functions__fresnels",
"sympy/core/tests/test_args.py::test_sympy__functions__special__error_functions__fresnelc",
"sympy/core/tests/test_args.py::test_sympy__functions__special__error_functions__erfs",
"sympy/core/tests/test_args.py::test_sympy__functions__special__error_functions__Ei",
"sympy/core/tests/test_args.py::test_sympy__functions__special__error_functions__li",
"sympy/core/tests/test_args.py::test_sympy__functions__special__error_functions__Li",
"sympy/core/tests/test_args.py::test_sympy__functions__special__error_functions__Si",
"sympy/core/tests/test_args.py::test_sympy__functions__special__error_functions__Ci",
"sympy/core/tests/test_args.py::test_sympy__functions__special__error_functions__Shi",
"sympy/core/tests/test_args.py::test_sympy__functions__special__error_functions__Chi",
"sympy/core/tests/test_args.py::test_sympy__functions__special__error_functions__expint",
"sympy/core/tests/test_args.py::test_sympy__functions__special__gamma_functions__gamma",
"sympy/core/tests/test_args.py::test_sympy__functions__special__gamma_functions__loggamma",
"sympy/core/tests/test_args.py::test_sympy__functions__special__gamma_functions__lowergamma",
"sympy/core/tests/test_args.py::test_sympy__functions__special__gamma_functions__polygamma",
"sympy/core/tests/test_args.py::test_sympy__functions__special__gamma_functions__uppergamma",
"sympy/core/tests/test_args.py::test_sympy__functions__special__beta_functions__beta",
"sympy/core/tests/test_args.py::test_sympy__functions__special__mathieu_functions__MathieuBase",
"sympy/core/tests/test_args.py::test_sympy__functions__special__mathieu_functions__mathieus",
"sympy/core/tests/test_args.py::test_sympy__functions__special__mathieu_functions__mathieuc",
"sympy/core/tests/test_args.py::test_sympy__functions__special__mathieu_functions__mathieusprime",
"sympy/core/tests/test_args.py::test_sympy__functions__special__mathieu_functions__mathieucprime",
"sympy/core/tests/test_args.py::test_sympy__functions__special__hyper__hyper",
"sympy/core/tests/test_args.py::test_sympy__functions__special__hyper__meijerg",
"sympy/core/tests/test_args.py::test_sympy__functions__special__hyper__HyperRep_power1",
"sympy/core/tests/test_args.py::test_sympy__functions__special__hyper__HyperRep_power2",
"sympy/core/tests/test_args.py::test_sympy__functions__special__hyper__HyperRep_log1",
"sympy/core/tests/test_args.py::test_sympy__functions__special__hyper__HyperRep_atanh",
"sympy/core/tests/test_args.py::test_sympy__functions__special__hyper__HyperRep_asin1",
"sympy/core/tests/test_args.py::test_sympy__functions__special__hyper__HyperRep_asin2",
"sympy/core/tests/test_args.py::test_sympy__functions__special__hyper__HyperRep_sqrts1",
"sympy/core/tests/test_args.py::test_sympy__functions__special__hyper__HyperRep_sqrts2",
"sympy/core/tests/test_args.py::test_sympy__functions__special__hyper__HyperRep_log2",
"sympy/core/tests/test_args.py::test_sympy__functions__special__hyper__HyperRep_cosasin",
"sympy/core/tests/test_args.py::test_sympy__functions__special__hyper__HyperRep_sinasin",
"sympy/core/tests/test_args.py::test_sympy__functions__special__polynomials__jacobi",
"sympy/core/tests/test_args.py::test_sympy__functions__special__polynomials__gegenbauer",
"sympy/core/tests/test_args.py::test_sympy__functions__special__polynomials__chebyshevt",
"sympy/core/tests/test_args.py::test_sympy__functions__special__polynomials__chebyshevt_root",
"sympy/core/tests/test_args.py::test_sympy__functions__special__polynomials__chebyshevu",
"sympy/core/tests/test_args.py::test_sympy__functions__special__polynomials__chebyshevu_root",
"sympy/core/tests/test_args.py::test_sympy__functions__special__polynomials__hermite",
"sympy/core/tests/test_args.py::test_sympy__functions__special__polynomials__legendre",
"sympy/core/tests/test_args.py::test_sympy__functions__special__polynomials__assoc_legendre",
"sympy/core/tests/test_args.py::test_sympy__functions__special__polynomials__laguerre",
"sympy/core/tests/test_args.py::test_sympy__functions__special__polynomials__assoc_laguerre",
"sympy/core/tests/test_args.py::test_sympy__functions__special__spherical_harmonics__Ynm",
"sympy/core/tests/test_args.py::test_sympy__functions__special__spherical_harmonics__Znm",
"sympy/core/tests/test_args.py::test_sympy__functions__special__tensor_functions__LeviCivita",
"sympy/core/tests/test_args.py::test_sympy__functions__special__tensor_functions__KroneckerDelta",
"sympy/core/tests/test_args.py::test_sympy__functions__special__zeta_functions__dirichlet_eta",
"sympy/core/tests/test_args.py::test_sympy__functions__special__zeta_functions__zeta",
"sympy/core/tests/test_args.py::test_sympy__functions__special__zeta_functions__lerchphi",
"sympy/core/tests/test_args.py::test_sympy__functions__special__zeta_functions__polylog",
"sympy/core/tests/test_args.py::test_sympy__functions__special__zeta_functions__stieltjes",
"sympy/core/tests/test_args.py::test_sympy__integrals__integrals__Integral",
"sympy/core/tests/test_args.py::test_sympy__integrals__risch__NonElementaryIntegral",
"sympy/core/tests/test_args.py::test_sympy__integrals__transforms__MellinTransform",
"sympy/core/tests/test_args.py::test_sympy__integrals__transforms__InverseMellinTransform",
"sympy/core/tests/test_args.py::test_sympy__integrals__transforms__LaplaceTransform",
"sympy/core/tests/test_args.py::test_sympy__integrals__transforms__InverseLaplaceTransform",
"sympy/core/tests/test_args.py::test_sympy__integrals__transforms__InverseFourierTransform",
"sympy/core/tests/test_args.py::test_sympy__integrals__transforms__FourierTransform",
"sympy/core/tests/test_args.py::test_sympy__integrals__transforms__InverseSineTransform",
"sympy/core/tests/test_args.py::test_sympy__integrals__transforms__SineTransform",
"sympy/core/tests/test_args.py::test_sympy__integrals__transforms__InverseCosineTransform",
"sympy/core/tests/test_args.py::test_sympy__integrals__transforms__CosineTransform",
"sympy/core/tests/test_args.py::test_sympy__integrals__transforms__InverseHankelTransform",
"sympy/core/tests/test_args.py::test_sympy__integrals__transforms__HankelTransform",
"sympy/core/tests/test_args.py::test_sympy__logic__boolalg__And",
"sympy/core/tests/test_args.py::test_sympy__logic__boolalg__BooleanFunction",
"sympy/core/tests/test_args.py::test_sympy__logic__boolalg__BooleanTrue",
"sympy/core/tests/test_args.py::test_sympy__logic__boolalg__BooleanFalse",
"sympy/core/tests/test_args.py::test_sympy__logic__boolalg__Equivalent",
"sympy/core/tests/test_args.py::test_sympy__logic__boolalg__ITE",
"sympy/core/tests/test_args.py::test_sympy__logic__boolalg__Implies",
"sympy/core/tests/test_args.py::test_sympy__logic__boolalg__Nand",
"sympy/core/tests/test_args.py::test_sympy__logic__boolalg__Nor",
"sympy/core/tests/test_args.py::test_sympy__logic__boolalg__Not",
"sympy/core/tests/test_args.py::test_sympy__logic__boolalg__Or",
"sympy/core/tests/test_args.py::test_sympy__logic__boolalg__Xor",
"sympy/core/tests/test_args.py::test_sympy__matrices__matrices__DeferredVector",
"sympy/core/tests/test_args.py::test_sympy__matrices__immutable__ImmutableMatrix",
"sympy/core/tests/test_args.py::test_sympy__matrices__immutable__ImmutableSparseMatrix",
"sympy/core/tests/test_args.py::test_sympy__matrices__expressions__slice__MatrixSlice",
"sympy/core/tests/test_args.py::test_sympy__matrices__expressions__blockmatrix__BlockDiagMatrix",
"sympy/core/tests/test_args.py::test_sympy__matrices__expressions__blockmatrix__BlockMatrix",
"sympy/core/tests/test_args.py::test_sympy__matrices__expressions__inverse__Inverse",
"sympy/core/tests/test_args.py::test_sympy__matrices__expressions__matadd__MatAdd",
"sympy/core/tests/test_args.py::test_sympy__matrices__expressions__matexpr__Identity",
"sympy/core/tests/test_args.py::test_sympy__matrices__expressions__matexpr__MatrixElement",
"sympy/core/tests/test_args.py::test_sympy__matrices__expressions__matexpr__ZeroMatrix",
"sympy/core/tests/test_args.py::test_sympy__matrices__expressions__matmul__MatMul",
"sympy/core/tests/test_args.py::test_sympy__matrices__expressions__diagonal__DiagonalMatrix",
"sympy/core/tests/test_args.py::test_sympy__matrices__expressions__diagonal__DiagonalOf",
"sympy/core/tests/test_args.py::test_sympy__matrices__expressions__hadamard__HadamardProduct",
"sympy/core/tests/test_args.py::test_sympy__matrices__expressions__matpow__MatPow",
"sympy/core/tests/test_args.py::test_sympy__matrices__expressions__transpose__Transpose",
"sympy/core/tests/test_args.py::test_sympy__matrices__expressions__adjoint__Adjoint",
"sympy/core/tests/test_args.py::test_sympy__matrices__expressions__trace__Trace",
"sympy/core/tests/test_args.py::test_sympy__matrices__expressions__determinant__Determinant",
"sympy/core/tests/test_args.py::test_sympy__matrices__expressions__funcmatrix__FunctionMatrix",
"sympy/core/tests/test_args.py::test_sympy__matrices__expressions__fourier__DFT",
"sympy/core/tests/test_args.py::test_sympy__matrices__expressions__fourier__IDFT",
"sympy/core/tests/test_args.py::test_sympy__matrices__expressions__factorizations__LofLU",
"sympy/core/tests/test_args.py::test_sympy__matrices__expressions__factorizations__UofLU",
"sympy/core/tests/test_args.py::test_sympy__matrices__expressions__factorizations__QofQR",
"sympy/core/tests/test_args.py::test_sympy__matrices__expressions__factorizations__RofQR",
"sympy/core/tests/test_args.py::test_sympy__matrices__expressions__factorizations__LofCholesky",
"sympy/core/tests/test_args.py::test_sympy__matrices__expressions__factorizations__UofCholesky",
"sympy/core/tests/test_args.py::test_sympy__matrices__expressions__factorizations__EigenVectors",
"sympy/core/tests/test_args.py::test_sympy__matrices__expressions__factorizations__EigenValues",
"sympy/core/tests/test_args.py::test_sympy__matrices__expressions__factorizations__UofSVD",
"sympy/core/tests/test_args.py::test_sympy__matrices__expressions__factorizations__VofSVD",
"sympy/core/tests/test_args.py::test_sympy__matrices__expressions__factorizations__SofSVD",
"sympy/core/tests/test_args.py::test_sympy__physics__vector__frame__CoordinateSym",
"sympy/core/tests/test_args.py::test_sympy__physics__paulialgebra__Pauli",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__anticommutator__AntiCommutator",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__cartesian__PositionBra3D",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__cartesian__PositionKet3D",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__cartesian__PositionState3D",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__cartesian__PxBra",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__cartesian__PxKet",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__cartesian__PxOp",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__cartesian__XBra",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__cartesian__XKet",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__cartesian__XOp",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__cartesian__YOp",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__cartesian__ZOp",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__cg__CG",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__cg__Wigner3j",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__cg__Wigner6j",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__cg__Wigner9j",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__circuitplot__Mz",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__circuitplot__Mx",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__commutator__Commutator",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__constants__HBar",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__dagger__Dagger",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__gate__CGate",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__gate__CGateS",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__gate__CNotGate",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__gate__Gate",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__gate__HadamardGate",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__gate__IdentityGate",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__gate__OneQubitGate",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__gate__PhaseGate",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__gate__SwapGate",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__gate__TGate",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__gate__TwoQubitGate",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__gate__UGate",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__gate__XGate",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__gate__YGate",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__gate__ZGate",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__grover__WGate",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__hilbert__ComplexSpace",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__hilbert__DirectSumHilbertSpace",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__hilbert__FockSpace",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__hilbert__HilbertSpace",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__hilbert__L2",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__hilbert__TensorPowerHilbertSpace",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__hilbert__TensorProductHilbertSpace",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__innerproduct__InnerProduct",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__operator__DifferentialOperator",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__operator__HermitianOperator",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__operator__IdentityOperator",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__operator__Operator",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__operator__OuterProduct",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__operator__UnitaryOperator",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__piab__PIABBra",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__boson__BosonOp",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__boson__BosonFockKet",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__boson__BosonFockBra",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__boson__BosonCoherentKet",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__boson__BosonCoherentBra",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__fermion__FermionOp",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__fermion__FermionFockKet",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__fermion__FermionFockBra",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__pauli__SigmaOpBase",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__pauli__SigmaX",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__pauli__SigmaY",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__pauli__SigmaZ",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__pauli__SigmaMinus",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__pauli__SigmaPlus",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__pauli__SigmaZKet",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__pauli__SigmaZBra",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__piab__PIABHamiltonian",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__piab__PIABKet",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__qexpr__QExpr",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__qft__Fourier",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__qft__IQFT",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__qft__QFT",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__qft__RkGate",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__qubit__IntQubit",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__qubit__IntQubitBra",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__qubit__IntQubitState",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__qubit__Qubit",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__qubit__QubitBra",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__qubit__QubitState",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__density__Density",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__spin__CoupledSpinState",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__spin__J2Op",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__spin__JminusOp",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__spin__JplusOp",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__spin__JxBra",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__spin__JxBraCoupled",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__spin__JxKet",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__spin__JxKetCoupled",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__spin__JxOp",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__spin__JyBra",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__spin__JyBraCoupled",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__spin__JyKet",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__spin__JyKetCoupled",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__spin__JyOp",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__spin__JzBra",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__spin__JzBraCoupled",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__spin__JzKet",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__spin__JzKetCoupled",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__spin__JzOp",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__spin__Rotation",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__spin__SpinState",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__spin__WignerD",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__state__Bra",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__state__BraBase",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__state__Ket",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__state__KetBase",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__state__State",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__state__StateBase",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__state__TimeDepBra",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__state__TimeDepKet",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__state__TimeDepState",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__state__Wavefunction",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__tensorproduct__TensorProduct",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__identitysearch__GateIdentity",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__sho1d__SHOOp",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__sho1d__RaisingOp",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__sho1d__LoweringOp",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__sho1d__NumberOp",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__sho1d__Hamiltonian",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__sho1d__SHOState",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__sho1d__SHOKet",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__sho1d__SHOBra",
"sympy/core/tests/test_args.py::test_sympy__physics__secondquant__AnnihilateBoson",
"sympy/core/tests/test_args.py::test_sympy__physics__secondquant__AnnihilateFermion",
"sympy/core/tests/test_args.py::test_sympy__physics__secondquant__AntiSymmetricTensor",
"sympy/core/tests/test_args.py::test_sympy__physics__secondquant__BosonState",
"sympy/core/tests/test_args.py::test_sympy__physics__secondquant__Commutator",
"sympy/core/tests/test_args.py::test_sympy__physics__secondquant__CreateBoson",
"sympy/core/tests/test_args.py::test_sympy__physics__secondquant__CreateFermion",
"sympy/core/tests/test_args.py::test_sympy__physics__secondquant__Dagger",
"sympy/core/tests/test_args.py::test_sympy__physics__secondquant__FermionState",
"sympy/core/tests/test_args.py::test_sympy__physics__secondquant__FermionicOperator",
"sympy/core/tests/test_args.py::test_sympy__physics__secondquant__FockState",
"sympy/core/tests/test_args.py::test_sympy__physics__secondquant__FockStateBosonBra",
"sympy/core/tests/test_args.py::test_sympy__physics__secondquant__FockStateBosonKet",
"sympy/core/tests/test_args.py::test_sympy__physics__secondquant__FockStateBra",
"sympy/core/tests/test_args.py::test_sympy__physics__secondquant__FockStateFermionBra",
"sympy/core/tests/test_args.py::test_sympy__physics__secondquant__FockStateFermionKet",
"sympy/core/tests/test_args.py::test_sympy__physics__secondquant__FockStateKet",
"sympy/core/tests/test_args.py::test_sympy__physics__secondquant__InnerProduct",
"sympy/core/tests/test_args.py::test_sympy__physics__secondquant__NO",
"sympy/core/tests/test_args.py::test_sympy__physics__secondquant__PermutationOperator",
"sympy/core/tests/test_args.py::test_sympy__physics__secondquant__SqOperator",
"sympy/core/tests/test_args.py::test_sympy__physics__secondquant__TensorSymbol",
"sympy/core/tests/test_args.py::test_sympy__physics__units__Unit",
"sympy/core/tests/test_args.py::test_sympy__physics__unitsystems__dimensions__Dimension",
"sympy/core/tests/test_args.py::test_sympy__physics__unitsystems__quantities__Quantity",
"sympy/core/tests/test_args.py::test_sympy__physics__unitsystems__units__Constant",
"sympy/core/tests/test_args.py::test_sympy__physics__unitsystems__units__Unit",
"sympy/core/tests/test_args.py::test_sympy__core__numbers__AlgebraicNumber",
"sympy/core/tests/test_args.py::test_sympy__polys__polytools__GroebnerBasis",
"sympy/core/tests/test_args.py::test_sympy__polys__polytools__Poly",
"sympy/core/tests/test_args.py::test_sympy__polys__polytools__PurePoly",
"sympy/core/tests/test_args.py::test_sympy__polys__rootoftools__RootOf",
"sympy/core/tests/test_args.py::test_sympy__polys__rootoftools__RootSum",
"sympy/core/tests/test_args.py::test_sympy__series__limits__Limit",
"sympy/core/tests/test_args.py::test_sympy__series__order__Order",
"sympy/core/tests/test_args.py::test_sympy__series__sequences__EmptySequence",
"sympy/core/tests/test_args.py::test_sympy__series__sequences__SeqPer",
"sympy/core/tests/test_args.py::test_sympy__series__sequences__SeqFormula",
"sympy/core/tests/test_args.py::test_sympy__series__sequences__SeqExprOp",
"sympy/core/tests/test_args.py::test_sympy__series__sequences__SeqAdd",
"sympy/core/tests/test_args.py::test_sympy__series__sequences__SeqMul",
"sympy/core/tests/test_args.py::test_sympy__series__fourier__FourierSeries",
"sympy/core/tests/test_args.py::test_sympy__series__formal__FormalPowerSeries",
"sympy/core/tests/test_args.py::test_sympy__simplify__hyperexpand__Hyper_Function",
"sympy/core/tests/test_args.py::test_sympy__simplify__hyperexpand__G_Function",
"sympy/core/tests/test_args.py::test_sympy__tensor__indexed__Idx",
"sympy/core/tests/test_args.py::test_sympy__tensor__indexed__Indexed",
"sympy/core/tests/test_args.py::test_sympy__tensor__indexed__IndexedBase",
"sympy/core/tests/test_args.py::test_sympy__tensor__tensor__TensorIndexType",
"sympy/core/tests/test_args.py::test_sympy__tensor__tensor__TensorSymmetry",
"sympy/core/tests/test_args.py::test_sympy__tensor__tensor__TensorType",
"sympy/core/tests/test_args.py::test_sympy__tensor__tensor__TensorHead",
"sympy/core/tests/test_args.py::test_sympy__tensor__tensor__TensorIndex",
"sympy/core/tests/test_args.py::test_sympy__tensor__tensor__TensAdd",
"sympy/core/tests/test_args.py::test_sympy__tensor__tensor__Tensor",
"sympy/core/tests/test_args.py::test_sympy__tensor__tensor__TensMul",
"sympy/core/tests/test_args.py::test_as_coeff_add",
"sympy/core/tests/test_args.py::test_sympy__geometry__curve__Curve",
"sympy/core/tests/test_args.py::test_sympy__geometry__point__Point",
"sympy/core/tests/test_args.py::test_sympy__geometry__point__Point2D",
"sympy/core/tests/test_args.py::test_sympy__geometry__point__Point3D",
"sympy/core/tests/test_args.py::test_sympy__geometry__ellipse__Ellipse",
"sympy/core/tests/test_args.py::test_sympy__geometry__ellipse__Circle",
"sympy/core/tests/test_args.py::test_sympy__geometry__line__Line",
"sympy/core/tests/test_args.py::test_sympy__geometry__line__Ray",
"sympy/core/tests/test_args.py::test_sympy__geometry__line__Segment",
"sympy/core/tests/test_args.py::test_sympy__geometry__line3d__Line3D",
"sympy/core/tests/test_args.py::test_sympy__geometry__line3d__Segment3D",
"sympy/core/tests/test_args.py::test_sympy__geometry__line3d__Ray3D",
"sympy/core/tests/test_args.py::test_sympy__geometry__plane__Plane",
"sympy/core/tests/test_args.py::test_sympy__geometry__polygon__Polygon",
"sympy/core/tests/test_args.py::test_sympy__geometry__polygon__RegularPolygon",
"sympy/core/tests/test_args.py::test_sympy__geometry__polygon__Triangle",
"sympy/core/tests/test_args.py::test_sympy__geometry__entity__GeometryEntity",
"sympy/core/tests/test_args.py::test_sympy__diffgeom__diffgeom__Manifold",
"sympy/core/tests/test_args.py::test_sympy__diffgeom__diffgeom__Patch",
"sympy/core/tests/test_args.py::test_sympy__diffgeom__diffgeom__CoordSystem",
"sympy/core/tests/test_args.py::test_sympy__diffgeom__diffgeom__BaseScalarField",
"sympy/core/tests/test_args.py::test_sympy__diffgeom__diffgeom__BaseVectorField",
"sympy/core/tests/test_args.py::test_sympy__diffgeom__diffgeom__Differential",
"sympy/core/tests/test_args.py::test_sympy__diffgeom__diffgeom__Commutator",
"sympy/core/tests/test_args.py::test_sympy__diffgeom__diffgeom__TensorProduct",
"sympy/core/tests/test_args.py::test_sympy__diffgeom__diffgeom__WedgeProduct",
"sympy/core/tests/test_args.py::test_sympy__diffgeom__diffgeom__LieDerivative",
"sympy/core/tests/test_args.py::test_sympy__diffgeom__diffgeom__CovarDerivativeOp",
"sympy/core/tests/test_args.py::test_sympy__categories__baseclasses__Class",
"sympy/core/tests/test_args.py::test_sympy__categories__baseclasses__Object",
"sympy/core/tests/test_args.py::test_sympy__categories__baseclasses__IdentityMorphism",
"sympy/core/tests/test_args.py::test_sympy__categories__baseclasses__NamedMorphism",
"sympy/core/tests/test_args.py::test_sympy__categories__baseclasses__CompositeMorphism",
"sympy/core/tests/test_args.py::test_sympy__categories__baseclasses__Diagram",
"sympy/core/tests/test_args.py::test_sympy__categories__baseclasses__Category",
"sympy/core/tests/test_args.py::test_sympy__ntheory__factor___totient",
"sympy/core/tests/test_args.py::test_sympy__ntheory__factor___divisor_sigma",
"sympy/core/tests/test_args.py::test_sympy__ntheory__factor___udivisor_sigma",
"sympy/core/tests/test_args.py::test_sympy__ntheory__residue_ntheory__mobius",
"sympy/core/tests/test_args.py::test_sympy__physics__optics__waves__TWave",
"sympy/core/tests/test_args.py::test_sympy__physics__optics__gaussopt__BeamParameter",
"sympy/core/tests/test_args.py::test_sympy__physics__optics__medium__Medium",
"sympy/core/tests/test_args.py::test_sympy__printing__codeprinter__Assignment",
"sympy/core/tests/test_args.py::test_sympy__vector__coordsysrect__CoordSysCartesian",
"sympy/core/tests/test_args.py::test_sympy__vector__point__Point",
"sympy/core/tests/test_args.py::test_sympy__vector__basisdependent__BasisDependent",
"sympy/core/tests/test_args.py::test_sympy__vector__basisdependent__BasisDependentMul",
"sympy/core/tests/test_args.py::test_sympy__vector__basisdependent__BasisDependentAdd",
"sympy/core/tests/test_args.py::test_sympy__vector__basisdependent__BasisDependentZero",
"sympy/core/tests/test_args.py::test_sympy__vector__vector__BaseVector",
"sympy/core/tests/test_args.py::test_sympy__vector__vector__VectorAdd",
"sympy/core/tests/test_args.py::test_sympy__vector__vector__VectorMul",
"sympy/core/tests/test_args.py::test_sympy__vector__vector__VectorZero",
"sympy/core/tests/test_args.py::test_sympy__vector__vector__Vector",
"sympy/core/tests/test_args.py::test_sympy__vector__dyadic__Dyadic",
"sympy/core/tests/test_args.py::test_sympy__vector__dyadic__BaseDyadic",
"sympy/core/tests/test_args.py::test_sympy__vector__dyadic__DyadicMul",
"sympy/core/tests/test_args.py::test_sympy__vector__dyadic__DyadicAdd",
"sympy/core/tests/test_args.py::test_sympy__vector__dyadic__DyadicZero",
"sympy/core/tests/test_args.py::test_sympy__vector__deloperator__Del",
"sympy/core/tests/test_args.py::test_sympy__vector__orienters__Orienter",
"sympy/core/tests/test_args.py::test_sympy__vector__orienters__ThreeAngleOrienter",
"sympy/core/tests/test_args.py::test_sympy__vector__orienters__AxisOrienter",
"sympy/core/tests/test_args.py::test_sympy__vector__orienters__BodyOrienter",
"sympy/core/tests/test_args.py::test_sympy__vector__orienters__SpaceOrienter",
"sympy/core/tests/test_args.py::test_sympy__vector__orienters__QuaternionOrienter",
"sympy/core/tests/test_args.py::test_sympy__vector__scalar__BaseScalar",
"sympy/core/tests/test_args.py::test_sympy__physics__wigner__Wigner3j",
"sympy/core/tests/test_subs.py::test_subs",
"sympy/core/tests/test_subs.py::test_trigonometric",
"sympy/core/tests/test_subs.py::test_powers",
"sympy/core/tests/test_subs.py::test_logexppow",
"sympy/core/tests/test_subs.py::test_bug",
"sympy/core/tests/test_subs.py::test_subbug1",
"sympy/core/tests/test_subs.py::test_subbug2",
"sympy/core/tests/test_subs.py::test_dict_set",
"sympy/core/tests/test_subs.py::test_dict_ambigous",
"sympy/core/tests/test_subs.py::test_deriv_sub_bug3",
"sympy/core/tests/test_subs.py::test_equality_subs1",
"sympy/core/tests/test_subs.py::test_equality_subs2",
"sympy/core/tests/test_subs.py::test_issue_3742",
"sympy/core/tests/test_subs.py::test_subs_dict1",
"sympy/core/tests/test_subs.py::test_mul",
"sympy/core/tests/test_subs.py::test_subs_simple",
"sympy/core/tests/test_subs.py::test_subs_constants",
"sympy/core/tests/test_subs.py::test_subs_commutative",
"sympy/core/tests/test_subs.py::test_subs_noncommutative",
"sympy/core/tests/test_subs.py::test_subs_basic_funcs",
"sympy/core/tests/test_subs.py::test_subs_wild",
"sympy/core/tests/test_subs.py::test_subs_mixed",
"sympy/core/tests/test_subs.py::test_division",
"sympy/core/tests/test_subs.py::test_add",
"sympy/core/tests/test_subs.py::test_subs_issue_4009",
"sympy/core/tests/test_subs.py::test_functions_subs",
"sympy/core/tests/test_subs.py::test_derivative_subs",
"sympy/core/tests/test_subs.py::test_derivative_subs2",
"sympy/core/tests/test_subs.py::test_derivative_subs3",
"sympy/core/tests/test_subs.py::test_issue_5284",
"sympy/core/tests/test_subs.py::test_subs_iter",
"sympy/core/tests/test_subs.py::test_subs_dict",
"sympy/core/tests/test_subs.py::test_no_arith_subs_on_floats",
"sympy/core/tests/test_subs.py::test_issue_5651",
"sympy/core/tests/test_subs.py::test_issue_6075",
"sympy/core/tests/test_subs.py::test_issue_6079",
"sympy/core/tests/test_subs.py::test_issue_4680",
"sympy/core/tests/test_subs.py::test_issue_6158",
"sympy/core/tests/test_subs.py::test_Function_subs",
"sympy/core/tests/test_subs.py::test_simultaneous_subs",
"sympy/core/tests/test_subs.py::test_issue_6419_6421",
"sympy/core/tests/test_subs.py::test_issue_6559",
"sympy/core/tests/test_subs.py::test_issue_5261",
"sympy/core/tests/test_subs.py::test_issue_6923",
"sympy/core/tests/test_subs.py::test_2arg_hack",
"sympy/core/tests/test_subs.py::test_noncommutative_subs",
"sympy/core/tests/test_subs.py::test_issue_2877",
"sympy/core/tests/test_subs.py::test_issue_5910",
"sympy/core/tests/test_subs.py::test_issue_5217",
"sympy/core/tests/test_subs.py::test_pow_eval_subs_no_cache",
"sympy/functions/special/tests/test_bessel.py::test_bessel_twoinputs",
"sympy/functions/special/tests/test_bessel.py::test_diff",
"sympy/functions/special/tests/test_bessel.py::test_rewrite",
"sympy/functions/special/tests/test_bessel.py::test_expand",
"sympy/functions/special/tests/test_bessel.py::test_fn",
"sympy/functions/special/tests/test_bessel.py::test_jn",
"sympy/functions/special/tests/test_bessel.py::test_yn",
"sympy/functions/special/tests/test_bessel.py::test_sympify_yn",
"sympy/functions/special/tests/test_bessel.py::test_jn_zeros",
"sympy/functions/special/tests/test_bessel.py::test_bessel_eval",
"sympy/functions/special/tests/test_bessel.py::test_bessel_nan",
"sympy/functions/special/tests/test_bessel.py::test_branching",
"sympy/functions/special/tests/test_bessel.py::test_airy_base",
"sympy/functions/special/tests/test_bessel.py::test_airyai",
"sympy/functions/special/tests/test_bessel.py::test_airybi",
"sympy/functions/special/tests/test_bessel.py::test_airyaiprime",
"sympy/functions/special/tests/test_bessel.py::test_airybiprime",
"sympy/geometry/tests/test_point.py::test_point",
"sympy/geometry/tests/test_point.py::test_point3D",
"sympy/geometry/tests/test_point.py::test_issue_9214",
"sympy/printing/tests/test_latex.py::test_printmethod",
"sympy/printing/tests/test_latex.py::test_latex_basic",
"sympy/printing/tests/test_latex.py::test_latex_builtins",
"sympy/printing/tests/test_latex.py::test_latex_Float",
"sympy/printing/tests/test_latex.py::test_latex_symbols",
"sympy/printing/tests/test_latex.py::test_latex_functions",
"sympy/printing/tests/test_latex.py::test_hyper_printing",
"sympy/printing/tests/test_latex.py::test_latex_bessel",
"sympy/printing/tests/test_latex.py::test_latex_fresnel",
"sympy/printing/tests/test_latex.py::test_latex_brackets",
"sympy/printing/tests/test_latex.py::test_latex_indexed",
"sympy/printing/tests/test_latex.py::test_latex_derivatives",
"sympy/printing/tests/test_latex.py::test_latex_subs",
"sympy/printing/tests/test_latex.py::test_latex_integrals",
"sympy/printing/tests/test_latex.py::test_latex_sets",
"sympy/printing/tests/test_latex.py::test_latex_Range",
"sympy/printing/tests/test_latex.py::test_latex_sequences",
"sympy/printing/tests/test_latex.py::test_latex_FourierSeries",
"sympy/printing/tests/test_latex.py::test_latex_FormalPowerSeries",
"sympy/printing/tests/test_latex.py::test_latex_intervals",
"sympy/printing/tests/test_latex.py::test_latex_emptyset",
"sympy/printing/tests/test_latex.py::test_latex_union",
"sympy/printing/tests/test_latex.py::test_latex_symmetric_difference",
"sympy/printing/tests/test_latex.py::test_latex_Complement",
"sympy/printing/tests/test_latex.py::test_latex_Complexes",
"sympy/printing/tests/test_latex.py::test_latex_productset",
"sympy/printing/tests/test_latex.py::test_latex_Naturals",
"sympy/printing/tests/test_latex.py::test_latex_Naturals0",
"sympy/printing/tests/test_latex.py::test_latex_Integers",
"sympy/printing/tests/test_latex.py::test_latex_ImageSet",
"sympy/printing/tests/test_latex.py::test_latex_ConditionSet",
"sympy/printing/tests/test_latex.py::test_latex_ComplexRegion",
"sympy/printing/tests/test_latex.py::test_latex_Contains",
"sympy/printing/tests/test_latex.py::test_latex_sum",
"sympy/printing/tests/test_latex.py::test_latex_product",
"sympy/printing/tests/test_latex.py::test_latex_limits",
"sympy/printing/tests/test_latex.py::test_issue_3568",
"sympy/printing/tests/test_latex.py::test_latex",
"sympy/printing/tests/test_latex.py::test_latex_dict",
"sympy/printing/tests/test_latex.py::test_latex_list",
"sympy/printing/tests/test_latex.py::test_latex_rational",
"sympy/printing/tests/test_latex.py::test_latex_inverse",
"sympy/printing/tests/test_latex.py::test_latex_DiracDelta",
"sympy/printing/tests/test_latex.py::test_latex_Heaviside",
"sympy/printing/tests/test_latex.py::test_latex_KroneckerDelta",
"sympy/printing/tests/test_latex.py::test_latex_LeviCivita",
"sympy/printing/tests/test_latex.py::test_mode",
"sympy/printing/tests/test_latex.py::test_latex_Piecewise",
"sympy/printing/tests/test_latex.py::test_latex_Matrix",
"sympy/printing/tests/test_latex.py::test_latex_matrix_with_functions",
"sympy/printing/tests/test_latex.py::test_latex_mul_symbol",
"sympy/printing/tests/test_latex.py::test_latex_issue_4381",
"sympy/printing/tests/test_latex.py::test_latex_issue_4576",
"sympy/printing/tests/test_latex.py::test_latex_pow_fraction",
"sympy/printing/tests/test_latex.py::test_noncommutative",
"sympy/printing/tests/test_latex.py::test_latex_order",
"sympy/printing/tests/test_latex.py::test_latex_Lambda",
"sympy/printing/tests/test_latex.py::test_latex_PolyElement",
"sympy/printing/tests/test_latex.py::test_latex_FracElement",
"sympy/printing/tests/test_latex.py::test_latex_Poly",
"sympy/printing/tests/test_latex.py::test_latex_RootOf",
"sympy/printing/tests/test_latex.py::test_latex_RootSum",
"sympy/printing/tests/test_latex.py::test_settings",
"sympy/printing/tests/test_latex.py::test_latex_numbers",
"sympy/printing/tests/test_latex.py::test_lamda",
"sympy/printing/tests/test_latex.py::test_custom_symbol_names",
"sympy/printing/tests/test_latex.py::test_matAdd",
"sympy/printing/tests/test_latex.py::test_matMul",
"sympy/printing/tests/test_latex.py::test_latex_MatrixSlice",
"sympy/printing/tests/test_latex.py::test_latex_RandomDomain",
"sympy/printing/tests/test_latex.py::test_PrettyPoly",
"sympy/printing/tests/test_latex.py::test_integral_transforms",
"sympy/printing/tests/test_latex.py::test_PolynomialRingBase",
"sympy/printing/tests/test_latex.py::test_categories",
"sympy/printing/tests/test_latex.py::test_Modules",
"sympy/printing/tests/test_latex.py::test_QuotientRing",
"sympy/printing/tests/test_latex.py::test_Tr",
"sympy/printing/tests/test_latex.py::test_Adjoint",
"sympy/printing/tests/test_latex.py::test_Hadamard",
"sympy/printing/tests/test_latex.py::test_ZeroMatrix",
"sympy/printing/tests/test_latex.py::test_boolean_args_order",
"sympy/printing/tests/test_latex.py::test_imaginary",
"sympy/printing/tests/test_latex.py::test_builtins_without_args",
"sympy/printing/tests/test_latex.py::test_latex_greek_functions",
"sympy/printing/tests/test_latex.py::test_translate",
"sympy/printing/tests/test_latex.py::test_other_symbols",
"sympy/printing/tests/test_latex.py::test_modifiers",
"sympy/printing/tests/test_latex.py::test_greek_symbols",
"sympy/printing/tests/test_latex.py::test_builtin_no_args",
"sympy/printing/tests/test_latex.py::test_issue_6853",
"sympy/printing/tests/test_latex.py::test_Mul",
"sympy/printing/tests/test_latex.py::test_Pow",
"sympy/printing/tests/test_latex.py::test_issue_7180",
"sympy/printing/tests/test_latex.py::test_issue_8409",
"sympy/printing/tests/test_latex.py::test_issue_8470",
"sympy/printing/tests/test_latex.py::test_issue_7117",
"sympy/printing/tests/test_latex.py::test_issue_2934",
"sympy/simplify/tests/test_simplify.py::test_issue_7263",
"sympy/simplify/tests/test_simplify.py::test_simplify_expr",
"sympy/simplify/tests/test_simplify.py::test_issue_3557",
"sympy/simplify/tests/test_simplify.py::test_simplify_other",
"sympy/simplify/tests/test_simplify.py::test_simplify_complex",
"sympy/simplify/tests/test_simplify.py::test_simplify_ratio",
"sympy/simplify/tests/test_simplify.py::test_simplify_measure",
"sympy/simplify/tests/test_simplify.py::test_simplify_issue_1308",
"sympy/simplify/tests/test_simplify.py::test_issue_5652",
"sympy/simplify/tests/test_simplify.py::test_simplify_fail1",
"sympy/simplify/tests/test_simplify.py::test_nthroot",
"sympy/simplify/tests/test_simplify.py::test_nthroot1",
"sympy/simplify/tests/test_simplify.py::test_separatevars",
"sympy/simplify/tests/test_simplify.py::test_separatevars_advanced_factor",
"sympy/simplify/tests/test_simplify.py::test_hypersimp",
"sympy/simplify/tests/test_simplify.py::test_nsimplify",
"sympy/simplify/tests/test_simplify.py::test_issue_9448",
"sympy/simplify/tests/test_simplify.py::test_extract_minus_sign",
"sympy/simplify/tests/test_simplify.py::test_diff",
"sympy/simplify/tests/test_simplify.py::test_logcombine_1",
"sympy/simplify/tests/test_simplify.py::test_logcombine_complex_coeff",
"sympy/simplify/tests/test_simplify.py::test_posify",
"sympy/simplify/tests/test_simplify.py::test_issue_4194",
"sympy/simplify/tests/test_simplify.py::test_as_content_primitive",
"sympy/simplify/tests/test_simplify.py::test_signsimp",
"sympy/simplify/tests/test_simplify.py::test_besselsimp",
"sympy/simplify/tests/test_simplify.py::test_Piecewise",
"sympy/simplify/tests/test_simplify.py::test_polymorphism",
"sympy/simplify/tests/test_simplify.py::test_issue_from_PR1599",
"sympy/simplify/tests/test_simplify.py::test_issue_6811",
"sympy/simplify/tests/test_simplify.py::test_issue_6920",
"sympy/simplify/tests/test_simplify.py::test_issue_7001",
"sympy/simplify/tests/test_simplify.py::test_inequality_no_auto_simplify",
"sympy/simplify/tests/test_simplify.py::test_issue_9398",
"sympy/simplify/tests/test_simplify.py::test_issue_9324_simplify",
"sympy/solvers/tests/test_inequalities.py::test_solve_poly_inequality",
"sympy/solvers/tests/test_inequalities.py::test_reduce_poly_inequalities_real_interval",
"sympy/solvers/tests/test_inequalities.py::test_reduce_poly_inequalities_complex_relational",
"sympy/solvers/tests/test_inequalities.py::test_reduce_rational_inequalities_real_relational",
"sympy/solvers/tests/test_inequalities.py::test_reduce_abs_inequalities",
"sympy/solvers/tests/test_inequalities.py::test_reduce_inequalities_general",
"sympy/solvers/tests/test_inequalities.py::test_reduce_inequalities_boolean",
"sympy/solvers/tests/test_inequalities.py::test_reduce_inequalities_multivariate",
"sympy/solvers/tests/test_inequalities.py::test_reduce_inequalities_errors",
"sympy/solvers/tests/test_inequalities.py::test_hacky_inequalities",
"sympy/solvers/tests/test_inequalities.py::test_issue_6343",
"sympy/solvers/tests/test_inequalities.py::test_issue_8235",
"sympy/solvers/tests/test_inequalities.py::test_issue_5526",
"sympy/solvers/tests/test_inequalities.py::test_solve_univariate_inequality",
"sympy/solvers/tests/test_inequalities.py::test_issue_9954",
"sympy/solvers/tests/test_inequalities.py::test_slow_general_univariate",
"sympy/solvers/tests/test_inequalities.py::test_issue_8545",
"sympy/solvers/tests/test_inequalities.py::test_issue_8974",
"sympy/solvers/tests/test_solveset.py::test_invert_real",
"sympy/solvers/tests/test_solveset.py::test_invert_complex",
"sympy/solvers/tests/test_solveset.py::test_domain_check",
"sympy/solvers/tests/test_solveset.py::test_is_function_class_equation",
"sympy/solvers/tests/test_solveset.py::test_garbage_input",
"sympy/solvers/tests/test_solveset.py::test_solve_mul",
"sympy/solvers/tests/test_solveset.py::test_solve_invert",
"sympy/solvers/tests/test_solveset.py::test_errorinverses",
"sympy/solvers/tests/test_solveset.py::test_solve_polynomial",
"sympy/solvers/tests/test_solveset.py::test_return_root_of",
"sympy/solvers/tests/test_solveset.py::test__has_rational_power",
"sympy/solvers/tests/test_solveset.py::test_solveset_sqrt_1",
"sympy/solvers/tests/test_solveset.py::test_solveset_sqrt_2",
"sympy/solvers/tests/test_solveset.py::test_solve_sqrt_3",
"sympy/solvers/tests/test_solveset.py::test_solve_polynomial_symbolic_param",
"sympy/solvers/tests/test_solveset.py::test_solve_rational",
"sympy/solvers/tests/test_solveset.py::test_solveset_real_gen_is_pow",
"sympy/solvers/tests/test_solveset.py::test_no_sol",
"sympy/solvers/tests/test_solveset.py::test_sol_zero_real",
"sympy/solvers/tests/test_solveset.py::test_no_sol_rational_extragenous",
"sympy/solvers/tests/test_solveset.py::test_solve_polynomial_cv_1a",
"sympy/solvers/tests/test_solveset.py::test_solveset_real_rational",
"sympy/solvers/tests/test_solveset.py::test_solveset_real_log",
"sympy/solvers/tests/test_solveset.py::test_poly_gens",
"sympy/solvers/tests/test_solveset.py::test_solve_abs",
"sympy/solvers/tests/test_solveset.py::test_real_imag_splitting",
"sympy/solvers/tests/test_solveset.py::test_units",
"sympy/solvers/tests/test_solveset.py::test_solve_only_exp_1",
"sympy/solvers/tests/test_solveset.py::test_atan2",
"sympy/solvers/tests/test_solveset.py::test_piecewise",
"sympy/solvers/tests/test_solveset.py::test_solveset_complex_polynomial",
"sympy/solvers/tests/test_solveset.py::test_sol_zero_complex",
"sympy/solvers/tests/test_solveset.py::test_solveset_complex_rational",
"sympy/solvers/tests/test_solveset.py::test_solveset_complex_exp",
"sympy/solvers/tests/test_solveset.py::test_solve_complex_log",
"sympy/solvers/tests/test_solveset.py::test_solve_complex_sqrt",
"sympy/solvers/tests/test_solveset.py::test_solveset_complex_tan",
"sympy/solvers/tests/test_solveset.py::test_solve_trig",
"sympy/solvers/tests/test_solveset.py::test_solve_invalid_sol",
"sympy/solvers/tests/test_solveset.py::test_solve_complex_unsolvable",
"sympy/solvers/tests/test_solveset.py::test_solveset",
"sympy/solvers/tests/test_solveset.py::test_conditonset",
"sympy/solvers/tests/test_solveset.py::test_solveset_domain",
"sympy/solvers/tests/test_solveset.py::test_improve_coverage",
"sympy/solvers/tests/test_solveset.py::test_issue_9522",
"sympy/solvers/tests/test_solveset.py::test_linear_eq_to_matrix",
"sympy/solvers/tests/test_solveset.py::test_linsolve",
"sympy/solvers/tests/test_solveset.py::test_issue_9556",
"sympy/solvers/tests/test_solveset.py::test_issue_9611",
"sympy/solvers/tests/test_solveset.py::test_issue_9557",
"sympy/solvers/tests/test_solveset.py::test_issue_9778",
"sympy/solvers/tests/test_solveset.py::test_issue_9849",
"sympy/solvers/tests/test_solveset.py::test_issue_9953",
"sympy/solvers/tests/test_solveset.py::test_issue_9913"
] | [] | BSD | 285 |
|
tornadoweb__tornado-1576 | 1ecc7386da17df3f1dfd100845355f7211119a62 | 2015-11-02 23:03:13 | c20c44d776d3bd9b2c002db5aaa9e3b5284a3043 | diff --git a/tornado/options.py b/tornado/options.py
index ba16b1a7..bdb5baa0 100644
--- a/tornado/options.py
+++ b/tornado/options.py
@@ -132,8 +132,10 @@ class OptionParser(object):
return name in self._options
def __getitem__(self, name):
- name = self._normalize_name(name)
- return self._options[name].value()
+ return self.__getattr__(name)
+
+ def __setitem__(self, name, value):
+ return self.__setattr__(name, value)
def items(self):
"""A sequence of (name, value) pairs.
| Options should support setitem
From http://stackoverflow.com/questions/33411269/attributeerror-in-python-tornado-to-configure-log-into-a-file/33417289
Options currently override getattr, setattr, and getitem. Item and attribute syntax should be symmetric so we need a setitem override to match setattr. | tornadoweb/tornado | diff --git a/tornado/test/options_test.py b/tornado/test/options_test.py
index c32184bb..2f2384b2 100644
--- a/tornado/test/options_test.py
+++ b/tornado/test/options_test.py
@@ -131,6 +131,12 @@ class OptionsTest(unittest.TestCase):
options = self._sample_options()
self.assertEqual(1, options['a'])
+ def test_setitem(self):
+ options = OptionParser()
+ options.define('foo', default=1, type=int)
+ options['foo'] = 2
+ self.assertEqual(options['foo'], 2)
+
def test_items(self):
options = self._sample_options()
# OptionParsers always define 'help'.
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_short_problem_statement",
"has_hyperlinks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 0,
"issue_text_score": 0,
"test_score": 1
},
"num_modified_files": 1
} | 4.3 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "pytest",
"pip_packages": [
"futures",
"mock",
"monotonic",
"trollius",
"pytest"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.5",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | attrs @ file:///opt/conda/conda-bld/attrs_1642510447205/work
certifi==2021.5.30
futures==2.2.0
importlib-metadata @ file:///tmp/build/80754af9/importlib-metadata_1631916693255/work
iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work
mock==5.2.0
monotonic==1.6
more-itertools @ file:///tmp/build/80754af9/more-itertools_1637733554872/work
packaging @ file:///tmp/build/80754af9/packaging_1637314298585/work
pluggy @ file:///tmp/build/80754af9/pluggy_1615976315926/work
py @ file:///opt/conda/conda-bld/py_1644396412707/work
pyparsing @ file:///tmp/build/80754af9/pyparsing_1635766073266/work
pytest==6.2.4
six==1.17.0
toml @ file:///tmp/build/80754af9/toml_1616166611790/work
-e git+https://github.com/tornadoweb/tornado.git@1ecc7386da17df3f1dfd100845355f7211119a62#egg=tornado
trollius==2.1.post2
typing_extensions @ file:///opt/conda/conda-bld/typing_extensions_1647553014482/work
zipp @ file:///tmp/build/80754af9/zipp_1633618647012/work
| name: tornado
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- attrs=21.4.0=pyhd3eb1b0_0
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2021.5.30=py36h06a4308_0
- importlib-metadata=4.8.1=py36h06a4308_0
- importlib_metadata=4.8.1=hd3eb1b0_0
- iniconfig=1.1.1=pyhd3eb1b0_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.3=he6710b0_2
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- more-itertools=8.12.0=pyhd3eb1b0_0
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- packaging=21.3=pyhd3eb1b0_0
- pip=21.2.2=py36h06a4308_0
- pluggy=0.13.1=py36h06a4308_0
- py=1.11.0=pyhd3eb1b0_0
- pyparsing=3.0.4=pyhd3eb1b0_0
- pytest=6.2.4=py36h06a4308_2
- python=3.6.13=h12debd9_1
- readline=8.2=h5eee18b_0
- setuptools=58.0.4=py36h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- toml=0.10.2=pyhd3eb1b0_0
- typing_extensions=4.1.1=pyh06a4308_0
- wheel=0.37.1=pyhd3eb1b0_0
- xz=5.6.4=h5eee18b_1
- zipp=3.6.0=pyhd3eb1b0_0
- zlib=1.2.13=h5eee18b_1
- pip:
- futures==2.2.0
- mock==5.2.0
- monotonic==1.6
- six==1.17.0
- trollius==2.1.post2
prefix: /opt/conda/envs/tornado
| [
"tornado/test/options_test.py::OptionsTest::test_setitem"
] | [] | [
"tornado/test/options_test.py::OptionsTest::test_as_dict",
"tornado/test/options_test.py::OptionsTest::test_dash_underscore_cli",
"tornado/test/options_test.py::OptionsTest::test_dash_underscore_file",
"tornado/test/options_test.py::OptionsTest::test_dash_underscore_introspection",
"tornado/test/options_test.py::OptionsTest::test_error_redefine",
"tornado/test/options_test.py::OptionsTest::test_getitem",
"tornado/test/options_test.py::OptionsTest::test_group_dict",
"tornado/test/options_test.py::OptionsTest::test_help",
"tornado/test/options_test.py::OptionsTest::test_items",
"tornado/test/options_test.py::OptionsTest::test_iter",
"tornado/test/options_test.py::OptionsTest::test_mock_patch",
"tornado/test/options_test.py::OptionsTest::test_multiple_int",
"tornado/test/options_test.py::OptionsTest::test_multiple_string",
"tornado/test/options_test.py::OptionsTest::test_parse_callbacks",
"tornado/test/options_test.py::OptionsTest::test_parse_command_line",
"tornado/test/options_test.py::OptionsTest::test_parse_config_file",
"tornado/test/options_test.py::OptionsTest::test_setattr",
"tornado/test/options_test.py::OptionsTest::test_setattr_type_check",
"tornado/test/options_test.py::OptionsTest::test_setattr_with_callback",
"tornado/test/options_test.py::OptionsTest::test_subcommand",
"tornado/test/options_test.py::OptionsTest::test_types"
] | [] | Apache License 2.0 | 286 |
|
sigmavirus24__github3.py-460 | 47487d093c0cbe24b4219a7137bedaab6b882548 | 2015-11-04 01:02:18 | 05ed0c6a02cffc6ddd0e82ce840c464e1c5fd8c4 | diff --git a/github3/github.py b/github3/github.py
index e575408b..4f5d0734 100644
--- a/github3/github.py
+++ b/github3/github.py
@@ -355,7 +355,10 @@ class GitHub(GitHubCore):
}
"""
url = self._build_url('emojis')
- return self._json(self._get(url), 200)
+ data = self._json(self._get(url), 200)
+ del data['ETag']
+ del data['Last-Modified']
+ return data
@requires_basic_auth
def feeds(self):
| GitHub.emojis() return value contains ETag and Last-Modified entries
emojis() returns the return value of _json to the user, which then contains
confusing ETag and Last-Modified enttries, caused by commit 8c42a709. Not sure
how you want to fix it, but easiest would be to delete those entries in
emojis() before returning the result. | sigmavirus24/github3.py | diff --git a/tests/integration/test_github.py b/tests/integration/test_github.py
index d27eb229..fe2726be 100644
--- a/tests/integration/test_github.py
+++ b/tests/integration/test_github.py
@@ -95,6 +95,15 @@ class TestGitHub(IntegrationHelper):
# Asserts that it's a string and looks ilke the URLs we expect to see
assert emojis['+1'].startswith('https://github')
+ def test_emojis_etag(self):
+ """Test the ability to retrieve from /emojis."""
+ cassette_name = self.cassette_name('emojis')
+ with self.recorder.use_cassette(cassette_name):
+ emojis = self.gh.emojis()
+
+ assert 'ETag' not in emojis
+ assert 'Last-Modified' not in emojis
+
def test_feeds(self):
"""Test the ability to retrieve a user's timelime URLs."""
self.basic_login()
| {
"commit_name": "head_commit",
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true,
"llm_score": {
"difficulty_score": 0,
"issue_text_score": 1,
"test_score": 0
},
"num_modified_files": 1
} | 1.0 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[test]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest",
"pytest-cov",
"pytest-xdist",
"pytest-mock",
"pytest-asyncio"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.9",
"reqs_path": [
"requirements.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | betamax==0.9.0
betamax-matchers==0.4.0
certifi==2025.1.31
charset-normalizer==3.4.1
coverage==7.8.0
exceptiongroup==1.2.2
execnet==2.1.1
-e git+https://github.com/sigmavirus24/github3.py.git@47487d093c0cbe24b4219a7137bedaab6b882548#egg=github3.py
idna==3.10
iniconfig==2.1.0
packaging==24.2
pluggy==1.5.0
pytest==8.3.5
pytest-asyncio==0.26.0
pytest-cov==6.0.0
pytest-mock==3.14.0
pytest-xdist==3.6.1
requests==2.32.3
requests-toolbelt==1.0.0
tomli==2.2.1
typing_extensions==4.13.0
uritemplate==4.1.1
uritemplate.py==3.0.2
urllib3==2.3.0
| name: github3.py
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=3.0.16=h5eee18b_0
- pip=25.0=py39h06a4308_0
- python=3.9.21=he870216_1
- readline=8.2=h5eee18b_0
- setuptools=75.8.0=py39h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- tzdata=2025a=h04d1e81_0
- wheel=0.45.1=py39h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- betamax==0.9.0
- betamax-matchers==0.4.0
- certifi==2025.1.31
- charset-normalizer==3.4.1
- coverage==7.8.0
- exceptiongroup==1.2.2
- execnet==2.1.1
- idna==3.10
- iniconfig==2.1.0
- packaging==24.2
- pluggy==1.5.0
- pytest==8.3.5
- pytest-asyncio==0.26.0
- pytest-cov==6.0.0
- pytest-mock==3.14.0
- pytest-xdist==3.6.1
- requests==2.32.3
- requests-toolbelt==1.0.0
- tomli==2.2.1
- typing-extensions==4.13.0
- uritemplate==4.1.1
- uritemplate-py==3.0.2
- urllib3==2.3.0
prefix: /opt/conda/envs/github3.py
| [
"tests/integration/test_github.py::TestGitHub::test_emojis_etag"
] | [
"tests/integration/test_github.py::TestGitHub::test_update_me"
] | [
"tests/integration/test_github.py::TestGitHub::test_all_events",
"tests/integration/test_github.py::TestGitHub::test_all_organizations",
"tests/integration/test_github.py::TestGitHub::test_all_repositories",
"tests/integration/test_github.py::TestGitHub::test_all_users",
"tests/integration/test_github.py::TestGitHub::test_authorize",
"tests/integration/test_github.py::TestGitHub::test_create_gist",
"tests/integration/test_github.py::TestGitHub::test_create_issue",
"tests/integration/test_github.py::TestGitHub::test_create_key",
"tests/integration/test_github.py::TestGitHub::test_create_repository",
"tests/integration/test_github.py::TestGitHub::test_emojis",
"tests/integration/test_github.py::TestGitHub::test_feeds",
"tests/integration/test_github.py::TestGitHub::test_followers",
"tests/integration/test_github.py::TestGitHub::test_followers_of",
"tests/integration/test_github.py::TestGitHub::test_gist",
"tests/integration/test_github.py::TestGitHub::test_gitignore_template",
"tests/integration/test_github.py::TestGitHub::test_gitignore_templates",
"tests/integration/test_github.py::TestGitHub::test_is_following",
"tests/integration/test_github.py::TestGitHub::test_is_starred",
"tests/integration/test_github.py::TestGitHub::test_issue",
"tests/integration/test_github.py::TestGitHub::test_me",
"tests/integration/test_github.py::TestGitHub::test_meta",
"tests/integration/test_github.py::TestGitHub::test_non_existent_gitignore_template",
"tests/integration/test_github.py::TestGitHub::test_notifications",
"tests/integration/test_github.py::TestGitHub::test_notifications_all",
"tests/integration/test_github.py::TestGitHub::test_octocat",
"tests/integration/test_github.py::TestGitHub::test_organization",
"tests/integration/test_github.py::TestGitHub::test_pull_request",
"tests/integration/test_github.py::TestGitHub::test_rate_limit",
"tests/integration/test_github.py::TestGitHub::test_repositories",
"tests/integration/test_github.py::TestGitHub::test_repositories_by",
"tests/integration/test_github.py::TestGitHub::test_repository",
"tests/integration/test_github.py::TestGitHub::test_repository_with_id",
"tests/integration/test_github.py::TestGitHub::test_search_code",
"tests/integration/test_github.py::TestGitHub::test_search_code_with_text_match",
"tests/integration/test_github.py::TestGitHub::test_search_issues",
"tests/integration/test_github.py::TestGitHub::test_search_repositories",
"tests/integration/test_github.py::TestGitHub::test_search_repositories_with_text_match",
"tests/integration/test_github.py::TestGitHub::test_search_users",
"tests/integration/test_github.py::TestGitHub::test_search_users_with_text_match",
"tests/integration/test_github.py::TestGitHub::test_user",
"tests/integration/test_github.py::TestGitHub::test_user_teams",
"tests/integration/test_github.py::TestGitHub::test_user_with_id",
"tests/integration/test_github.py::TestGitHub::test_zen"
] | [] | BSD 3-Clause "New" or "Revised" License | 287 |
|
sympy__sympy-10115 | c67d601999dae4ebf16f055454954a6a556e6857 | 2015-11-04 16:53:02 | 0241b35cae5f2adc04dc37b25f7dc9c5f00bd746 | diff --git a/sympy/sets/sets.py b/sympy/sets/sets.py
index 9e761ddcd8..ce747c602b 100644
--- a/sympy/sets/sets.py
+++ b/sympy/sets/sets.py
@@ -1063,8 +1063,8 @@ def _eval_imageset(self, f):
else:
return imageset(f, Interval(self.start, sing[0],
self.left_open, True)) + \
- Union(*[imageset(f, Interval(sing[i], sing[i + 1]), True, True)
- for i in range(1, len(sing) - 1)]) + \
+ Union(*[imageset(f, Interval(sing[i], sing[i + 1], True, True))
+ for i in range(0, len(sing) - 1)]) + \
imageset(f, Interval(sing[-1], self.end, True, self.right_open))
@property
| imageset(lambda x: x**2/(x**2 - 4), S.Reals) returns (1, ∞)
```
>>> f = x**2/(x**2 - 4)
>>> imageset(x, f, S.Reals)
(1, ∞) # this is wrong
>>> imageset(x, f, Interval(1, oo))
(-∞, -1/3] ∪ (1, ∞) # this is correct
```
Since `[1, ∞).is_subset(S.Reals)` | sympy/sympy | diff --git a/sympy/sets/tests/test_sets.py b/sympy/sets/tests/test_sets.py
index f9a640dfb0..71f6cc8657 100644
--- a/sympy/sets/tests/test_sets.py
+++ b/sympy/sets/tests/test_sets.py
@@ -922,3 +922,10 @@ def test_issue_Symbol_inter():
Intersection(r, FiniteSet(sin(x), cos(x)))
assert Intersection(FiniteSet(x**2, 1, sin(x)), FiniteSet(x**2, 2, sin(x)), r) == \
Intersection(r, FiniteSet(x**2, sin(x)))
+
+
+def test_issue_10113():
+ f = x**2/(x**2 - 4)
+ assert imageset(x, f, S.Reals) == Union(Interval(-oo, 0), Interval(1, oo, True, True))
+ assert imageset(x, f, Interval(-2, 2)) == Interval(-oo, 0)
+ assert imageset(x, f, Interval(-2, 3)) == Union(Interval(-oo, 0), Interval(S(9)/5, oo))
| {
"commit_name": "head_commit",
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true,
"llm_score": {
"difficulty_score": 2,
"issue_text_score": 0,
"test_score": 0
},
"num_modified_files": 1
} | 0.7 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "pytest",
"pip_packages": [
"pytest"
],
"pre_install": null,
"python": "3.7",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | attrs @ file:///croot/attrs_1668696182826/work
certifi @ file:///croot/certifi_1671487769961/work/certifi
flit_core @ file:///opt/conda/conda-bld/flit-core_1644941570762/work/source/flit_core
importlib-metadata @ file:///tmp/build/80754af9/importlib-metadata_1648562407465/work
iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work
mpmath==1.3.0
packaging @ file:///croot/packaging_1671697413597/work
pluggy @ file:///tmp/build/80754af9/pluggy_1648042572264/work
py @ file:///opt/conda/conda-bld/py_1644396412707/work
pytest==7.1.2
-e git+https://github.com/sympy/sympy.git@c67d601999dae4ebf16f055454954a6a556e6857#egg=sympy
tomli @ file:///opt/conda/conda-bld/tomli_1657175507142/work
typing_extensions @ file:///croot/typing_extensions_1669924550328/work
zipp @ file:///croot/zipp_1672387121353/work
| name: sympy
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- attrs=22.1.0=py37h06a4308_0
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2022.12.7=py37h06a4308_0
- flit-core=3.6.0=pyhd3eb1b0_0
- importlib-metadata=4.11.3=py37h06a4308_0
- importlib_metadata=4.11.3=hd3eb1b0_0
- iniconfig=1.1.1=pyhd3eb1b0_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- packaging=22.0=py37h06a4308_0
- pip=22.3.1=py37h06a4308_0
- pluggy=1.0.0=py37h06a4308_1
- py=1.11.0=pyhd3eb1b0_0
- pytest=7.1.2=py37h06a4308_0
- python=3.7.16=h7a1cb2a_0
- readline=8.2=h5eee18b_0
- setuptools=65.6.3=py37h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- tomli=2.0.1=py37h06a4308_0
- typing_extensions=4.4.0=py37h06a4308_0
- wheel=0.38.4=py37h06a4308_0
- xz=5.6.4=h5eee18b_1
- zipp=3.11.0=py37h06a4308_0
- zlib=1.2.13=h5eee18b_1
- pip:
- mpmath==1.3.0
prefix: /opt/conda/envs/sympy
| [
"sympy/sets/tests/test_sets.py::test_issue_10113"
] | [] | [
"sympy/sets/tests/test_sets.py::test_interval_arguments",
"sympy/sets/tests/test_sets.py::test_interval_symbolic_end_points",
"sympy/sets/tests/test_sets.py::test_union",
"sympy/sets/tests/test_sets.py::test_difference",
"sympy/sets/tests/test_sets.py::test_Complement",
"sympy/sets/tests/test_sets.py::test_complement",
"sympy/sets/tests/test_sets.py::test_intersect",
"sympy/sets/tests/test_sets.py::test_intersection",
"sympy/sets/tests/test_sets.py::test_issue_9623",
"sympy/sets/tests/test_sets.py::test_is_disjoint",
"sympy/sets/tests/test_sets.py::test_ProductSet_of_single_arg_is_arg",
"sympy/sets/tests/test_sets.py::test_interval_subs",
"sympy/sets/tests/test_sets.py::test_interval_to_mpi",
"sympy/sets/tests/test_sets.py::test_measure",
"sympy/sets/tests/test_sets.py::test_is_subset",
"sympy/sets/tests/test_sets.py::test_is_proper_subset",
"sympy/sets/tests/test_sets.py::test_is_superset",
"sympy/sets/tests/test_sets.py::test_is_proper_superset",
"sympy/sets/tests/test_sets.py::test_contains",
"sympy/sets/tests/test_sets.py::test_interval_symbolic",
"sympy/sets/tests/test_sets.py::test_union_contains",
"sympy/sets/tests/test_sets.py::test_is_number",
"sympy/sets/tests/test_sets.py::test_Interval_is_left_unbounded",
"sympy/sets/tests/test_sets.py::test_Interval_is_right_unbounded",
"sympy/sets/tests/test_sets.py::test_Interval_as_relational",
"sympy/sets/tests/test_sets.py::test_Finite_as_relational",
"sympy/sets/tests/test_sets.py::test_Union_as_relational",
"sympy/sets/tests/test_sets.py::test_Intersection_as_relational",
"sympy/sets/tests/test_sets.py::test_EmptySet",
"sympy/sets/tests/test_sets.py::test_finite_basic",
"sympy/sets/tests/test_sets.py::test_powerset",
"sympy/sets/tests/test_sets.py::test_product_basic",
"sympy/sets/tests/test_sets.py::test_real",
"sympy/sets/tests/test_sets.py::test_supinf",
"sympy/sets/tests/test_sets.py::test_universalset",
"sympy/sets/tests/test_sets.py::test_Union_of_ProductSets_shares",
"sympy/sets/tests/test_sets.py::test_Interval_free_symbols",
"sympy/sets/tests/test_sets.py::test_image_interval",
"sympy/sets/tests/test_sets.py::test_image_piecewise",
"sympy/sets/tests/test_sets.py::test_image_FiniteSet",
"sympy/sets/tests/test_sets.py::test_image_Union",
"sympy/sets/tests/test_sets.py::test_image_EmptySet",
"sympy/sets/tests/test_sets.py::test_issue_5724_7680",
"sympy/sets/tests/test_sets.py::test_boundary",
"sympy/sets/tests/test_sets.py::test_boundary_Union",
"sympy/sets/tests/test_sets.py::test_boundary_ProductSet",
"sympy/sets/tests/test_sets.py::test_boundary_ProductSet_line",
"sympy/sets/tests/test_sets.py::test_is_open",
"sympy/sets/tests/test_sets.py::test_is_closed",
"sympy/sets/tests/test_sets.py::test_closure",
"sympy/sets/tests/test_sets.py::test_interior",
"sympy/sets/tests/test_sets.py::test_issue_7841",
"sympy/sets/tests/test_sets.py::test_Eq",
"sympy/sets/tests/test_sets.py::test_SymmetricDifference",
"sympy/sets/tests/test_sets.py::test_issue_9536",
"sympy/sets/tests/test_sets.py::test_issue_9637",
"sympy/sets/tests/test_sets.py::test_issue_9808",
"sympy/sets/tests/test_sets.py::test_issue_9956",
"sympy/sets/tests/test_sets.py::test_issue_Symbol_inter"
] | [] | BSD | 288 |
|
infobloxopen__infoblox-client-6 | 3de58f527e14a03dcda5c537a1d82671a1aadb99 | 2015-11-05 13:46:52 | 3de58f527e14a03dcda5c537a1d82671a1aadb99 | diff --git a/infoblox_client/object_manager.py b/infoblox_client/object_manager.py
index d61987c..3a19fdd 100644
--- a/infoblox_client/object_manager.py
+++ b/infoblox_client/object_manager.py
@@ -246,15 +246,15 @@ class InfobloxObjectManager(object):
zone_format=None, ns_group=None, prefix=None,
extattrs=None):
try:
- obj.DNSZone.create(self.connector,
- fqdn=dns_zone,
- view=dns_view,
- extattrs=extattrs,
- zone_format=zone_format,
- ns_group=ns_group,
- prefix=prefix,
- grid_primary=grid_primary,
- grid_secondaries=grid_secondaries)
+ return obj.DNSZone.create(self.connector,
+ fqdn=dns_zone,
+ view=dns_view,
+ extattrs=extattrs,
+ zone_format=zone_format,
+ ns_group=ns_group,
+ prefix=prefix,
+ grid_primary=grid_primary,
+ grid_secondaries=grid_secondaries)
except ib_ex.InfobloxCannotCreateObject:
LOG.warning('Unable to create DNS zone %(dns_zone_fqdn)s '
'for %(dns_view)s',
| Need to return Zone if it was created
Currentry None is returned from create_dns_zone:
https://github.com/infobloxopen/infoblox-client/blob/master/infoblox_client/object_manager.py#L249
Need to return created DnsZone object. | infobloxopen/infoblox-client | diff --git a/infoblox_client/tests/unit/test_object_manager.py b/infoblox_client/tests/unit/test_object_manager.py
index b24897d..73d43ed 100644
--- a/infoblox_client/tests/unit/test_object_manager.py
+++ b/infoblox_client/tests/unit/test_object_manager.py
@@ -591,8 +591,9 @@ class ObjectManipulatorTestCase(base.TestCase):
ibom = om.InfobloxObjectManager(connector)
- ibom.create_dns_zone(dns_view_name, fqdn, primary_dns_members,
- secondary_dns_members, zone_format=zone_format)
+ zone = ibom.create_dns_zone(dns_view_name, fqdn, primary_dns_members,
+ secondary_dns_members,
+ zone_format=zone_format)
matcher = PayloadMatcher({'view': dns_view_name,
'fqdn': fqdn})
@@ -610,6 +611,7 @@ class ObjectManipulatorTestCase(base.TestCase):
}
connector.create_object.assert_called_once_with('zone_auth', payload,
mock.ANY)
+ self.assertIsInstance(zone, objects.DNSZone)
def test_create_dns_zone_creates_zone_auth_object(self):
dns_view_name = 'dns-view-name'
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_short_problem_statement"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 0,
"issue_text_score": 0,
"test_score": 0
},
"num_modified_files": 1
} | 0.0 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[dev]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest",
"mock"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.9",
"reqs_path": [
"requirements.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | certifi==2025.1.31
charset-normalizer==3.4.1
debtcollector==3.0.0
exceptiongroup==1.2.2
idna==3.10
-e git+https://github.com/infobloxopen/infoblox-client.git@3de58f527e14a03dcda5c537a1d82671a1aadb99#egg=infoblox_client
iniconfig==2.1.0
iso8601==2.1.0
mock==5.2.0
msgpack==1.1.0
netaddr==1.3.0
oslo.config==9.7.1
oslo.context==5.7.1
oslo.i18n==6.5.1
oslo.log==7.1.0
oslo.serialization==5.7.0
oslo.utils==8.2.0
packaging==24.2
pbr==6.1.1
pluggy==1.5.0
psutil==7.0.0
pyparsing==3.2.3
pytest==8.3.5
python-dateutil==2.9.0.post0
PyYAML==6.0.2
requests==2.32.3
rfc3986==2.0.0
six==1.17.0
stevedore==5.4.1
tomli==2.2.1
tzdata==2025.2
urllib3==2.3.0
wrapt==1.17.2
| name: infoblox-client
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=3.0.16=h5eee18b_0
- pip=25.0=py39h06a4308_0
- python=3.9.21=he870216_1
- readline=8.2=h5eee18b_0
- setuptools=75.8.0=py39h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- certifi==2025.1.31
- charset-normalizer==3.4.1
- debtcollector==3.0.0
- exceptiongroup==1.2.2
- idna==3.10
- iniconfig==2.1.0
- iso8601==2.1.0
- mock==5.2.0
- msgpack==1.1.0
- netaddr==1.3.0
- oslo-config==9.7.1
- oslo-context==5.7.1
- oslo-i18n==6.5.1
- oslo-log==7.1.0
- oslo-serialization==5.7.0
- oslo-utils==8.2.0
- packaging==24.2
- pbr==6.1.1
- pluggy==1.5.0
- psutil==7.0.0
- pyparsing==3.2.3
- pytest==8.3.5
- python-dateutil==2.9.0.post0
- pyyaml==6.0.2
- requests==2.32.3
- rfc3986==2.0.0
- six==1.17.0
- stevedore==5.4.1
- tomli==2.2.1
- tzdata==2025.2
- urllib3==2.3.0
- wheel==0.23.0
- wrapt==1.17.2
prefix: /opt/conda/envs/infoblox-client
| [
"infoblox_client/tests/unit/test_object_manager.py::ObjectManipulatorTestCase::test_create_dns_zone_with_grid_secondaries"
] | [] | [
"infoblox_client/tests/unit/test_object_manager.py::ObjectManipulatorTestCase::test_bind_names_updates_host_record",
"infoblox_client/tests/unit/test_object_manager.py::ObjectManipulatorTestCase::test_bind_names_with_a_record",
"infoblox_client/tests/unit/test_object_manager.py::ObjectManipulatorTestCase::test_create_dns_view_creates_view_object",
"infoblox_client/tests/unit/test_object_manager.py::ObjectManipulatorTestCase::test_create_dns_zone_creates_zone_auth_object",
"infoblox_client/tests/unit/test_object_manager.py::ObjectManipulatorTestCase::test_create_fixed_address_for_given_ip",
"infoblox_client/tests/unit/test_object_manager.py::ObjectManipulatorTestCase::test_create_fixed_address_from_cidr",
"infoblox_client/tests/unit/test_object_manager.py::ObjectManipulatorTestCase::test_create_fixed_address_from_range",
"infoblox_client/tests/unit/test_object_manager.py::ObjectManipulatorTestCase::test_create_host_record_creates_host_record_object",
"infoblox_client/tests/unit/test_object_manager.py::ObjectManipulatorTestCase::test_create_host_record_range_create_host_record_object",
"infoblox_client/tests/unit/test_object_manager.py::ObjectManipulatorTestCase::test_create_ip_range_creates_range_object",
"infoblox_client/tests/unit/test_object_manager.py::ObjectManipulatorTestCase::test_create_net_view_creates_network_view_object",
"infoblox_client/tests/unit/test_object_manager.py::ObjectManipulatorTestCase::test_default_net_view_is_never_deleted",
"infoblox_client/tests/unit/test_object_manager.py::ObjectManipulatorTestCase::test_delete_all_associated_objects",
"infoblox_client/tests/unit/test_object_manager.py::ObjectManipulatorTestCase::test_delete_fixed_address",
"infoblox_client/tests/unit/test_object_manager.py::ObjectManipulatorTestCase::test_delete_host_record_deletes_host_record_object",
"infoblox_client/tests/unit/test_object_manager.py::ObjectManipulatorTestCase::test_delete_ip_range_deletes_infoblox_object",
"infoblox_client/tests/unit/test_object_manager.py::ObjectManipulatorTestCase::test_delete_network_deletes_infoblox_network",
"infoblox_client/tests/unit/test_object_manager.py::ObjectManipulatorTestCase::test_delete_network_view_deletes_infoblox_object",
"infoblox_client/tests/unit/test_object_manager.py::ObjectManipulatorTestCase::test_delete_object_by_ref",
"infoblox_client/tests/unit/test_object_manager.py::ObjectManipulatorTestCase::test_get_member_gets_member_object",
"infoblox_client/tests/unit/test_object_manager.py::ObjectManipulatorTestCase::test_get_network_gets_network_object",
"infoblox_client/tests/unit/test_object_manager.py::ObjectManipulatorTestCase::test_has_networks",
"infoblox_client/tests/unit/test_object_manager.py::ObjectManipulatorTestCase::test_member_is_assigned_as_list_on_network_create",
"infoblox_client/tests/unit/test_object_manager.py::ObjectManipulatorTestCase::test_network_exists",
"infoblox_client/tests/unit/test_object_manager.py::ObjectManipulatorTestCase::test_object_is_not_created_if_already_exists",
"infoblox_client/tests/unit/test_object_manager.py::ObjectManipulatorTestCase::test_restart_services_calls_infoblox_function",
"infoblox_client/tests/unit/test_object_manager.py::ObjectManipulatorTestCase::test_throws_network_not_available_on_get_network",
"infoblox_client/tests/unit/test_object_manager.py::ObjectManipulatorTestCase::test_update_network_updates_eas_if_not_null",
"infoblox_client/tests/unit/test_object_manager.py::ObjectManipulatorTestCase::test_update_network_updates_object"
] | [] | Apache License 2.0 | 289 |
|
sympy__sympy-10119 | ab3d6f0fb676a13e4e5b48bf04072bcedd190ecd | 2015-11-05 17:08:50 | 0241b35cae5f2adc04dc37b25f7dc9c5f00bd746 | diff --git a/sympy/matrices/matrices.py b/sympy/matrices/matrices.py
index 96d2a4c295..0a61971a3e 100644
--- a/sympy/matrices/matrices.py
+++ b/sympy/matrices/matrices.py
@@ -4325,7 +4325,7 @@ def gauss_jordan_solve(self, b, freevar=False):
row, col = aug[:, :-1].shape
# solve by reduced row echelon form
- A, pivots = aug.rref()
+ A, pivots = aug.rref(simplify=True)
A, v = A[:, :-1], A[:, -1]
pivots = list(filter(lambda p: p < col, pivots))
rank = len(pivots)
diff --git a/sympy/solvers/solveset.py b/sympy/solvers/solveset.py
index 132c550e37..ae65843752 100644
--- a/sympy/solvers/solveset.py
+++ b/sympy/solvers/solveset.py
@@ -12,8 +12,8 @@
from sympy.core.numbers import I, Number, Rational, oo
from sympy.core.function import (Lambda, expand, expand_complex)
from sympy.core.relational import Eq
+from sympy.simplify.simplify import simplify, fraction, trigsimp
from sympy.core.symbol import Symbol
-from sympy.simplify.simplify import fraction, trigsimp
from sympy.functions import (log, Abs, tan, cot, sin, cos, sec, csc, exp,
acos, asin, atan, acsc, asec, arg,
Piecewise, piecewise_fold)
@@ -1210,7 +1210,7 @@ def linsolve(system, *symbols):
>>> a, b, c, d, e, f = symbols('a, b, c, d, e, f')
>>> eqns = [a*x + b*y - c, d*x + e*y - f]
>>> linsolve(eqns, x, y)
- {(-b*(f - c*d/a)/(a*(e - b*d/a)) + c/a, (f - c*d/a)/(e - b*d/a))}
+ {((-b*f + c*e)/(a*e - b*d), (a*f - c*d)/(a*e - b*d))}
* A degenerate system returns solution as set of given
symbols.
@@ -1275,11 +1275,10 @@ def linsolve(system, *symbols):
for s in sol:
for k, v in enumerate(params):
s = s.xreplace({v: symbols[free_syms[k]]})
- solution.append(s)
-
+ solution.append(simplify(s))
else:
for s in sol:
- solution.append(s)
+ solution.append(simplify(s))
# Return solutions
solution = FiniteSet(tuple(solution))
| linsolve does not find solutions that solve_linear_system does
For some overdetermined systems, `linsolve` does not find solutions which `solve_linear_system` does. For example:
```python
In [12]: from sympy.solvers.solveset import linsolve
from sympy import *
A, B, J1, J2 = symbols('A B J1 J2')
augmatrix = Matrix([
[ 2*I*J1, 2*I*J2,-2/J1],
[-2*I*J2, -2*I*J1, 2/J2],
[ 0, 2, 2*I/(J1*J2)],
[2, 0, 0],
])
linsolve(augmatrix, A, B)
solve_linear_system(augmatrix, A, B)
Out[16]: EmptySet()
Out[17]: {A: 0, B: I/(J1*J2)}
```
On the other hand:
```python
In [23]: augmatrix = Matrix([
[2*I*J2,-2/J1],
[-2*I*J1, 2/J2],
[ 2, 2*I/(J1*J2)],
])
linsolve(augmatrix, A)
solve_linear_system(augmatrix, A)
Out[24]: {(I/(J1*J2),)}
Out[25]: {A: I/(J1*J2)}
```
works fine.
I understand that this issue is problematic because `solve_linear_system` is being deprecated in favour of `linsolve`: #10000.
| sympy/sympy | diff --git a/sympy/solvers/tests/test_solveset.py b/sympy/solvers/tests/test_solveset.py
index ba77f552fc..7e2b8c389d 100644
--- a/sympy/solvers/tests/test_solveset.py
+++ b/sympy/solvers/tests/test_solveset.py
@@ -979,8 +979,7 @@ def test_linsolve():
A = Matrix([[a, b], [c, d]])
B = Matrix([[e], [f]])
system2 = (A, B)
- sol = FiniteSet((-b*(f - c*e/a)/(a*(d - b*c/a)) + e/a,
- (f - c*e/a)/(d - b*c/a)))
+ sol = FiniteSet(((-b*f + d*e)/(a*d - b*c), (a*f - c*e)/(a*d - b*c)))
assert linsolve(system2, [x, y]) == sol
# Test for Dummy Symbols issue #9667
@@ -996,6 +995,17 @@ def test_linsolve():
b = Matrix([0, 0, 1])
assert linsolve((A, b), (x, y, z)) == EmptySet()
+ # Issue #10056
+ A, B, J1, J2 = symbols('A B J1 J2')
+ Augmatrix = Matrix([
+ [2*I*J1, 2*I*J2, -2/J1],
+ [-2*I*J2, -2*I*J1, 2/J2],
+ [0, 2, 2*I/(J1*J2)],
+ [2, 0, 0],
+ ])
+
+ assert linsolve(Augmatrix, A, B) == FiniteSet((0, I/(J1*J2)))
+
# Issue #10121 - Assignment of free variables
a, b, c, d, e = symbols('a, b, c, d, e')
Augmatrix = Matrix([[0, 1, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0]])
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 1,
"issue_text_score": 0,
"test_score": 1
},
"num_modified_files": 2
} | 0.7 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "pytest",
"pip_packages": [
"mpmath>=0.19",
"pytest"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.4",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | attrs @ file:///opt/conda/conda-bld/attrs_1642510447205/work
certifi==2021.5.30
importlib-metadata @ file:///tmp/build/80754af9/importlib-metadata_1631916693255/work
iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work
more-itertools @ file:///tmp/build/80754af9/more-itertools_1637733554872/work
mpmath==1.3.0
packaging @ file:///tmp/build/80754af9/packaging_1637314298585/work
pluggy @ file:///tmp/build/80754af9/pluggy_1615976315926/work
py @ file:///opt/conda/conda-bld/py_1644396412707/work
pyparsing @ file:///tmp/build/80754af9/pyparsing_1635766073266/work
pytest==6.2.4
-e git+https://github.com/sympy/sympy.git@ab3d6f0fb676a13e4e5b48bf04072bcedd190ecd#egg=sympy
toml @ file:///tmp/build/80754af9/toml_1616166611790/work
typing_extensions @ file:///opt/conda/conda-bld/typing_extensions_1647553014482/work
zipp @ file:///tmp/build/80754af9/zipp_1633618647012/work
| name: sympy
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- attrs=21.4.0=pyhd3eb1b0_0
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2021.5.30=py36h06a4308_0
- importlib-metadata=4.8.1=py36h06a4308_0
- importlib_metadata=4.8.1=hd3eb1b0_0
- iniconfig=1.1.1=pyhd3eb1b0_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.3=he6710b0_2
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- more-itertools=8.12.0=pyhd3eb1b0_0
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- packaging=21.3=pyhd3eb1b0_0
- pip=21.2.2=py36h06a4308_0
- pluggy=0.13.1=py36h06a4308_0
- py=1.11.0=pyhd3eb1b0_0
- pyparsing=3.0.4=pyhd3eb1b0_0
- pytest=6.2.4=py36h06a4308_2
- python=3.6.13=h12debd9_1
- readline=8.2=h5eee18b_0
- setuptools=58.0.4=py36h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- toml=0.10.2=pyhd3eb1b0_0
- typing_extensions=4.1.1=pyh06a4308_0
- wheel=0.37.1=pyhd3eb1b0_0
- xz=5.6.4=h5eee18b_1
- zipp=3.6.0=pyhd3eb1b0_0
- zlib=1.2.13=h5eee18b_1
- pip:
- mpmath==1.3.0
prefix: /opt/conda/envs/sympy
| [
"sympy/solvers/tests/test_solveset.py::test_linsolve"
] | [] | [
"sympy/solvers/tests/test_solveset.py::test_invert_real",
"sympy/solvers/tests/test_solveset.py::test_invert_complex",
"sympy/solvers/tests/test_solveset.py::test_domain_check",
"sympy/solvers/tests/test_solveset.py::test_is_function_class_equation",
"sympy/solvers/tests/test_solveset.py::test_garbage_input",
"sympy/solvers/tests/test_solveset.py::test_solve_mul",
"sympy/solvers/tests/test_solveset.py::test_solve_invert",
"sympy/solvers/tests/test_solveset.py::test_errorinverses",
"sympy/solvers/tests/test_solveset.py::test_solve_polynomial",
"sympy/solvers/tests/test_solveset.py::test_return_root_of",
"sympy/solvers/tests/test_solveset.py::test__has_rational_power",
"sympy/solvers/tests/test_solveset.py::test_solveset_sqrt_1",
"sympy/solvers/tests/test_solveset.py::test_solveset_sqrt_2",
"sympy/solvers/tests/test_solveset.py::test_solve_sqrt_3",
"sympy/solvers/tests/test_solveset.py::test_solve_polynomial_symbolic_param",
"sympy/solvers/tests/test_solveset.py::test_solve_rational",
"sympy/solvers/tests/test_solveset.py::test_solveset_real_gen_is_pow",
"sympy/solvers/tests/test_solveset.py::test_no_sol",
"sympy/solvers/tests/test_solveset.py::test_sol_zero_real",
"sympy/solvers/tests/test_solveset.py::test_no_sol_rational_extragenous",
"sympy/solvers/tests/test_solveset.py::test_solve_polynomial_cv_1a",
"sympy/solvers/tests/test_solveset.py::test_solveset_real_rational",
"sympy/solvers/tests/test_solveset.py::test_solveset_real_log",
"sympy/solvers/tests/test_solveset.py::test_poly_gens",
"sympy/solvers/tests/test_solveset.py::test_solve_abs",
"sympy/solvers/tests/test_solveset.py::test_real_imag_splitting",
"sympy/solvers/tests/test_solveset.py::test_units",
"sympy/solvers/tests/test_solveset.py::test_solve_only_exp_1",
"sympy/solvers/tests/test_solveset.py::test_atan2",
"sympy/solvers/tests/test_solveset.py::test_piecewise",
"sympy/solvers/tests/test_solveset.py::test_solveset_complex_polynomial",
"sympy/solvers/tests/test_solveset.py::test_sol_zero_complex",
"sympy/solvers/tests/test_solveset.py::test_solveset_complex_rational",
"sympy/solvers/tests/test_solveset.py::test_solveset_complex_exp",
"sympy/solvers/tests/test_solveset.py::test_solve_complex_log",
"sympy/solvers/tests/test_solveset.py::test_solve_complex_sqrt",
"sympy/solvers/tests/test_solveset.py::test_solveset_complex_tan",
"sympy/solvers/tests/test_solveset.py::test_solve_trig",
"sympy/solvers/tests/test_solveset.py::test_solve_invalid_sol",
"sympy/solvers/tests/test_solveset.py::test_solve_complex_unsolvable",
"sympy/solvers/tests/test_solveset.py::test_solveset",
"sympy/solvers/tests/test_solveset.py::test_conditonset",
"sympy/solvers/tests/test_solveset.py::test_solveset_domain",
"sympy/solvers/tests/test_solveset.py::test_improve_coverage",
"sympy/solvers/tests/test_solveset.py::test_issue_9522",
"sympy/solvers/tests/test_solveset.py::test_linear_eq_to_matrix",
"sympy/solvers/tests/test_solveset.py::test_issue_9556",
"sympy/solvers/tests/test_solveset.py::test_issue_9611",
"sympy/solvers/tests/test_solveset.py::test_issue_9557",
"sympy/solvers/tests/test_solveset.py::test_issue_9778",
"sympy/solvers/tests/test_solveset.py::test_issue_9849",
"sympy/solvers/tests/test_solveset.py::test_issue_9953",
"sympy/solvers/tests/test_solveset.py::test_issue_9913"
] | [] | BSD | 290 |
|
sigmavirus24__github3.py-466 | dfbab2eb984045dc8f260dc81adf70f86d3c3e37 | 2015-11-07 00:57:43 | 05ed0c6a02cffc6ddd0e82ce840c464e1c5fd8c4 | diff --git a/AUTHORS.rst b/AUTHORS.rst
index 7bd1fec1..7d7615b9 100644
--- a/AUTHORS.rst
+++ b/AUTHORS.rst
@@ -106,3 +106,5 @@ Contributors
- Sourav Singh(@souravsingh)
- Matt Chung (@itsmemattchung)
+
+- Chris Thompson (@notyetsecure)
diff --git a/github3/issues/milestone.py b/github3/issues/milestone.py
index e55b9e74..55d86bd1 100644
--- a/github3/issues/milestone.py
+++ b/github3/issues/milestone.py
@@ -26,7 +26,9 @@ class Milestone(GitHubCore):
self.description = mile.get('description')
#: :class:`User <github3.users.User>` object representing the creator
#: of the milestone.
- self.creator = User(mile.get('creator'), self)
+ self.creator = None
+ if mile.get('creator'):
+ self.creator = User(mile.get('creator'), self)
#: Number of issues associated with this milestone which are still
#: open.
self.open_issues = mile.get('open_issues')
| Null Milestone creator causing Repository.issue() to crash
When trying to get an issue that has a Milestone without a creator, github3.py crashes.
I think the fix is simple -- add a guard check before trying to create the User for the milestone.creator (like what is done for getting the milestone from an issue -- it first checks if the milestone truth-y before acting on it).
I'm working on a PR with a regression test and a patch, which I should have up shortly.
Here's a simple test case to reproduce the exception:
```
import github3
repo = github3.repository("Code4HR", "localart")
milestone = repo.milestone(2)
```
Here's the traceback from iPython (with Python 3.5.0):
```
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-50-4132b3c2312f> in <module>()
----> 1 r.milestone(2)
python3.5/site-packages/github3/repos/repo.py in milestone(self, number)
1664 base_url=self._api)
1665 json = self._json(self._get(url), 200)
-> 1666 return Milestone(json, self) if json else None
1667
1668 @requires_auth
python3.5/site-packages/github3/issues/milestone.py in __init__(self, mile, session)
28 #: :class:`User <github3.users.User>` object representing the creator
29 #: of the milestone.
---> 30 self.creator = User(mile.get('creator'), self._session)
31 #: Number of issues associated with this milestone which are still
32 #: open.
python3.5/site-packages/github3/users.py in __init__(self, user, session)
121
122 def __init__(self, user, session=None):
--> 123 super(User, self).__init__(user, session)
124 if not self.type:
125 self.type = 'User'
python3.5/site-packages/github3/models.py in __init__(self, acct, session)
312 #: Tells you what type of account this is
313 self.type = None
--> 314 if acct.get('type'):
315 self.type = acct.get('type')
316 self._api = acct.get('url', '')
AttributeError: 'NoneType' object has no attribute 'get'
``` | sigmavirus24/github3.py | diff --git a/tests/test_issues.py b/tests/test_issues.py
index c36e3267..cdfa422b 100644
--- a/tests/test_issues.py
+++ b/tests/test_issues.py
@@ -121,6 +121,12 @@ class TestMilestone(BaseCase):
'2013-12-31T23:59:59Z')
self.mock_assertions()
+ def test_issue_465(self):
+ json = self.m.as_dict().copy()
+ json['creator'] = None
+ m = Milestone(json)
+ assert m.creator is None
+
class TestIssue(BaseCase):
def __init__(self, methodName='runTest'):
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 1,
"issue_text_score": 1,
"test_score": 0
},
"num_modified_files": 2
} | 1.0 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[test]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest",
"pytest-cov",
"pytest-xdist",
"pytest-mock",
"pytest-asyncio"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.9",
"reqs_path": [
"requirements.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | betamax==0.9.0
betamax-matchers==0.4.0
certifi==2025.1.31
charset-normalizer==3.4.1
coverage==7.8.0
exceptiongroup==1.2.2
execnet==2.1.1
-e git+https://github.com/sigmavirus24/github3.py.git@dfbab2eb984045dc8f260dc81adf70f86d3c3e37#egg=github3.py
idna==3.10
iniconfig==2.1.0
packaging==24.2
pluggy==1.5.0
pytest==8.3.5
pytest-asyncio==0.26.0
pytest-cov==6.0.0
pytest-mock==3.14.0
pytest-xdist==3.6.1
requests==2.32.3
requests-toolbelt==1.0.0
tomli==2.2.1
typing_extensions==4.13.0
uritemplate==4.1.1
uritemplate.py==3.0.2
urllib3==2.3.0
| name: github3.py
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=3.0.16=h5eee18b_0
- pip=25.0=py39h06a4308_0
- python=3.9.21=he870216_1
- readline=8.2=h5eee18b_0
- setuptools=75.8.0=py39h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- tzdata=2025a=h04d1e81_0
- wheel=0.45.1=py39h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- betamax==0.9.0
- betamax-matchers==0.4.0
- certifi==2025.1.31
- charset-normalizer==3.4.1
- coverage==7.8.0
- exceptiongroup==1.2.2
- execnet==2.1.1
- idna==3.10
- iniconfig==2.1.0
- packaging==24.2
- pluggy==1.5.0
- pytest==8.3.5
- pytest-asyncio==0.26.0
- pytest-cov==6.0.0
- pytest-mock==3.14.0
- pytest-xdist==3.6.1
- requests==2.32.3
- requests-toolbelt==1.0.0
- tomli==2.2.1
- typing-extensions==4.13.0
- uritemplate==4.1.1
- uritemplate-py==3.0.2
- urllib3==2.3.0
prefix: /opt/conda/envs/github3.py
| [
"tests/test_issues.py::TestMilestone::test_issue_465"
] | [] | [
"tests/test_issues.py::TestLabel::test_delete",
"tests/test_issues.py::TestLabel::test_equality",
"tests/test_issues.py::TestLabel::test_repr",
"tests/test_issues.py::TestLabel::test_str",
"tests/test_issues.py::TestLabel::test_update",
"tests/test_issues.py::TestMilestone::test_delete",
"tests/test_issues.py::TestMilestone::test_due_on",
"tests/test_issues.py::TestMilestone::test_id",
"tests/test_issues.py::TestMilestone::test_repr",
"tests/test_issues.py::TestMilestone::test_str",
"tests/test_issues.py::TestMilestone::test_update",
"tests/test_issues.py::TestIssue::test_add_labels",
"tests/test_issues.py::TestIssue::test_assign",
"tests/test_issues.py::TestIssue::test_close",
"tests/test_issues.py::TestIssue::test_comment",
"tests/test_issues.py::TestIssue::test_create_comment",
"tests/test_issues.py::TestIssue::test_edit",
"tests/test_issues.py::TestIssue::test_enterprise",
"tests/test_issues.py::TestIssue::test_equality",
"tests/test_issues.py::TestIssue::test_is_closed",
"tests/test_issues.py::TestIssue::test_issue_137",
"tests/test_issues.py::TestIssue::test_remove_all_labels",
"tests/test_issues.py::TestIssue::test_remove_label",
"tests/test_issues.py::TestIssue::test_reopen",
"tests/test_issues.py::TestIssue::test_replace_labels",
"tests/test_issues.py::TestIssue::test_repr",
"tests/test_issues.py::TestIssueEvent::test_equality",
"tests/test_issues.py::TestIssueEvent::test_repr"
] | [] | BSD 3-Clause "New" or "Revised" License | 291 |
|
zopefoundation__zope.publisher-9 | 57a3cee97207ab4a4f05924a07857d007109e17c | 2015-11-09 08:55:38 | 57a3cee97207ab4a4f05924a07857d007109e17c | diff --git a/src/zope/publisher/http.py b/src/zope/publisher/http.py
index 51ef486..f571f05 100644
--- a/src/zope/publisher/http.py
+++ b/src/zope/publisher/http.py
@@ -721,7 +721,7 @@ class HTTPResponse(BaseResponse):
result.append(
("X-Powered-By", "Zope (www.zope.org), Python (www.python.org)"))
- for key, values in headers.items():
+ for key, values in sorted(headers.items(), key=lambda x: x[0].lower()):
if key.lower() == key:
# only change non-literal header names
key = '-'.join([k.capitalize() for k in key.split('-')])
| Response headers are in random order
`HTTPResponse.getHeaders()` returns a list of headers in dictionary-internal order. This causes problems like https://github.com/zopefoundation/zope.app.publication/issues/3. | zopefoundation/zope.publisher | diff --git a/src/zope/publisher/tests/test_browserrequest.py b/src/zope/publisher/tests/test_browserrequest.py
index 36c1233..250f93c 100644
--- a/src/zope/publisher/tests/test_browserrequest.py
+++ b/src/zope/publisher/tests/test_browserrequest.py
@@ -152,10 +152,10 @@ class BrowserTests(HTTPTests):
self.assertEqual(
res,
"Status: 200 Ok\r\n"
+ "X-Powered-By: Zope (www.zope.org), Python (www.python.org)\r\n"
"Content-Length: 6\r\n"
"Content-Type: text/plain;charset=utf-8\r\n"
"X-Content-Type-Warning: guessed from content\r\n"
- "X-Powered-By: Zope (www.zope.org), Python (www.python.org)\r\n"
"\r\n"
"'5', 6")
diff --git a/src/zope/publisher/tests/test_http.py b/src/zope/publisher/tests/test_http.py
index 0772204..9859d6f 100644
--- a/src/zope/publisher/tests/test_http.py
+++ b/src/zope/publisher/tests/test_http.py
@@ -236,7 +236,6 @@ class HTTPTests(unittest.TestCase):
response = request.response
publish(request, handle_errors=False)
headers = response.getHeaders()
- headers.sort()
return (
"Status: %s\r\n" % response.getStatusString()
+
@@ -273,8 +272,8 @@ class HTTPTests(unittest.TestCase):
self.assertEqual(
res,
"Status: 200 Ok\r\n"
- "Content-Length: 6\r\n"
"X-Powered-By: Zope (www.zope.org), Python (www.python.org)\r\n"
+ "Content-Length: 6\r\n"
"\r\n"
"'5', 6")
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_short_problem_statement",
"has_hyperlinks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 0,
"issue_text_score": 0,
"test_score": 2
},
"num_modified_files": 1
} | 4.2 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[test]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest",
"pytest-cov",
"pytest-xdist",
"pytest-mock",
"pytest-asyncio"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.9",
"reqs_path": [
"requirements/base.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | coverage==7.8.0
exceptiongroup==1.2.2
execnet==2.1.1
iniconfig==2.1.0
packaging==24.2
pluggy==1.5.0
pytest==8.3.5
pytest-asyncio==0.26.0
pytest-cov==6.0.0
pytest-mock==3.14.0
pytest-xdist==3.6.1
python-gettext==5.0
pytz==2025.2
six==1.17.0
tomli==2.2.1
typing_extensions==4.13.0
zope.browser==3.1
zope.component==6.0
zope.configuration==6.0
zope.contenttype==5.2
zope.deprecation==5.1
zope.event==5.0
zope.exceptions==5.2
zope.hookable==7.0
zope.i18n==5.2
zope.i18nmessageid==7.0
zope.interface==7.2
zope.location==5.1
zope.proxy==6.1
-e git+https://github.com/zopefoundation/zope.publisher.git@57a3cee97207ab4a4f05924a07857d007109e17c#egg=zope.publisher
zope.schema==7.0.1
zope.security==7.3
zope.testing==5.1
| name: zope.publisher
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=3.0.16=h5eee18b_0
- pip=25.0=py39h06a4308_0
- python=3.9.21=he870216_1
- readline=8.2=h5eee18b_0
- setuptools=75.8.0=py39h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- tzdata=2025a=h04d1e81_0
- wheel=0.45.1=py39h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- coverage==7.8.0
- exceptiongroup==1.2.2
- execnet==2.1.1
- iniconfig==2.1.0
- packaging==24.2
- pluggy==1.5.0
- pytest==8.3.5
- pytest-asyncio==0.26.0
- pytest-cov==6.0.0
- pytest-mock==3.14.0
- pytest-xdist==3.6.1
- python-gettext==5.0
- pytz==2025.2
- six==1.17.0
- tomli==2.2.1
- typing-extensions==4.13.0
- zope-browser==3.1
- zope-component==6.0
- zope-configuration==6.0
- zope-contenttype==5.2
- zope-deprecation==5.1
- zope-event==5.0
- zope-exceptions==5.2
- zope-hookable==7.0
- zope-i18n==5.2
- zope-i18nmessageid==7.0
- zope-interface==7.2
- zope-location==5.1
- zope-proxy==6.1
- zope-schema==7.0.1
- zope-security==7.3
- zope-testing==5.1
prefix: /opt/conda/envs/zope.publisher
| [
"src/zope/publisher/tests/test_browserrequest.py::BrowserTests::testTraversalToItem"
] | [
"src/zope/publisher/tests/test_browserrequest.py::HTTPTests::testCookieErrorToLog",
"src/zope/publisher/tests/test_browserrequest.py::BrowserTests::testCookieErrorToLog",
"src/zope/publisher/tests/test_http.py::HTTPTests::testCookieErrorToLog",
"src/zope/publisher/tests/test_http.py::ConcreteHTTPTests::testCookieErrorToLog",
"src/zope/publisher/tests/test_http.py::TestHTTPResponse::testSetCookie"
] | [
"src/zope/publisher/tests/test_browserrequest.py::HTTPTests::testBasicAuth",
"src/zope/publisher/tests/test_browserrequest.py::HTTPTests::testCookies",
"src/zope/publisher/tests/test_browserrequest.py::HTTPTests::testCookiesUnicode",
"src/zope/publisher/tests/test_browserrequest.py::HTTPTests::testDeduceServerURL",
"src/zope/publisher/tests/test_browserrequest.py::HTTPTests::testHeaders",
"src/zope/publisher/tests/test_browserrequest.py::HTTPTests::testInterface",
"src/zope/publisher/tests/test_browserrequest.py::HTTPTests::testRedirect",
"src/zope/publisher/tests/test_browserrequest.py::HTTPTests::testRequestEnvironment",
"src/zope/publisher/tests/test_browserrequest.py::HTTPTests::testRequestLocale",
"src/zope/publisher/tests/test_browserrequest.py::HTTPTests::testResponseWriteFaile",
"src/zope/publisher/tests/test_browserrequest.py::HTTPTests::testSetPrincipal",
"src/zope/publisher/tests/test_browserrequest.py::HTTPTests::testTraversalToItem",
"src/zope/publisher/tests/test_browserrequest.py::HTTPTests::testUnicodeURLs",
"src/zope/publisher/tests/test_browserrequest.py::HTTPTests::testUnregisteredStatus",
"src/zope/publisher/tests/test_browserrequest.py::HTTPTests::testUntrustedRedirect",
"src/zope/publisher/tests/test_browserrequest.py::HTTPTests::test_PathTrailingWhitespace",
"src/zope/publisher/tests/test_browserrequest.py::HTTPTests::test_double_dots",
"src/zope/publisher/tests/test_browserrequest.py::HTTPTests::test_getVirtualHostRoot",
"src/zope/publisher/tests/test_browserrequest.py::HTTPTests::test_method",
"src/zope/publisher/tests/test_browserrequest.py::HTTPTests::test_repr",
"src/zope/publisher/tests/test_browserrequest.py::HTTPTests::test_setApplicationNames",
"src/zope/publisher/tests/test_browserrequest.py::HTTPTests::test_setApplicationServer",
"src/zope/publisher/tests/test_browserrequest.py::HTTPTests::test_setVirtualHostRoot",
"src/zope/publisher/tests/test_browserrequest.py::HTTPTests::test_traverse",
"src/zope/publisher/tests/test_browserrequest.py::HTTPTests::test_traverseDuplicateHooks",
"src/zope/publisher/tests/test_browserrequest.py::HTTPTests::test_unacceptable_charset",
"src/zope/publisher/tests/test_browserrequest.py::BrowserTests::testBadPath",
"src/zope/publisher/tests/test_browserrequest.py::BrowserTests::testBadPath2",
"src/zope/publisher/tests/test_browserrequest.py::BrowserTests::testBasicAuth",
"src/zope/publisher/tests/test_browserrequest.py::BrowserTests::testCookies",
"src/zope/publisher/tests/test_browserrequest.py::BrowserTests::testCookiesUnicode",
"src/zope/publisher/tests/test_browserrequest.py::BrowserTests::testDeduceServerURL",
"src/zope/publisher/tests/test_browserrequest.py::BrowserTests::testDefault",
"src/zope/publisher/tests/test_browserrequest.py::BrowserTests::testDefault2",
"src/zope/publisher/tests/test_browserrequest.py::BrowserTests::testDefault3",
"src/zope/publisher/tests/test_browserrequest.py::BrowserTests::testDefault4",
"src/zope/publisher/tests/test_browserrequest.py::BrowserTests::testDefault6",
"src/zope/publisher/tests/test_browserrequest.py::BrowserTests::testDefaultPOST",
"src/zope/publisher/tests/test_browserrequest.py::BrowserTests::testFileUploadPost",
"src/zope/publisher/tests/test_browserrequest.py::BrowserTests::testForm",
"src/zope/publisher/tests/test_browserrequest.py::BrowserTests::testFormAcceptsStarButNotUTF8",
"src/zope/publisher/tests/test_browserrequest.py::BrowserTests::testFormBooleanTypes",
"src/zope/publisher/tests/test_browserrequest.py::BrowserTests::testFormDefaults",
"src/zope/publisher/tests/test_browserrequest.py::BrowserTests::testFormDefaults2",
"src/zope/publisher/tests/test_browserrequest.py::BrowserTests::testFormFieldName",
"src/zope/publisher/tests/test_browserrequest.py::BrowserTests::testFormFieldValue",
"src/zope/publisher/tests/test_browserrequest.py::BrowserTests::testFormFloatTypes",
"src/zope/publisher/tests/test_browserrequest.py::BrowserTests::testFormIntTypes",
"src/zope/publisher/tests/test_browserrequest.py::BrowserTests::testFormLinesTypes",
"src/zope/publisher/tests/test_browserrequest.py::BrowserTests::testFormListRecordTypes",
"src/zope/publisher/tests/test_browserrequest.py::BrowserTests::testFormListTypes",
"src/zope/publisher/tests/test_browserrequest.py::BrowserTests::testFormListTypes2",
"src/zope/publisher/tests/test_browserrequest.py::BrowserTests::testFormLongTypes",
"src/zope/publisher/tests/test_browserrequest.py::BrowserTests::testFormMultipleRecordsTypes",
"src/zope/publisher/tests/test_browserrequest.py::BrowserTests::testFormNoEncodingUsesUTF8",
"src/zope/publisher/tests/test_browserrequest.py::BrowserTests::testFormRecordsTypes",
"src/zope/publisher/tests/test_browserrequest.py::BrowserTests::testFormRequiredTypes",
"src/zope/publisher/tests/test_browserrequest.py::BrowserTests::testFormStringTypes",
"src/zope/publisher/tests/test_browserrequest.py::BrowserTests::testFormTextTypes",
"src/zope/publisher/tests/test_browserrequest.py::BrowserTests::testFormTokensTypes",
"src/zope/publisher/tests/test_browserrequest.py::BrowserTests::testFormTupleRecordTypes",
"src/zope/publisher/tests/test_browserrequest.py::BrowserTests::testFormTupleTypes",
"src/zope/publisher/tests/test_browserrequest.py::BrowserTests::testHeaders",
"src/zope/publisher/tests/test_browserrequest.py::BrowserTests::testInterface",
"src/zope/publisher/tests/test_browserrequest.py::BrowserTests::testIssue394",
"src/zope/publisher/tests/test_browserrequest.py::BrowserTests::testIssue559",
"src/zope/publisher/tests/test_browserrequest.py::BrowserTests::testNoDefault",
"src/zope/publisher/tests/test_browserrequest.py::BrowserTests::testNoneFieldNamePost",
"src/zope/publisher/tests/test_browserrequest.py::BrowserTests::testQueryStringIgnoredForPOST",
"src/zope/publisher/tests/test_browserrequest.py::BrowserTests::testRedirect",
"src/zope/publisher/tests/test_browserrequest.py::BrowserTests::testRequestEnvironment",
"src/zope/publisher/tests/test_browserrequest.py::BrowserTests::testRequestLocale",
"src/zope/publisher/tests/test_browserrequest.py::BrowserTests::testResponseWriteFaile",
"src/zope/publisher/tests/test_browserrequest.py::BrowserTests::testSetPrincipal",
"src/zope/publisher/tests/test_browserrequest.py::BrowserTests::testUnicodeURLs",
"src/zope/publisher/tests/test_browserrequest.py::BrowserTests::testUnregisteredStatus",
"src/zope/publisher/tests/test_browserrequest.py::BrowserTests::testUntrustedRedirect",
"src/zope/publisher/tests/test_browserrequest.py::BrowserTests::test_PathTrailingWhitespace",
"src/zope/publisher/tests/test_browserrequest.py::BrowserTests::test_double_dots",
"src/zope/publisher/tests/test_browserrequest.py::BrowserTests::test_getVirtualHostRoot",
"src/zope/publisher/tests/test_browserrequest.py::BrowserTests::test_method",
"src/zope/publisher/tests/test_browserrequest.py::BrowserTests::test_post_body_not_consumed_unnecessarily",
"src/zope/publisher/tests/test_browserrequest.py::BrowserTests::test_post_body_not_necessarily",
"src/zope/publisher/tests/test_browserrequest.py::BrowserTests::test_repr",
"src/zope/publisher/tests/test_browserrequest.py::BrowserTests::test_setApplicationNames",
"src/zope/publisher/tests/test_browserrequest.py::BrowserTests::test_setApplicationServer",
"src/zope/publisher/tests/test_browserrequest.py::BrowserTests::test_setVirtualHostRoot",
"src/zope/publisher/tests/test_browserrequest.py::BrowserTests::test_traverse",
"src/zope/publisher/tests/test_browserrequest.py::BrowserTests::test_traverseDuplicateHooks",
"src/zope/publisher/tests/test_browserrequest.py::BrowserTests::test_unacceptable_charset",
"src/zope/publisher/tests/test_browserrequest.py::APITests::testEnvironment",
"src/zope/publisher/tests/test_browserrequest.py::APITests::testGetAndDefaultInMapping",
"src/zope/publisher/tests/test_browserrequest.py::APITests::testHaveCustomTestsForIApplicationRequest",
"src/zope/publisher/tests/test_browserrequest.py::APITests::testHaveCustomTestsForIPublicationRequest",
"src/zope/publisher/tests/test_browserrequest.py::APITests::testHaveCustomTestsForIPublisherRequest",
"src/zope/publisher/tests/test_browserrequest.py::APITests::testHoldCloseAndGetResponse",
"src/zope/publisher/tests/test_browserrequest.py::APITests::testIReadMapping",
"src/zope/publisher/tests/test_browserrequest.py::APITests::testPublicationManagement",
"src/zope/publisher/tests/test_browserrequest.py::APITests::testSkinManagement",
"src/zope/publisher/tests/test_browserrequest.py::APITests::testTraversalStack",
"src/zope/publisher/tests/test_browserrequest.py::APITests::testVerifyIApplicationRequest",
"src/zope/publisher/tests/test_browserrequest.py::APITests::testVerifyIPublicationRequest",
"src/zope/publisher/tests/test_browserrequest.py::APITests::testVerifyIPublisherRequest",
"src/zope/publisher/tests/test_browserrequest.py::APITests::testVerifyISkinnable",
"src/zope/publisher/tests/test_browserrequest.py::APITests::test_IApplicationRequest_bodyStream",
"src/zope/publisher/tests/test_browserrequest.py::APITests::test_IBrowserRequest",
"src/zope/publisher/tests/test_browserrequest.py::APITests::test_IPublicationRequest_getPositionalArguments",
"src/zope/publisher/tests/test_browserrequest.py::APITests::test_IPublisherRequest_processInputs",
"src/zope/publisher/tests/test_browserrequest.py::APITests::test_IPublisherRequest_retry",
"src/zope/publisher/tests/test_browserrequest.py::APITests::test_IPublisherRequest_traverse",
"src/zope/publisher/tests/test_browserrequest.py::APITests::test_ISkinnable",
"src/zope/publisher/tests/test_browserrequest.py::APITests::test___len__",
"src/zope/publisher/tests/test_browserrequest.py::APITests::test_items",
"src/zope/publisher/tests/test_browserrequest.py::APITests::test_keys",
"src/zope/publisher/tests/test_browserrequest.py::APITests::test_values",
"src/zope/publisher/tests/test_browserrequest.py::test_suite",
"src/zope/publisher/tests/test_http.py::HTTPInputStreamTests::testCachingWithContentLength",
"src/zope/publisher/tests/test_http.py::HTTPInputStreamTests::testGetCacheStream",
"src/zope/publisher/tests/test_http.py::HTTPInputStreamTests::testRead",
"src/zope/publisher/tests/test_http.py::HTTPInputStreamTests::testReadLine",
"src/zope/publisher/tests/test_http.py::HTTPInputStreamTests::testReadLines",
"src/zope/publisher/tests/test_http.py::HTTPInputStreamTests::testWorkingWithNonClosingStreams",
"src/zope/publisher/tests/test_http.py::HTTPTests::testBasicAuth",
"src/zope/publisher/tests/test_http.py::HTTPTests::testCookies",
"src/zope/publisher/tests/test_http.py::HTTPTests::testCookiesUnicode",
"src/zope/publisher/tests/test_http.py::HTTPTests::testDeduceServerURL",
"src/zope/publisher/tests/test_http.py::HTTPTests::testHeaders",
"src/zope/publisher/tests/test_http.py::HTTPTests::testInterface",
"src/zope/publisher/tests/test_http.py::HTTPTests::testRedirect",
"src/zope/publisher/tests/test_http.py::HTTPTests::testRequestEnvironment",
"src/zope/publisher/tests/test_http.py::HTTPTests::testRequestLocale",
"src/zope/publisher/tests/test_http.py::HTTPTests::testResponseWriteFaile",
"src/zope/publisher/tests/test_http.py::HTTPTests::testSetPrincipal",
"src/zope/publisher/tests/test_http.py::HTTPTests::testTraversalToItem",
"src/zope/publisher/tests/test_http.py::HTTPTests::testUnicodeURLs",
"src/zope/publisher/tests/test_http.py::HTTPTests::testUnregisteredStatus",
"src/zope/publisher/tests/test_http.py::HTTPTests::testUntrustedRedirect",
"src/zope/publisher/tests/test_http.py::HTTPTests::test_PathTrailingWhitespace",
"src/zope/publisher/tests/test_http.py::HTTPTests::test_double_dots",
"src/zope/publisher/tests/test_http.py::HTTPTests::test_getVirtualHostRoot",
"src/zope/publisher/tests/test_http.py::HTTPTests::test_method",
"src/zope/publisher/tests/test_http.py::HTTPTests::test_repr",
"src/zope/publisher/tests/test_http.py::HTTPTests::test_setApplicationNames",
"src/zope/publisher/tests/test_http.py::HTTPTests::test_setApplicationServer",
"src/zope/publisher/tests/test_http.py::HTTPTests::test_setVirtualHostRoot",
"src/zope/publisher/tests/test_http.py::HTTPTests::test_traverse",
"src/zope/publisher/tests/test_http.py::HTTPTests::test_traverseDuplicateHooks",
"src/zope/publisher/tests/test_http.py::HTTPTests::test_unacceptable_charset",
"src/zope/publisher/tests/test_http.py::ConcreteHTTPTests::testBasicAuth",
"src/zope/publisher/tests/test_http.py::ConcreteHTTPTests::testCookies",
"src/zope/publisher/tests/test_http.py::ConcreteHTTPTests::testCookiesUnicode",
"src/zope/publisher/tests/test_http.py::ConcreteHTTPTests::testDeduceServerURL",
"src/zope/publisher/tests/test_http.py::ConcreteHTTPTests::testHeaders",
"src/zope/publisher/tests/test_http.py::ConcreteHTTPTests::testInterface",
"src/zope/publisher/tests/test_http.py::ConcreteHTTPTests::testRedirect",
"src/zope/publisher/tests/test_http.py::ConcreteHTTPTests::testRequestEnvironment",
"src/zope/publisher/tests/test_http.py::ConcreteHTTPTests::testRequestLocale",
"src/zope/publisher/tests/test_http.py::ConcreteHTTPTests::testResponseWriteFaile",
"src/zope/publisher/tests/test_http.py::ConcreteHTTPTests::testSetPrincipal",
"src/zope/publisher/tests/test_http.py::ConcreteHTTPTests::testTraversalToItem",
"src/zope/publisher/tests/test_http.py::ConcreteHTTPTests::testUnicodeURLs",
"src/zope/publisher/tests/test_http.py::ConcreteHTTPTests::testUnregisteredStatus",
"src/zope/publisher/tests/test_http.py::ConcreteHTTPTests::testUntrustedRedirect",
"src/zope/publisher/tests/test_http.py::ConcreteHTTPTests::test_PathTrailingWhitespace",
"src/zope/publisher/tests/test_http.py::ConcreteHTTPTests::test_double_dots",
"src/zope/publisher/tests/test_http.py::ConcreteHTTPTests::test_getVirtualHostRoot",
"src/zope/publisher/tests/test_http.py::ConcreteHTTPTests::test_method",
"src/zope/publisher/tests/test_http.py::ConcreteHTTPTests::test_non_existing_charset",
"src/zope/publisher/tests/test_http.py::ConcreteHTTPTests::test_repr",
"src/zope/publisher/tests/test_http.py::ConcreteHTTPTests::test_setApplicationNames",
"src/zope/publisher/tests/test_http.py::ConcreteHTTPTests::test_setApplicationServer",
"src/zope/publisher/tests/test_http.py::ConcreteHTTPTests::test_setVirtualHostRoot",
"src/zope/publisher/tests/test_http.py::ConcreteHTTPTests::test_shiftNameToApplication",
"src/zope/publisher/tests/test_http.py::ConcreteHTTPTests::test_traverse",
"src/zope/publisher/tests/test_http.py::ConcreteHTTPTests::test_traverseDuplicateHooks",
"src/zope/publisher/tests/test_http.py::ConcreteHTTPTests::test_unacceptable_charset",
"src/zope/publisher/tests/test_http.py::TestHTTPResponse::testContentLength",
"src/zope/publisher/tests/test_http.py::TestHTTPResponse::testContentType",
"src/zope/publisher/tests/test_http.py::TestHTTPResponse::testInterface",
"src/zope/publisher/tests/test_http.py::TestHTTPResponse::testWrite_noContentLength",
"src/zope/publisher/tests/test_http.py::TestHTTPResponse::test_handleException",
"src/zope/publisher/tests/test_http.py::APITests::testEnvironment",
"src/zope/publisher/tests/test_http.py::APITests::testGetAndDefaultInMapping",
"src/zope/publisher/tests/test_http.py::APITests::testHaveCustomTestsForIApplicationRequest",
"src/zope/publisher/tests/test_http.py::APITests::testHaveCustomTestsForIPublicationRequest",
"src/zope/publisher/tests/test_http.py::APITests::testHaveCustomTestsForIPublisherRequest",
"src/zope/publisher/tests/test_http.py::APITests::testHoldCloseAndGetResponse",
"src/zope/publisher/tests/test_http.py::APITests::testIReadMapping",
"src/zope/publisher/tests/test_http.py::APITests::testPublicationManagement",
"src/zope/publisher/tests/test_http.py::APITests::testSkinManagement",
"src/zope/publisher/tests/test_http.py::APITests::testTraversalStack",
"src/zope/publisher/tests/test_http.py::APITests::testVerifyIApplicationRequest",
"src/zope/publisher/tests/test_http.py::APITests::testVerifyIPublicationRequest",
"src/zope/publisher/tests/test_http.py::APITests::testVerifyIPublisherRequest",
"src/zope/publisher/tests/test_http.py::APITests::test_IApplicationRequest_bodyStream",
"src/zope/publisher/tests/test_http.py::APITests::test_IPublicationRequest_getPositionalArguments",
"src/zope/publisher/tests/test_http.py::APITests::test_IPublisherRequest_processInputs",
"src/zope/publisher/tests/test_http.py::APITests::test_IPublisherRequest_retry",
"src/zope/publisher/tests/test_http.py::APITests::test_IPublisherRequest_traverse",
"src/zope/publisher/tests/test_http.py::APITests::test___len__",
"src/zope/publisher/tests/test_http.py::APITests::test_items",
"src/zope/publisher/tests/test_http.py::APITests::test_keys",
"src/zope/publisher/tests/test_http.py::APITests::test_values",
"src/zope/publisher/tests/test_http.py::test_suite"
] | [] | Zope Public License 2.1 | 292 |
|
msgpack__msgpack-python-158 | c8513898e222a91ad7f6520aa8a4a5a1711cdc65 | 2015-11-09 18:54:44 | 0e2021d3a3d1218ca191f4e802df0af3bbfaa51f | diff --git a/.travis.yml b/.travis.yml
index eced353..7695184 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -1,18 +1,18 @@
sudo: false
-cache:
- directories:
- - $HOME/.cache/pip
+cache: pip
language: python
python:
- - 3.5
+ - 2.7
branches:
only:
- master
env:
- - TOXENV=py27-c,py33-c,py34-c,py35-c
- - TOXENV=py27-pure,py33-pure,py34-pure,py35-pure
+ - TOXENV=py26-c,py27-c
+ - TOXENV=py32-c,py33-c,py34-c
+ - TOXENV=py26-pure,py27-pure
+ - TOXENV=py32-pure,py33-pure,py34-pure
- TOXENV=pypy-pure,pypy3-pure
install:
diff --git a/ChangeLog.rst b/ChangeLog.rst
index f20bb75..35535b4 100644
--- a/ChangeLog.rst
+++ b/ChangeLog.rst
@@ -1,6 +1,6 @@
0.4.7
=====
-:release date: 2016-01-25
+:release date: TBD
Bugs fixed
----------
diff --git a/msgpack/_packer.pyx b/msgpack/_packer.pyx
index 6392655..7c1e53d 100644
--- a/msgpack/_packer.pyx
+++ b/msgpack/_packer.pyx
@@ -63,6 +63,13 @@ cdef class Packer(object):
:param bool use_bin_type:
Use bin type introduced in msgpack spec 2.0 for bytes.
It also enable str8 type for unicode.
+ :param bool strict_types:
+ If set to true, types will be checked to be exact. Derived classes
+ from serializeable types will not be serialized and will be
+ treated as unsupported type and forwarded to default.
+ Additionally tuples will not be serialized as lists.
+ This is useful when trying to implement accurate serialization
+ for python types.
"""
cdef msgpack_packer pk
cdef object _default
@@ -70,6 +77,7 @@ cdef class Packer(object):
cdef object _berrors
cdef char *encoding
cdef char *unicode_errors
+ cdef bint strict_types
cdef bool use_float
cdef bint autoreset
@@ -82,10 +90,12 @@ cdef class Packer(object):
self.pk.length = 0
def __init__(self, default=None, encoding='utf-8', unicode_errors='strict',
- use_single_float=False, bint autoreset=1, bint use_bin_type=0):
+ use_single_float=False, bint autoreset=1, bint use_bin_type=0,
+ bint strict_types=0):
"""
"""
self.use_float = use_single_float
+ self.strict_types = strict_types
self.autoreset = autoreset
self.pk.use_bin_type = use_bin_type
if default is not None:
@@ -121,6 +131,7 @@ cdef class Packer(object):
cdef dict d
cdef size_t L
cdef int default_used = 0
+ cdef bint strict_types = self.strict_types
if nest_limit < 0:
raise PackValueError("recursion limit exceeded.")
@@ -128,12 +139,12 @@ cdef class Packer(object):
while True:
if o is None:
ret = msgpack_pack_nil(&self.pk)
- elif isinstance(o, bool):
+ elif PyBool_Check(o) if strict_types else isinstance(o, bool):
if o:
ret = msgpack_pack_true(&self.pk)
else:
ret = msgpack_pack_false(&self.pk)
- elif PyLong_Check(o):
+ elif PyLong_CheckExact(o) if strict_types else PyLong_Check(o):
# PyInt_Check(long) is True for Python 3.
# So we should test long before int.
try:
@@ -150,17 +161,17 @@ cdef class Packer(object):
continue
else:
raise
- elif PyInt_Check(o):
+ elif PyInt_CheckExact(o) if strict_types else PyInt_Check(o):
longval = o
ret = msgpack_pack_long(&self.pk, longval)
- elif PyFloat_Check(o):
+ elif PyFloat_CheckExact(o) if strict_types else PyFloat_Check(o):
if self.use_float:
fval = o
ret = msgpack_pack_float(&self.pk, fval)
else:
dval = o
ret = msgpack_pack_double(&self.pk, dval)
- elif PyBytes_Check(o):
+ elif PyBytes_CheckExact(o) if strict_types else PyBytes_Check(o):
L = len(o)
if L > (2**32)-1:
raise ValueError("bytes is too large")
@@ -168,17 +179,17 @@ cdef class Packer(object):
ret = msgpack_pack_bin(&self.pk, L)
if ret == 0:
ret = msgpack_pack_raw_body(&self.pk, rawval, L)
- elif PyUnicode_Check(o):
+ elif PyUnicode_CheckExact(o) if strict_types else PyUnicode_Check(o):
if not self.encoding:
raise TypeError("Can't encode unicode string: no encoding is specified")
o = PyUnicode_AsEncodedString(o, self.encoding, self.unicode_errors)
L = len(o)
if L > (2**32)-1:
- raise ValueError("unicode string is too large")
+ raise ValueError("dict is too large")
rawval = o
- ret = msgpack_pack_raw(&self.pk, L)
+ ret = msgpack_pack_raw(&self.pk, len(o))
if ret == 0:
- ret = msgpack_pack_raw_body(&self.pk, rawval, L)
+ ret = msgpack_pack_raw_body(&self.pk, rawval, len(o))
elif PyDict_CheckExact(o):
d = <dict>o
L = len(d)
@@ -191,7 +202,7 @@ cdef class Packer(object):
if ret != 0: break
ret = self._pack(v, nest_limit-1)
if ret != 0: break
- elif PyDict_Check(o):
+ elif not strict_types and PyDict_Check(o):
L = len(o)
if L > (2**32)-1:
raise ValueError("dict is too large")
@@ -202,7 +213,7 @@ cdef class Packer(object):
if ret != 0: break
ret = self._pack(v, nest_limit-1)
if ret != 0: break
- elif isinstance(o, ExtType):
+ elif type(o) is ExtType if strict_types else isinstance(o, ExtType):
# This should be before Tuple because ExtType is namedtuple.
longval = o.code
rawval = o.data
@@ -211,7 +222,7 @@ cdef class Packer(object):
raise ValueError("EXT data is too large")
ret = msgpack_pack_ext(&self.pk, longval, L)
ret = msgpack_pack_raw_body(&self.pk, rawval, L)
- elif PyTuple_Check(o) or PyList_Check(o):
+ elif PyList_CheckExact(o) if strict_types else (PyTuple_Check(o) or PyList_Check(o)):
L = len(o)
if L > (2**32)-1:
raise ValueError("list is too large")
diff --git a/msgpack/_unpacker.pyx b/msgpack/_unpacker.pyx
index 1aefc64..aec3b7d 100644
--- a/msgpack/_unpacker.pyx
+++ b/msgpack/_unpacker.pyx
@@ -209,7 +209,7 @@ cdef class Unpacker(object):
:param int max_buffer_size:
Limits size of data waiting unpacked. 0 means system's INT_MAX (default).
Raises `BufferFull` exception when it is insufficient.
- You shoud set this parameter when unpacking data from untrusted source.
+ You shoud set this parameter when unpacking data from untrasted source.
:param int max_str_len:
Limits max length of str. (default: 2**31-1)
diff --git a/msgpack/_version.py b/msgpack/_version.py
index 37c172d..2c1c96c 100644
--- a/msgpack/_version.py
+++ b/msgpack/_version.py
@@ -1,1 +1,1 @@
-version = (0, 4, 7)
+version = (0, 4, 6)
diff --git a/msgpack/fallback.py b/msgpack/fallback.py
index f682611..11280ed 100644
--- a/msgpack/fallback.py
+++ b/msgpack/fallback.py
@@ -69,6 +69,13 @@ TYPE_EXT = 5
DEFAULT_RECURSE_LIMIT = 511
+def _check_type_strict(obj, t, type=type, tuple=tuple):
+ if type(t) is tuple:
+ return type(obj) in t
+ else:
+ return type(obj) is t
+
+
def unpack(stream, **kwargs):
"""
Unpack an object from `stream`.
@@ -138,7 +145,7 @@ class Unpacker(object):
:param int max_buffer_size:
Limits size of data waiting unpacked. 0 means system's INT_MAX (default).
Raises `BufferFull` exception when it is insufficient.
- You shoud set this parameter when unpacking data from untrusted source.
+ You shoud set this parameter when unpacking data from untrasted source.
:param int max_str_len:
Limits max length of str. (default: 2**31-1)
@@ -609,9 +616,18 @@ class Packer(object):
:param bool use_bin_type:
Use bin type introduced in msgpack spec 2.0 for bytes.
It also enable str8 type for unicode.
+ :param bool strict_types:
+ If set to true, types will be checked to be exact. Derived classes
+ from serializeable types will not be serialized and will be
+ treated as unsupported type and forwarded to default.
+ Additionally tuples will not be serialized as lists.
+ This is useful when trying to implement accurate serialization
+ for python types.
"""
def __init__(self, default=None, encoding='utf-8', unicode_errors='strict',
- use_single_float=False, autoreset=True, use_bin_type=False):
+ use_single_float=False, autoreset=True, use_bin_type=False,
+ strict_types=False):
+ self._strict_types = strict_types
self._use_float = use_single_float
self._autoreset = autoreset
self._use_bin_type = use_bin_type
@@ -623,18 +639,24 @@ class Packer(object):
raise TypeError("default must be callable")
self._default = default
- def _pack(self, obj, nest_limit=DEFAULT_RECURSE_LIMIT, isinstance=isinstance):
+ def _pack(self, obj, nest_limit=DEFAULT_RECURSE_LIMIT,
+ check=isinstance, check_type_strict=_check_type_strict):
default_used = False
+ if self._strict_types:
+ check = check_type_strict
+ list_types = list
+ else:
+ list_types = (list, tuple)
while True:
if nest_limit < 0:
raise PackValueError("recursion limit exceeded")
if obj is None:
return self._buffer.write(b"\xc0")
- if isinstance(obj, bool):
+ if check(obj, bool):
if obj:
return self._buffer.write(b"\xc3")
return self._buffer.write(b"\xc2")
- if isinstance(obj, int_types):
+ if check(obj, int_types):
if 0 <= obj < 0x80:
return self._buffer.write(struct.pack("B", obj))
if -0x20 <= obj < 0:
@@ -660,7 +682,7 @@ class Packer(object):
default_used = True
continue
raise PackValueError("Integer value out of range")
- if self._use_bin_type and isinstance(obj, bytes):
+ if self._use_bin_type and check(obj, bytes):
n = len(obj)
if n <= 0xff:
self._buffer.write(struct.pack('>BB', 0xc4, n))
@@ -671,8 +693,8 @@ class Packer(object):
else:
raise PackValueError("Bytes is too large")
return self._buffer.write(obj)
- if isinstance(obj, (Unicode, bytes)):
- if isinstance(obj, Unicode):
+ if check(obj, (Unicode, bytes)):
+ if check(obj, Unicode):
if self._encoding is None:
raise TypeError(
"Can't encode unicode string: "
@@ -690,11 +712,11 @@ class Packer(object):
else:
raise PackValueError("String is too large")
return self._buffer.write(obj)
- if isinstance(obj, float):
+ if check(obj, float):
if self._use_float:
return self._buffer.write(struct.pack(">Bf", 0xca, obj))
return self._buffer.write(struct.pack(">Bd", 0xcb, obj))
- if isinstance(obj, ExtType):
+ if check(obj, ExtType):
code = obj.code
data = obj.data
assert isinstance(code, int)
@@ -719,13 +741,13 @@ class Packer(object):
self._buffer.write(struct.pack("b", code))
self._buffer.write(data)
return
- if isinstance(obj, (list, tuple)):
+ if check(obj, list_types):
n = len(obj)
self._fb_pack_array_header(n)
for i in xrange(n):
self._pack(obj[i], nest_limit - 1)
return
- if isinstance(obj, dict):
+ if check(obj, dict):
return self._fb_pack_map_pairs(len(obj), dict_iteritems(obj),
nest_limit - 1)
if not default_used and self._default is not None:
diff --git a/tox.ini b/tox.ini
index b6e7a7f..15feb51 100644
--- a/tox.ini
+++ b/tox.ini
@@ -1,5 +1,5 @@
[tox]
-envlist = {py27,py33,py34,py35}-{c,pure},{pypy,pypy3}-pure,py27-x86,py34-x86
+envlist = {py26,py27,py32,py33,py34}-{c,pure},{pypy,pypy3}-pure,py27-x86,py34-x86
[variants:pure]
setenv=
@@ -36,3 +36,4 @@ commands=
python -c 'import sys; print(hex(sys.maxsize))'
python -c 'from msgpack import _packer, _unpacker'
py.test
+
| Serialization of namedtuples
So I saw this referenced in the issue "Allow custom encoding (not character encoding but default function encoding) of unicode strings #73" and was wondering of there's a work around or any plans to implement a fix in the future.
I'm using version 0.4.6 and as far as I can tell there's no way to define custom serialization of namedtuples (or any object that inherits from native python types msgpack-python supports) with the current implementation. The problem is that any class that inherits from tuple somewhere in their class hierarchy will return True for isinstance(obj, (tuple)), which will not give the user's default callable a chance to run. On solution I see (after a brief code review) is as simple as moving the if block that calls the self._default function from the bottom to right after the `if obj is None:` block. | msgpack/msgpack-python | diff --git a/test/test_stricttype.py b/test/test_stricttype.py
new file mode 100644
index 0000000..a20b5eb
--- /dev/null
+++ b/test/test_stricttype.py
@@ -0,0 +1,15 @@
+# coding: utf-8
+
+from collections import namedtuple
+from msgpack import packb, unpackb
+
+
+def test_namedtuple():
+ T = namedtuple('T', "foo bar")
+ def default(o):
+ if isinstance(o, T):
+ return dict(o._asdict())
+ raise TypeError('Unsupported type %s' % (type(o),))
+ packed = packb(T(1, 42), strict_types=True, use_bin_type=True, default=default)
+ unpacked = unpackb(packed, encoding='utf-8')
+ assert unpacked == {'foo': 1, 'bar': 42}
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_issue_reference",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 2,
"issue_text_score": 1,
"test_score": 2
},
"num_modified_files": 7
} | 0.4 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[dev]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "pytest",
"pip_packages": [
"pytest"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.5",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | attrs @ file:///opt/conda/conda-bld/attrs_1642510447205/work
certifi==2021.5.30
importlib-metadata @ file:///tmp/build/80754af9/importlib-metadata_1631916693255/work
iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work
more-itertools @ file:///tmp/build/80754af9/more-itertools_1637733554872/work
-e git+https://github.com/msgpack/msgpack-python.git@c8513898e222a91ad7f6520aa8a4a5a1711cdc65#egg=msgpack_python
packaging @ file:///tmp/build/80754af9/packaging_1637314298585/work
pluggy @ file:///tmp/build/80754af9/pluggy_1615976315926/work
py @ file:///opt/conda/conda-bld/py_1644396412707/work
pyparsing @ file:///tmp/build/80754af9/pyparsing_1635766073266/work
pytest==6.2.4
toml @ file:///tmp/build/80754af9/toml_1616166611790/work
typing_extensions @ file:///opt/conda/conda-bld/typing_extensions_1647553014482/work
zipp @ file:///tmp/build/80754af9/zipp_1633618647012/work
| name: msgpack-python
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- attrs=21.4.0=pyhd3eb1b0_0
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2021.5.30=py36h06a4308_0
- importlib-metadata=4.8.1=py36h06a4308_0
- importlib_metadata=4.8.1=hd3eb1b0_0
- iniconfig=1.1.1=pyhd3eb1b0_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.3=he6710b0_2
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- more-itertools=8.12.0=pyhd3eb1b0_0
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- packaging=21.3=pyhd3eb1b0_0
- pip=21.2.2=py36h06a4308_0
- pluggy=0.13.1=py36h06a4308_0
- py=1.11.0=pyhd3eb1b0_0
- pyparsing=3.0.4=pyhd3eb1b0_0
- pytest=6.2.4=py36h06a4308_2
- python=3.6.13=h12debd9_1
- readline=8.2=h5eee18b_0
- setuptools=58.0.4=py36h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- toml=0.10.2=pyhd3eb1b0_0
- typing_extensions=4.1.1=pyh06a4308_0
- wheel=0.37.1=pyhd3eb1b0_0
- xz=5.6.4=h5eee18b_1
- zipp=3.6.0=pyhd3eb1b0_0
- zlib=1.2.13=h5eee18b_1
prefix: /opt/conda/envs/msgpack-python
| [
"test/test_stricttype.py::test_namedtuple"
] | [] | [] | [] | Apache License 2.0 | 293 |
|
craffel__mir_eval-157 | 3a6a8ce53eb7974db52104a834210b505b43f711 | 2015-11-10 21:04:57 | 4a35625bf2bbbd71d15916f634d563b3878ac5d0 | diff --git a/mir_eval/sonify.py b/mir_eval/sonify.py
index 23703e3..66a8319 100644
--- a/mir_eval/sonify.py
+++ b/mir_eval/sonify.py
@@ -125,7 +125,7 @@ def time_frequency(gram, frequencies, times, fs, function=np.sin, length=None):
return output
-def chroma(chromagram, times, fs):
+def chroma(chromagram, times, fs, **kwargs):
"""Reverse synthesis of a chromagram (semitone matrix)
Parameters
@@ -138,6 +138,9 @@ def chroma(chromagram, times, fs):
The start time of each column in the chromagram
fs : int
Sampling rate to synthesize audio data at
+ kwargs
+ Additional keyword arguments to pass to
+ :func:`mir_eval.sonify.time_frequency`
Returns
-------
@@ -165,10 +168,10 @@ def chroma(chromagram, times, fs):
gram *= shepard_weight.reshape(-1, 1)
# Compute frequencies
frequencies = 440.0*(2.0**((notes - 69)/12.0))
- return time_frequency(gram, frequencies, times, fs)
+ return time_frequency(gram, frequencies, times, fs, **kwargs)
-def chords(chord_labels, intervals, fs):
+def chords(chord_labels, intervals, fs, **kwargs):
"""Synthesizes chord labels
Parameters
@@ -179,6 +182,9 @@ def chords(chord_labels, intervals, fs):
Start and end times of each chord label
fs : int
Sampling rate to synthesize at
+ kwargs
+ Additional keyword arguments to pass to
+ :func:`mir_eval.sonify.time_frequency`
Returns
-------
@@ -200,4 +206,4 @@ def chords(chord_labels, intervals, fs):
chromagram = np.array([np.roll(interval_bitmap, root)
for (interval_bitmap, root)
in zip(interval_bitmaps, roots)]).T
- return chroma(chromagram, times, fs)
+ return chroma(chromagram, times, fs, **kwargs)
| sonify.chroma and sonify.chords should pass **kwargs to time_frequency
So that `length` and `function` can be set. | craffel/mir_eval | diff --git a/tests/test_sonify.py b/tests/test_sonify.py
index 03a2ec4..a1975c9 100644
--- a/tests/test_sonify.py
+++ b/tests/test_sonify.py
@@ -36,6 +36,10 @@ def test_chroma():
np.random.standard_normal((12, 1000)),
np.linspace(0, 10, 1000), fs)
assert len(signal) == 10*fs
+ signal = mir_eval.sonify.chroma(
+ np.random.standard_normal((12, 1000)),
+ np.linspace(0, 10, 1000), fs, length=fs*11)
+ assert len(signal) == 11*fs
def test_chords():
@@ -45,3 +49,7 @@ def test_chords():
['C', 'C:maj', 'D:min7', 'E:min', 'C#', 'C', 'C', 'C', 'C', 'C'],
intervals, fs)
assert len(signal) == 10*fs
+ signal = mir_eval.sonify.chords(
+ ['C', 'C:maj', 'D:min7', 'E:min', 'C#', 'C', 'C', 'C', 'C', 'C'],
+ intervals, fs, length=fs*11)
+ assert len(signal) == 11*fs
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 0,
"issue_text_score": 0,
"test_score": 1
},
"num_modified_files": 1
} | 0.1 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "numpy>=1.7.0 scipy>=0.9.0 future six",
"pip_packages": [
"nose",
"pep8",
"pytest"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.9",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | exceptiongroup==1.2.2
future @ file:///croot/future_1730902796226/work
iniconfig==2.1.0
-e git+https://github.com/craffel/mir_eval.git@3a6a8ce53eb7974db52104a834210b505b43f711#egg=mir_eval
nose==1.3.7
numpy @ file:///croot/numpy_and_numpy_base_1736283260865/work/dist/numpy-2.0.2-cp39-cp39-linux_x86_64.whl#sha256=3387e3e62932fa288bc18e8f445ce19e998b418a65ed2064dd40a054f976a6c7
packaging==24.2
pep8==1.7.1
pluggy==1.5.0
pytest==8.3.5
scipy @ file:///croot/scipy_1733756309941/work/dist/scipy-1.13.1-cp39-cp39-linux_x86_64.whl#sha256=3b247b926209f2d9f719ebae39faf3ff891b2596150ed8f8349adfc3eb19441c
six @ file:///tmp/build/80754af9/six_1644875935023/work
tomli==2.2.1
| name: mir_eval
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- blas=1.0=openblas
- ca-certificates=2025.2.25=h06a4308_0
- future=1.0.0=py39h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgfortran-ng=11.2.0=h00389a5_1
- libgfortran5=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libopenblas=0.3.21=h043d6bf_0
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- numpy=2.0.2=py39heeff2f4_0
- numpy-base=2.0.2=py39h8a23956_0
- openssl=3.0.16=h5eee18b_0
- pip=25.0=py39h06a4308_0
- pybind11-abi=4=hd3eb1b0_1
- python=3.9.21=he870216_1
- readline=8.2=h5eee18b_0
- scipy=1.13.1=py39heeff2f4_1
- setuptools=72.1.0=py39h06a4308_0
- six=1.16.0=pyhd3eb1b0_1
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- tzdata=2025a=h04d1e81_0
- wheel=0.45.1=py39h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- exceptiongroup==1.2.2
- iniconfig==2.1.0
- nose==1.3.7
- packaging==24.2
- pep8==1.7.1
- pluggy==1.5.0
- pytest==8.3.5
- tomli==2.2.1
prefix: /opt/conda/envs/mir_eval
| [
"tests/test_sonify.py::test_chroma"
] | [
"tests/test_sonify.py::test_clicks",
"tests/test_sonify.py::test_chords"
] | [
"tests/test_sonify.py::test_time_frequency"
] | [] | MIT License | 294 |
|
tomerfiliba__plumbum-243 | 0db72571329ef8f8167b93c7cd9d737dfb37ebbf | 2015-11-11 06:35:45 | d24e80c5364a777a2393c3acb24a7a7220f023fc | diff --git a/plumbum/cli/progress.py b/plumbum/cli/progress.py
index 3ca68b2..080c80a 100644
--- a/plumbum/cli/progress.py
+++ b/plumbum/cli/progress.py
@@ -103,9 +103,9 @@ class ProgressBase(six.ABC):
pass
@classmethod
- def range(cls, *value, **kargs):
+ def range(cls, value, **kargs):
"""Fast shortcut to create a range based progress bar, assumes work done in body"""
- return cls(range(*value), body=True, **kargs)
+ return cls(range(value), value, body=True, **kargs)
@classmethod
def wrap(cls, iterator, length=None, **kargs):
diff --git a/plumbum/commands/base.py b/plumbum/commands/base.py
index f20ee15..900f0ce 100644
--- a/plumbum/commands/base.py
+++ b/plumbum/commands/base.py
@@ -5,6 +5,7 @@ from plumbum.commands.processes import run_proc, iter_lines
from plumbum.lib import six
from tempfile import TemporaryFile
from subprocess import PIPE, Popen
+from types import MethodType
class RedirectionError(Exception):
@@ -296,6 +297,16 @@ class Pipeline(BaseCommand):
dstproc.returncode = rc_src or rc_dst
return dstproc.returncode
dstproc.wait = wait2
+
+ dstproc_verify = dstproc.verify
+ def verify(proc, retcode, timeout, stdout, stderr):
+ #TODO: right now it's impossible to specify different expected
+ # return codes for different stages of the pipeline, but we
+ # should make that possible.
+ proc.srcproc.verify(retcode, timeout, stdout, stderr)
+ dstproc_verify(retcode, timeout, stdout, stderr)
+ dstproc.verify = MethodType(verify, dstproc)
+
return dstproc
class BaseRedirection(BaseCommand):
diff --git a/plumbum/commands/processes.py b/plumbum/commands/processes.py
index 2129dde..06a5dca 100644
--- a/plumbum/commands/processes.py
+++ b/plumbum/commands/processes.py
@@ -20,18 +20,7 @@ except ImportError:
# utility functions
#===================================================================================================
def _check_process(proc, retcode, timeout, stdout, stderr):
- if getattr(proc, "_timed_out", False):
- raise ProcessTimedOut("Process did not terminate within %s seconds" % (timeout,),
- getattr(proc, "argv", None))
-
- if retcode is not None:
- if hasattr(retcode, "__contains__"):
- if proc.returncode not in retcode:
- raise ProcessExecutionError(getattr(proc, "argv", None), proc.returncode,
- stdout, stderr)
- elif proc.returncode != retcode:
- raise ProcessExecutionError(getattr(proc, "argv", None), proc.returncode,
- stdout, stderr)
+ proc.verify(retcode, timeout, stdout, stderr)
return proc.returncode, stdout, stderr
def _iter_lines(proc, decode, linesize):
diff --git a/plumbum/machines/base.py b/plumbum/machines/base.py
index 109f4f3..a384e4d 100644
--- a/plumbum/machines/base.py
+++ b/plumbum/machines/base.py
@@ -1,4 +1,21 @@
from plumbum.commands.processes import CommandNotFound
+from plumbum.commands.processes import ProcessExecutionError
+from plumbum.commands.processes import ProcessTimedOut
+
+class PopenAddons(object):
+ def verify(self, retcode, timeout, stdout, stderr):
+ if getattr(self, "_timed_out", False):
+ raise ProcessTimedOut("Process did not terminate within %s seconds" % (timeout,),
+ getattr(self, "argv", None))
+
+ if retcode is not None:
+ if hasattr(retcode, "__contains__"):
+ if self.returncode not in retcode:
+ raise ProcessExecutionError(getattr(self, "argv", None), self.returncode,
+ stdout, stderr)
+ elif self.returncode != retcode:
+ raise ProcessExecutionError(getattr(self, "argv", None), self.returncode,
+ stdout, stderr)
class BaseMachine(object):
diff --git a/plumbum/machines/local.py b/plumbum/machines/local.py
index e821c25..0cd64e5 100644
--- a/plumbum/machines/local.py
+++ b/plumbum/machines/local.py
@@ -16,6 +16,7 @@ from plumbum.lib import ProcInfo, IS_WIN32, six, StaticProperty
from plumbum.commands.daemons import win32_daemonize, posix_daemonize
from plumbum.commands.processes import iter_lines
from plumbum.machines.base import BaseMachine
+from plumbum.machines.base import PopenAddons
from plumbum.machines.env import BaseEnv
if sys.version_info >= (3, 2):
@@ -31,11 +32,12 @@ else:
from subprocess import Popen, PIPE
has_new_subprocess = False
-class IterablePopen(Popen):
+class IterablePopen(Popen, PopenAddons):
iter_lines = iter_lines
def __iter__(self):
return self.iter_lines()
+
logger = logging.getLogger("plumbum.local")
diff --git a/plumbum/machines/paramiko_machine.py b/plumbum/machines/paramiko_machine.py
index 43c5ed1..8f45ad8 100644
--- a/plumbum/machines/paramiko_machine.py
+++ b/plumbum/machines/paramiko_machine.py
@@ -2,6 +2,7 @@ import logging
import errno
import stat
import socket
+from plumbum.machines.base import PopenAddons
from plumbum.machines.remote import BaseRemoteMachine
from plumbum.machines.session import ShellSession
from plumbum.lib import _setdoc, six
@@ -23,7 +24,7 @@ except ImportError:
logger = logging.getLogger("plumbum.paramiko")
-class ParamikoPopen(object):
+class ParamikoPopen(PopenAddons):
def __init__(self, argv, stdin, stdout, stderr, encoding, stdin_file = None,
stdout_file = None, stderr_file = None):
self.argv = argv
diff --git a/plumbum/machines/session.py b/plumbum/machines/session.py
index 3767294..43b4b37 100644
--- a/plumbum/machines/session.py
+++ b/plumbum/machines/session.py
@@ -4,6 +4,7 @@ import logging
import threading
from plumbum.commands import BaseCommand, run_proc
from plumbum.lib import six
+from plumbum.machines.base import PopenAddons
class ShellSessionError(Exception):
@@ -53,7 +54,7 @@ class MarkedPipe(object):
return line
-class SessionPopen(object):
+class SessionPopen(PopenAddons):
"""A shell-session-based ``Popen``-like object (has the following attributes: ``stdin``,
``stdout``, ``stderr``, ``returncode``)"""
def __init__(self, argv, isatty, stdin, stdout, stderr, encoding):
| ProcessExecutionError is misleading when piped commands fail
Relates to #145
```
Type "help", "copyright", "credits" or "license" for more information.
>>> from plumbum.cmd import cat, head
>>> from plumbum import FG
>>> (cat['/dev/urndom'] | head['-c', '10']) & FG()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/nail/home/josnyder/consul-backups/env/local/lib/python2.7/site-packages/plumbum/commands/modifiers.py", line 143, in __rand__
cmd(retcode = self.retcode, stdin = None, stdout = None, stderr = None)
File "/nail/home/josnyder/consul-backups/env/local/lib/python2.7/site-packages/plumbum/commands/base.py", line 89, in __call__
return self.run(args, **kwargs)[1]
File "/nail/home/josnyder/consul-backups/env/local/lib/python2.7/site-packages/plumbum/commands/base.py", line 219, in run
return p.run()
File "/nail/home/josnyder/consul-backups/env/local/lib/python2.7/site-packages/plumbum/commands/base.py", line 181, in runner
return run_proc(p, retcode, timeout)
File "/nail/home/josnyder/consul-backups/env/local/lib/python2.7/site-packages/plumbum/commands/processes.py", line 217, in run_proc
return _check_process(proc, retcode, timeout, stdout, stderr)
File "/nail/home/josnyder/consul-backups/env/local/lib/python2.7/site-packages/plumbum/commands/processes.py", line 34, in _check_process
stdout, stderr)
plumbum.commands.processes.ProcessExecutionError: Command line: ['/usr/bin/head', '-c', '10']
Exit code: 1
```
In this example, the process which failed is the cat process. The exception message is misleading, because it implies that the head process failed. | tomerfiliba/plumbum | diff --git a/tests/test_local.py b/tests/test_local.py
index d5bd458..a1fadcd 100644
--- a/tests/test_local.py
+++ b/tests/test_local.py
@@ -7,6 +7,7 @@ from plumbum import (local, LocalPath, FG, BG, TF, RETCODE, ERROUT,
CommandNotFound, ProcessExecutionError, ProcessTimedOut)
from plumbum.lib import six, IS_WIN32
from plumbum.fs.atomic import AtomicFile, AtomicCounterFile, PidFile
+from plumbum.machines.local import LocalCommand
from plumbum.path import RelativePath
import plumbum
from plumbum._testtools import (skipIf, skip_on_windows,
@@ -295,13 +296,26 @@ class LocalMachineTest(unittest.TestCase):
def test_run(self):
from plumbum.cmd import ls, grep
- rc, out, err = (ls | grep["non_exist1N9"]).run(retcode = 1)
+ rc, out, err = (ls | grep["non_exist1N9"]).run(retcode = (0, 1))
self.assertEqual(rc, 1)
def test_timeout(self):
from plumbum.cmd import sleep
self.assertRaises(ProcessTimedOut, sleep, 10, timeout = 5)
+ @skip_on_windows
+ def test_fair_error_attribution(self):
+ # use LocalCommand directly for predictable argv
+ false = LocalCommand('false')
+ true = LocalCommand('true')
+ try:
+ (false | true) & FG
+ except ProcessExecutionError as e:
+ self.assertEqual(e.argv, ['false'])
+ else:
+ self.fail("Expected a ProcessExecutionError")
+
+
@skip_on_windows
def test_iter_lines_timeout(self):
from plumbum.cmd import ping
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 2,
"issue_text_score": 0,
"test_score": 3
},
"num_modified_files": 7
} | 1.6 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.5",
"reqs_path": [
"dev-requirements.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | attrs==22.2.0
bcrypt==4.0.1
certifi==2021.5.30
cffi==1.15.1
cryptography==40.0.2
importlib-metadata==4.8.3
iniconfig==1.1.1
packaging==21.3
paramiko==3.5.1
pluggy==1.0.0
-e git+https://github.com/tomerfiliba/plumbum.git@0db72571329ef8f8167b93c7cd9d737dfb37ebbf#egg=plumbum
py==1.11.0
pycparser==2.21
PyNaCl==1.5.0
pyparsing==3.1.4
pytest==7.0.1
tomli==1.2.3
typing_extensions==4.1.1
zipp==3.6.0
| name: plumbum
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2021.5.30=py36h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.3=he6710b0_2
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- pip=21.2.2=py36h06a4308_0
- python=3.6.13=h12debd9_1
- readline=8.2=h5eee18b_0
- setuptools=58.0.4=py36h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- wheel=0.37.1=pyhd3eb1b0_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- attrs==22.2.0
- bcrypt==4.0.1
- cffi==1.15.1
- cryptography==40.0.2
- importlib-metadata==4.8.3
- iniconfig==1.1.1
- packaging==21.3
- paramiko==3.5.1
- pluggy==1.0.0
- py==1.11.0
- pycparser==2.21
- pynacl==1.5.0
- pyparsing==3.1.4
- pytest==7.0.1
- tomli==1.2.3
- typing-extensions==4.1.1
- zipp==3.6.0
prefix: /opt/conda/envs/plumbum
| [
"tests/test_local.py::LocalMachineTest::test_fair_error_attribution"
] | [
"tests/test_local.py::LocalMachineTest::test_arg_expansion",
"tests/test_local.py::LocalMachineTest::test_as_user",
"tests/test_local.py::LocalMachineTest::test_atomic_counter",
"tests/test_local.py::LocalMachineTest::test_atomic_file2",
"tests/test_local.py::LocalMachineTest::test_bound_env",
"tests/test_local.py::LocalMachineTest::test_cwd",
"tests/test_local.py::LocalMachineTest::test_env",
"tests/test_local.py::LocalMachineTest::test_imports",
"tests/test_local.py::LocalMachineTest::test_iter_lines_error",
"tests/test_local.py::LocalMachineTest::test_iter_lines_timeout",
"tests/test_local.py::LocalMachineTest::test_list_processes",
"tests/test_local.py::LocalMachineTest::test_local",
"tests/test_local.py::LocalMachineTest::test_mixing_chdir",
"tests/test_local.py::LocalMachineTest::test_modifiers",
"tests/test_local.py::LocalMachineTest::test_path",
"tests/test_local.py::LocalMachineTest::test_pgrep",
"tests/test_local.py::LocalMachineTest::test_pid_file",
"tests/test_local.py::LocalMachineTest::test_pipeline_failure",
"tests/test_local.py::LocalMachineTest::test_piping",
"tests/test_local.py::LocalMachineTest::test_popen",
"tests/test_local.py::LocalMachineTest::test_quoting",
"tests/test_local.py::LocalMachineTest::test_redirection",
"tests/test_local.py::LocalMachineTest::test_run",
"tests/test_local.py::LocalMachineTest::test_session",
"tests/test_local.py::LocalMachineTest::test_timeout"
] | [
"tests/test_local.py::LocalPathTest::test_chown",
"tests/test_local.py::LocalPathTest::test_compare_pathlib",
"tests/test_local.py::LocalPathTest::test_dirname",
"tests/test_local.py::LocalPathTest::test_name",
"tests/test_local.py::LocalPathTest::test_newname",
"tests/test_local.py::LocalPathTest::test_parts",
"tests/test_local.py::LocalPathTest::test_read_write",
"tests/test_local.py::LocalPathTest::test_relative_to",
"tests/test_local.py::LocalPathTest::test_root_drive",
"tests/test_local.py::LocalPathTest::test_split",
"tests/test_local.py::LocalPathTest::test_stem",
"tests/test_local.py::LocalPathTest::test_suffix",
"tests/test_local.py::LocalPathTest::test_suffix_expected",
"tests/test_local.py::LocalPathTest::test_uri",
"tests/test_local.py::LocalMachineTest::test_atomic_counter2",
"tests/test_local.py::LocalMachineTest::test_atomic_file",
"tests/test_local.py::LocalMachineTest::test_contains",
"tests/test_local.py::LocalMachineTest::test_direct_open_tmpdir",
"tests/test_local.py::LocalMachineTest::test_get",
"tests/test_local.py::LocalMachineTest::test_getattr",
"tests/test_local.py::LocalMachineTest::test_issue_139",
"tests/test_local.py::LocalMachineTest::test_links",
"tests/test_local.py::LocalMachineTest::test_local_daemon",
"tests/test_local.py::LocalMachineTest::test_nesting_lists_as_argv",
"tests/test_local.py::LocalMachineTest::test_read_write",
"tests/test_local.py::LocalMachineTest::test_shadowed_by_dir",
"tests/test_local.py::LocalMachineTest::test_tempdir"
] | [] | MIT License | 295 |
|
refnx__refnx-15 | 828e06645c2d04138505c4b22b1348e4a92ffa82 | 2015-11-12 03:41:18 | 568a56132fe0cd8418cff41ffedfc276bdb99af4 | diff --git a/refnx/dataset/data1d.py b/refnx/dataset/data1d.py
index 11737c90..cc231aca 100644
--- a/refnx/dataset/data1d.py
+++ b/refnx/dataset/data1d.py
@@ -1,5 +1,5 @@
""""
- A basic representation of a 1D dataset
+A basic representation of a 1D dataset
"""
from __future__ import division
@@ -12,25 +12,24 @@ import refnx.util.nsplice as nsplice
class Data1D(object):
"""
A basic representation of a 1D dataset.
- """
+ Parameters
+ ----------
+ data_tuple : tuple of np.ndarray, optional
+ Tuple containing the data. The tuple should have between 2 and 4
+ members.
+ data_tuple[0] - x
+ data_tuple[1] - y
+ data_tuple[2] - standard deviation of y, y_sd
+ data_tuple[3] - standard deviation of x, x_sd
+
+ `data_tuple` must be at least two long, `x` and `y`.
+ If the tuple is at least 3 long then the third member is `y_sd`.
+ If the tuple is 4 long then the fourth member is `x_sd`.
+ All arrays must have the same shape.
+ """
def __init__(self, data_tuple=None, curvefitter=None):
- """
- Parameters
- ----------
- dataTuple : tuple of np.ndarray, optional
- Tuple containing the data. The tuple should have between 2 and 4
- members.
- data_tuple[0] - x
- data_tuple[1] - y
- data_tuple[2] - standard deviation of y, y_sd
- data_tuple[3] - standard deviation of x, x_sd
-
- `data_tuple` must be at least two long, `x` and `y`.
- If the tuple is at least 3 long then the third member is `y_sd`.
- If the tuple is 4 long then the fourth member is `x_sd`.
- All arrays must have the same shape.
- """
+
self.filename = None
self.fit = None
self.params = None
diff --git a/refnx/dataset/reflectdataset.py b/refnx/dataset/reflectdataset.py
index e6b4fad9..a18958d2 100644
--- a/refnx/dataset/reflectdataset.py
+++ b/refnx/dataset/reflectdataset.py
@@ -52,8 +52,9 @@ class ReflectDataset(Data1D):
Parameters
----------
- f : file-like
- The file to save the data to.
+ f : str or file-like
+ The file to write the spectrum to, or a str that specifies the file
+ name
"""
s = string.Template(self._template_ref_xml)
self.time = strftime("%a, %d %b %Y %H:%M:%S +0000", gmtime())
@@ -66,7 +67,17 @@ class ReflectDataset(Data1D):
self._xdataSD = repr(self.x_sd.tolist()).strip(',[]')
thefile = s.safe_substitute(self.__dict__)
- f.write(thefile)
+
+ auto_fh = None
+ g = f
+ if not hasattr(f, 'write'):
+ auto_fh = open(f, 'wb')
+ g = auto_fh
+
+ g.write(thefile.encode('utf-8'))
+
+ if auto_fh is not None:
+ auto_fh.close()
def load(self, f):
"""
@@ -75,13 +86,14 @@ class ReflectDataset(Data1D):
Parameters
----------
f : str or file-like
- File to load reflectivity data from.
+ The file to load the spectrum from, or a str that specifies the file
+ name
"""
- own_fh = None
+ auto_fh = None
g = f
if not hasattr(f, 'read'):
- own_fh = open(f, 'rb')
- g = own_fh
+ auto_fh = open(f, 'rb')
+ g = auto_fh
try:
tree = ET.ElementTree()
tree.parse(g)
@@ -103,5 +115,5 @@ class ReflectDataset(Data1D):
g.seek(0)
super(ReflectDataset, self).load(g)
finally:
- if own_fh is not None:
- own_fh.close()
\ No newline at end of file
+ if auto_fh is not None:
+ auto_fh.close()
diff --git a/refnx/reduce/event.py b/refnx/reduce/event.py
index 038341dc..1718255d 100644
--- a/refnx/reduce/event.py
+++ b/refnx/reduce/event.py
@@ -1,7 +1,6 @@
# -*- coding: utf-8 -*-
"""
-unpack streaming file
-@author: andrew
+Unpack event files
"""
import numpy as np
@@ -70,7 +69,7 @@ def process_event_stream(events, frame_bins, t_bins, y_bins, x_bins):
return detector, localframe_bins
-def events(f, endoflastevent=127, max_frames=np.inf):
+def events(f, end_last_event=127, max_frames=np.inf):
"""
Unpacks event data from packedbinary format for the ANSTO Platypus
instrument
@@ -78,27 +77,29 @@ def events(f, endoflastevent=127, max_frames=np.inf):
Parameters
----------
- f : file
- The file to read the data from.
- endoflastevent : uint
- The file position to start the read from. The data starts from byte
- 127.
+ f : file-like or str
+ The file to read the data from. If `f` is not file-like then f is
+ assumed to be a path pointing to the event file.
+ end_last_event : uint
+ The reading of event data starts from `end_last_event + 1`. The default
+ of 127 corresponds to a file header that is 128 bytes long.
max_frames : int
- Stop reading the event file when you get to this many frames.
+ Stop reading the event file when have read this many frames.
Returns
-------
- (f_events, t_events, y_events, x_events), endoflastevent:
+ (f_events, t_events, y_events, x_events), end_last_event:
x_events, y_events, t_events and f_events are numpy arrays containing
- the events. endoflastevent is a byte offset to the end of the last
+ the events. end_last_event is a byte offset to the end of the last
successful event read from the file. Use this value to extract more
events from the same file at a future date.
"""
- if not f:
- return None
+ fi = f
+ auto_f = None
+ if not hasattr(fi, 'read'):
+ auto_f = open(f, 'rb')
+ fi = auto_f
- state = 0
- event_ended = 0
frame_number = -1
dt = 0
t = 0
@@ -110,7 +111,7 @@ def events(f, endoflastevent=127, max_frames=np.inf):
t_events = np.array((), dtype='uint32')
f_events = np.array((), dtype='int32')
- BUFSIZE = 32768
+ bufsize = 32768
while True and frame_number < max_frames:
x_neutrons = []
@@ -118,10 +119,10 @@ def events(f, endoflastevent=127, max_frames=np.inf):
t_neutrons = []
f_neutrons = []
- f.seek(endoflastevent + 1)
- buf = f.read(BUFSIZE)
+ fi.seek(end_last_event + 1)
+ buf = fi.read(bufsize)
- filepos = endoflastevent + 1
+ filepos = end_last_event + 1
if not len(buf):
break
@@ -142,7 +143,7 @@ def events(f, endoflastevent=127, max_frames=np.inf):
state += 1
else:
if state == 2:
- y = y | ((c & 0xF) * 64)
+ y |= (c & 0xF) * 64
if y & 0x200:
y = -(0x100000000 - (y | 0xFFFFFC00))
@@ -153,14 +154,14 @@ def events(f, endoflastevent=127, max_frames=np.inf):
if state == 2:
dt = c >> 4
else:
- dt |= (c) << (2 + 6 * (state - 3))
+ dt |= c << 2 + 6 * (state - 3)
if not event_ended:
state += 1
else:
- #print "got to state", state, event_ended, x, y, frame_number, t, dt
+ # print "got to state", state, event_ended, x, y, frame_number, t, dt
state = 0
- endoflastevent = filepos + i
+ end_last_event = filepos + i
if x == 0 and y == 0 and dt == 0xFFFFFFFF:
t = 0
frame_number += 1
@@ -181,5 +182,9 @@ def events(f, endoflastevent=127, max_frames=np.inf):
t_events = np.append(t_events, t_neutrons)
f_events = np.append(f_events, f_neutrons)
- t_events = t_events // 1000
- return (f_events, t_events, y_events, x_events), endoflastevent
\ No newline at end of file
+ t_events //= 1000
+
+ if auto_f:
+ auto_f.close()
+
+ return (f_events, t_events, y_events, x_events), end_last_event
diff --git a/refnx/reduce/platypusnexus.py b/refnx/reduce/platypusnexus.py
index 51026ba3..e85c6cce 100644
--- a/refnx/reduce/platypusnexus.py
+++ b/refnx/reduce/platypusnexus.py
@@ -886,20 +886,21 @@ class PlatypusNexus(object):
Parameters
----------
- f : file-like object
- The file to write the spectrum to
+ f : file-like or str
+ The file to write the spectrum to, or a str that specifies the file
+ name
scanpoint : int
- Which scanpoint to write.
+ Which scanpoint to write
"""
if self.processed_spectrum is None:
return False
m_lambda = self.processed_spectrum['m_lambda'][scanpoint]
m_spec = self.processed_spectrum['m_spec'][scanpoint]
- m_spec_sd = self.processed_spectrum['m_spec'][scanpoint]
- m_lambda_sd = self.processed_spectrum['m_lambda_sd'][scanpoint]
+ m_spec_sd = self.processed_spectrum['m_spec_sd'][scanpoint]
+ m_lambda_fwhm = self.processed_spectrum['m_lambda_fwhm'][scanpoint]
- stacked_data = np.c_[m_lambda, m_spec, m_spec_sd, m_lambda_sd]
+ stacked_data = np.c_[m_lambda, m_spec, m_spec_sd, m_lambda_fwhm]
np.savetxt(f, stacked_data, delimiter='\t')
return True
@@ -911,12 +912,12 @@ class PlatypusNexus(object):
Parameters
----------
- f : file-like object
- The file to write the spectrum to
+ f : file-like or str
+ The file to write the spectrum to, or a str that specifies the file
+ name
scanpoint : int
- Which scanpoint to write.
+ Which scanpoint to write
"""
-
spectrum_template = """<?xml version="1.0"?>
<REFroot xmlns="">
<REFentry time="$time">
@@ -930,7 +931,6 @@ class PlatypusNexus(object):
</REFdata>
</REFentry>
</REFroot>"""
-
if self.processed_spectrum is None:
return
@@ -941,26 +941,37 @@ class PlatypusNexus(object):
m_lambda = self.processed_spectrum['m_lambda']
m_spec = self.processed_spectrum['m_spec']
- m_spec_sd = self.processed_spectrum['m_spec']
- m_lambda_sd = self.processed_spectrum['m_lambda_sd']
+ m_spec_sd = self.processed_spectrum['m_spec_sd']
+ m_lambda_fwhm = self.processed_spectrum['m_lambda_fwhm']
# sort the data
sorted = np.argsort(self.m_lambda[0])
r = m_spec[:, sorted]
l = m_lambda[:, sorted]
- dl = m_lambda_sd[:, sorted]
+ dl = m_lambda_fwhm [:, sorted]
dr = m_spec_sd[:, sorted]
d['n_spectra'] = self.processed_spectrum['n_spectra']
d['runnumber'] = 'PLP{:07d}'.format(self.cat.datafile_number)
- d['r'] = string.translate(repr(r[scanpoint].tolist()), None, ',[]')
- d['dr'] = string.translate(repr(dr[scanpoint].tolist()), None, ',[]')
- d['l'] = string.translate(repr(l[scanpoint].tolist()), None, ',[]')
- d['dl'] = string.translate(repr(dl[scanpoint].tolist()), None, ',[]')
+ d['r'] = repr(r[scanpoint].tolist()).strip(',[]')
+ d['dr'] = repr(dr[scanpoint].tolist()).strip(',[]')
+ d['l'] = repr(l[scanpoint].tolist()).strip(',[]')
+ d['dl'] = repr(dl[scanpoint].tolist()).strip(',[]')
thefile = s.safe_substitute(d)
- f.write(thefile)
- f.truncate()
+
+ g = f
+ auto_fh = None
+
+ if not hasattr(f, 'write'):
+ auto_fh = open(f, 'wb')
+ g = auto_fh
+
+ g.write(thefile.encode('utf-8'))
+ g.truncate()
+
+ if auto_fh is not None:
+ auto_fh.close()
return True
@@ -968,8 +979,8 @@ class PlatypusNexus(object):
def spectrum(self):
return (self.processed_spectrum['m_lambda'],
self.processed_spectrum['m_spec'],
- self.processed_spectrum['m_spec'],
- self.processed_spectrum['m_lambda_sd'])
+ self.processed_spectrum['m_spec_sd'],
+ self.processed_spectrum['m_lambda_fwhm'])
def create_detector_norm(h5norm, x_min, x_max):
diff --git a/refnx/reduce/reduce.py b/refnx/reduce/reduce.py
index 3f9b7f21..b487a5a5 100644
--- a/refnx/reduce/reduce.py
+++ b/refnx/reduce/reduce.py
@@ -402,7 +402,7 @@ class ReducePlatypus(object):
with open(fname, 'wb') as f:
dataset.save(f)
fname = 'PLP{0:07d}_{1}.xml'.format(self.datafile_number, i)
- with open(fname, 'w') as f:
+ with open(fname, 'wb') as f:
dataset.save_xml(f)
reduction['fname'] = fnames
@@ -481,7 +481,7 @@ def reduce_stitch(reflect_list, direct_list, norm_file_num=None,
with open(fname, 'wb') as f:
combined_dataset.save(f)
fname = 'c_PLP{0:07d}.xml'.format(reflect_list[0])
- with open(fname, 'w') as f:
+ with open(fname, 'wb') as f:
combined_dataset.save_xml(f)
return combined_dataset, fname
diff --git a/refnx/util/general.py b/refnx/util/general.py
index 122e55fc..66fd567a 100644
--- a/refnx/util/general.py
+++ b/refnx/util/general.py
@@ -1,4 +1,7 @@
#!/usr/bin/python
+"""
+Functions for various calculations related to reflectometry
+"""
from __future__ import division
import numpy as np
| PlatypusNexus.write_spectrum_xml doesn't work.
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-7-1d0132abf492> in <module>()
----> 1 f.write_spectrum_xml('PLP0024619.spec')
C:\Miniconda3\envs\dev3\lib\site-packages\refnx\reduce\platypusnexus.py in write_spectrum_xml(self, f, scanpoint)
953 d['runnumber'] = 'PLP{:07d}'.format(self.cat.datafile_number)
954
--> 955 d['r'] = string.translate(repr(r[scanpoint].tolist()), None, ',[]')
956 d['dr'] = string.translate(repr(dr[scanpoint].tolist()), None, ',[]')
957 d['l'] = string.translate(repr(l[scanpoint].tolist()), None, ',[]')
AttributeError: 'module' object has no attribute 'translate | refnx/refnx | diff --git a/refnx/dataset/test/test_reflectdataset.py b/refnx/dataset/test/test_reflectdataset.py
index 2bfbab6e..36cfa16f 100644
--- a/refnx/dataset/test/test_reflectdataset.py
+++ b/refnx/dataset/test/test_reflectdataset.py
@@ -10,8 +10,15 @@ path = os.path.dirname(os.path.abspath(__file__))
class TestReflectDataset(unittest.TestCase):
def setUp(self):
- pass
-
+ data = ReflectDataset()
+
+ x1 = np.linspace(0, 10, 5)
+ y1 = 2 * x1
+ e1 = np.ones_like(x1)
+ dx1 = np.ones_like(x1)
+ data.add_data((x1, y1, e1, dx1))
+ self.data = data
+
def test_load(self):
# test reflectivity calculation with values generated from Motofit
dataset = ReflectDataset()
@@ -77,6 +84,10 @@ class TestReflectDataset(unittest.TestCase):
assert_(data.npoints==13)
+ def test_save_xml(self):
+ self.data.save_xml('test.xml')
+ with open('test.xml', 'wb') as f:
+ self.data.save_xml(f)
if __name__ == '__main__':
unittest.main()
\ No newline at end of file
diff --git a/refnx/reduce/test/test_event.py b/refnx/reduce/test/test_event.py
index 072b0815..25257484 100644
--- a/refnx/reduce/test/test_event.py
+++ b/refnx/reduce/test/test_event.py
@@ -32,6 +32,13 @@ class TestEvent(unittest.TestCase):
max_f = np.max(f)
assert_equal(9, max_f)
+ def test_open_with_path(self):
+ # give the event reader a file path
+ event_list, fpos = event.events(self.event_file_path, max_frames=10)
+ f, t, y, x = event_list
+ max_f = np.max(f)
+ assert_equal(9, max_f)
+
def test_values(self):
# We know the values of all the events in the file from another program
# test that a set of random events are correct.
diff --git a/refnx/reduce/test/test_platypusnexus.py b/refnx/reduce/test/test_platypusnexus.py
index 706121ae..62bc03ab 100644
--- a/refnx/reduce/test/test_platypusnexus.py
+++ b/refnx/reduce/test/test_platypusnexus.py
@@ -144,6 +144,22 @@ class TestPlatypusNexus(unittest.TestCase):
assert_array_less(res, np.ones_like(res) * 0.08)
assert_array_less(np.ones_like(res) * 0.07, res)
+ def test_save_spectrum(self):
+ # test saving spectrum
+ self.f113.process()
+
+ # can save the spectra by supplying a filename
+ self.f113.write_spectrum_xml('test.xml')
+ self.f113.write_spectrum_dat('test.dat')
+
+ # can save by supplying file handle:
+ with open('test.xml', 'wb') as f:
+ self.f113.write_spectrum_xml(f)
+
+ # can save by supplying file handle:
+ with open('test.dat', 'wb') as f:
+ self.f113.write_spectrum_xml(f)
+
if __name__ == '__main__':
unittest.main()
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 2,
"issue_text_score": 2,
"test_score": 2
},
"num_modified_files": 6
} | 0.0 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[dev]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "numpy>=1.16.0 scipy>=1.0.0 emcee>=2.2.1 six>=1.11.0 uncertainties>=3.0.1 pandas>=0.23.4 pytest>=3.6.0 h5py>=2.8.0 xlrd>=1.1.0 ptemcee>=1.0.0",
"pip_packages": [
"pytest"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.6",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | asteval==0.9.26
attrs @ file:///opt/conda/conda-bld/attrs_1642510447205/work
certifi==2021.5.30
emcee @ file:///home/conda/feedstock_root/build_artifacts/emcee_1713796893786/work
future==0.18.2
h5py @ file:///tmp/build/80754af9/h5py_1593454121459/work
importlib-metadata @ file:///tmp/build/80754af9/importlib-metadata_1631916693255/work
iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work
lmfit==1.0.3
more-itertools @ file:///tmp/build/80754af9/more-itertools_1637733554872/work
numpy @ file:///tmp/build/80754af9/numpy_and_numpy_base_1603483703303/work
packaging @ file:///tmp/build/80754af9/packaging_1637314298585/work
pandas==1.1.5
pluggy @ file:///tmp/build/80754af9/pluggy_1615976315926/work
ptemcee==1.0.0
py @ file:///opt/conda/conda-bld/py_1644396412707/work
pyparsing @ file:///tmp/build/80754af9/pyparsing_1635766073266/work
pytest==6.2.4
python-dateutil @ file:///tmp/build/80754af9/python-dateutil_1626374649649/work
pytz==2021.3
-e git+https://github.com/refnx/refnx.git@828e06645c2d04138505c4b22b1348e4a92ffa82#egg=refnx
scipy @ file:///tmp/build/80754af9/scipy_1597686635649/work
six @ file:///tmp/build/80754af9/six_1644875935023/work
toml @ file:///tmp/build/80754af9/toml_1616166611790/work
typing_extensions @ file:///opt/conda/conda-bld/typing_extensions_1647553014482/work
uncertainties @ file:///home/conda/feedstock_root/build_artifacts/uncertainties_1720452225073/work
xlrd @ file:///croot/xlrd_1685030938141/work
zipp @ file:///tmp/build/80754af9/zipp_1633618647012/work
| name: refnx
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- attrs=21.4.0=pyhd3eb1b0_0
- blas=1.0=openblas
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2021.5.30=py36h06a4308_0
- emcee=3.1.6=pyhd8ed1ab_0
- future=0.18.2=py36_1
- h5py=2.10.0=py36hd6299e0_1
- hdf5=1.10.6=hb1b8bf9_0
- importlib-metadata=4.8.1=py36h06a4308_0
- importlib_metadata=4.8.1=hd3eb1b0_0
- iniconfig=1.1.1=pyhd3eb1b0_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.3=he6710b0_2
- libgcc-ng=11.2.0=h1234567_1
- libgfortran-ng=7.5.0=ha8ba4b0_17
- libgfortran4=7.5.0=ha8ba4b0_17
- libgomp=11.2.0=h1234567_1
- libopenblas=0.3.18=hf726d26_0
- libstdcxx-ng=11.2.0=h1234567_1
- more-itertools=8.12.0=pyhd3eb1b0_0
- ncurses=6.4=h6a678d5_0
- numpy=1.19.2=py36h6163131_0
- numpy-base=1.19.2=py36h75fe3a5_0
- openssl=1.1.1w=h7f8727e_0
- packaging=21.3=pyhd3eb1b0_0
- pandas=1.1.5=py36ha9443f7_0
- pip=21.2.2=py36h06a4308_0
- pluggy=0.13.1=py36h06a4308_0
- ptemcee=1.0.0=py_0
- py=1.11.0=pyhd3eb1b0_0
- pyparsing=3.0.4=pyhd3eb1b0_0
- pytest=6.2.4=py36h06a4308_2
- python=3.6.13=h12debd9_1
- python-dateutil=2.8.2=pyhd3eb1b0_0
- pytz=2021.3=pyhd3eb1b0_0
- readline=8.2=h5eee18b_0
- scipy=1.5.2=py36habc2bb6_0
- setuptools=58.0.4=py36h06a4308_0
- six=1.16.0=pyhd3eb1b0_1
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- toml=0.10.2=pyhd3eb1b0_0
- typing_extensions=4.1.1=pyh06a4308_0
- uncertainties=3.2.2=pyhd8ed1ab_1
- wheel=0.37.1=pyhd3eb1b0_0
- xlrd=2.0.1=pyhd3eb1b0_1
- xz=5.6.4=h5eee18b_1
- zipp=3.6.0=pyhd3eb1b0_0
- zlib=1.2.13=h5eee18b_1
- pip:
- asteval==0.9.26
- lmfit==1.0.3
prefix: /opt/conda/envs/refnx
| [
"refnx/dataset/test/test_reflectdataset.py::TestReflectDataset::test_save_xml",
"refnx/reduce/test/test_event.py::TestEvent::test_open_with_path"
] | [
"refnx/reduce/test/test_platypusnexus.py::TestPlatypusNexus::test_calculate_bins",
"refnx/reduce/test/test_platypusnexus.py::TestPlatypusNexus::test_event",
"refnx/reduce/test/test_platypusnexus.py::TestPlatypusNexus::test_reduction_runs",
"refnx/reduce/test/test_platypusnexus.py::TestPlatypusNexus::test_save_spectrum"
] | [
"refnx/dataset/test/test_reflectdataset.py::TestReflectDataset::test_add_data",
"refnx/dataset/test/test_reflectdataset.py::TestReflectDataset::test_load",
"refnx/reduce/test/test_event.py::TestEvent::test_max_frames",
"refnx/reduce/test/test_event.py::TestEvent::test_num_events",
"refnx/reduce/test/test_event.py::TestEvent::test_process_event_stream",
"refnx/reduce/test/test_event.py::TestEvent::test_values",
"refnx/reduce/test/test_platypusnexus.py::TestPlatypusNexus::test_background_subtract",
"refnx/reduce/test/test_platypusnexus.py::TestPlatypusNexus::test_background_subtract_line",
"refnx/reduce/test/test_platypusnexus.py::TestPlatypusNexus::test_chod",
"refnx/reduce/test/test_platypusnexus.py::TestPlatypusNexus::test_find_specular_ridge",
"refnx/reduce/test/test_platypusnexus.py::TestPlatypusNexus::test_multiple_acquisitions",
"refnx/reduce/test/test_platypusnexus.py::TestPlatypusNexus::test_phase_angle"
] | [] | BSD 3-Clause "New" or "Revised" License | 296 |
|
sympy__sympy-10135 | 81cc72003d4a58d0fbd1425b8b16a1b6ddec7010 | 2015-11-12 04:45:40 | 0241b35cae5f2adc04dc37b25f7dc9c5f00bd746 | diff --git a/sympy/matrices/matrices.py b/sympy/matrices/matrices.py
index 80a6a9c1a5..3a248551eb 100644
--- a/sympy/matrices/matrices.py
+++ b/sympy/matrices/matrices.py
@@ -4336,11 +4336,8 @@ def gauss_jordan_solve(self, b, freevar=False):
if not v[rank:, 0].is_zero:
raise ValueError("Linear system has no solution")
- # Get index of free symbols (free parameter)
- free_var_index = []
- for r in range(col):
- if r not in pivots:
- free_var_index.append(r) # non-pivots columns are free variables
+ # Get index of free symbols (free parameters)
+ free_var_index = permutation[len(pivots):] # non-pivots columns are free variables
# Free parameters
dummygen = numbered_symbols("tau", Dummy)
| Incorrect circular references in solutions from linsolve in underdetermined systems
**Edit**: See comment below pinpointing the problem and providing a possible solution
I am sorry that this is hardly a minimal working example, but this is a real world problem and though I've been playing around with it I can't reproduce it with simpler systems:
```python
V, f, J = symbols('V f J')
freevars_gen = numbered_symbols('x')
free_vars = [next(freevars_gen) for i in range(17)]
m = Matrix([
[ 0, 0, 0, 2*I*J, 0, -2*I*J, 2*I*J, 2*I*J, 2*I*f, 0, 0, 0, 0, 0, 0, 0, 0, 2*I*V**2*f**3/J**4],
[-2*I*J, 0, 0, 0, 2*I*J, 0, -2*I*J, -2*I*J, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4*I*V**2*f**3/(3*J**4)],
[ 2*I*J, 2*I*J, 0, 0, 0, -2*I*J, 2*I*J, 0, -2*I*f, 0, 0, 0, 0, 0, 2*I*f, 0, 0, 8*I*V**2*f**3/(3*J**4)],
[-2*I*J, -2*I*J, -2*I*J, 0, 2*I*J, 0, 0, 0, 0, 2*I*V**2/f, -4*I*V**2/f, -2*I*V**2/f, 2*V, 2*V, 0, -2*I*f, 2*I*V**2/f, 2*I*V**2*f*(-2*V**2 + f**2)/(3*J**4)],
[ 0, 0, -2*I*J, -2*I*J, 2*I*J, 0, 0, -2*I*J, 0, 0, 0, 0, 0, 0, 0, 2*I*f, 0, -4*I*V**2*f**3/J**4],
[ 0, -2*I*J, 0, -2*I*J, 2*I*J, 0, -2*I*J, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -8*I*V**2*f**3/(3*J**4)],
[ 0, 2*I*J, 2*I*J, 2*I*J, 0, -2*I*J, 0, 0, 0, 2*I*V**2/f, -4*I*V**2/f, -2*I*V**2/f, 2*V, 2*V, -2*I*f, 0, 2*I*V**2/f, 4*I*V**2*f*(-V**2 + f**2)/(3*J**4)],
[ 2*I*J, 0, 2*I*J, 0, 0, -2*I*J, 0, 2*I*J, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]])
solve_linear_system(m,*free_vars)
dict(zip(free_vars, [simplify(result) for result in list(linsolve(m, *free_vars))[0]]))
Out[43]:
{x1: x7 + f*x14/(2*J) - f*x15/J - 5*V**2*f**3/(6*J**5),
x8: x14 - x15 - 2*V**2*f**2/J**4,
x3: x4 - x6 - x7 - f*x14/(2*J) + f*x15/J + 13*V**2*f**3/(6*J**5),
x5: x4 + f*x14/(2*J) - 5*V**2*f**3/(6*J**5),
x2: x6 + f*x14/(2*J) - V**2*f**3/(6*J**5),
x9: 2*x10 + x11 - x16 + I*f*x12/V + I*f*x13/V + f**2*x14/V**2 - 2*V**2*f**2/(3*J**4) - 4*f**4/(3*J**4),
x0: x4 - x6 - x7 - 2*V**2*f**3/(3*J**5)}
Out[44]:
{x13: x13,
x12: x12,
x4: x6 - f*x14/(2*J) + 5*V**2*f**3/(6*J**5),
x14: x14,
x6: x7,
x3: -x5 + x6 - x7 - f*x14/J + f*x15/J + 3*V**2*f**3/J**5,
x10: x10,
x11: x11,
x1: x5 + f*x14/(2*J) - f*x15/J - 5*V**2*f**3/(6*J**5),
x8: x14 - x15 - 2*V**2*f**2/J**4,
x16: x16,
x5: x6,
x2: x7 + f*x14/(2*J) - V**2*f**3/(6*J**5),
x9: 2*x10 + x11 - x16 + I*f*x12/V + I*f*x13/V + f**2*x14/V**2 - 2*V**2*f**2/(3*J**4) - 4*f**4/(3*J**4),
x7: x5,
x0: -x5 + x6 - x7 - f*x14/(2*J) + V**2*f**3/(6*J**5),
x15: x15}
```
`linsolve` will only get this far with the changes in #10119 merged. Now observe in the `linsolve` answer we have a number of free variables denoted by terms in the dict like `x13: x13`. If we wanted to arrive at a result of the form in `solve_linear_system` we could just delete these terms from the dict, so that's fine.
But look at the x5, x6, x7 terms. We have circular references `x5: x6`, `x6: x7`, `x7: x5`, whereas one might expect something like `x5: x7`, `x6: x7`, `x7: x7` If you look at say the solution for x3 you find x5, x6, x7 all appear despite clearly not being independent. For simpler undetermined matrices this does not seem to happen, so I'm not sure what's the particular feature of this one causing the problem.
@aktech @hargup
| sympy/sympy | diff --git a/sympy/solvers/tests/test_solveset.py b/sympy/solvers/tests/test_solveset.py
index db313f87ed..ec6f518db7 100644
--- a/sympy/solvers/tests/test_solveset.py
+++ b/sympy/solvers/tests/test_solveset.py
@@ -976,6 +976,11 @@ def test_linsolve():
b = Matrix([0, 0, 1])
assert linsolve((A, b), (x, y, z)) == EmptySet()
+ # Issue #10121 - Assignment of free variables
+ a, b, c, d, e = symbols('a, b, c, d, e')
+ Augmatrix = Matrix([[0, 1, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0]])
+ assert linsolve(Augmatrix, a, b, c, d, e) == FiniteSet((a, 0, c, 0, e))
+
def test_issue_9556():
x = Symbol('x')
| {
"commit_name": "head_commit",
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true,
"llm_score": {
"difficulty_score": 1,
"issue_text_score": 1,
"test_score": 2
},
"num_modified_files": 1
} | 0.7 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "pytest",
"pip_packages": [
"pytest",
"pytest-cov",
"pytest-xdist",
"pytest-mock",
"pytest-asyncio"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.6",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | attrs @ file:///opt/conda/conda-bld/attrs_1642510447205/work
certifi==2021.5.30
coverage==6.2
execnet==1.9.0
importlib-metadata @ file:///tmp/build/80754af9/importlib-metadata_1631916693255/work
iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work
more-itertools @ file:///tmp/build/80754af9/more-itertools_1637733554872/work
mpmath==1.3.0
packaging @ file:///tmp/build/80754af9/packaging_1637314298585/work
pluggy @ file:///tmp/build/80754af9/pluggy_1615976315926/work
py @ file:///opt/conda/conda-bld/py_1644396412707/work
pyparsing @ file:///tmp/build/80754af9/pyparsing_1635766073266/work
pytest==6.2.4
pytest-asyncio==0.16.0
pytest-cov==4.0.0
pytest-mock==3.6.1
pytest-xdist==3.0.2
-e git+https://github.com/sympy/sympy.git@81cc72003d4a58d0fbd1425b8b16a1b6ddec7010#egg=sympy
toml @ file:///tmp/build/80754af9/toml_1616166611790/work
tomli==1.2.3
typing_extensions @ file:///opt/conda/conda-bld/typing_extensions_1647553014482/work
zipp @ file:///tmp/build/80754af9/zipp_1633618647012/work
| name: sympy
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- attrs=21.4.0=pyhd3eb1b0_0
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2021.5.30=py36h06a4308_0
- importlib-metadata=4.8.1=py36h06a4308_0
- importlib_metadata=4.8.1=hd3eb1b0_0
- iniconfig=1.1.1=pyhd3eb1b0_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.3=he6710b0_2
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- more-itertools=8.12.0=pyhd3eb1b0_0
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- packaging=21.3=pyhd3eb1b0_0
- pip=21.2.2=py36h06a4308_0
- pluggy=0.13.1=py36h06a4308_0
- py=1.11.0=pyhd3eb1b0_0
- pyparsing=3.0.4=pyhd3eb1b0_0
- pytest=6.2.4=py36h06a4308_2
- python=3.6.13=h12debd9_1
- readline=8.2=h5eee18b_0
- setuptools=58.0.4=py36h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- toml=0.10.2=pyhd3eb1b0_0
- typing_extensions=4.1.1=pyh06a4308_0
- wheel=0.37.1=pyhd3eb1b0_0
- xz=5.6.4=h5eee18b_1
- zipp=3.6.0=pyhd3eb1b0_0
- zlib=1.2.13=h5eee18b_1
- pip:
- coverage==6.2
- execnet==1.9.0
- mpmath==1.3.0
- pytest-asyncio==0.16.0
- pytest-cov==4.0.0
- pytest-mock==3.6.1
- pytest-xdist==3.0.2
- tomli==1.2.3
prefix: /opt/conda/envs/sympy
| [
"sympy/solvers/tests/test_solveset.py::test_linsolve"
] | [] | [
"sympy/solvers/tests/test_solveset.py::test_invert_real",
"sympy/solvers/tests/test_solveset.py::test_invert_complex",
"sympy/solvers/tests/test_solveset.py::test_domain_check",
"sympy/solvers/tests/test_solveset.py::test_is_function_class_equation",
"sympy/solvers/tests/test_solveset.py::test_garbage_input",
"sympy/solvers/tests/test_solveset.py::test_solve_mul",
"sympy/solvers/tests/test_solveset.py::test_solve_invert",
"sympy/solvers/tests/test_solveset.py::test_errorinverses",
"sympy/solvers/tests/test_solveset.py::test_solve_polynomial",
"sympy/solvers/tests/test_solveset.py::test_return_root_of",
"sympy/solvers/tests/test_solveset.py::test__has_rational_power",
"sympy/solvers/tests/test_solveset.py::test_solveset_sqrt_1",
"sympy/solvers/tests/test_solveset.py::test_solveset_sqrt_2",
"sympy/solvers/tests/test_solveset.py::test_solve_sqrt_3",
"sympy/solvers/tests/test_solveset.py::test_solve_polynomial_symbolic_param",
"sympy/solvers/tests/test_solveset.py::test_solve_rational",
"sympy/solvers/tests/test_solveset.py::test_solveset_real_gen_is_pow",
"sympy/solvers/tests/test_solveset.py::test_no_sol",
"sympy/solvers/tests/test_solveset.py::test_sol_zero_real",
"sympy/solvers/tests/test_solveset.py::test_no_sol_rational_extragenous",
"sympy/solvers/tests/test_solveset.py::test_solve_polynomial_cv_1a",
"sympy/solvers/tests/test_solveset.py::test_solveset_real_rational",
"sympy/solvers/tests/test_solveset.py::test_solveset_real_log",
"sympy/solvers/tests/test_solveset.py::test_poly_gens",
"sympy/solvers/tests/test_solveset.py::test_solve_abs",
"sympy/solvers/tests/test_solveset.py::test_real_imag_splitting",
"sympy/solvers/tests/test_solveset.py::test_units",
"sympy/solvers/tests/test_solveset.py::test_solve_only_exp_1",
"sympy/solvers/tests/test_solveset.py::test_atan2",
"sympy/solvers/tests/test_solveset.py::test_piecewise",
"sympy/solvers/tests/test_solveset.py::test_solveset_complex_polynomial",
"sympy/solvers/tests/test_solveset.py::test_sol_zero_complex",
"sympy/solvers/tests/test_solveset.py::test_solveset_complex_rational",
"sympy/solvers/tests/test_solveset.py::test_solveset_complex_exp",
"sympy/solvers/tests/test_solveset.py::test_solve_complex_log",
"sympy/solvers/tests/test_solveset.py::test_solve_complex_sqrt",
"sympy/solvers/tests/test_solveset.py::test_solveset_complex_tan",
"sympy/solvers/tests/test_solveset.py::test_solve_trig",
"sympy/solvers/tests/test_solveset.py::test_solve_invalid_sol",
"sympy/solvers/tests/test_solveset.py::test_solve_complex_unsolvable",
"sympy/solvers/tests/test_solveset.py::test_solveset",
"sympy/solvers/tests/test_solveset.py::test_conditonset",
"sympy/solvers/tests/test_solveset.py::test_solveset_domain",
"sympy/solvers/tests/test_solveset.py::test_improve_coverage",
"sympy/solvers/tests/test_solveset.py::test_issue_9522",
"sympy/solvers/tests/test_solveset.py::test_linear_eq_to_matrix",
"sympy/solvers/tests/test_solveset.py::test_issue_9556",
"sympy/solvers/tests/test_solveset.py::test_issue_9611",
"sympy/solvers/tests/test_solveset.py::test_issue_9557",
"sympy/solvers/tests/test_solveset.py::test_issue_9778",
"sympy/solvers/tests/test_solveset.py::test_issue_9849",
"sympy/solvers/tests/test_solveset.py::test_issue_9953",
"sympy/solvers/tests/test_solveset.py::test_issue_9913"
] | [] | BSD | 297 |
|
falconry__falcon-651 | a8154de497b3ec5d6e5579026e74e9073e353819 | 2015-11-13 11:56:13 | b78ffaac7c412d3b3d6cd3c70dd05024d79d2cce | kgriffs: I think this makes sense. It is a breaking change, but one that should be easy for developers to accommodate. A couple testing suggestions inline. | diff --git a/falcon/api.py b/falcon/api.py
index cdc2c66..1a6b944 100644
--- a/falcon/api.py
+++ b/falcon/api.py
@@ -178,7 +178,8 @@ class API(object):
# e.g. a 404.
responder, params, resource = self._get_responder(req)
- self._call_rsrc_mw(middleware_stack, req, resp, resource)
+ self._call_rsrc_mw(middleware_stack, req, resp, resource,
+ params)
responder(req, resp, **params)
self._call_resp_mw(middleware_stack, req, resp, resource)
@@ -537,13 +538,13 @@ class API(object):
# Put executed component on the stack
stack.append(component) # keep track from outside
- def _call_rsrc_mw(self, stack, req, resp, resource):
+ def _call_rsrc_mw(self, stack, req, resp, resource, params):
"""Run process_resource middleware methods."""
for component in self._middleware:
_, process_resource, _ = component
if process_resource is not None:
- process_resource(req, resp, resource)
+ process_resource(req, resp, resource, params)
def _call_resp_mw(self, stack, req, resp, resource):
"""Run process_response middleware."""
| Pass params to process_resource
This is needed for feature parity with global *before* hooks. We can use a shim to avoid breaking existing middleware. | falconry/falcon | diff --git a/tests/test_httpstatus.py b/tests/test_httpstatus.py
index 3569e6b..f525be1 100644
--- a/tests/test_httpstatus.py
+++ b/tests/test_httpstatus.py
@@ -166,7 +166,7 @@ class TestHTTPStatusWithGlobalHooks(testing.TestBase):
def test_raise_status_in_process_resource(self):
""" Make sure we can raise status from middleware process resource """
class TestMiddleware:
- def process_resource(self, req, resp, resource):
+ def process_resource(self, req, resp, resource, params):
raise HTTPStatus(falcon.HTTP_200,
headers={"X-Failed": "False"},
body="Pass")
diff --git a/tests/test_middlewares.py b/tests/test_middlewares.py
index 226e57f..519852a 100644
--- a/tests/test_middlewares.py
+++ b/tests/test_middlewares.py
@@ -1,3 +1,5 @@
+import json
+
import falcon
import falcon.testing as testing
from datetime import datetime
@@ -11,7 +13,7 @@ class RequestTimeMiddleware(object):
global context
context['start_time'] = datetime.utcnow()
- def process_resource(self, req, resp, resource):
+ def process_resource(self, req, resp, resource, params):
global context
context['mid_time'] = datetime.utcnow()
@@ -34,7 +36,7 @@ class ExecutedFirstMiddleware(object):
context['executed_methods'].append(
'{0}.{1}'.format(self.__class__.__name__, 'process_request'))
- def process_resource(self, req, resp, resource):
+ def process_resource(self, req, resp, resource, params):
global context
context['executed_methods'].append(
'{0}.{1}'.format(self.__class__.__name__, 'process_resource'))
@@ -55,9 +57,17 @@ class RemoveBasePathMiddleware(object):
req.path = req.path.replace('/base_path', '', 1)
+class AccessParamsMiddleware(object):
+
+ def process_resource(self, req, resp, resource, params):
+ global context
+ params['added'] = True
+ context['params'] = params
+
+
class MiddlewareClassResource(object):
- def on_get(self, req, resp):
+ def on_get(self, req, resp, **kwargs):
resp.status = falcon.HTTP_200
resp.body = {'status': 'ok'}
@@ -368,3 +378,23 @@ class TestRemoveBasePathMiddleware(TestMiddleware):
self.assertEqual(self.srmock.status, falcon.HTTP_200)
self.simulate_request('/base_pathIncorrect/sub_path')
self.assertEqual(self.srmock.status, falcon.HTTP_404)
+
+
+class TestResourceMiddleware(TestMiddleware):
+
+ def test_can_access_resource_params(self):
+ """Test that params can be accessed from within process_resource"""
+ global context
+
+ class Resource:
+ def on_get(self, req, resp, **params):
+ resp.data = json.dumps(params)
+
+ self.api = falcon.API(middleware=AccessParamsMiddleware())
+ self.api.add_route('/path/{id}', Resource())
+ resp = self.simulate_request('/path/22')
+
+ self.assertIn('params', context)
+ self.assertTrue(context['params'])
+ self.assertEqual(context['params']['id'], '22')
+ self.assertEqual(json.loads(resp[0]), {"added": True, "id": "22"})
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_short_problem_statement"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 1,
"issue_text_score": 1,
"test_score": 0
},
"num_modified_files": 1
} | 0.3 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "pytest",
"pip_packages": [
"nose",
"coverage",
"ddt",
"pyyaml",
"requests",
"testtools",
"pytest"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.7",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | attrs @ file:///croot/attrs_1668696182826/work
certifi @ file:///croot/certifi_1671487769961/work/certifi
charset-normalizer==3.4.1
coverage==7.2.7
ddt==1.7.2
-e git+https://github.com/falconry/falcon.git@a8154de497b3ec5d6e5579026e74e9073e353819#egg=falcon
flit_core @ file:///opt/conda/conda-bld/flit-core_1644941570762/work/source/flit_core
idna==3.10
importlib-metadata @ file:///tmp/build/80754af9/importlib-metadata_1648562407465/work
iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work
nose==1.3.7
packaging @ file:///croot/packaging_1671697413597/work
pluggy @ file:///tmp/build/80754af9/pluggy_1648042572264/work
py @ file:///opt/conda/conda-bld/py_1644396412707/work
pytest==7.1.2
python-mimeparse==1.6.0
PyYAML==6.0.1
requests==2.31.0
six==1.17.0
testtools==2.7.1
tomli @ file:///opt/conda/conda-bld/tomli_1657175507142/work
typing_extensions @ file:///croot/typing_extensions_1669924550328/work
urllib3==2.0.7
zipp @ file:///croot/zipp_1672387121353/work
| name: falcon
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- attrs=22.1.0=py37h06a4308_0
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2022.12.7=py37h06a4308_0
- flit-core=3.6.0=pyhd3eb1b0_0
- importlib-metadata=4.11.3=py37h06a4308_0
- importlib_metadata=4.11.3=hd3eb1b0_0
- iniconfig=1.1.1=pyhd3eb1b0_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- packaging=22.0=py37h06a4308_0
- pip=22.3.1=py37h06a4308_0
- pluggy=1.0.0=py37h06a4308_1
- py=1.11.0=pyhd3eb1b0_0
- pytest=7.1.2=py37h06a4308_0
- python=3.7.16=h7a1cb2a_0
- readline=8.2=h5eee18b_0
- setuptools=65.6.3=py37h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- tomli=2.0.1=py37h06a4308_0
- typing_extensions=4.4.0=py37h06a4308_0
- wheel=0.38.4=py37h06a4308_0
- xz=5.6.4=h5eee18b_1
- zipp=3.11.0=py37h06a4308_0
- zlib=1.2.13=h5eee18b_1
- pip:
- charset-normalizer==3.4.1
- coverage==7.2.7
- ddt==1.7.2
- idna==3.10
- nose==1.3.7
- python-mimeparse==1.6.0
- pyyaml==6.0.1
- requests==2.31.0
- six==1.17.0
- testtools==2.7.1
- urllib3==2.0.7
prefix: /opt/conda/envs/falcon
| [
"tests/test_httpstatus.py::TestHTTPStatusWithGlobalHooks::test_raise_status_in_process_resource",
"tests/test_middlewares.py::TestRequestTimeMiddleware::test_log_get_request",
"tests/test_middlewares.py::TestSeveralMiddlewares::test_generate_trans_id_and_time_with_request",
"tests/test_middlewares.py::TestSeveralMiddlewares::test_middleware_execution_order",
"tests/test_middlewares.py::TestSeveralMiddlewares::test_order_mw_executed_when_exception_in_resp",
"tests/test_middlewares.py::TestSeveralMiddlewares::test_order_mw_executed_when_exception_in_rsrc",
"tests/test_middlewares.py::TestResourceMiddleware::test_can_access_resource_params"
] | [] | [
"tests/test_httpstatus.py::TestHTTPStatus::test_raise_status_empty_body",
"tests/test_httpstatus.py::TestHTTPStatus::test_raise_status_in_before_hook",
"tests/test_httpstatus.py::TestHTTPStatus::test_raise_status_in_responder",
"tests/test_httpstatus.py::TestHTTPStatus::test_raise_status_runs_after_hooks",
"tests/test_httpstatus.py::TestHTTPStatus::test_raise_status_survives_after_hooks",
"tests/test_httpstatus.py::TestHTTPStatusWithGlobalHooks::test_raise_status_in_before_hook",
"tests/test_httpstatus.py::TestHTTPStatusWithGlobalHooks::test_raise_status_in_process_request",
"tests/test_httpstatus.py::TestHTTPStatusWithGlobalHooks::test_raise_status_runs_after_hooks",
"tests/test_httpstatus.py::TestHTTPStatusWithGlobalHooks::test_raise_status_runs_process_response",
"tests/test_httpstatus.py::TestHTTPStatusWithGlobalHooks::test_raise_status_survives_after_hooks",
"tests/test_middlewares.py::TestRequestTimeMiddleware::test_add_invalid_middleware",
"tests/test_middlewares.py::TestRequestTimeMiddleware::test_response_middleware_raises_exception",
"tests/test_middlewares.py::TestTransactionIdMiddleware::test_generate_trans_id_with_request",
"tests/test_middlewares.py::TestSeveralMiddlewares::test_inner_mw_throw_exception",
"tests/test_middlewares.py::TestSeveralMiddlewares::test_inner_mw_with_ex_handler_throw_exception",
"tests/test_middlewares.py::TestSeveralMiddlewares::test_order_mw_executed_when_exception_in_req",
"tests/test_middlewares.py::TestSeveralMiddlewares::test_outer_mw_with_ex_handler_throw_exception",
"tests/test_middlewares.py::TestRemoveBasePathMiddleware::test_base_path_is_removed_before_routing"
] | [] | Apache License 2.0 | 298 |
Stranger6667__pyanyapi-33 | 433dc8263c6c346d772120ad6f402714eb95c72a | 2015-11-15 11:30:16 | aebee636ad26f387850a6c8ab820ce4aac3f9adb | codecov-io: ## [Current coverage][1] is `100.00%`
> Merging **#33** into **master** will not affect coverage as of [`13e366f`][3]
```diff
@@ master #33 diff @@
======================================
Files 7 7
Stmts 348 351 +3
Branches 36 38 +2
Methods 0 0
======================================
+ Hit 348 351 +3
Partial 0 0
Missed 0 0
```
> Review entire [Coverage Diff][4] as of [`13e366f`][3]
[1]: https://codecov.io/github/Stranger6667/pyanyapi?ref=13e366f7c2915fc8f7f7e7c1396ac9772f6942e8
[2]: https://codecov.io/github/Stranger6667/pyanyapi/features/suggestions?ref=13e366f7c2915fc8f7f7e7c1396ac9772f6942e8
[3]: https://codecov.io/github/Stranger6667/pyanyapi/commit/13e366f7c2915fc8f7f7e7c1396ac9772f6942e8
[4]: https://codecov.io/github/Stranger6667/pyanyapi/compare/b1f0bc477bb850dc39c4646ff359e59d764a9f77...13e366f7c2915fc8f7f7e7c1396ac9772f6942e8
> Powered by [Codecov](https://codecov.io). Updated on successful CI builds. | diff --git a/CHANGELOG.md b/CHANGELOG.md
index 016a9b7..ecfdb61 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,7 @@ History
----------------
* Fixed `lxml` installation on PyPy (#34).
+* Add support for subparsers (#32).
0.5.3 - 30.10.2015
----------------
diff --git a/README.rst b/README.rst
index ad508c4..7600418 100644
--- a/README.rst
+++ b/README.rst
@@ -105,6 +105,36 @@ list. Here comes "base-children" setup style.
>>> api.test
['123 ', ' 234']
+There is another option to interact with sub-elements. Sub parsers!
+
+.. code:: python
+
+ from pyanyapi import HTMLParser
+
+
+ class SubParser(HTMLParser):
+ settings = {
+ 'href': 'string(//@href)',
+ 'text': 'string(//text())'
+ }
+
+
+ class Parser(HTMLParser):
+ settings = {
+ 'elem': {
+ 'base': './/a',
+ 'parser': SubParser
+ }
+ }
+
+ >>> api = Parser().parse('<html><body><a href='#test'>test</body></html>')
+ >>> api.elem[0].href
+ #test
+ >>> api.elem[0].text
+ test
+
+Also you can pass sub parsers as classes or like instances.
+
Settings inheritance
~~~~~~~~~~~~~~~~~~~~
diff --git a/pyanyapi/interfaces.py b/pyanyapi/interfaces.py
index 121f684..53734a7 100644
--- a/pyanyapi/interfaces.py
+++ b/pyanyapi/interfaces.py
@@ -141,6 +141,12 @@ class XPathInterface(BaseInterface):
child_query = settings.get('children')
if child_query:
return [self.maybe_strip(''.join(element.xpath(child_query))) for element in result]
+ sub_parser = settings.get('parser')
+ if sub_parser:
+ return [
+ (sub_parser() if callable(sub_parser) else sub_parser).parse(etree.tostring(element))
+ for element in result
+ ]
return result
return self.parse(settings)
| Improve children syntax
As we discussed =D
Add supporting for childrens parse for every parent element
Example settings:
```python
class IMDBParser(HTMLParser):
settings = {
'films_blocks': {
'base': '//div[@class="media"]',
'children': {
'title': '/h4',
'link': '/span/a/@href'
}
}
}
```
Example usage:
```
parsed_elements.film_blocks[0].title
```
or something like dictionary with childs in Element object.
| Stranger6667/pyanyapi | diff --git a/tests/conftest.py b/tests/conftest.py
index 06f9542..d127796 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -4,7 +4,7 @@ import sys
import pytest
-from pyanyapi import JSONParser, RegExpParser, CombinedParser, interface_property, interface_method
+from pyanyapi import JSONParser, RegExpParser, CombinedParser, interface_property, interface_method, HTMLParser
class EmptyValuesParser(CombinedParser):
@@ -74,6 +74,13 @@ class ChildParser(ParentParser):
}
+class SubParser(HTMLParser):
+ settings = {
+ 'href': 'string(//@href)',
+ 'text': 'string(//text())'
+ }
+
+
class SimpleParser(RegExpParser):
settings = {
'test': '\d+.\d+',
diff --git a/tests/test_parsers.py b/tests/test_parsers.py
index e13a167..163b42c 100644
--- a/tests/test_parsers.py
+++ b/tests/test_parsers.py
@@ -4,12 +4,21 @@ import re
import pytest
from ._compat import patch
-from .conftest import ChildParser, SimpleParser, lxml_is_supported, lxml_is_not_supported
-from pyanyapi import XMLObjectifyParser, XMLParser, JSONParser, YAMLParser, RegExpParser, AJAXParser, CSVParser
+from .conftest import ChildParser, SubParser, SimpleParser, lxml_is_supported, lxml_is_not_supported
+from pyanyapi import (
+ XMLObjectifyParser,
+ XMLParser,
+ JSONParser,
+ YAMLParser,
+ RegExpParser,
+ AJAXParser,
+ CSVParser,
+ HTMLParser,
+)
from pyanyapi.exceptions import ResponseParseError
-HTML_CONTENT = "<html><body><a href='#test'></body></html>"
+HTML_CONTENT = "<html><body><a href='#test'>test</body></html>"
XML_CONTENT = '''<?xml version="1.0" encoding="UTF-8"?>
<response>
<id>32e9a4a2</id>
@@ -289,3 +298,21 @@ def test_csv_parser_error():
parsed = CSVParser({'test': '1:1'}).parse(123)
with pytest.raises(ResponseParseError):
parsed.test
+
+
+@lxml_is_supported
[email protected]('sub_parser', (SubParser, SubParser()))
+def test_children(sub_parser):
+
+ class Parser(HTMLParser):
+ settings = {
+ 'elem': {
+ 'base': './/a',
+ 'parser': sub_parser
+ }
+ }
+
+ api = Parser().parse(HTML_CONTENT)
+ sub_api = api.elem[0]
+ assert sub_api.href == '#test'
+ assert sub_api.text == 'test'
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 2,
"issue_text_score": 2,
"test_score": 0
},
"num_modified_files": 3
} | 0.5 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest",
"pytest-cov"
],
"pre_install": [],
"python": "3.5",
"reqs_path": [
"requirements.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | attrs==22.2.0
certifi==2021.5.30
coverage==6.2
importlib-metadata==4.8.3
iniconfig==1.1.1
lxml==5.3.1
packaging==21.3
pluggy==1.0.0
py==1.11.0
-e git+https://github.com/Stranger6667/pyanyapi.git@433dc8263c6c346d772120ad6f402714eb95c72a#egg=pyanyapi
pyparsing==3.1.4
pytest==7.0.1
pytest-cov==4.0.0
PyYAML==3.11
tomli==1.2.3
typing_extensions==4.1.1
ujson==4.3.0
zipp==3.6.0
| name: pyanyapi
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2021.5.30=py36h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.3=he6710b0_2
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- pip=21.2.2=py36h06a4308_0
- python=3.6.13=h12debd9_1
- readline=8.2=h5eee18b_0
- setuptools=58.0.4=py36h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- wheel=0.37.1=pyhd3eb1b0_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- attrs==22.2.0
- coverage==6.2
- importlib-metadata==4.8.3
- iniconfig==1.1.1
- lxml==5.3.1
- packaging==21.3
- pluggy==1.0.0
- py==1.11.0
- pyparsing==3.1.4
- pytest==7.0.1
- pytest-cov==4.0.0
- pyyaml==3.11
- tomli==1.2.3
- typing-extensions==4.1.1
- ujson==4.3.0
- zipp==3.6.0
prefix: /opt/conda/envs/pyanyapi
| [
"tests/test_parsers.py::test_children[SubParser]",
"tests/test_parsers.py::test_children[sub_parser1]"
] | [] | [
"tests/test_parsers.py::test_xml_objectify_parser",
"tests/test_parsers.py::test_xml_objectify_parser_error",
"tests/test_parsers.py::test_xml_parser_error",
"tests/test_parsers.py::test_yaml_parser_error",
"tests/test_parsers.py::test_xml_parsed[settings0]",
"tests/test_parsers.py::test_xml_parsed[settings1]",
"tests/test_parsers.py::test_xml_simple_settings",
"tests/test_parsers.py::test_json_parsed",
"tests/test_parsers.py::test_multiple_parser_join",
"tests/test_parsers.py::test_multiply_parsers_declaration",
"tests/test_parsers.py::test_empty_values[{\"container\":{\"test\":\"value\"}}-test-value]",
"tests/test_parsers.py::test_empty_values[{\"container\":{\"test\":\"value\"}}-second-None]",
"tests/test_parsers.py::test_empty_values[{\"container\":{\"fail\":[1]}}-second-None]",
"tests/test_parsers.py::test_empty_values[{\"container\":[[1],[],[3]]}-third-expected3]",
"tests/test_parsers.py::test_empty_values[{\"container\":null}-null-None]",
"tests/test_parsers.py::test_empty_values[{\"container\":[1,2]}-test-1,2]",
"tests/test_parsers.py::test_attributes",
"tests/test_parsers.py::test_efficient_parsing",
"tests/test_parsers.py::test_simple_config_xml_parser",
"tests/test_parsers.py::test_simple_config_json_parser",
"tests/test_parsers.py::test_settings_inheritance",
"tests/test_parsers.py::test_complex_config",
"tests/test_parsers.py::test_json_parse",
"tests/test_parsers.py::test_json_value_error_parse",
"tests/test_parsers.py::test_regexp_parse",
"tests/test_parsers.py::test_yaml_parse",
"tests/test_parsers.py::test_ajax_parser",
"tests/test_parsers.py::test_ajax_parser_cache",
"tests/test_parsers.py::test_ajax_parser_invalid_settings",
"tests/test_parsers.py::test_parse_memoization",
"tests/test_parsers.py::test_regexp_settings",
"tests/test_parsers.py::test_parse_all",
"tests/test_parsers.py::test_parse_all_combined_parser",
"tests/test_parsers.py::test_parse_csv",
"tests/test_parsers.py::test_parse_csv_custom_delimiter",
"tests/test_parsers.py::test_csv_parser_error"
] | [] | MIT License | 299 |
Subsets and Splits